From 522eeac40e6d183c5f520aa2c88186a58a91cd7f Mon Sep 17 00:00:00 2001 From: Jack Ryan <thisisjackryan1@gmail.com> Date: Sun, 11 Feb 2024 12:15:34 -0600 Subject: [PATCH] Updates --- asset-manifest.json | 12 ++++++------ index.html | 2 +- static/css/main.34eac904.css | 2 ++ static/css/main.34eac904.css.map | 1 + static/css/main.fdca129c.css | 2 -- static/css/main.fdca129c.css.map | 1 - static/js/main.e9c9ba71.js.map | 1 - static/js/{main.e9c9ba71.js => main.fc2a7381.js} | 6 +++--- ...1.js.LICENSE.txt => main.fc2a7381.js.LICENSE.txt} | 0 static/js/main.fc2a7381.js.map | 1 + 10 files changed, 14 insertions(+), 14 deletions(-) create mode 100644 static/css/main.34eac904.css create mode 100644 static/css/main.34eac904.css.map delete mode 100644 static/css/main.fdca129c.css delete mode 100644 static/css/main.fdca129c.css.map delete mode 100644 static/js/main.e9c9ba71.js.map rename static/js/{main.e9c9ba71.js => main.fc2a7381.js} (85%) rename static/js/{main.e9c9ba71.js.LICENSE.txt => main.fc2a7381.js.LICENSE.txt} (100%) create mode 100644 static/js/main.fc2a7381.js.map diff --git a/asset-manifest.json b/asset-manifest.json index 472d24a..2e7e1f3 100644 --- a/asset-manifest.json +++ b/asset-manifest.json @@ -1,15 +1,15 @@ { "files": { - "main.css": "/Friendly-Betting/static/css/main.fdca129c.css", - "main.js": "/Friendly-Betting/static/js/main.e9c9ba71.js", + "main.css": "/Friendly-Betting/static/css/main.34eac904.css", + "main.js": "/Friendly-Betting/static/js/main.fc2a7381.js", "static/js/787.7e4c938d.chunk.js": "/Friendly-Betting/static/js/787.7e4c938d.chunk.js", "index.html": "/Friendly-Betting/index.html", - "main.fdca129c.css.map": "/Friendly-Betting/static/css/main.fdca129c.css.map", - "main.e9c9ba71.js.map": "/Friendly-Betting/static/js/main.e9c9ba71.js.map", + "main.34eac904.css.map": "/Friendly-Betting/static/css/main.34eac904.css.map", + "main.fc2a7381.js.map": "/Friendly-Betting/static/js/main.fc2a7381.js.map", "787.7e4c938d.chunk.js.map": "/Friendly-Betting/static/js/787.7e4c938d.chunk.js.map" }, "entrypoints": [ - "static/css/main.fdca129c.css", - "static/js/main.e9c9ba71.js" + "static/css/main.34eac904.css", + "static/js/main.fc2a7381.js" ] } \ No newline at end of file diff --git a/index.html b/index.html index dc63ffe..d1753b6 100644 --- a/index.html +++ b/index.html @@ -1 +1 @@ -<!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="/Friendly-Betting/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="Web site created using create-react-app"/><link rel="apple-touch-icon" href="/Friendly-Betting/logo192.png"/><link rel="manifest" href="/Friendly-Betting/manifest.json"/><title>React App</title><script defer="defer" src="/Friendly-Betting/static/js/main.e9c9ba71.js"></script><link href="/Friendly-Betting/static/css/main.fdca129c.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html> \ No newline at end of file +<!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="/Friendly-Betting/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="Web site created using create-react-app"/><link rel="apple-touch-icon" href="/Friendly-Betting/logo192.png"/><link rel="manifest" href="/Friendly-Betting/manifest.json"/><title>React App</title><script defer="defer" src="/Friendly-Betting/static/js/main.fc2a7381.js"></script><link href="/Friendly-Betting/static/css/main.34eac904.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html> \ No newline at end of file diff --git a/static/css/main.34eac904.css b/static/css/main.34eac904.css new file mode 100644 index 0000000..11fd97a --- /dev/null +++ b/static/css/main.34eac904.css @@ -0,0 +1,2 @@ +body{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:source-code-pro,Menlo,Monaco,Consolas,Courier New,monospace;margin:0}.sticky{position:-webkit-sticky;position:sticky}.bottom-0{bottom:0}.left-0{left:0}.right-0{right:0}.top-0{top:0}.m-2{margin:.5rem}.m-4{margin:1rem}.mx-8{margin-left:2rem;margin-right:2rem}.my-4{margin-bottom:1rem;margin-top:1rem}.mb-2{margin-bottom:.5rem}.flex{display:flex}.h-6{height:1.5rem}.w-12{width:3rem}.flex-1{flex:1 1}.flex-col{flex-direction:column}.items-center{align-items:center}.justify-center{justify-content:center}.justify-around{justify-content:space-around}.gap-2{gap:.5rem}.gap-4{gap:1rem}.gap-8{gap:2rem}.break-words{overflow-wrap:break-word}.p-12{padding:3rem}.p-16{padding:4rem}.p-2{padding:.5rem}.pb-4{padding-bottom:1rem}.pb-8{padding-bottom:2rem}.pl-8{padding-left:2rem}.pt-12{padding-top:3rem}.text-center{text-align:center}:root{--midnight-green:#114b5f;--cardinal:#ba3b46;--cadet-gray:#95a3a4;--dark-purple:#170a1c;--alabaster:#e2e8dd;--dark-spring-green:#007a45;--gradient-top:linear-gradient(0deg,#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd);--gradient-right:linear-gradient(90deg,#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd);--gradient-bottom:linear-gradient(180deg,#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd);--gradient-left:linear-gradient(270deg,#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd);--gradient-top-right:linear-gradient(45deg,#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd);--gradient-bottom-right:linear-gradient(135deg,#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd);--gradient-top-left:linear-gradient(225deg,#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd);--gradient-bottom-left:linear-gradient(315deg,#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd);--gradient-radial:radial-gradient(#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd)}body{background-color:#114b5f;background-color:var(--midnight-green);color:#e2e8dd;color:var(--alabaster);font-family:Roboto,sans-serif;font-size:1.25em;height:100vh;width:100vw}.x1{flex:1 1}.x2{flex:2 1}.x3{flex:3 1}.flex.center{align-items:center;justify-content:center}.header{background-color:#95a3a4;background-color:var(--cadet-gray);color:#e2e8dd;color:var(--alabaster);display:flex;font-size:1.25em;padding:2rem 1rem 1rem}.pages{align-items:center;gap:1em;justify-content:center}.Link{color:#e2e8dd;color:var(--alabaster);text-decoration:none}.Link:hover{color:#170a1c;color:var(--dark-purple)}.blob{align-items:center;background-color:#95a3a433;border-radius:5px;box-shadow:4px 4px 4px 0 #00000040;display:flex;flex-direction:column;justify-content:center;margin:6rem 10rem;padding:1.5em}.green{color:#03ff03}.red{color:red}.row{flex-direction:row}.SignIn_signIn__3t4GY{align-items:center;background-color:var(--cadet-gray);border:2px solid #000;border-radius:5px;box-shadow:10px 10px 10px 5px #000000bf;color:var(--alabaster);display:flex;flex-direction:column;justify-content:center;margin:4rem 15rem;padding:2rem;transition:opacity .5s ease-in-out}.SignIn_signInTransition__DVaCC{opacity:0}.SignIn_signIn__3t4GY input{font-size:1rem;margin:.5rem;padding:1rem .5rem;width:75%}.SignIn_signInLabel__6itNQ{border-bottom:2px solid var(--alabaster);font-size:2rem;padding-bottom:0;text-align:center}.SignIn_swapSignIn__WlTGP{border-bottom:2px solid;color:blue;font-size:.75rem;text-decoration:none}.SignIn_swapSignIn__WlTGP:hover{border-bottom:2px solid;color:#00008b}.MoneyLine_MoneyLine__GZY-g{font-size:2em}.MoneyLine_betContainer__MPUkR{border-bottom:1px dashed var(--alabaster)}.MoneyLine_bet__iBwWG{padding-left:2rem}.MoneyLine_betTextArea__Q9aMH{background-color:var(--cadet-gray);border:1px solid var(--alabaster);border-radius:5px;color:var(--alabaster);font-size:.5em;height:6em;padding:.5rem;text-align:left;width:20em}.MoneyLine_betTextArea__Q9aMH:focus{border:2px solid var(--alabaster);outline:none}.MoneyLine_contestantInput__RtHW6{background-color:var(--cadet-gray);border:1px solid;border-radius:5px;height:3rem}.MoneyLine_contestantInput__RtHW6:focus{border:2px solid var(--alabaster);outline:none}.MoneyLine_label__SXs1d{border-bottom:1px solid var(--alabaster);color:var(--alabaster);font-size:.75em;padding:.5rem}.MoneyLine_odds__5UKBZ{color:var(--alabaster);font-size:.5em;padding-left:.5rem}.MoneyLine_odds__5UKBZ input{width:4rem}.MoneyLine_betLabel__xK-Pn{border-bottom:1px dashed var(--alabaster);font-weight:400}hr{border:none;border-top:1px dashed var(--alabaster);height:1px;width:75%}.Players_disable__2Lrxc{background-color:#a9a9a9}.Players_friends__S-rHI{background-color:#95a3a433;border-radius:5px;box-shadow:4px 4px 4px 0 #00000040;display:flex;flex-direction:column;font-size:.9em;gap:2rem;margin:1em 2.5em;padding:1em 3em}.Players_addFiendForm__No56b{background-color:var(--cadet-gray);border:2px solid #000;border-radius:5px;box-shadow:5px 5px 5px 0 #000000bf;font-size:1.5em;left:50%;padding:1em;position:absolute;top:50%;transform:translate(-50%,-50%)}.Players_x__50IpE{font-size:smaller;margin-left:.5rem;margin-right:.5rem}.Players_x__50IpE:hover{color:#000;cursor:pointer}.Players_shareBet__IEGN8{background-color:var(--cadet-gray);border:2px solid #000;border-radius:5px;box-shadow:5px 5px 5px 0 #000000bf;font-size:1.5em;left:50%;padding:2em;position:absolute;top:50%;transform:translate(-50%,-50%)}.Players_friendsLabel__doMbx{font-size:1.5em;margin-bottom:1.5rem}.Players_friendsLabel__doMbx span{border-bottom:2px solid var(--alabaster)}.Players_container__wuYC4{cursor:pointer;display:block;font-size:22px;margin-bottom:12px;padding-left:35px;position:relative;-webkit-user-select:none;user-select:none}.Players_container__wuYC4 input{cursor:pointer;height:0;opacity:0;position:absolute;width:0}.Players_checkmark__OI0Ce{background-color:#eee;height:25px;left:0;position:absolute;top:0;width:25px}.Players_container__wuYC4:hover input~.Players_checkmark__OI0Ce{background-color:#ccc}.Players_container__wuYC4 input:checked~.Players_checkmark__OI0Ce{background-color:#2196f3}.Players_checkmark__OI0Ce:after{content:"";display:none;position:absolute}.Players_container__wuYC4 input:checked~.Players_checkmark__OI0Ce:after{display:block}.Players_container__wuYC4 .Players_checkmark__OI0Ce:after{border:solid #fff;border-width:0 3px 3px 0;height:10px;left:9px;top:5px;transform:rotate(45deg);width:5px}.OverUnder_OverUnder__lZCyp{flex:2 1;font-size:2em}.OverUnder_betContainer__GC\+uq{border-bottom:1px dashed var(--alabaster)}.OverUnder_BetTextArea__Y0xal{background-color:var(--cadet-gray);border:1px solid var(--alabaster);border-radius:5px;color:var(--alabaster);font-size:.5em;height:6em;padding:.5rem;text-align:left;width:20em}.OverUnder_betLabel__fUG2h{border-bottom:1px dashed var(--alabaster);font-weight:400;padding-bottom:1rem;padding-left:1em}.OverUnder_lineLabel__uLemh span{border-bottom:1px solid var(--alabaster)}.OverUnder_line__xiV\+Z{border-left:1px solid var(--alabaster);border-right:1px solid var(--alabaster);flex-direction:column;gap:1rem;margin:1em;padding:0 1.5em}.OverUnder_actualLine__NevcO,.OverUnder_line__xiV\+Z{align-items:center;display:flex;justify-content:center}.OverUnder_actualLine__NevcO{font-size:1.5em}.Prop_prop__DRZFt{flex:2 1;font-size:2em}.Prop_betContainer__KSYFf{border-bottom:1px dashed var(--alabaster)}.Prop_betTextarea__fXQn9{background-color:var(--cadet-gray);border:1px solid var(--alabaster);border-radius:5px;color:var(--alabaster);font-size:.5em;height:6em;padding:.5rem;text-align:left;width:20em}.Prop_PreSetBetting__MzpqW{background-color:var(--cadet-gray);border:1px solid #000;border-radius:5px;box-shadow:5px 5px 5px 0 #000000bf;left:50%;padding:1em;position:absolute;top:50%;transform:translate(-50%,-50%)}.Prop_settings__9dmn0{font-size:.75em}.Prop_title__GEvyW{font-size:.75em;margin-bottom:1rem;text-align:center}.Prop_title__GEvyW span{border-bottom:2px solid var(--alabaster)}.Prop_label__zDU93{font-size:1em}.Prop_x__tu9O2:hover{color:#000;cursor:pointer}.Prop_optionInput__MuLBG{background-color:var(--alabaster);border:1px solid;border-radius:5px;height:2rem;padding:.25rem .5rem}h4 span{border-bottom:2px solid var(--alabaster);font-size:1em;margin-bottom:.5rem;padding-bottom:.05em}.Components_greenButtons__FGl7E{background-color:#9dc9a4;border:none;border-radius:5px;box-shadow:4px 4px 4px 0 #00000040;color:#000;font-size:1.1rem;font-weight:100;padding:1rem 2.25rem}.Components_redSpring__YTemv{background-color:#ff9a9a}.Components_big__0VZG0{font-size:1.1rem;font-weight:100;padding:1rem 2.25rem}.Components_small__5JtmR{padding:0}.Components_DeleteButton__X\+vUS{background-color:red;border:none;border-radius:5px;box-shadow:4px 4px 4px 0 #00000040;padding:1rem 2.25rem}.Components_DeleteButton__X\+vUS:hover{background-color:darkred}.Components_DeleteButton__X\+vUS:active{box-shadow:inset 4px 4px 4px 0 #00000040}.Bets_betNav__NdIy7{background-color:var(--cadet-gray);border:2px solid #000;border-radius:5px;box-shadow:5px 5px 5px 0 #000000bf;left:50%;padding:1em;position:absolute;top:50%;transform:translate(-50%,-50%)}.Bets_betNav__NdIy7 h1{margin-bottom:1em;text-align:center}.Bets_betNav__NdIy7 h1 span{border-bottom:2px solid var(--alabaster)}.Bets_BettingLinks__UtSL7{align-items:left;display:flex;flex-direction:column;gap:1em;justify-content:center;margin:1em}.Bets_x__IOVNi{display:flex;justify-content:right;margin-bottom:.5rem}.Bets_x__IOVNi span:hover{color:#000;cursor:pointer}.Bets_bet__pvKP6{background-color:var(--cadet-gray);border:2px solid #000;border-radius:5px;box-shadow:5px 5px 5px 0 #000000bf;margin:1em 2em;padding:.5rem 2em}.Bets_bet__pvKP6:hover{background-color:#879494}.Bets_bet__pvKP6:active{box-shadow:inset 3px 3px 3px 0 #000000bf}.Bets_link__ibFCG{color:var(--alabaster);text-decoration:none} +/*# sourceMappingURL=main.34eac904.css.map*/ \ No newline at end of file diff --git a/static/css/main.34eac904.css.map b/static/css/main.34eac904.css.map new file mode 100644 index 0000000..1aa9b3f --- /dev/null +++ b/static/css/main.34eac904.css.map @@ -0,0 +1 @@ +{"version":3,"file":"static/css/main.34eac904.css","mappings":"AAAA,KAIE,kCAAm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B,OAAQ,CAFR,sBAAuB,CAGvB,UAEJ,CACA,eACI,YAAa,CACb,qBAAsB,CACtB,mBACJ,CACA,0BAEI,UAAY,CADZ,cAEJ,CAEA,iBACE,kCAAmC,CAInC,qBAAuB,CADvB,iBAAkB,CAElB,kCAA4C,CAH5C,cAAe,CADf,iBAMF,CAEA,uBACE,wBACF,CAEA,wBACE,wCACF,CAEA,kBAEE,sBAAuB,CADvB,oBAEF","sources":["index.css","App.css","Components/SignInPage/SignIn.module.css","Components/Bets/MoneyLineBets/MoneyLine.module.css","Components/Bets/Players/Players.module.css","Components/Bets/OverUnderBets/OverUnder.module.css","Components/Bets/PropBets/Prop.module.css","Components/Components/Components.module.css","Components/Bets/Bets.module.css"],"sourcesContent":["body {\n margin: 0;\n font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',\n monospace;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n\n\n","/* @tailwind base; \n@tailwind components; */\n@tailwind utilities; \n\n\n:root{\n --midnight-green: #114b5fff;\n --cardinal: #ba3b46ff;\n --cadet-gray: #95a3a4ff;\n --dark-purple: #170a1cff;\n --alabaster: #e2e8ddff;\n --dark-spring-green: #007a45ff;\n \n /* CSS HSL */\n /*\n --midnight-green: hsla(195, 70%, 22%, 1);\n --cardinal: hsla(355, 52%, 48%, 1);\n --cadet-gray: hsla(184, 8%, 61%, 1);\n --dark-purple: hsla(283, 47%, 7%, 1);\n --alabaster: hsla(93, 19%, 89%, 1);\n */\n --gradient-top: linear-gradient(0deg, #114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n --gradient-right: linear-gradient(90deg, #114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n --gradient-bottom: linear-gradient(180deg, #114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n --gradient-left: linear-gradient(270deg, #114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n --gradient-top-right: linear-gradient(45deg, #114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n --gradient-bottom-right: linear-gradient(135deg, #114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n --gradient-top-left: linear-gradient(225deg, #114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n --gradient-bottom-left: linear-gradient(315deg, #114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n --gradient-radial: radial-gradient(#114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n}\n\n\n\n\n\nbody{\n background-color: var(--midnight-green);\n color: var(--alabaster);\n font-family: 'Roboto', sans-serif;\n font-size: 1.25em;\n height: 100vh;\n width: 100vw;\n\n}\n\n\n\n.x1{flex: 1;}\n.x2{flex: 2;}\n.x3{flex: 3;}\n\n.flex.center{\n justify-content: center;\n align-items: center;\n}\n\n.header{\n display: flex;\n padding: 1rem;\n padding-top: 2rem;\n background-color: var(--cadet-gray);\n color: var(--alabaster);\n font-size: 1.25em;\n}\n.pages{\n justify-content: center;\n align-items: center;\n gap:1em;\n}\n.Link{\n text-decoration: none;\n color: var(--alabaster);\n\n}\n.Link:hover{\n color: var(--dark-purple);\n}\n\n\n.blob{\n display: flex;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n background-color: rgba(149, 163, 164, .2);\n border-radius: 5px;\n box-shadow: 4px 4px 4px 0px rgba(0,0,0,0.25);\n margin: 6rem 10rem;\n padding: 1.5em;\n}\n\n.green{\n color: rgb(3, 255, 3);\n}\n\n.red{\n color: red;\n}\n\n.row{\n flex-direction: row;\n}\n\n\n\n\n\n","\n\n\n.signIn{\n display: flex;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n border: solid 2px black;\n border-radius: 5px;\n margin: 4rem 15rem;\n padding:2rem ;\n background-color: var(--cadet-gray);\n color:var(--alabaster);\n box-shadow: 10px 10px 10px 5px rgba(0,0,0,0.75);\n transition: opacity .5s ease-in-out;\n }\n\n .signInTransition {\n opacity: 0;\n }\n .signIn input{\n padding: 1rem 0.5rem;\n margin: 0.5rem;\n width: 75%;\n font-size: 1rem;\n }\n\n .signInLabel{\n text-align: center;\n border-bottom: var(--alabaster) 2px solid;\n padding-bottom: 0px;\n font-size: 2rem;\n }\n\n .swapSignIn{\n text-decoration: none;\n border-bottom:solid 2px;\n color: blue;\n font-size: 0.75rem;\n }\n .swapSignIn:hover{\n border-bottom:solid 2px;\n color: darkblue;\n }","\n\n.MoneyLine{\n font-size: 2em;\n}\n.betContainer{\n border-bottom:dashed 1px var(--alabaster);\n}\n.bet{\n padding-left:2rem\n}\n.betTextArea {\n width: 20em;\n height: 6em;\n font-size: .5em;\n text-align: left;\n padding: .5rem;;\n border-radius: 5px;\n border: 1px solid var(--alabaster);\n background-color: var(--cadet-gray);\n color: var(--alabaster);\n}\n.betTextArea:focus{\n outline:none;\n border: solid 2px var(--alabaster);\n}\n\n.contestantInput{\n height: 3rem;\n background-color: var(--cadet-gray);\n border-radius: 5px;\n border: 1px solid;\n}\n.contestantInput:focus{\n outline:none;\n border: solid 2px var(--alabaster);\n \n}\n.label{\n font-size: .75em;\n padding: .5rem;\n border-bottom: 1px solid var(--alabaster);\n color: var(--alabaster);\n}\n.odds{\n font-size: .5em;\n padding-left: .5rem;\n color: var(--alabaster);\n}\n.odds input{\n width: 4rem;\n}\n\n.betLabel{\n font-weight: normal;\n border-bottom: dashed 1px var(--alabaster);\n}\nhr {\n border: none;\n border-top: 1px dashed var(--alabaster);\n height: 1px;\n width: 75%;\n }","\n\n\n\n.disable{\n background-color: darkgray;\n \n}\n\n.friends{\n display: flex;\n flex-direction: column;\n gap: 2rem;\n background-color: rgba(149, 163, 164, .2);\n border-radius: 5px;\n box-shadow: 4px 4px 4px 0px rgba(0,0,0,0.25);\n margin: 1em 2.5em;\n padding: 1em 3em;\n font-size: .9em;\n\n\n}\n\n\n.addFiendForm{\n position:absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n border: solid black 2px;\n border-radius: 5px;\n background-color: var(--cadet-gray);\n padding:1em;\n font-size: 1.5em;\n box-shadow: 5px 5px 5px 0px rgba(0,0,0,0.75);\n}\n \n \n.x {\n margin-left: 0.5rem;\n margin-right: 0.5rem;\n font-size: smaller;\n}\n \n.x:hover{\n cursor: pointer;\n color: black;\n}\n\n.shareBet{\n font-size: 1.5em;\n background-color: var(--cadet-gray);\n position: absolute;\n top:50%;\n left:50%;\n transform: translate(-50%, -50%);\n border: solid black 2px;\n padding: 2em;\n box-shadow: 5px 5px 5px 0px rgba(0,0,0,0.75);\n border-radius: 5px;\n}\n\n.friendsLabel{\n font-size: 1.5em;\n margin-bottom: 1.5rem;\n}\n\n.friendsLabel span{\n border-bottom: solid var(--alabaster) 2px;\n}\n \n/* The container */\n.container {\n display: block;\n position: relative;\n padding-left: 35px;\n margin-bottom: 12px;\n cursor: pointer;\n font-size: 22px;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n\n/* Hide the browser's default checkbox */\n.container input {\n position: absolute;\n opacity: 0;\n cursor: pointer;\n height: 0;\n width: 0;\n}\n\n.checkmark {\n position: absolute;\n top: 0;\n left: 0;\n height: 25px;\n width: 25px;\n background-color: #eee;\n}\n \n /* On mouse-over, add a grey background color */\n.container:hover input ~ .checkmark {\n background-color: #ccc;\n}\n \n /* When the checkbox is checked, add a blue background */\n.container input:checked ~ .checkmark {\n background-color: #2196F3;\n}\n \n /* Create the checkmark/indicator (hidden when not checked) */\n.checkmark:after {\n content: \"\";\n position: absolute;\n display: none;\n }\n \n /* Show the checkmark when checked */\n.container input:checked ~ .checkmark:after {\n display: block;\n}\n \n /* Style the checkmark/indicator */\n.container .checkmark:after {\n left: 9px;\n top: 5px;\n width: 5px;\n height: 10px;\n border: solid white;\n border-width: 0 3px 3px 0;\n -webkit-transform: rotate(45deg);\n -ms-transform: rotate(45deg);\n transform: rotate(45deg);\n}",".OverUnder{\n font-size: 2em;\n flex:2;\n}\n\n.betContainer{\n border-bottom:dashed 1px var(--alabaster);\n}\n.BetTextArea{\n width: 20em;\n height: 6em;\n font-size: .5em;\n text-align: left;\n padding: .5rem;;\n border-radius: 5px;\n border: 1px solid var(--alabaster);\n background-color: var(--cadet-gray);\n color: var(--alabaster);\n}\n\n.betLabel{\n font-weight: normal;\n border-bottom: dashed 1px var(--alabaster);\n padding-bottom: 1rem;\n padding-left: 1em;\n}\n\n.lineLabel span{\n border-bottom: solid 1px var(--alabaster);\n}\n\n.line{\n display: flex;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n margin: 1em ;\n gap:1rem;\n padding: 0em 1.5em;\n border-left: solid 1px var(--alabaster);\n border-right: solid 1px var(--alabaster);\n}\n.actualLine{\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 1.5em;\n}","\n\n.prop{\n font-size: 2em;\n flex:2;\n}\n\n.betContainer{\n border-bottom:dashed 1px var(--alabaster);\n}\n.betTextarea{\n width: 20em;\n height: 6em;\n font-size: .5em;\n text-align: left;\n padding: .5rem;;\n border-radius: 5px;\n border: 1px solid var(--alabaster);\n background-color: var(--cadet-gray);\n color: var(--alabaster);\n}\n\n.PreSetBetting{\n position: absolute;\n top:50%;\n left: 50%;\n transform: translate(-50%, -50%);\n background-color: var(--cadet-gray);\n border-radius: 5px;\n padding: 1em;\n box-shadow: 5px 5px 5px 0px rgba(0,0,0,0.75);\n border:solid black 1px;\n}\n\n.settings{\n font-size: .75em;\n}\n\n.title{\n text-align: center;\n font-size:0.75em ;\n margin-bottom: 1rem;\n}\n\n.title span{\n border-bottom: solid var(--alabaster) 2px;\n}\n\n.label {\n font-size: 1em;\n}\n.x:hover {\n cursor: pointer;\n color: black;\n}\n\n.optionInput{\n height: 2rem;\n background-color: var(--alabaster);\n border-radius: 5px;\n border: 1px solid;\n padding: 0.25rem 0.5rem;\n}\n\nh4 span{\n font-size: 1em;\n margin-bottom: 0.5rem;\n border-bottom:solid var(--alabaster) 2px;\n padding-bottom: 0.05em;\n}\n",".greenButtons {\n background-color: #9DC9A4;\n border-radius: 5px;\n border: none;\n box-shadow: 4px 4px 4px 0px rgba(0,0,0,0.25);\n font-size: 1.1rem;\n font-weight: 100;\n padding:1rem 2.25rem;\n color: black;\n\n\n\n}\n\n.redSpring {\n background-color: #FF9A9A;\n}\n\n.big{\n padding:1rem 2.25rem;\n font-size: 1.1rem;\n font-weight: 100;\n}\n\n.small{\n padding: 0;\n}\n\n.DeleteButton{\n background-color: red;\n border-radius: 5px;\n border: none;\n box-shadow: 4px 4px 4px 0px rgba(0,0,0,0.25);\n padding: 1rem 2.25rem;\n}\n.DeleteButton:hover{\n background-color: darkred;\n}\n\n.DeleteButton:active{\n box-shadow: 4px 4px 4px 0px rgba(0,0,0,0.25) inset;\n}","\n\n\n\n\n\n/* BetNav.jsx */\n.betNav{\n background-color: var(--cadet-gray);\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n padding: 1em;\n border-radius: 5px;\n border: solid black 2px;\n box-shadow: 5px 5px 5px 0px rgba(0,0,0,0.75);\n \n}\n.betNav h1{\n text-align: center;\n margin-bottom: 1em;\n}\n.betNav h1 span{\n border-bottom: solid var(--alabaster) 2px;\n} \n\n.BettingLinks{\n display: flex;\n justify-content: center;\n align-items: left;\n gap: 1em;\n margin: 1em;\n flex-direction: column;\n}\n.x{\n display: flex;\n justify-content: right;\n margin-bottom: 0.5rem;\n}\n.x span:hover{\n cursor: pointer;\n color: black;\n}\n\n.bet{\n background-color: var(--cadet-gray);\n padding: 0.5rem 2em;\n margin: 1em 2em;\n border-radius: 5px;\n border: solid black 2px;\n box-shadow: 5px 5px 5px 0px rgba(0,0,0,0.75);\n \n}\n\n.bet:hover{\n background-color: rgb(135, 148, 148);\n}\n\n.bet:active{\n box-shadow: 3px 3px 3px 0px rgba(0,0,0,0.75) inset;\n}\n\n.link{\n text-decoration: none;\n color: var(--alabaster);\n}"],"names":[],"sourceRoot":""} \ No newline at end of file diff --git a/static/css/main.fdca129c.css b/static/css/main.fdca129c.css deleted file mode 100644 index 0bf9e3d..0000000 --- a/static/css/main.fdca129c.css +++ /dev/null @@ -1,2 +0,0 @@ -body{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:source-code-pro,Menlo,Monaco,Consolas,Courier New,monospace;margin:0}:root{--midnight-green:#114b5f;--cardinal:#ba3b46;--cadet-gray:#95a3a4;--dark-purple:#170a1c;--alabaster:#e2e8dd;--dark-spring-green:#007a45;--gradient-top:linear-gradient(0deg,#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd);--gradient-right:linear-gradient(90deg,#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd);--gradient-bottom:linear-gradient(180deg,#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd);--gradient-left:linear-gradient(270deg,#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd);--gradient-top-right:linear-gradient(45deg,#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd);--gradient-bottom-right:linear-gradient(135deg,#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd);--gradient-top-left:linear-gradient(225deg,#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd);--gradient-bottom-left:linear-gradient(315deg,#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd);--gradient-radial:radial-gradient(#114b5f,#ba3b46,#95a3a4,#170a1c,#e2e8dd)}body{background-color:#114b5f;background-color:var(--midnight-green);color:#e2e8dd;color:var(--alabaster);font-family:Roboto,sans-serif;font-size:1.25em;height:100vh;width:100vw}.flex{display:flex}.x1{flex:1 1}.x2{flex:2 1}.x3{flex:3 1}.pad{padding:3rem}.flex.center{align-items:center;justify-content:center}.header{background-color:#95a3a4;background-color:var(--cadet-gray);color:#e2e8dd;color:var(--alabaster);display:flex;font-size:1.25em;padding:2rem 1rem 1rem}.pages{align-items:center;gap:1em;justify-content:center}.Link{color:#e2e8dd;color:var(--alabaster);text-decoration:none}.Link:hover{color:#170a1c;color:var(--dark-purple)}.blob{align-items:center;background-color:#95a3a433;display:flex;flex-direction:column;justify-content:center;margin:6rem 10rem;padding:1em}.betButton,.blob{border-radius:5px;box-shadow:4px 4px 4px 0 #00000040}.betButton{background-color:#9dc9a4;border:none;font-size:1.1rem;font-weight:100;padding:1rem 2.25rem}.green{color:#03ff03}.red{color:red}.row{flex-direction:row}.SignIn_signIn__3t4GY{align-items:center;background-color:var(--cadet-gray);border:2px solid #000;border-radius:5px;box-shadow:10px 10px 10px 5px #000000bf;color:var(--alabaster);display:flex;flex-direction:column;justify-content:center;margin:4rem 15rem;padding:2rem;transition:opacity .5s ease-in-out}.SignIn_signInTransition__DVaCC{opacity:0}.SignIn_signIn__3t4GY input{font-size:1rem;margin:.5rem;padding:1rem .5rem;width:75%}.SignIn_signInLabel__6itNQ{border-bottom:2px solid var(--alabaster);font-size:2rem;padding-bottom:0;text-align:center}.SignIn_swapSignIn__WlTGP{border-bottom:2px solid;color:blue;font-size:.75rem;text-decoration:none}.SignIn_swapSignIn__WlTGP:hover{border-bottom:2px solid;color:#00008b}.MoneyLine_MoneyLine__GZY-g{font-size:2em}.MoneyLine_betContainer__MPUkR{border-bottom:1px dashed var(--alabaster);padding-bottom:2rem}.MoneyLine_bet__iBwWG{padding-left:2rem}.MoneyLine_bet__iBwWG textarea{background-color:var(--cadet-gray);border:1px solid var(--alabaster);border-radius:5px;color:var(--alabaster);font-size:.5em;height:6em;padding:.5rem;text-align:left;width:20em}.MoneyLine_bet__iBwWG textarea:focus{border:2px solid var(--alabaster);outline:none}.MoneyLine_contestant__VUCuJ{display:flex;flex-direction:column;margin:1rem 2rem}.MoneyLine_contestant__VUCuJ input{align-items:center;justify-content:center}.MoneyLine_contestantInput__RtHW6{background-color:var(--cadet-gray);border:1px solid;border-radius:5px;height:3rem}.MoneyLine_contestantInput__RtHW6:focus{border:2px solid var(--alabaster);outline:none}.MoneyLine_label__SXs1d{border-bottom:1px solid var(--alabaster);color:var(--alabaster);font-size:.75em;padding:.5rem}.MoneyLine_odds__5UKBZ span{color:var(--alabaster);font-size:.5em;padding-left:.5rem}.MoneyLine_odds__5UKBZ{align-items:center;display:flex;gap:.5rem;justify-content:center;padding:.5rem}.MoneyLine_odds__5UKBZ input{width:4rem}.MoneyLine_ViewLabel__dee3p{align-items:center;display:flex;gap:2em;justify-content:left;margin:1rem 2rem}.MoneyLine_betLabel__xK-Pn{border-bottom:1px dashed var(--alabaster);font-weight:400;padding-bottom:1rem;padding-left:1em}hr{border:none;border-top:1px dashed var(--alabaster);height:1px;width:75%}.Players_disable__2Lrxc{background-color:#a9a9a9}.Players_friends__S-rHI{background-color:#95a3a433;border-radius:5px;box-shadow:4px 4px 4px 0 #00000040;display:flex;flex-direction:column;font-size:.9em;gap:2rem;margin:1em 2.5em;padding:1em 3em}.Players_addFiendForm__No56b{background-color:var(--cadet-gray);border:2px solid #000;border-radius:5px;box-shadow:5px 5px 5px 0 #000000bf;font-size:1.5em;left:50%;padding:1em;position:absolute;top:50%;transform:translate(-50%,-50%)}.Players_x__50IpE{display:flex;justify-content:right;margin-bottom:.5rem}.Players_x__50IpE span{font-size:smaller;margin-left:.5rem;margin-right:.5rem}.Players_x__50IpE span:hover{color:#000;cursor:pointer}.Players_or__vxIC5{align-items:center;display:flex;justify-content:center;text-align:center}.Players_shareBet__IEGN8{background-color:var(--cadet-gray);border:2px solid #000;border-radius:5px;box-shadow:5px 5px 5px 0 #000000bf;font-size:1.5em;left:50%;padding:2em;position:absolute;top:50%;transform:translate(-50%,-50%)}.Players_friendsLabel__doMbx{font-size:1.5em;margin-bottom:1.5rem}.Players_friendsLabel__doMbx span{border-bottom:2px solid var(--alabaster)}.Players_container__wuYC4{cursor:pointer;display:block;font-size:22px;margin-bottom:12px;padding-left:35px;position:relative;-webkit-user-select:none;user-select:none}.Players_container__wuYC4 input{cursor:pointer;height:0;opacity:0;position:absolute;width:0}.Players_checkmark__OI0Ce{background-color:#eee;height:25px;left:0;position:absolute;top:0;width:25px}.Players_container__wuYC4:hover input~.Players_checkmark__OI0Ce{background-color:#ccc}.Players_container__wuYC4 input:checked~.Players_checkmark__OI0Ce{background-color:#2196f3}.Players_checkmark__OI0Ce:after{content:"";display:none;position:absolute}.Players_container__wuYC4 input:checked~.Players_checkmark__OI0Ce:after{display:block}.Players_container__wuYC4 .Players_checkmark__OI0Ce:after{border:solid #fff;border-width:0 3px 3px 0;height:10px;left:9px;top:5px;transform:rotate(45deg);width:5px}.OverUnder_OverUnder__lZCyp{flex:2 1;font-size:2em}.OverUnder_betContainer__GC\+uq{border-bottom:1px dashed var(--alabaster);display:flex;flex-direction:column;gap:1rem;padding-bottom:2rem}.OverUnder_bet__SUjBe textarea{background-color:var(--cadet-gray);border:1px solid var(--alabaster);border-radius:5px;color:var(--alabaster);font-size:.5em;height:6em;padding:.5rem;text-align:left;width:20em}.OverUnder_setting__o-g2F{align-items:center;display:flex;gap:1rem;margin:.5rem}.OverUnder_input__FR6oC{height:1.5rem;width:3rem}.OverUnder_betLabel__fUG2h{border-bottom:1px dashed var(--alabaster);font-weight:400;padding-bottom:1rem;padding-left:1em}.OverUnder_lineLabel__uLemh span{border-bottom:1px solid var(--alabaster)}.OverUnder_line__xiV\+Z{border-left:1px solid var(--alabaster);border-right:1px solid var(--alabaster);flex-direction:column;gap:1rem;margin:1em;padding:0 1.5em}.OverUnder_actualLine__NevcO,.OverUnder_line__xiV\+Z{align-items:center;display:flex;justify-content:center}.OverUnder_actualLine__NevcO{font-size:1.5em}.OverUnder_remain__s69rd{word-wrap:break-word;text-align:center}.OverUnder_remain__s69rd,.OverUnder_section__A\+HHD{align-items:center;display:flex;justify-content:center}.OverUnder_section__A\+HHD{flex-direction:column}.OverUnder_section__A\+HHD p{text-align:center}.OverUnder_pad__Qx6VE{padding:4rem}.Prop_prop__DRZFt{flex:2 1;font-size:2em}.Prop_betContainer__KSYFf{border-bottom:1px dashed var(--alabaster);display:flex;flex-direction:column;gap:1rem;padding-bottom:2rem}.Prop_bet__7E-T- textarea{background-color:var(--cadet-gray);border:1px solid var(--alabaster);border-radius:5px;color:var(--alabaster);font-size:.5em;height:6em;padding:.5rem;text-align:left;width:20em}.Prop_PreSetBetting__MzpqW{background-color:var(--cadet-gray);border:1px solid #000;border-radius:5px;box-shadow:5px 5px 5px 0 #000000bf;left:50%;padding:1em;position:absolute;top:50%;transform:translate(-50%,-50%)}.Prop_settings__9dmn0{display:flex;gap:1rem;margin:1em}.Prop_settings__9dmn0 label{font-size:.75em}.Prop_title__GEvyW{font-size:.75em;margin-bottom:1rem;text-align:center}.Prop_title__GEvyW span{border-bottom:2px solid var(--alabaster)}.Prop_label__zDU93{font-size:1em}.Prop_x__tu9O2{display:flex;justify-content:right;margin-bottom:.5rem}.Prop_x__tu9O2 span:hover{color:#000;cursor:pointer}.Prop_option__nu2JJ{align-items:center;display:flex;gap:.5rem;justify-content:center;padding:.5rem}.Prop_optionInput__MuLBG{background-color:var(--alabaster);border:1px solid;border-radius:5px;height:2rem;padding:.25rem .5rem}.Prop_options__EQ8Hr{padding-left:2em}h4 span{border-bottom:2px solid var(--alabaster);font-size:1em;margin-bottom:.5rem;padding-bottom:.05em}.Bets_betNav__NdIy7{background-color:var(--cadet-gray);border:2px solid #000;border-radius:5px;box-shadow:5px 5px 5px 0 #000000bf;left:50%;padding:1em;position:absolute;top:50%;transform:translate(-50%,-50%)}.Bets_betNav__NdIy7 h1{margin-bottom:1em;text-align:center}.Bets_betNav__NdIy7 h1 span{border-bottom:2px solid var(--alabaster)}.Bets_BettingLinks__UtSL7{align-items:left;display:flex;flex-direction:column;gap:1em;justify-content:center;margin:1em}.Bets_x__IOVNi{display:flex;justify-content:right;margin-bottom:.5rem}.Bets_x__IOVNi span:hover{color:#000;cursor:pointer}.Bets_bet__pvKP6{background-color:var(--cadet-gray);border:2px solid #000;border-radius:5px;box-shadow:5px 5px 5px 0 #000000bf;margin:1em 2em;padding:.5rem 2em}.Bets_bet__pvKP6:hover{box-shadow:inset 3px 3px 3px 0 #000000bf}.Bets_link__ibFCG{color:var(--alabaster);text-decoration:none} -/*# sourceMappingURL=main.fdca129c.css.map*/ \ No newline at end of file diff --git a/static/css/main.fdca129c.css.map b/static/css/main.fdca129c.css.map deleted file mode 100644 index d7ea7b8..0000000 --- a/static/css/main.fdca129c.css.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"static/css/main.fdca129c.css","mappings":"AAAA,KAIE,kCAAmC,CACnC,iCAAkC,CAHlC,uEACW,CAFX,QAKF,CCLA,MACE,wBAA2B,CAC3B,kBAAqB,CACrB,oBAAuB,CACvB,qBAAwB,CACxB,mBAAsB,CACtB,2BAA8B,CAU9B,4EAA4F,CAC5F,+EAA+F,CAC/F,iFAAiG,CACjG,+EAA+F,CAC/F,mFAAmG,CACnG,uFAAuG,CACvG,mFAAmG,CACnG,sFAAsG,CACtG,0EACF,CAGA,KACE,wBAAuC,CAAvC,sCAAuC,CACvC,aAAuB,CAAvB,sBAAuB,CACvB,6BAAiC,CACjC,gBAAiB,CACjB,YAAa,CACb,WAEF,CAKA,MAAM,YAAc,CAEpB,IAAI,QAAQ,CACZ,IAAI,QAAQ,CACZ,IAAI,QAAQ,CAEZ,KACE,YACF,CAEA,aAEE,kBAAmB,CADnB,sBAEF,CAEA,QAIE,wBAAmC,CAAnC,kCAAmC,CACnC,aAAwB,CAAxB,sBAAwB,CAJxB,YAAa,CAKb,gBAAiB,CAHjB,sBAIF,CACA,OAEE,kBAAmB,CACnB,OAAO,CAFP,sBAGF,CACA,MAEE,aAAuB,CAAvB,sBAAuB,CADvB,oBAGF,CACA,YACE,aAAyB,CAAzB,wBACF,CAGA,MAGE,kBAAmB,CAEnB,0BAAyC,CAJzC,YAAa,CAGb,qBAAsB,CAFtB,sBAAuB,CAMvB,iBAAkB,CAClB,WACF,CAEA,iBANE,iBAAkB,CAClB,kCAaF,CARA,WACE,wBAAyB,CAGzB,WAAY,CAEZ,gBAAiB,CACjB,eAAgB,CALhB,oBAMF,CAEA,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B,CAFnB,YAAa,CAGb,SAAU,CAFV,sBAAuB,CAGvB,aACJ,CACA,yBAEI,iCAAkC,CAElC,gBAAiB,CADjB,iBAAkB,CAFlB,WAAY,CAIZ,oBACJ,CAEA,qBACI,gBACJ,CACA,QAGI,wCAAwC,CAFxC,aAAc,CACd,mBAAqB,CAErB,oBACJ,CClFA,oBACI,kCAAmC,CAOnC,qBAAuB,CADvB,iBAAkB,CAElB,kCAA4C,CAL5C,QAAS,CAET,WAAY,CAJZ,iBAAkB,CAClB,OAAQ,CAER,8BAMJ,CACA,uBAEI,iBAAkB,CADlB,iBAEJ,CACA,4BACI,wCACJ,CAEA,0BAGI,gBAAiB,CAFjB,YAAa,CAKb,qBAAsB,CAFtB,OAAQ,CAFR,sBAAuB,CAGvB,UAEJ,CACA,eACI,YAAa,CACb,qBAAsB,CACtB,mBACJ,CACA,0BAEI,UAAY,CADZ,cAEJ,CAEA,iBACE,kCAAmC,CAInC,qBAAuB,CADvB,iBAAkB,CAElB,kCAA4C,CAH5C,cAAe,CADf,iBAMF,CACA,uBACE,wCACF,CACA,kBAEE,sBAAuB,CADvB,oBAEF","sources":["index.css","App.css","Components/SignInPage/SignIn.module.css","Components/Bets/MoneyLineBets/MoneyLine.module.css","Components/Bets/Players/Players.module.css","Components/Bets/OverUnderBets/OverUnder.module.css","Components/Bets/PropBets/Prop.module.css","Components/Bets/Bets.module.css"],"sourcesContent":["body {\n margin: 0;\n font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',\n monospace;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n\n\n","/* CSS HEX */\n:root{\n --midnight-green: #114b5fff;\n --cardinal: #ba3b46ff;\n --cadet-gray: #95a3a4ff;\n --dark-purple: #170a1cff;\n --alabaster: #e2e8ddff;\n --dark-spring-green: #007a45ff;\n \n /* CSS HSL */\n /*\n --midnight-green: hsla(195, 70%, 22%, 1);\n --cardinal: hsla(355, 52%, 48%, 1);\n --cadet-gray: hsla(184, 8%, 61%, 1);\n --dark-purple: hsla(283, 47%, 7%, 1);\n --alabaster: hsla(93, 19%, 89%, 1);\n */\n --gradient-top: linear-gradient(0deg, #114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n --gradient-right: linear-gradient(90deg, #114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n --gradient-bottom: linear-gradient(180deg, #114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n --gradient-left: linear-gradient(270deg, #114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n --gradient-top-right: linear-gradient(45deg, #114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n --gradient-bottom-right: linear-gradient(135deg, #114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n --gradient-top-left: linear-gradient(225deg, #114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n --gradient-bottom-left: linear-gradient(315deg, #114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n --gradient-radial: radial-gradient(#114b5fff, #ba3b46ff, #95a3a4ff, #170a1cff, #e2e8ddff);\n}\n\n\nbody{\n background-color: var(--midnight-green);\n color: var(--alabaster);\n font-family: 'Roboto', sans-serif;\n font-size: 1.25em;\n height: 100vh;\n width: 100vw;\n\n}\n\n\n\n\n.flex{display: flex;}\n\n.x1{flex: 1;}\n.x2{flex: 2;}\n.x3{flex: 3;}\n\n.pad{\n padding: 3rem;\n}\n\n.flex.center{\n justify-content: center;\n align-items: center;\n}\n\n.header{\n display: flex;\n padding: 1rem;\n padding-top: 2rem;\n background-color: var(--cadet-gray);\n color: var(--alabaster);\n font-size: 1.25em;\n}\n.pages{\n justify-content: center;\n align-items: center;\n gap:1em;\n}\n.Link{\n text-decoration: none;\n color: var(--alabaster);\n\n}\n.Link:hover{\n color: var(--dark-purple);\n}\n\n\n.blob{\n display: flex;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n background-color: rgba(149, 163, 164, .2);\n border-radius: 5px;\n box-shadow: 4px 4px 4px 0px rgba(0,0,0,0.25);\n margin: 6rem 10rem;\n padding: 1em;\n}\n\n.betButton{\n background-color: #9DC9A4;\n padding:1rem 2.25rem;\n border-radius: 5px;\n border: none;\n box-shadow: 4px 4px 4px 0px rgba(0,0,0,0.25);\n font-size: 1.1rem;\n font-weight: 100;\n}\n\n.green{\n color: rgb(3, 255, 3);\n}\n\n.red{\n color: red;\n}\n\n.row{\n flex-direction: row;\n}\n\n\n\n\n\n","\n\n\n.signIn{\n display: flex;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n border: solid 2px black;\n border-radius: 5px;\n margin: 4rem 15rem;\n padding:2rem ;\n background-color: var(--cadet-gray);\n color:var(--alabaster);\n box-shadow: 10px 10px 10px 5px rgba(0,0,0,0.75);\n transition: opacity .5s ease-in-out;\n }\n\n .signInTransition {\n opacity: 0;\n }\n .signIn input{\n padding: 1rem 0.5rem;\n margin: 0.5rem;\n width: 75%;\n font-size: 1rem;\n }\n\n .signInLabel{\n text-align: center;\n border-bottom: var(--alabaster) 2px solid;\n padding-bottom: 0px;\n font-size: 2rem;\n }\n\n .swapSignIn{\n text-decoration: none;\n border-bottom:solid 2px;\n color: blue;\n font-size: 0.75rem;\n }\n .swapSignIn:hover{\n border-bottom:solid 2px;\n color: darkblue;\n }","\n\n.MoneyLine{\n font-size: 2em;\n}\n.betContainer{\n padding-bottom: 2rem;\n border-bottom:dashed 1px var(--alabaster);\n}\n.bet{\n padding-left:2rem\n}\n.bet textarea{\n width: 20em;\n height: 6em;\n font-size: .5em;\n text-align: left;\n padding: .5rem;;\n border-radius: 5px;\n border: 1px solid var(--alabaster);\n background-color: var(--cadet-gray);\n color: var(--alabaster);\n}\n.bet textarea:focus{\n outline:none;\n border: solid 2px var(--alabaster);\n}\n.contestant{\n display: flex;\n flex-direction: column;\n margin: 1rem 2rem;\n}\n.contestant input{\n \n justify-content: center;\n align-items: center;\n}\n.contestantInput{\n height: 3rem;\n background-color: var(--cadet-gray);\n border-radius: 5px;\n border: 1px solid;\n}\n.contestantInput:focus{\n outline:none;\n border: solid 2px var(--alabaster);\n \n}\n.label{\n font-size: .75em;\n padding: .5rem;\n border-bottom: 1px solid var(--alabaster);\n color: var(--alabaster);\n}\n.odds span{\n font-size: .5em;\n padding-left: .5rem;\n color: var(--alabaster);\n}\n.odds {\n display: flex;\n justify-content: center;\n align-items: center;\n gap:0.5rem;\n padding: 0.5rem;\n}\n.odds input{\n width: 4rem;\n}\n\n\n\n.ViewLabel{\n display: flex;\n justify-content: left;\n align-items: center;\n gap: 2em;\n margin: 1rem 2rem;\n}\n\n\n.betLabel{\n font-weight: normal;\n border-bottom: dashed 1px var(--alabaster);\n padding-bottom: 1rem;\n padding-left: 1em;\n}\nhr {\n border: none;\n border-top: 1px dashed var(--alabaster);\n height: 1px;\n width: 75%;\n }","\n\n\n\n.disable{\n background-color: darkgray;\n \n}\n\n.friends{\n display: flex;\n flex-direction: column;\n gap: 2rem;\n background-color: rgba(149, 163, 164, .2);\n border-radius: 5px;\n box-shadow: 4px 4px 4px 0px rgba(0,0,0,0.25);\n margin: 1em 2.5em;\n padding: 1em 3em;\n font-size: .9em;\n\n\n}\n\n\n.addFiendForm{\n position:absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n border: solid black 2px;\n border-radius: 5px;\n background-color: var(--cadet-gray);\n padding:1em;\n font-size: 1.5em;\n box-shadow: 5px 5px 5px 0px rgba(0,0,0,0.75);\n}\n \n \n.x{\n display: flex;\n justify-content: right;\n margin-bottom: 0.5rem;\n}\n.x span{\n margin-left: 0.5rem;\n margin-right: 0.5rem;\n font-size: smaller;\n}\n \n.x span:hover{\n cursor: pointer;\n color: black;\n}\n\n.or{\n display: flex;\n justify-content: center;\n align-items: center;\n text-align: center;\n}\n\n\n.shareBet{\n font-size: 1.5em;\n background-color: var(--cadet-gray);\n position: absolute;\n top:50%;\n left:50%;\n transform: translate(-50%, -50%);\n border: solid black 2px;\n padding: 2em;\n box-shadow: 5px 5px 5px 0px rgba(0,0,0,0.75);\n border-radius: 5px;\n}\n\n.friendsLabel{\n font-size: 1.5em;\n margin-bottom: 1.5rem;\n}\n\n.friendsLabel span{\n border-bottom: solid var(--alabaster) 2px;\n}\n \n/* The container */\n.container {\n display: block;\n position: relative;\n padding-left: 35px;\n margin-bottom: 12px;\n cursor: pointer;\n font-size: 22px;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n\n/* Hide the browser's default checkbox */\n.container input {\n position: absolute;\n opacity: 0;\n cursor: pointer;\n height: 0;\n width: 0;\n}\n\n.checkmark {\n position: absolute;\n top: 0;\n left: 0;\n height: 25px;\n width: 25px;\n background-color: #eee;\n}\n \n /* On mouse-over, add a grey background color */\n.container:hover input ~ .checkmark {\n background-color: #ccc;\n}\n \n /* When the checkbox is checked, add a blue background */\n.container input:checked ~ .checkmark {\n background-color: #2196F3;\n}\n \n /* Create the checkmark/indicator (hidden when not checked) */\n.checkmark:after {\n content: \"\";\n position: absolute;\n display: none;\n }\n \n /* Show the checkmark when checked */\n.container input:checked ~ .checkmark:after {\n display: block;\n}\n \n /* Style the checkmark/indicator */\n.container .checkmark:after {\n left: 9px;\n top: 5px;\n width: 5px;\n height: 10px;\n border: solid white;\n border-width: 0 3px 3px 0;\n -webkit-transform: rotate(45deg);\n -ms-transform: rotate(45deg);\n transform: rotate(45deg);\n}",".OverUnder{\n font-size: 2em;\n flex:2;\n}\n\n.betContainer{\n padding-bottom: 2rem;\n border-bottom:dashed 1px var(--alabaster);\n display: flex;\n flex-direction: column;\n gap: 1rem;\n}\n.bet textarea{\n width: 20em;\n height: 6em;\n font-size: .5em;\n text-align: left;\n padding: .5rem;;\n border-radius: 5px;\n border: 1px solid var(--alabaster);\n background-color: var(--cadet-gray);\n color: var(--alabaster);\n}\n.setting{\n display: flex;\n align-items: center;\n gap:1rem;\n margin:.5rem;\n}\n\n.input{\n height: 1.5rem;\n width: 3rem;\n}\n\n.betLabel{\n font-weight: normal;\n border-bottom: dashed 1px var(--alabaster);\n padding-bottom: 1rem;\n padding-left: 1em;\n}\n\n.lineLabel span{\n border-bottom: solid 1px var(--alabaster);\n}\n.line{\n display: flex;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n margin: 1em ;\n gap:1rem;\n padding: 0em 1.5em;\n border-left: solid 1px var(--alabaster);\n border-right: solid 1px var(--alabaster);\n}\n.actualLine{\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 1.5em;\n}\n.remain{\n display: flex;\n justify-content: center;\n align-items: center;\n text-align: center;\n word-wrap: break-word\n}\n.section{\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n}\n.section p {\n text-align: center;\n}\n.pad{\n padding: 4rem;\n}\n","\n\n.prop{\n font-size: 2em;\n flex:2;\n}\n\n.betContainer{\n padding-bottom: 2rem;\n border-bottom:dashed 1px var(--alabaster);\n display: flex;\n flex-direction: column;\n gap: 1rem;\n}\n.bet textarea{\n width: 20em;\n height: 6em;\n font-size: .5em;\n text-align: left;\n padding: .5rem;;\n border-radius: 5px;\n border: 1px solid var(--alabaster);\n background-color: var(--cadet-gray);\n color: var(--alabaster);\n}\n\n.PreSetBetting{\n position: absolute;\n top:50%;\n left: 50%;\n transform: translate(-50%, -50%);\n background-color: var(--cadet-gray);\n border-radius: 5px;\n padding: 1em;\n box-shadow: 5px 5px 5px 0px rgba(0,0,0,0.75);\n border:solid black 1px;\n}\n.settings{\n display: flex;\n gap:1rem;\n margin:1em;\n}\n.settings label{\n font-size: .75em;\n}\n.title{\n text-align: center;\n font-size:0.75em ;\n margin-bottom: 1rem;\n}\n.title span{\n border-bottom: solid var(--alabaster) 2px;\n}\n.label{\n font-size: 1em;\n}\n.x{\n display: flex;\n justify-content: right;\n margin-bottom: 0.5rem;\n}\n.x span:hover{\n cursor: pointer;\n color: black;\n}\n\n.option{\n display: flex;\n justify-content: center;\n align-items: center;\n gap:0.5rem;\n padding: 0.5rem;\n}\n.optionInput{\n height: 2rem;\n background-color: var(--alabaster);\n border-radius: 5px;\n border: 1px solid;\n padding: 0.25rem 0.5rem;\n}\n\n.options{\n padding-left: 2em;\n}\nh4 span{\n font-size: 1em;\n margin-bottom: 0.5rem;\n border-bottom:solid var(--alabaster) 2px;\n padding-bottom: 0.05em;\n}\n","\n\n\n\n\n\n/* BetNav.jsx */\n.betNav{\n background-color: var(--cadet-gray);\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n padding: 1em;\n border-radius: 5px;\n border: solid black 2px;\n box-shadow: 5px 5px 5px 0px rgba(0,0,0,0.75);\n \n}\n.betNav h1{\n text-align: center;\n margin-bottom: 1em;\n}\n.betNav h1 span{\n border-bottom: solid var(--alabaster) 2px;\n} \n\n.BettingLinks{\n display: flex;\n justify-content: center;\n align-items: left;\n gap: 1em;\n margin: 1em;\n flex-direction: column;\n}\n.x{\n display: flex;\n justify-content: right;\n margin-bottom: 0.5rem;\n}\n.x span:hover{\n cursor: pointer;\n color: black;\n}\n\n.bet{\n background-color: var(--cadet-gray);\n padding: 0.5rem 2em;\n margin: 1em 2em;\n border-radius: 5px;\n border: solid black 2px;\n box-shadow: 5px 5px 5px 0px rgba(0,0,0,0.75);\n \n}\n.bet:hover{\n box-shadow: 3px 3px 3px 0px rgba(0,0,0,0.75) inset;\n}\n.link{\n text-decoration: none;\n color: var(--alabaster);\n}"],"names":[],"sourceRoot":""} \ No newline at end of file diff --git a/static/js/main.e9c9ba71.js.map b/static/js/main.e9c9ba71.js.map deleted file mode 100644 index d4b45d9..0000000 --- a/static/js/main.e9c9ba71.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"static/js/main.e9c9ba71.js","mappings":";wCAYa,IAAIA,EAAGC,EAAQ,KAASC,EAAGD,EAAQ,KAAa,SAASE,EAAEC,GAAG,IAAI,IAAIC,EAAE,yDAAyDD,EAAEE,EAAE,EAA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I,GAAG,OAORC","sources":["../node_modules/react-dom/cjs/react-dom.production.min.js","../node_modules/react-dom/client.js","../node_modules/react-dom/index.js","../node_modules/react/cjs/react-jsx-runtime.production.min.js","../node_modules/react/cjs/react.production.min.js","../node_modules/react/index.js","../node_modules/react/jsx-runtime.js","../node_modules/scheduler/cjs/scheduler.production.min.js","../node_modules/scheduler/index.js","../webpack/bootstrap","../webpack/runtime/create fake namespace object","../webpack/runtime/define property getters","../webpack/runtime/ensure chunk","../webpack/runtime/get javascript chunk filename","../webpack/runtime/get mini-css chunk filename","../webpack/runtime/global","../webpack/runtime/hasOwnProperty shorthand","../webpack/runtime/load script","../webpack/runtime/make namespace object","../webpack/runtime/publicPath","../webpack/runtime/jsonp chunk loading","../node_modules/@firebase/util/src/constants.ts","../node_modules/@firebase/util/src/crypt.ts","../node_modules/@firebase/util/src/defaults.ts","../node_modules/@firebase/util/src/global.ts","../node_modules/@firebase/util/src/deferred.ts","../node_modules/@firebase/util/src/environment.ts","../node_modules/@firebase/util/src/errors.ts","../node_modules/@firebase/util/src/obj.ts","../node_modules/@firebase/util/src/query.ts","../node_modules/@firebase/util/src/subscribe.ts","../node_modules/@firebase/util/src/utf8.ts","../node_modules/@firebase/util/src/exponential_backoff.ts","../node_modules/@firebase/util/src/compat.ts","../node_modules/@firebase/component/src/component.ts","../node_modules/@firebase/component/src/constants.ts","../node_modules/@firebase/component/src/provider.ts","../node_modules/@firebase/component/src/component_container.ts","../node_modules/@firebase/logger/src/logger.ts","../node_modules/idb/build/wrap-idb-value.js","../node_modules/idb/build/index.js","../node_modules/@firebase/app/src/platformLoggerService.ts","../node_modules/@firebase/app/src/logger.ts","../node_modules/@firebase/app/src/constants.ts","../node_modules/@firebase/app/src/internal.ts","../node_modules/@firebase/app/src/errors.ts","../node_modules/@firebase/app/src/firebaseApp.ts","../node_modules/@firebase/app/src/api.ts","../node_modules/@firebase/app/src/indexeddb.ts","../node_modules/@firebase/app/src/heartbeatService.ts","../node_modules/@firebase/app/src/registerCoreComponents.ts","../node_modules/@firebase/app/src/index.ts","../node_modules/firebase/app/index.ts","../node_modules/@firebase/installations/node_modules/idb/build/wrap-idb-value.js","../node_modules/@firebase/installations/node_modules/idb/build/index.js","../node_modules/@firebase/installations/src/util/constants.ts","../node_modules/@firebase/installations/src/util/errors.ts","../node_modules/@firebase/installations/src/functions/common.ts","../node_modules/@firebase/installations/src/util/sleep.ts","../node_modules/@firebase/installations/src/helpers/generate-fid.ts","../node_modules/@firebase/installations/src/helpers/buffer-to-base64-url-safe.ts","../node_modules/@firebase/installations/src/util/get-key.ts","../node_modules/@firebase/installations/src/helpers/fid-changed.ts","../node_modules/@firebase/installations/src/helpers/idb-manager.ts","../node_modules/@firebase/installations/src/helpers/get-installation-entry.ts","../node_modules/@firebase/installations/src/functions/create-installation-request.ts","../node_modules/@firebase/installations/src/functions/generate-auth-token-request.ts","../node_modules/@firebase/installations/src/helpers/refresh-auth-token.ts","../node_modules/@firebase/installations/src/api/get-token.ts","../node_modules/@firebase/installations/src/helpers/extract-app-config.ts","../node_modules/@firebase/installations/src/functions/config.ts","../node_modules/@firebase/installations/src/api/get-id.ts","../node_modules/@firebase/installations/src/index.ts","../node_modules/@firebase/analytics/src/constants.ts","../node_modules/@firebase/analytics/src/logger.ts","../node_modules/@firebase/analytics/src/errors.ts","../node_modules/@firebase/analytics/src/helpers.ts","../node_modules/@firebase/analytics/src/get-config.ts","../node_modules/@firebase/analytics/src/functions.ts","../node_modules/@firebase/analytics/src/initialize-analytics.ts","../node_modules/@firebase/analytics/src/factory.ts","../node_modules/@firebase/analytics/src/api.ts","../node_modules/@firebase/analytics/src/index.ts","../node_modules/tslib/tslib.es6.mjs","../node_modules/@firebase/auth/src/core/errors.ts","../node_modules/@firebase/auth/src/core/util/log.ts","../node_modules/@firebase/auth/src/core/util/assert.ts","../node_modules/@firebase/auth/src/core/util/location.ts","../node_modules/@firebase/auth/src/core/util/delay.ts","../node_modules/@firebase/auth/src/core/util/navigator.ts","../node_modules/@firebase/auth/src/core/util/emulator.ts","../node_modules/@firebase/auth/src/core/util/fetch_provider.ts","../node_modules/@firebase/auth/src/api/errors.ts","../node_modules/@firebase/auth/src/api/index.ts","../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha.ts","../node_modules/@firebase/auth/src/api/authentication/recaptcha.ts","../node_modules/@firebase/auth/src/core/util/time.ts","../node_modules/@firebase/auth/src/core/user/id_token_result.ts","../node_modules/@firebase/auth/src/core/user/invalidation.ts","../node_modules/@firebase/auth/src/core/user/proactive_refresh.ts","../node_modules/@firebase/auth/src/core/user/user_metadata.ts","../node_modules/@firebase/auth/src/core/user/reload.ts","../node_modules/@firebase/auth/src/api/account_management/account.ts","../node_modules/@firebase/auth/src/core/user/token_manager.ts","../node_modules/@firebase/auth/src/api/authentication/token.ts","../node_modules/@firebase/auth/src/core/user/user_impl.ts","../node_modules/@firebase/auth/src/core/util/instantiator.ts","../node_modules/@firebase/auth/src/core/persistence/in_memory.ts","../node_modules/@firebase/auth/src/core/persistence/persistence_user_manager.ts","../node_modules/@firebase/auth/src/core/util/browser.ts","../node_modules/@firebase/auth/src/core/util/version.ts","../node_modules/@firebase/auth/src/core/auth/middleware.ts","../node_modules/@firebase/auth/src/core/auth/password_policy_impl.ts","../node_modules/@firebase/auth/src/core/auth/auth_impl.ts","../node_modules/@firebase/auth/src/api/password_policy/get_password_policy.ts","../node_modules/@firebase/auth/src/platform_browser/load_js.ts","../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha_enterprise_verifier.ts","../node_modules/@firebase/auth/src/core/auth/emulator.ts","../node_modules/@firebase/auth/src/core/credentials/auth_credential.ts","../node_modules/@firebase/auth/src/api/account_management/email_and_password.ts","../node_modules/@firebase/auth/src/api/authentication/email_and_password.ts","../node_modules/@firebase/auth/src/core/credentials/email.ts","../node_modules/@firebase/auth/src/api/authentication/email_link.ts","../node_modules/@firebase/auth/src/api/authentication/idp.ts","../node_modules/@firebase/auth/src/core/credentials/oauth.ts","../node_modules/@firebase/auth/src/api/authentication/sms.ts","../node_modules/@firebase/auth/src/core/credentials/phone.ts","../node_modules/@firebase/auth/src/core/action_code_url.ts","../node_modules/@firebase/auth/src/core/providers/email.ts","../node_modules/@firebase/auth/src/core/providers/federated.ts","../node_modules/@firebase/auth/src/core/providers/oauth.ts","../node_modules/@firebase/auth/src/core/providers/facebook.ts","../node_modules/@firebase/auth/src/core/providers/google.ts","../node_modules/@firebase/auth/src/core/providers/github.ts","../node_modules/@firebase/auth/src/core/providers/twitter.ts","../node_modules/@firebase/auth/src/api/authentication/sign_up.ts","../node_modules/@firebase/auth/src/core/user/user_credential_impl.ts","../node_modules/@firebase/auth/src/mfa/mfa_error.ts","../node_modules/@firebase/auth/src/core/user/link_unlink.ts","../node_modules/@firebase/auth/src/core/user/reauthenticate.ts","../node_modules/@firebase/auth/src/core/strategies/credential.ts","../node_modules/@firebase/auth/src/core/strategies/email_and_password.ts","../node_modules/@firebase/auth/src/mfa/mfa_user.ts","../node_modules/@firebase/auth/src/core/persistence/index.ts","../node_modules/@firebase/auth/src/platform_browser/persistence/browser.ts","../node_modules/@firebase/auth/src/platform_browser/persistence/local_storage.ts","../node_modules/@firebase/auth/src/platform_browser/persistence/session_storage.ts","../node_modules/@firebase/auth/src/platform_browser/messagechannel/receiver.ts","../node_modules/@firebase/auth/src/platform_browser/messagechannel/promise.ts","../node_modules/@firebase/auth/src/core/util/event_id.ts","../node_modules/@firebase/auth/src/platform_browser/messagechannel/sender.ts","../node_modules/@firebase/auth/src/platform_browser/auth_window.ts","../node_modules/@firebase/auth/src/platform_browser/util/worker.ts","../node_modules/@firebase/auth/src/platform_browser/persistence/indexed_db.ts","../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha_loader.ts","../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha_verifier.ts","../node_modules/@firebase/auth/src/platform_browser/strategies/phone.ts","../node_modules/@firebase/auth/src/api/account_management/mfa.ts","../node_modules/@firebase/auth/src/api/authentication/mfa.ts","../node_modules/@firebase/auth/src/platform_browser/providers/phone.ts","../node_modules/@firebase/auth/src/core/util/resolver.ts","../node_modules/@firebase/auth/src/core/strategies/idp.ts","../node_modules/@firebase/auth/src/core/strategies/abstract_popup_redirect_operation.ts","../node_modules/@firebase/auth/src/platform_browser/strategies/popup.ts","../node_modules/@firebase/auth/src/core/strategies/redirect.ts","../node_modules/@firebase/auth/src/platform_browser/strategies/redirect.ts","../node_modules/@firebase/auth/src/core/auth/auth_event_manager.ts","../node_modules/@firebase/auth/src/core/util/validate_origin.ts","../node_modules/@firebase/auth/src/api/project_config/get_project_config.ts","../node_modules/@firebase/auth/src/platform_browser/iframe/gapi.ts","../node_modules/@firebase/auth/src/platform_browser/iframe/iframe.ts","../node_modules/@firebase/auth/src/platform_browser/util/popup.ts","../node_modules/@firebase/auth/src/core/util/handler.ts","../node_modules/@firebase/auth/src/platform_browser/popup_redirect.ts","../node_modules/@firebase/auth/src/core/auth/firebase_internal.ts","../node_modules/@firebase/auth/src/platform_browser/index.ts","../node_modules/@firebase/auth/src/core/auth/register.ts","../node_modules/@firebase/auth/src/core/auth/initialize.ts","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/base.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/disposable/disposable.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/array/array.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/event.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/browserfeature.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/string/internal.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/useragent/util.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/reflect/reflect.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/useragent/useragent.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/useragent/browser.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/useragent/engine.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/browserevent.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/eventtype.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listenable.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listenablekey.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listener.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listenermap.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/object/object.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/events.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/eventtarget.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/json/json.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/workqueue.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/run.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/freelist.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/string/string.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/xhrio.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/throwexception.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/timer/timer.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/throttle.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/eventhandler.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/webchanneldebug.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/requeststats.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/errorcode.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/eventtype.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/xmlhttpfactory.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/xmlhttp.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/channelrequest.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/environment.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/webchannelbase.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/uri/uri.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/disposable/dispose.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/wirev8.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/forwardchannelrequestpool.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/structs/structs.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/uri/utils.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/wire.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/json/nativejsonprocessor.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/functions/functions.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/netutils.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/fetchxmlhttpfactory.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/json/hybrid.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/httpstatus.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/rpc/httpcors.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/webchannelbasetransport.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/crypt/md5.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/crypt/hash.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/math/integer.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchanneltransport.js","../node_modules/@firebase/webchannel-wrapper/dist/temp/src/index.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchanneltransportfactory.js","../node_modules/@firebase/firestore/src/auth/user.ts","../node_modules/@firebase/firestore/src/core/version.ts","../node_modules/@firebase/firestore/src/util/log.ts","../node_modules/@firebase/firestore/src/platform/browser/format_json.ts","../node_modules/@firebase/firestore/src/util/assert.ts","../node_modules/@firebase/firestore/src/util/error.ts","../node_modules/@firebase/firestore/src/util/promise.ts","../node_modules/@firebase/firestore/src/api/credentials.ts","../node_modules/@firebase/firestore/src/platform/browser/random_bytes.ts","../node_modules/@firebase/firestore/src/util/misc.ts","../node_modules/@firebase/firestore/src/lite-api/timestamp.ts","../node_modules/@firebase/firestore/src/core/snapshot_version.ts","../node_modules/@firebase/firestore/src/model/path.ts","../node_modules/@firebase/firestore/src/model/document_key.ts","../node_modules/@firebase/firestore/src/model/field_index.ts","../node_modules/@firebase/firestore/src/local/persistence_transaction.ts","../node_modules/@firebase/firestore/src/local/local_store.ts","../node_modules/@firebase/firestore/src/local/persistence_promise.ts","../node_modules/@firebase/firestore/src/local/simple_db.ts","../node_modules/@firebase/firestore/src/core/listen_sequence.ts","../node_modules/@firebase/firestore/src/util/types.ts","../node_modules/@firebase/firestore/src/local/indexeddb_sentinels.ts","../node_modules/@firebase/firestore/src/local/indexeddb_schema_legacy.ts","../node_modules/@firebase/firestore/src/util/obj.ts","../node_modules/@firebase/firestore/src/util/sorted_map.ts","../node_modules/@firebase/firestore/src/util/sorted_set.ts","../node_modules/@firebase/firestore/src/model/field_mask.ts","../node_modules/@firebase/firestore/src/util/base64_decode_error.ts","../node_modules/@firebase/firestore/src/util/byte_string.ts","../node_modules/@firebase/firestore/src/platform/browser/base64.ts","../node_modules/@firebase/firestore/src/model/normalize.ts","../node_modules/@firebase/firestore/src/model/server_timestamps.ts","../node_modules/@firebase/firestore/src/core/database_info.ts","../node_modules/@firebase/firestore/src/model/values.ts","../node_modules/@firebase/firestore/src/model/object_value.ts","../node_modules/@firebase/firestore/src/model/document.ts","../node_modules/@firebase/firestore/src/core/bound.ts","../node_modules/@firebase/firestore/src/core/order_by.ts","../node_modules/@firebase/firestore/src/core/filter.ts","../node_modules/@firebase/firestore/src/core/target.ts","../node_modules/@firebase/firestore/src/core/query.ts","../node_modules/@firebase/firestore/src/util/obj_map.ts","../node_modules/@firebase/firestore/src/model/collections.ts","../node_modules/@firebase/firestore/src/remote/number_serializer.ts","../node_modules/@firebase/firestore/src/model/transform_operation.ts","../node_modules/@firebase/firestore/src/model/mutation.ts","../node_modules/@firebase/firestore/src/model/mutation_batch.ts","../node_modules/@firebase/firestore/src/model/overlay.ts","../node_modules/@firebase/firestore/src/remote/existence_filter.ts","../node_modules/@firebase/firestore/src/remote/rpc_error.ts","../node_modules/@firebase/firestore/src/util/testing_hooks_spi.ts","../node_modules/@firebase/firestore/src/platform/browser/text_serializer.ts","../node_modules/@firebase/firestore/src/remote/bloom_filter.ts","../node_modules/@firebase/firestore/src/remote/remote_event.ts","../node_modules/@firebase/firestore/src/remote/watch_change.ts","../node_modules/@firebase/firestore/src/remote/serializer.ts","../node_modules/@firebase/firestore/src/local/target_data.ts","../node_modules/@firebase/firestore/src/local/local_serializer.ts","../node_modules/@firebase/firestore/src/index/firestore_index_value_writer.ts","../node_modules/@firebase/firestore/src/local/memory_index_manager.ts","../node_modules/@firebase/firestore/src/local/indexeddb_index_manager.ts","../node_modules/@firebase/firestore/src/local/lru_garbage_collector.ts","../node_modules/@firebase/firestore/src/core/target_id_generator.ts","../node_modules/@firebase/firestore/src/local/remote_document_change_buffer.ts","../node_modules/@firebase/firestore/src/local/overlayed_document.ts","../node_modules/@firebase/firestore/src/local/local_documents_view.ts","../node_modules/@firebase/firestore/src/local/memory_bundle_cache.ts","../node_modules/@firebase/firestore/src/local/memory_document_overlay_cache.ts","../node_modules/@firebase/firestore/src/local/reference_set.ts","../node_modules/@firebase/firestore/src/local/memory_mutation_queue.ts","../node_modules/@firebase/firestore/src/local/memory_remote_document_cache.ts","../node_modules/@firebase/firestore/src/local/memory_target_cache.ts","../node_modules/@firebase/firestore/src/local/memory_persistence.ts","../node_modules/@firebase/firestore/src/local/local_view_changes.ts","../node_modules/@firebase/firestore/src/local/query_context.ts","../node_modules/@firebase/firestore/src/local/query_engine.ts","../node_modules/@firebase/firestore/src/local/local_store_impl.ts","../node_modules/@firebase/firestore/src/local/shared_client_state.ts","../node_modules/@firebase/firestore/src/remote/connectivity_monitor_noop.ts","../node_modules/@firebase/firestore/src/platform/browser/connectivity_monitor.ts","../node_modules/@firebase/firestore/src/util/debug_uid.ts","../node_modules/@firebase/firestore/src/remote/rest_connection.ts","../node_modules/@firebase/firestore/src/remote/stream_bridge.ts","../node_modules/@firebase/firestore/src/platform/browser/webchannel_connection.ts","../node_modules/@firebase/firestore/src/platform/browser/dom.ts","../node_modules/@firebase/firestore/src/platform/browser/serializer.ts","../node_modules/@firebase/firestore/src/remote/backoff.ts","../node_modules/@firebase/firestore/src/remote/persistent_stream.ts","../node_modules/@firebase/firestore/src/remote/datastore.ts","../node_modules/@firebase/firestore/src/remote/online_state_tracker.ts","../node_modules/@firebase/firestore/src/remote/remote_store.ts","../node_modules/@firebase/firestore/src/util/async_queue.ts","../node_modules/@firebase/firestore/src/model/document_set.ts","../node_modules/@firebase/firestore/src/core/view_snapshot.ts","../node_modules/@firebase/firestore/src/core/event_manager.ts","../node_modules/@firebase/firestore/src/core/view.ts","../node_modules/@firebase/firestore/src/core/sync_engine_impl.ts","../node_modules/@firebase/firestore/src/core/component_provider.ts","../node_modules/@firebase/firestore/src/platform/browser/connection.ts","../node_modules/@firebase/firestore/src/util/async_observer.ts","../node_modules/@firebase/firestore/src/core/firestore_client.ts","../node_modules/@firebase/firestore/src/api/long_polling_options.ts","../node_modules/@firebase/firestore/src/lite-api/components.ts","../node_modules/@firebase/firestore/src/util/input_validation.ts","../node_modules/@firebase/firestore/src/lite-api/settings.ts","../node_modules/@firebase/firestore/src/local/lru_garbage_collector_impl.ts","../node_modules/@firebase/firestore/src/lite-api/database.ts","../node_modules/@firebase/util/src/emulator.ts","../node_modules/@firebase/firestore/src/lite-api/reference.ts","../node_modules/@firebase/firestore/src/util/async_queue_impl.ts","../node_modules/@firebase/firestore/src/api/database.ts","../node_modules/@firebase/firestore/src/lite-api/bytes.ts","../node_modules/@firebase/firestore/src/lite-api/field_path.ts","../node_modules/@firebase/firestore/src/lite-api/field_value.ts","../node_modules/@firebase/firestore/src/lite-api/geo_point.ts","../node_modules/@firebase/firestore/src/lite-api/user_data_reader.ts","../node_modules/@firebase/firestore/src/lite-api/snapshot.ts","../node_modules/@firebase/firestore/src/lite-api/query.ts","../node_modules/@firebase/firestore/src/lite-api/user_data_writer.ts","../node_modules/@firebase/firestore/src/lite-api/reference_impl.ts","../node_modules/@firebase/firestore/src/api/snapshot.ts","../node_modules/@firebase/firestore/src/api/reference_impl.ts","../node_modules/@firebase/firestore/src/api/persistent_cache_index_manager.ts","../node_modules/@firebase/firestore/src/register.ts","../node_modules/@firebase/firestore/src/index.ts","Config/firebase-config.js","../node_modules/@firebase/auth/src/core/index.ts","../node_modules/@remix-run/router/history.ts","../node_modules/@remix-run/router/utils.ts","../node_modules/@remix-run/router/router.ts","../node_modules/react-router/lib/context.ts","../node_modules/react-router/lib/hooks.tsx","../node_modules/react-router/lib/components.tsx","webpack://friendlybetting/./src/Components/SignInPage/SignIn.module.css?a8d9","Components/SignInPage/SignIn.jsx","Components/SignInPage/CreateAccount.jsx","../node_modules/react-router-dom/dom.ts","../node_modules/react-router-dom/index.tsx","Components/Header.jsx","Components/NotFound.jsx","Components/Welcome.jsx","webpack://friendlybetting/./src/Components/Bets/MoneyLineBets/MoneyLine.module.css?5dfc","webpack://friendlybetting/./src/Components/Bets/Players/Players.module.css?ca9c","Components/Bets/Players/AddFriend.jsx","Components/Bets/Players/Players.jsx","Components/Bets/Players/ShareBet.jsx","Components/Bets/MoneyLineBets/CreateMoneyLine.jsx","Components/Bets/MoneyLineBets/MoneyLine.jsx","webpack://friendlybetting/./src/Components/Bets/OverUnderBets/OverUnder.module.css?b5a4","Components/Bets/OverUnderBets/CreateOverUnder.jsx","Components/Bets/OverUnderBets/OverUnder.jsx","webpack://friendlybetting/./src/Components/Bets/PropBets/Prop.module.css?4924","Components/Bets/PropBets/PreSetBettingOptions.jsx","Components/Bets/PropBets/CreateProp.jsx","Components/Bets/PropBets/Prop.jsx","Components/Bets/MoneyLineBets/ViewMoneyLine.jsx","Components/Bets/OverUnderBets/ViewOverUnder.jsx","Components/Bets/PropBets/ViewProp.jsx","webpack://friendlybetting/./src/Components/Bets/Bets.module.css?8472","Components/Bets/BetNav.jsx","Components/Bets/DisplayBet.jsx","Components/Bets/DisplayAllBets.jsx","Components/Friends/Friends.jsx","App.js","reportWebVitals.js","index.js"],"sourcesContent":["/**\n * @license React\n * react-dom.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n'use strict';var aa=require(\"react\"),ca=require(\"scheduler\");function p(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;c<arguments.length;c++)b+=\"&args[]=\"+encodeURIComponent(arguments[c]);return\"Minified React error #\"+a+\"; visit \"+b+\" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.\"}var da=new Set,ea={};function fa(a,b){ha(a,b);ha(a+\"Capture\",b)}\nfunction ha(a,b){ea[a]=b;for(a=0;a<b.length;a++)da.add(b[a])}\nvar ia=!(\"undefined\"===typeof window||\"undefined\"===typeof window.document||\"undefined\"===typeof window.document.createElement),ja=Object.prototype.hasOwnProperty,ka=/^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$/,la=\n{},ma={};function oa(a){if(ja.call(ma,a))return!0;if(ja.call(la,a))return!1;if(ka.test(a))return ma[a]=!0;la[a]=!0;return!1}function pa(a,b,c,d){if(null!==c&&0===c.type)return!1;switch(typeof b){case \"function\":case \"symbol\":return!0;case \"boolean\":if(d)return!1;if(null!==c)return!c.acceptsBooleans;a=a.toLowerCase().slice(0,5);return\"data-\"!==a&&\"aria-\"!==a;default:return!1}}\nfunction qa(a,b,c,d){if(null===b||\"undefined\"===typeof b||pa(a,b,c,d))return!0;if(d)return!1;if(null!==c)switch(c.type){case 3:return!b;case 4:return!1===b;case 5:return isNaN(b);case 6:return isNaN(b)||1>b}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});\"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope\".split(\" \").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}\n\"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height\".split(\" \").forEach(function(a){var b=a.replace(ra,\nsa);z[b]=new v(b,1,!1,a,null,!1,!1)});\"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type\".split(\" \").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/1999/xlink\",!1,!1)});[\"xml:base\",\"xml:lang\",\"xml:space\"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});\nz.xlinkHref=new v(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2<b.length)||\"o\"!==b[0]&&\"O\"!==b[0]||\"n\"!==b[1]&&\"N\"!==b[1])qa(b,c,e,d)&&(c=null),d||null===e?oa(b)&&(null===c?a.removeAttribute(b):a.setAttribute(b,\"\"+c)):e.mustUseProperty?a[e.propertyName]=null===c?3===e.type?!1:\"\":c:(b=e.attributeName,d=e.attributeNamespace,null===c?a.removeAttribute(b):(e=e.type,c=3===e||4===e&&!0===c?\"\":\"\"+c,d?a.setAttributeNS(d,b,c):a.setAttribute(b,c)))}\nvar ua=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,va=Symbol.for(\"react.element\"),wa=Symbol.for(\"react.portal\"),ya=Symbol.for(\"react.fragment\"),za=Symbol.for(\"react.strict_mode\"),Aa=Symbol.for(\"react.profiler\"),Ba=Symbol.for(\"react.provider\"),Ca=Symbol.for(\"react.context\"),Da=Symbol.for(\"react.forward_ref\"),Ea=Symbol.for(\"react.suspense\"),Fa=Symbol.for(\"react.suspense_list\"),Ga=Symbol.for(\"react.memo\"),Ha=Symbol.for(\"react.lazy\");Symbol.for(\"react.scope\");Symbol.for(\"react.debug_trace_mode\");\nvar Ia=Symbol.for(\"react.offscreen\");Symbol.for(\"react.legacy_hidden\");Symbol.for(\"react.cache\");Symbol.for(\"react.tracing_marker\");var Ja=Symbol.iterator;function Ka(a){if(null===a||\"object\"!==typeof a)return null;a=Ja&&a[Ja]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}var A=Object.assign,La;function Ma(a){if(void 0===La)try{throw Error();}catch(c){var b=c.stack.trim().match(/\\n( *(at )?)/);La=b&&b[1]||\"\"}return\"\\n\"+La+a}var Na=!1;\nfunction Oa(a,b){if(!a||Na)return\"\";Na=!0;var c=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(b)if(b=function(){throw Error();},Object.defineProperty(b.prototype,\"props\",{set:function(){throw Error();}}),\"object\"===typeof Reflect&&Reflect.construct){try{Reflect.construct(b,[])}catch(l){var d=l}Reflect.construct(a,[],b)}else{try{b.call()}catch(l){d=l}a.call(b.prototype)}else{try{throw Error();}catch(l){d=l}a()}}catch(l){if(l&&d&&\"string\"===typeof l.stack){for(var e=l.stack.split(\"\\n\"),\nf=d.stack.split(\"\\n\"),g=e.length-1,h=f.length-1;1<=g&&0<=h&&e[g]!==f[h];)h--;for(;1<=g&&0<=h;g--,h--)if(e[g]!==f[h]){if(1!==g||1!==h){do if(g--,h--,0>h||e[g]!==f[h]){var k=\"\\n\"+e[g].replace(\" at new \",\" at \");a.displayName&&k.includes(\"<anonymous>\")&&(k=k.replace(\"<anonymous>\",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Ma(a):\"\"}\nfunction Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma(\"Lazy\");case 13:return Ma(\"Suspense\");case 19:return Ma(\"SuspenseList\");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return\"\"}}\nfunction Qa(a){if(null==a)return null;if(\"function\"===typeof a)return a.displayName||a.name||null;if(\"string\"===typeof a)return a;switch(a){case ya:return\"Fragment\";case wa:return\"Portal\";case Aa:return\"Profiler\";case za:return\"StrictMode\";case Ea:return\"Suspense\";case Fa:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||\"Context\")+\".Consumer\";case Ba:return(a._context.displayName||\"Context\")+\".Provider\";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||\nb.name||\"\",a=\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||\"Memo\";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}\nfunction Ra(a){var b=a.type;switch(a.tag){case 24:return\"Cache\";case 9:return(b.displayName||\"Context\")+\".Consumer\";case 10:return(b._context.displayName||\"Context\")+\".Provider\";case 18:return\"DehydratedFragment\";case 11:return a=b.render,a=a.displayName||a.name||\"\",b.displayName||(\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");case 7:return\"Fragment\";case 5:return b;case 4:return\"Portal\";case 3:return\"Root\";case 6:return\"Text\";case 16:return Qa(b);case 8:return b===za?\"StrictMode\":\"Mode\";case 22:return\"Offscreen\";\ncase 12:return\"Profiler\";case 21:return\"Scope\";case 13:return\"Suspense\";case 19:return\"SuspenseList\";case 25:return\"TracingMarker\";case 1:case 0:case 17:case 2:case 14:case 15:if(\"function\"===typeof b)return b.displayName||b.name||null;if(\"string\"===typeof b)return b}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"string\":case \"undefined\":return a;case \"object\":return a;default:return\"\"}}\nfunction Ta(a){var b=a.type;return(a=a.nodeName)&&\"input\"===a.toLowerCase()&&(\"checkbox\"===b||\"radio\"===b)}\nfunction Ua(a){var b=Ta(a)?\"checked\":\"value\",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=\"\"+a[b];if(!a.hasOwnProperty(b)&&\"undefined\"!==typeof c&&\"function\"===typeof c.get&&\"function\"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=\"\"+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=\"\"+a},stopTracking:function(){a._valueTracker=\nnull;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d=\"\";a&&(d=Ta(a)?a.checked?\"true\":\"false\":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||(\"undefined\"!==typeof document?document:void 0);if(\"undefined\"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}\nfunction Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?\"\":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:\"checkbox\"===b.type||\"radio\"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,\"checked\",b,!1)}\nfunction bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if(\"number\"===d){if(0===c&&\"\"===a.value||a.value!=c)a.value=\"\"+c}else a.value!==\"\"+c&&(a.value=\"\"+c);else if(\"submit\"===d||\"reset\"===d){a.removeAttribute(\"value\");return}b.hasOwnProperty(\"value\")?cb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction db(a,b,c){if(b.hasOwnProperty(\"value\")||b.hasOwnProperty(\"defaultValue\")){var d=b.type;if(!(\"submit\"!==d&&\"reset\"!==d||void 0!==b.value&&null!==b.value))return;b=\"\"+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;\"\"!==c&&(a.name=\"\");a.defaultChecked=!!a._wrapperState.initialChecked;\"\"!==c&&(a.name=c)}\nfunction cb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}var eb=Array.isArray;\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e<c.length;e++)b[\"$\"+c[e]]=!0;for(c=0;c<a.length;c++)e=b.hasOwnProperty(\"$\"+a[c].value),a[c].selected!==e&&(a[c].selected=e),e&&d&&(a[c].defaultSelected=!0)}else{c=\"\"+Sa(c);b=null;for(e=0;e<a.length;e++){if(a[e].value===c){a[e].selected=!0;d&&(a[e].defaultSelected=!0);return}null!==b||a[e].disabled||(b=a[e])}null!==b&&(b.selected=!0)}}\nfunction gb(a,b){if(null!=b.dangerouslySetInnerHTML)throw Error(p(91));return A({},b,{value:void 0,defaultValue:void 0,children:\"\"+a._wrapperState.initialValue})}function hb(a,b){var c=b.value;if(null==c){c=b.children;b=b.defaultValue;if(null!=c){if(null!=b)throw Error(p(92));if(eb(c)){if(1<c.length)throw Error(p(93));c=c[0]}b=c}null==b&&(b=\"\");c=b}a._wrapperState={initialValue:Sa(c)}}\nfunction ib(a,b){var c=Sa(b.value),d=Sa(b.defaultValue);null!=c&&(c=\"\"+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=\"\"+d)}function jb(a){var b=a.textContent;b===a._wrapperState.initialValue&&\"\"!==b&&null!==b&&(a.value=b)}function kb(a){switch(a){case \"svg\":return\"http://www.w3.org/2000/svg\";case \"math\":return\"http://www.w3.org/1998/Math/MathML\";default:return\"http://www.w3.org/1999/xhtml\"}}\nfunction lb(a,b){return null==a||\"http://www.w3.org/1999/xhtml\"===a?kb(b):\"http://www.w3.org/2000/svg\"===a&&\"foreignObject\"===b?\"http://www.w3.org/1999/xhtml\":a}\nvar mb,nb=function(a){return\"undefined\"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,c,d,e)})}:a}(function(a,b){if(\"http://www.w3.org/2000/svg\"!==a.namespaceURI||\"innerHTML\"in a)a.innerHTML=b;else{mb=mb||document.createElement(\"div\");mb.innerHTML=\"<svg>\"+b.valueOf().toString()+\"</svg>\";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,\nzoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(\"\"+b).trim():b+\"px\"}\nfunction sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=rb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});\nfunction ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if(\"object\"!==typeof b.dangerouslySetInnerHTML||!(\"__html\"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(p(62));}}\nfunction vb(a,b){if(-1===a.indexOf(\"-\"))return\"string\"===typeof b.is;switch(a){case \"annotation-xml\":case \"color-profile\":case \"font-face\":case \"font-face-src\":case \"font-face-uri\":case \"font-face-format\":case \"font-face-name\":case \"missing-glyph\":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;\nfunction Bb(a){if(a=Cb(a)){if(\"function\"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a<b.length;a++)Bb(b[a])}}function Gb(a,b){return a(b)}function Hb(){}var Ib=!1;function Jb(a,b,c){if(Ib)return a(b,c);Ib=!0;try{return Gb(a,b,c)}finally{if(Ib=!1,null!==zb||null!==Ab)Hb(),Fb()}}\nfunction Kb(a,b){var c=a.stateNode;if(null===c)return null;var d=Db(c);if(null===d)return null;c=d[b];a:switch(b){case \"onClick\":case \"onClickCapture\":case \"onDoubleClick\":case \"onDoubleClickCapture\":case \"onMouseDown\":case \"onMouseDownCapture\":case \"onMouseMove\":case \"onMouseMoveCapture\":case \"onMouseUp\":case \"onMouseUpCapture\":case \"onMouseEnter\":(d=!d.disabled)||(a=a.type,d=!(\"button\"===a||\"input\"===a||\"select\"===a||\"textarea\"===a));a=!d;break a;default:a=!1}if(a)return null;if(c&&\"function\"!==\ntypeof c)throw Error(p(231,b,typeof c));return c}var Lb=!1;if(ia)try{var Mb={};Object.defineProperty(Mb,\"passive\",{get:function(){Lb=!0}});window.addEventListener(\"test\",Mb,Mb);window.removeEventListener(\"test\",Mb,Mb)}catch(a){Lb=!1}function Nb(a,b,c,d,e,f,g,h,k){var l=Array.prototype.slice.call(arguments,3);try{b.apply(c,l)}catch(m){this.onError(m)}}var Ob=!1,Pb=null,Qb=!1,Rb=null,Sb={onError:function(a){Ob=!0;Pb=a}};function Tb(a,b,c,d,e,f,g,h,k){Ob=!1;Pb=null;Nb.apply(Sb,arguments)}\nfunction Ub(a,b,c,d,e,f,g,h,k){Tb.apply(this,arguments);if(Ob){if(Ob){var l=Pb;Ob=!1;Pb=null}else throw Error(p(198));Qb||(Qb=!0,Rb=l)}}function Vb(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else{a=b;do b=a,0!==(b.flags&4098)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function Wb(a){if(13===a.tag){var b=a.memoizedState;null===b&&(a=a.alternate,null!==a&&(b=a.memoizedState));if(null!==b)return b.dehydrated}return null}function Xb(a){if(Vb(a)!==a)throw Error(p(188));}\nfunction Yb(a){var b=a.alternate;if(!b){b=Vb(a);if(null===b)throw Error(p(188));return b!==a?null:a}for(var c=a,d=b;;){var e=c.return;if(null===e)break;var f=e.alternate;if(null===f){d=e.return;if(null!==d){c=d;continue}break}if(e.child===f.child){for(f=e.child;f;){if(f===c)return Xb(e),a;if(f===d)return Xb(e),b;f=f.sibling}throw Error(p(188));}if(c.return!==d.return)c=e,d=f;else{for(var g=!1,h=e.child;h;){if(h===c){g=!0;c=e;d=f;break}if(h===d){g=!0;d=e;c=f;break}h=h.sibling}if(!g){for(h=f.child;h;){if(h===\nc){g=!0;c=f;d=e;break}if(h===d){g=!0;d=f;c=e;break}h=h.sibling}if(!g)throw Error(p(189));}}if(c.alternate!==d)throw Error(p(190));}if(3!==c.tag)throw Error(p(188));return c.stateNode.current===c?a:b}function Zb(a){a=Yb(a);return null!==a?$b(a):null}function $b(a){if(5===a.tag||6===a.tag)return a;for(a=a.child;null!==a;){var b=$b(a);if(null!==b)return b;a=a.sibling}return null}\nvar ac=ca.unstable_scheduleCallback,bc=ca.unstable_cancelCallback,cc=ca.unstable_shouldYield,dc=ca.unstable_requestPaint,B=ca.unstable_now,ec=ca.unstable_getCurrentPriorityLevel,fc=ca.unstable_ImmediatePriority,gc=ca.unstable_UserBlockingPriority,hc=ca.unstable_NormalPriority,ic=ca.unstable_LowPriority,jc=ca.unstable_IdlePriority,kc=null,lc=null;function mc(a){if(lc&&\"function\"===typeof lc.onCommitFiberRoot)try{lc.onCommitFiberRoot(kc,a,void 0,128===(a.current.flags&128))}catch(b){}}\nvar oc=Math.clz32?Math.clz32:nc,pc=Math.log,qc=Math.LN2;function nc(a){a>>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;\nfunction tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;\ndefault:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0<b;)c=31-oc(b),e=1<<c,d|=a[c],b&=~e;return d}\nfunction vc(a,b){switch(a){case 1:case 2:case 4:return b+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return b+5E3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}\nfunction wc(a,b){for(var c=a.suspendedLanes,d=a.pingedLanes,e=a.expirationTimes,f=a.pendingLanes;0<f;){var g=31-oc(f),h=1<<g,k=e[g];if(-1===k){if(0===(h&c)||0!==(h&d))e[g]=vc(h,b)}else k<=b&&(a.expiredLanes|=h);f&=~h}}function xc(a){a=a.pendingLanes&-1073741825;return 0!==a?a:a&1073741824?1073741824:0}function yc(){var a=rc;rc<<=1;0===(rc&4194240)&&(rc=64);return a}function zc(a){for(var b=[],c=0;31>c;c++)b.push(a);return b}\nfunction Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0<c;){var e=31-oc(c),f=1<<e;b[e]=0;d[e]=-1;a[e]=-1;c&=~f}}\nfunction Cc(a,b){var c=a.entangledLanes|=b;for(a=a.entanglements;c;){var d=31-oc(c),e=1<<d;e&b|a[d]&b&&(a[d]|=b);c&=~e}}var C=0;function Dc(a){a&=-a;return 1<a?4<a?0!==(a&268435455)?16:536870912:4:1}var Ec,Fc,Gc,Hc,Ic,Jc=!1,Kc=[],Lc=null,Mc=null,Nc=null,Oc=new Map,Pc=new Map,Qc=[],Rc=\"mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit\".split(\" \");\nfunction Sc(a,b){switch(a){case \"focusin\":case \"focusout\":Lc=null;break;case \"dragenter\":case \"dragleave\":Mc=null;break;case \"mouseover\":case \"mouseout\":Nc=null;break;case \"pointerover\":case \"pointerout\":Oc.delete(b.pointerId);break;case \"gotpointercapture\":case \"lostpointercapture\":Pc.delete(b.pointerId)}}\nfunction Tc(a,b,c,d,e,f){if(null===a||a.nativeEvent!==f)return a={blockedOn:b,domEventName:c,eventSystemFlags:d,nativeEvent:f,targetContainers:[e]},null!==b&&(b=Cb(b),null!==b&&Fc(b)),a;a.eventSystemFlags|=d;b=a.targetContainers;null!==e&&-1===b.indexOf(e)&&b.push(e);return a}\nfunction Uc(a,b,c,d,e){switch(b){case \"focusin\":return Lc=Tc(Lc,a,b,c,d,e),!0;case \"dragenter\":return Mc=Tc(Mc,a,b,c,d,e),!0;case \"mouseover\":return Nc=Tc(Nc,a,b,c,d,e),!0;case \"pointerover\":var f=e.pointerId;Oc.set(f,Tc(Oc.get(f)||null,a,b,c,d,e));return!0;case \"gotpointercapture\":return f=e.pointerId,Pc.set(f,Tc(Pc.get(f)||null,a,b,c,d,e)),!0}return!1}\nfunction Vc(a){var b=Wc(a.target);if(null!==b){var c=Vb(b);if(null!==c)if(b=c.tag,13===b){if(b=Wb(c),null!==b){a.blockedOn=b;Ic(a.priority,function(){Gc(c)});return}}else if(3===b&&c.stateNode.current.memoizedState.isDehydrated){a.blockedOn=3===c.tag?c.stateNode.containerInfo:null;return}}a.blockedOn=null}\nfunction Xc(a){if(null!==a.blockedOn)return!1;for(var b=a.targetContainers;0<b.length;){var c=Yc(a.domEventName,a.eventSystemFlags,b[0],a.nativeEvent);if(null===c){c=a.nativeEvent;var d=new c.constructor(c.type,c);wb=d;c.target.dispatchEvent(d);wb=null}else return b=Cb(c),null!==b&&Fc(b),a.blockedOn=c,!1;b.shift()}return!0}function Zc(a,b,c){Xc(a)&&c.delete(b)}function $c(){Jc=!1;null!==Lc&&Xc(Lc)&&(Lc=null);null!==Mc&&Xc(Mc)&&(Mc=null);null!==Nc&&Xc(Nc)&&(Nc=null);Oc.forEach(Zc);Pc.forEach(Zc)}\nfunction ad(a,b){a.blockedOn===b&&(a.blockedOn=null,Jc||(Jc=!0,ca.unstable_scheduleCallback(ca.unstable_NormalPriority,$c)))}\nfunction bd(a){function b(b){return ad(b,a)}if(0<Kc.length){ad(Kc[0],a);for(var c=1;c<Kc.length;c++){var d=Kc[c];d.blockedOn===a&&(d.blockedOn=null)}}null!==Lc&&ad(Lc,a);null!==Mc&&ad(Mc,a);null!==Nc&&ad(Nc,a);Oc.forEach(b);Pc.forEach(b);for(c=0;c<Qc.length;c++)d=Qc[c],d.blockedOn===a&&(d.blockedOn=null);for(;0<Qc.length&&(c=Qc[0],null===c.blockedOn);)Vc(c),null===c.blockedOn&&Qc.shift()}var cd=ua.ReactCurrentBatchConfig,dd=!0;\nfunction ed(a,b,c,d){var e=C,f=cd.transition;cd.transition=null;try{C=1,fd(a,b,c,d)}finally{C=e,cd.transition=f}}function gd(a,b,c,d){var e=C,f=cd.transition;cd.transition=null;try{C=4,fd(a,b,c,d)}finally{C=e,cd.transition=f}}\nfunction fd(a,b,c,d){if(dd){var e=Yc(a,b,c,d);if(null===e)hd(a,b,d,id,c),Sc(a,d);else if(Uc(e,a,b,c,d))d.stopPropagation();else if(Sc(a,d),b&4&&-1<Rc.indexOf(a)){for(;null!==e;){var f=Cb(e);null!==f&&Ec(f);f=Yc(a,b,c,d);null===f&&hd(a,b,d,id,c);if(f===e)break;e=f}null!==e&&d.stopPropagation()}else hd(a,b,d,null,c)}}var id=null;\nfunction Yc(a,b,c,d){id=null;a=xb(d);a=Wc(a);if(null!==a)if(b=Vb(a),null===b)a=null;else if(c=b.tag,13===c){a=Wb(b);if(null!==a)return a;a=null}else if(3===c){if(b.stateNode.current.memoizedState.isDehydrated)return 3===b.tag?b.stateNode.containerInfo:null;a=null}else b!==a&&(a=null);id=a;return null}\nfunction jd(a){switch(a){case \"cancel\":case \"click\":case \"close\":case \"contextmenu\":case \"copy\":case \"cut\":case \"auxclick\":case \"dblclick\":case \"dragend\":case \"dragstart\":case \"drop\":case \"focusin\":case \"focusout\":case \"input\":case \"invalid\":case \"keydown\":case \"keypress\":case \"keyup\":case \"mousedown\":case \"mouseup\":case \"paste\":case \"pause\":case \"play\":case \"pointercancel\":case \"pointerdown\":case \"pointerup\":case \"ratechange\":case \"reset\":case \"resize\":case \"seeked\":case \"submit\":case \"touchcancel\":case \"touchend\":case \"touchstart\":case \"volumechange\":case \"change\":case \"selectionchange\":case \"textInput\":case \"compositionstart\":case \"compositionend\":case \"compositionupdate\":case \"beforeblur\":case \"afterblur\":case \"beforeinput\":case \"blur\":case \"fullscreenchange\":case \"focus\":case \"hashchange\":case \"popstate\":case \"select\":case \"selectstart\":return 1;case \"drag\":case \"dragenter\":case \"dragexit\":case \"dragleave\":case \"dragover\":case \"mousemove\":case \"mouseout\":case \"mouseover\":case \"pointermove\":case \"pointerout\":case \"pointerover\":case \"scroll\":case \"toggle\":case \"touchmove\":case \"wheel\":case \"mouseenter\":case \"mouseleave\":case \"pointerenter\":case \"pointerleave\":return 4;\ncase \"message\":switch(ec()){case fc:return 1;case gc:return 4;case hc:case ic:return 16;case jc:return 536870912;default:return 16}default:return 16}}var kd=null,ld=null,md=null;function nd(){if(md)return md;var a,b=ld,c=b.length,d,e=\"value\"in kd?kd.value:kd.textContent,f=e.length;for(a=0;a<c&&b[a]===e[a];a++);var g=c-a;for(d=1;d<=g&&b[c-d]===e[f-d];d++);return md=e.slice(a,1<d?1-d:void 0)}\nfunction od(a){var b=a.keyCode;\"charCode\"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;10===a&&(a=13);return 32<=a||13===a?a:0}function pd(){return!0}function qd(){return!1}\nfunction rd(a){function b(b,d,e,f,g){this._reactName=b;this._targetInst=e;this.type=d;this.nativeEvent=f;this.target=g;this.currentTarget=null;for(var c in a)a.hasOwnProperty(c)&&(b=a[c],this[c]=b?b(f):f[c]);this.isDefaultPrevented=(null!=f.defaultPrevented?f.defaultPrevented:!1===f.returnValue)?pd:qd;this.isPropagationStopped=qd;return this}A(b.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():\"unknown\"!==typeof a.returnValue&&\n(a.returnValue=!1),this.isDefaultPrevented=pd)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():\"unknown\"!==typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=pd)},persist:function(){},isPersistent:pd});return b}\nvar sd={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},td=rd(sd),ud=A({},sd,{view:0,detail:0}),vd=rd(ud),wd,xd,yd,Ad=A({},ud,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:zd,button:0,buttons:0,relatedTarget:function(a){return void 0===a.relatedTarget?a.fromElement===a.srcElement?a.toElement:a.fromElement:a.relatedTarget},movementX:function(a){if(\"movementX\"in\na)return a.movementX;a!==yd&&(yd&&\"mousemove\"===a.type?(wd=a.screenX-yd.screenX,xd=a.screenY-yd.screenY):xd=wd=0,yd=a);return wd},movementY:function(a){return\"movementY\"in a?a.movementY:xd}}),Bd=rd(Ad),Cd=A({},Ad,{dataTransfer:0}),Dd=rd(Cd),Ed=A({},ud,{relatedTarget:0}),Fd=rd(Ed),Gd=A({},sd,{animationName:0,elapsedTime:0,pseudoElement:0}),Hd=rd(Gd),Id=A({},sd,{clipboardData:function(a){return\"clipboardData\"in a?a.clipboardData:window.clipboardData}}),Jd=rd(Id),Kd=A({},sd,{data:0}),Ld=rd(Kd),Md={Esc:\"Escape\",\nSpacebar:\" \",Left:\"ArrowLeft\",Up:\"ArrowUp\",Right:\"ArrowRight\",Down:\"ArrowDown\",Del:\"Delete\",Win:\"OS\",Menu:\"ContextMenu\",Apps:\"ContextMenu\",Scroll:\"ScrollLock\",MozPrintableKey:\"Unidentified\"},Nd={8:\"Backspace\",9:\"Tab\",12:\"Clear\",13:\"Enter\",16:\"Shift\",17:\"Control\",18:\"Alt\",19:\"Pause\",20:\"CapsLock\",27:\"Escape\",32:\" \",33:\"PageUp\",34:\"PageDown\",35:\"End\",36:\"Home\",37:\"ArrowLeft\",38:\"ArrowUp\",39:\"ArrowRight\",40:\"ArrowDown\",45:\"Insert\",46:\"Delete\",112:\"F1\",113:\"F2\",114:\"F3\",115:\"F4\",116:\"F5\",117:\"F6\",118:\"F7\",\n119:\"F8\",120:\"F9\",121:\"F10\",122:\"F11\",123:\"F12\",144:\"NumLock\",145:\"ScrollLock\",224:\"Meta\"},Od={Alt:\"altKey\",Control:\"ctrlKey\",Meta:\"metaKey\",Shift:\"shiftKey\"};function Pd(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):(a=Od[a])?!!b[a]:!1}function zd(){return Pd}\nvar Qd=A({},ud,{key:function(a){if(a.key){var b=Md[a.key]||a.key;if(\"Unidentified\"!==b)return b}return\"keypress\"===a.type?(a=od(a),13===a?\"Enter\":String.fromCharCode(a)):\"keydown\"===a.type||\"keyup\"===a.type?Nd[a.keyCode]||\"Unidentified\":\"\"},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:zd,charCode:function(a){return\"keypress\"===a.type?od(a):0},keyCode:function(a){return\"keydown\"===a.type||\"keyup\"===a.type?a.keyCode:0},which:function(a){return\"keypress\"===\na.type?od(a):\"keydown\"===a.type||\"keyup\"===a.type?a.keyCode:0}}),Rd=rd(Qd),Sd=A({},Ad,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Td=rd(Sd),Ud=A({},ud,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:zd}),Vd=rd(Ud),Wd=A({},sd,{propertyName:0,elapsedTime:0,pseudoElement:0}),Xd=rd(Wd),Yd=A({},Ad,{deltaX:function(a){return\"deltaX\"in a?a.deltaX:\"wheelDeltaX\"in a?-a.wheelDeltaX:0},\ndeltaY:function(a){return\"deltaY\"in a?a.deltaY:\"wheelDeltaY\"in a?-a.wheelDeltaY:\"wheelDelta\"in a?-a.wheelDelta:0},deltaZ:0,deltaMode:0}),Zd=rd(Yd),$d=[9,13,27,32],ae=ia&&\"CompositionEvent\"in window,be=null;ia&&\"documentMode\"in document&&(be=document.documentMode);var ce=ia&&\"TextEvent\"in window&&!be,de=ia&&(!ae||be&&8<be&&11>=be),ee=String.fromCharCode(32),fe=!1;\nfunction ge(a,b){switch(a){case \"keyup\":return-1!==$d.indexOf(b.keyCode);case \"keydown\":return 229!==b.keyCode;case \"keypress\":case \"mousedown\":case \"focusout\":return!0;default:return!1}}function he(a){a=a.detail;return\"object\"===typeof a&&\"data\"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case \"compositionend\":return he(b);case \"keypress\":if(32!==b.which)return null;fe=!0;return ee;case \"textInput\":return a=b.data,a===ee&&fe?null:a;default:return null}}\nfunction ke(a,b){if(ie)return\"compositionend\"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case \"paste\":return null;case \"keypress\":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1<b.char.length)return b.char;if(b.which)return String.fromCharCode(b.which)}return null;case \"compositionend\":return de&&\"ko\"!==b.locale?null:b.data;default:return null}}\nvar le={color:!0,date:!0,datetime:!0,\"datetime-local\":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function me(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return\"input\"===b?!!le[a.type]:\"textarea\"===b?!0:!1}function ne(a,b,c,d){Eb(d);b=oe(b,\"onChange\");0<b.length&&(c=new td(\"onChange\",\"change\",null,c,d),a.push({event:c,listeners:b}))}var pe=null,qe=null;function re(a){se(a,0)}function te(a){var b=ue(a);if(Wa(b))return a}\nfunction ve(a,b){if(\"change\"===a)return b}var we=!1;if(ia){var xe;if(ia){var ye=\"oninput\"in document;if(!ye){var ze=document.createElement(\"div\");ze.setAttribute(\"oninput\",\"return;\");ye=\"function\"===typeof ze.oninput}xe=ye}else xe=!1;we=xe&&(!document.documentMode||9<document.documentMode)}function Ae(){pe&&(pe.detachEvent(\"onpropertychange\",Be),qe=pe=null)}function Be(a){if(\"value\"===a.propertyName&&te(qe)){var b=[];ne(b,qe,a,xb(a));Jb(re,b)}}\nfunction Ce(a,b,c){\"focusin\"===a?(Ae(),pe=b,qe=c,pe.attachEvent(\"onpropertychange\",Be)):\"focusout\"===a&&Ae()}function De(a){if(\"selectionchange\"===a||\"keyup\"===a||\"keydown\"===a)return te(qe)}function Ee(a,b){if(\"click\"===a)return te(b)}function Fe(a,b){if(\"input\"===a||\"change\"===a)return te(b)}function Ge(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var He=\"function\"===typeof Object.is?Object.is:Ge;\nfunction Ie(a,b){if(He(a,b))return!0;if(\"object\"!==typeof a||null===a||\"object\"!==typeof b||null===b)return!1;var c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return!1;for(d=0;d<c.length;d++){var e=c[d];if(!ja.call(b,e)||!He(a[e],b[e]))return!1}return!0}function Je(a){for(;a&&a.firstChild;)a=a.firstChild;return a}\nfunction Ke(a,b){var c=Je(a);a=0;for(var d;c;){if(3===c.nodeType){d=a+c.textContent.length;if(a<=b&&d>=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c=\"string\"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&(\"input\"===b&&(\"text\"===a.type||\"search\"===a.type||\"tel\"===a.type||\"url\"===a.type||\"password\"===a.type)||\"textarea\"===b||\"true\"===a.contentEditable)}\nfunction Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),\"selectionStart\"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,\nd);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});\"function\"===typeof c.focus&&c.focus();for(c=0;c<b.length;c++)a=b[c],a.element.scrollLeft=a.left,a.element.scrollTop=a.top}}\nvar Pe=ia&&\"documentMode\"in document&&11>=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;\nfunction Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,\"selectionStart\"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0<d.length&&(b=new td(\"onSelect\",\"select\",null,b,c),a.push({event:b,listeners:d}),b.target=Qe)))}\nfunction Ve(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c[\"Webkit\"+a]=\"webkit\"+b;c[\"Moz\"+a]=\"moz\"+b;return c}var We={animationend:Ve(\"Animation\",\"AnimationEnd\"),animationiteration:Ve(\"Animation\",\"AnimationIteration\"),animationstart:Ve(\"Animation\",\"AnimationStart\"),transitionend:Ve(\"Transition\",\"TransitionEnd\")},Xe={},Ye={};\nia&&(Ye=document.createElement(\"div\").style,\"AnimationEvent\"in window||(delete We.animationend.animation,delete We.animationiteration.animation,delete We.animationstart.animation),\"TransitionEvent\"in window||delete We.transitionend.transition);function Ze(a){if(Xe[a])return Xe[a];if(!We[a])return a;var b=We[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in Ye)return Xe[a]=b[c];return a}var $e=Ze(\"animationend\"),af=Ze(\"animationiteration\"),bf=Ze(\"animationstart\"),cf=Ze(\"transitionend\"),df=new Map,ef=\"abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel\".split(\" \");\nfunction ff(a,b){df.set(a,b);fa(b,[a])}for(var gf=0;gf<ef.length;gf++){var hf=ef[gf],jf=hf.toLowerCase(),kf=hf[0].toUpperCase()+hf.slice(1);ff(jf,\"on\"+kf)}ff($e,\"onAnimationEnd\");ff(af,\"onAnimationIteration\");ff(bf,\"onAnimationStart\");ff(\"dblclick\",\"onDoubleClick\");ff(\"focusin\",\"onFocus\");ff(\"focusout\",\"onBlur\");ff(cf,\"onTransitionEnd\");ha(\"onMouseEnter\",[\"mouseout\",\"mouseover\"]);ha(\"onMouseLeave\",[\"mouseout\",\"mouseover\"]);ha(\"onPointerEnter\",[\"pointerout\",\"pointerover\"]);\nha(\"onPointerLeave\",[\"pointerout\",\"pointerover\"]);fa(\"onChange\",\"change click focusin focusout input keydown keyup selectionchange\".split(\" \"));fa(\"onSelect\",\"focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange\".split(\" \"));fa(\"onBeforeInput\",[\"compositionend\",\"keypress\",\"textInput\",\"paste\"]);fa(\"onCompositionEnd\",\"compositionend focusout keydown keypress keyup mousedown\".split(\" \"));fa(\"onCompositionStart\",\"compositionstart focusout keydown keypress keyup mousedown\".split(\" \"));\nfa(\"onCompositionUpdate\",\"compositionupdate focusout keydown keypress keyup mousedown\".split(\" \"));var lf=\"abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting\".split(\" \"),mf=new Set(\"cancel close invalid load scroll toggle\".split(\" \").concat(lf));\nfunction nf(a,b,c){var d=a.type||\"unknown-event\";a.currentTarget=c;Ub(d,b,void 0,a);a.currentTarget=null}\nfunction se(a,b){b=0!==(b&4);for(var c=0;c<a.length;c++){var d=a[c],e=d.event;d=d.listeners;a:{var f=void 0;if(b)for(var g=d.length-1;0<=g;g--){var h=d[g],k=h.instance,l=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;nf(e,h,l);f=k}else for(g=0;g<d.length;g++){h=d[g];k=h.instance;l=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;nf(e,h,l);f=k}}}if(Qb)throw a=Rb,Qb=!1,Rb=null,a;}\nfunction D(a,b){var c=b[of];void 0===c&&(c=b[of]=new Set);var d=a+\"__bubble\";c.has(d)||(pf(b,a,2,!1),c.add(d))}function qf(a,b,c){var d=0;b&&(d|=4);pf(c,a,d,b)}var rf=\"_reactListening\"+Math.random().toString(36).slice(2);function sf(a){if(!a[rf]){a[rf]=!0;da.forEach(function(b){\"selectionchange\"!==b&&(mf.has(b)||qf(b,!1,a),qf(b,!0,a))});var b=9===a.nodeType?a:a.ownerDocument;null===b||b[rf]||(b[rf]=!0,qf(\"selectionchange\",!1,b))}}\nfunction pf(a,b,c,d){switch(jd(b)){case 1:var e=ed;break;case 4:e=gd;break;default:e=fd}c=e.bind(null,b,c,a);e=void 0;!Lb||\"touchstart\"!==b&&\"touchmove\"!==b&&\"wheel\"!==b||(e=!0);d?void 0!==e?a.addEventListener(b,c,{capture:!0,passive:e}):a.addEventListener(b,c,!0):void 0!==e?a.addEventListener(b,c,{passive:e}):a.addEventListener(b,c,!1)}\nfunction hd(a,b,c,d,e){var f=d;if(0===(b&1)&&0===(b&2)&&null!==d)a:for(;;){if(null===d)return;var g=d.tag;if(3===g||4===g){var h=d.stateNode.containerInfo;if(h===e||8===h.nodeType&&h.parentNode===e)break;if(4===g)for(g=d.return;null!==g;){var k=g.tag;if(3===k||4===k)if(k=g.stateNode.containerInfo,k===e||8===k.nodeType&&k.parentNode===e)return;g=g.return}for(;null!==h;){g=Wc(h);if(null===g)return;k=g.tag;if(5===k||6===k){d=f=g;continue a}h=h.parentNode}}d=d.return}Jb(function(){var d=f,e=xb(c),g=[];\na:{var h=df.get(a);if(void 0!==h){var k=td,n=a;switch(a){case \"keypress\":if(0===od(c))break a;case \"keydown\":case \"keyup\":k=Rd;break;case \"focusin\":n=\"focus\";k=Fd;break;case \"focusout\":n=\"blur\";k=Fd;break;case \"beforeblur\":case \"afterblur\":k=Fd;break;case \"click\":if(2===c.button)break a;case \"auxclick\":case \"dblclick\":case \"mousedown\":case \"mousemove\":case \"mouseup\":case \"mouseout\":case \"mouseover\":case \"contextmenu\":k=Bd;break;case \"drag\":case \"dragend\":case \"dragenter\":case \"dragexit\":case \"dragleave\":case \"dragover\":case \"dragstart\":case \"drop\":k=\nDd;break;case \"touchcancel\":case \"touchend\":case \"touchmove\":case \"touchstart\":k=Vd;break;case $e:case af:case bf:k=Hd;break;case cf:k=Xd;break;case \"scroll\":k=vd;break;case \"wheel\":k=Zd;break;case \"copy\":case \"cut\":case \"paste\":k=Jd;break;case \"gotpointercapture\":case \"lostpointercapture\":case \"pointercancel\":case \"pointerdown\":case \"pointermove\":case \"pointerout\":case \"pointerover\":case \"pointerup\":k=Td}var t=0!==(b&4),J=!t&&\"scroll\"===a,x=t?null!==h?h+\"Capture\":null:h;t=[];for(var w=d,u;null!==\nw;){u=w;var F=u.stateNode;5===u.tag&&null!==F&&(u=F,null!==x&&(F=Kb(w,x),null!=F&&t.push(tf(w,F,u))));if(J)break;w=w.return}0<t.length&&(h=new k(h,n,null,c,e),g.push({event:h,listeners:t}))}}if(0===(b&7)){a:{h=\"mouseover\"===a||\"pointerover\"===a;k=\"mouseout\"===a||\"pointerout\"===a;if(h&&c!==wb&&(n=c.relatedTarget||c.fromElement)&&(Wc(n)||n[uf]))break a;if(k||h){h=e.window===e?e:(h=e.ownerDocument)?h.defaultView||h.parentWindow:window;if(k){if(n=c.relatedTarget||c.toElement,k=d,n=n?Wc(n):null,null!==\nn&&(J=Vb(n),n!==J||5!==n.tag&&6!==n.tag))n=null}else k=null,n=d;if(k!==n){t=Bd;F=\"onMouseLeave\";x=\"onMouseEnter\";w=\"mouse\";if(\"pointerout\"===a||\"pointerover\"===a)t=Td,F=\"onPointerLeave\",x=\"onPointerEnter\",w=\"pointer\";J=null==k?h:ue(k);u=null==n?h:ue(n);h=new t(F,w+\"leave\",k,c,e);h.target=J;h.relatedTarget=u;F=null;Wc(e)===d&&(t=new t(x,w+\"enter\",n,c,e),t.target=u,t.relatedTarget=J,F=t);J=F;if(k&&n)b:{t=k;x=n;w=0;for(u=t;u;u=vf(u))w++;u=0;for(F=x;F;F=vf(F))u++;for(;0<w-u;)t=vf(t),w--;for(;0<u-w;)x=\nvf(x),u--;for(;w--;){if(t===x||null!==x&&t===x.alternate)break b;t=vf(t);x=vf(x)}t=null}else t=null;null!==k&&wf(g,h,k,t,!1);null!==n&&null!==J&&wf(g,J,n,t,!0)}}}a:{h=d?ue(d):window;k=h.nodeName&&h.nodeName.toLowerCase();if(\"select\"===k||\"input\"===k&&\"file\"===h.type)var na=ve;else if(me(h))if(we)na=Fe;else{na=De;var xa=Ce}else(k=h.nodeName)&&\"input\"===k.toLowerCase()&&(\"checkbox\"===h.type||\"radio\"===h.type)&&(na=Ee);if(na&&(na=na(a,d))){ne(g,na,c,e);break a}xa&&xa(a,h,d);\"focusout\"===a&&(xa=h._wrapperState)&&\nxa.controlled&&\"number\"===h.type&&cb(h,\"number\",h.value)}xa=d?ue(d):window;switch(a){case \"focusin\":if(me(xa)||\"true\"===xa.contentEditable)Qe=xa,Re=d,Se=null;break;case \"focusout\":Se=Re=Qe=null;break;case \"mousedown\":Te=!0;break;case \"contextmenu\":case \"mouseup\":case \"dragend\":Te=!1;Ue(g,c,e);break;case \"selectionchange\":if(Pe)break;case \"keydown\":case \"keyup\":Ue(g,c,e)}var $a;if(ae)b:{switch(a){case \"compositionstart\":var ba=\"onCompositionStart\";break b;case \"compositionend\":ba=\"onCompositionEnd\";\nbreak b;case \"compositionupdate\":ba=\"onCompositionUpdate\";break b}ba=void 0}else ie?ge(a,c)&&(ba=\"onCompositionEnd\"):\"keydown\"===a&&229===c.keyCode&&(ba=\"onCompositionStart\");ba&&(de&&\"ko\"!==c.locale&&(ie||\"onCompositionStart\"!==ba?\"onCompositionEnd\"===ba&&ie&&($a=nd()):(kd=e,ld=\"value\"in kd?kd.value:kd.textContent,ie=!0)),xa=oe(d,ba),0<xa.length&&(ba=new Ld(ba,a,null,c,e),g.push({event:ba,listeners:xa}),$a?ba.data=$a:($a=he(c),null!==$a&&(ba.data=$a))));if($a=ce?je(a,c):ke(a,c))d=oe(d,\"onBeforeInput\"),\n0<d.length&&(e=new Ld(\"onBeforeInput\",\"beforeinput\",null,c,e),g.push({event:e,listeners:d}),e.data=$a)}se(g,b)})}function tf(a,b,c){return{instance:a,listener:b,currentTarget:c}}function oe(a,b){for(var c=b+\"Capture\",d=[];null!==a;){var e=a,f=e.stateNode;5===e.tag&&null!==f&&(e=f,f=Kb(a,c),null!=f&&d.unshift(tf(a,f,e)),f=Kb(a,b),null!=f&&d.push(tf(a,f,e)));a=a.return}return d}function vf(a){if(null===a)return null;do a=a.return;while(a&&5!==a.tag);return a?a:null}\nfunction wf(a,b,c,d,e){for(var f=b._reactName,g=[];null!==c&&c!==d;){var h=c,k=h.alternate,l=h.stateNode;if(null!==k&&k===d)break;5===h.tag&&null!==l&&(h=l,e?(k=Kb(c,f),null!=k&&g.unshift(tf(c,k,h))):e||(k=Kb(c,f),null!=k&&g.push(tf(c,k,h))));c=c.return}0!==g.length&&a.push({event:b,listeners:g})}var xf=/\\r\\n?/g,yf=/\\u0000|\\uFFFD/g;function zf(a){return(\"string\"===typeof a?a:\"\"+a).replace(xf,\"\\n\").replace(yf,\"\")}function Af(a,b,c){b=zf(b);if(zf(a)!==b&&c)throw Error(p(425));}function Bf(){}\nvar Cf=null,Df=null;function Ef(a,b){return\"textarea\"===a||\"noscript\"===a||\"string\"===typeof b.children||\"number\"===typeof b.children||\"object\"===typeof b.dangerouslySetInnerHTML&&null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html}\nvar Ff=\"function\"===typeof setTimeout?setTimeout:void 0,Gf=\"function\"===typeof clearTimeout?clearTimeout:void 0,Hf=\"function\"===typeof Promise?Promise:void 0,Jf=\"function\"===typeof queueMicrotask?queueMicrotask:\"undefined\"!==typeof Hf?function(a){return Hf.resolve(null).then(a).catch(If)}:Ff;function If(a){setTimeout(function(){throw a;})}\nfunction Kf(a,b){var c=b,d=0;do{var e=c.nextSibling;a.removeChild(c);if(e&&8===e.nodeType)if(c=e.data,\"/$\"===c){if(0===d){a.removeChild(e);bd(b);return}d--}else\"$\"!==c&&\"$?\"!==c&&\"$!\"!==c||d++;c=e}while(c);bd(b)}function Lf(a){for(;null!=a;a=a.nextSibling){var b=a.nodeType;if(1===b||3===b)break;if(8===b){b=a.data;if(\"$\"===b||\"$!\"===b||\"$?\"===b)break;if(\"/$\"===b)return null}}return a}\nfunction Mf(a){a=a.previousSibling;for(var b=0;a;){if(8===a.nodeType){var c=a.data;if(\"$\"===c||\"$!\"===c||\"$?\"===c){if(0===b)return a;b--}else\"/$\"===c&&b++}a=a.previousSibling}return null}var Nf=Math.random().toString(36).slice(2),Of=\"__reactFiber$\"+Nf,Pf=\"__reactProps$\"+Nf,uf=\"__reactContainer$\"+Nf,of=\"__reactEvents$\"+Nf,Qf=\"__reactListeners$\"+Nf,Rf=\"__reactHandles$\"+Nf;\nfunction Wc(a){var b=a[Of];if(b)return b;for(var c=a.parentNode;c;){if(b=c[uf]||c[Of]){c=b.alternate;if(null!==b.child||null!==c&&null!==c.child)for(a=Mf(a);null!==a;){if(c=a[Of])return c;a=Mf(a)}return b}a=c;c=a.parentNode}return null}function Cb(a){a=a[Of]||a[uf];return!a||5!==a.tag&&6!==a.tag&&13!==a.tag&&3!==a.tag?null:a}function ue(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(p(33));}function Db(a){return a[Pf]||null}var Sf=[],Tf=-1;function Uf(a){return{current:a}}\nfunction E(a){0>Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}\nfunction Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||\"Unknown\",e));return A({},c,d)}\nfunction cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}\nfunction jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a<c.length;a++){var d=c[a];do d=d(!0);while(null!==d)}eg=null;fg=!1}catch(e){throw null!==eg&&(eg=eg.slice(a+1)),ac(fc,jg),e;}finally{C=b,gg=!1}}return null}var kg=[],lg=0,mg=null,ng=0,og=[],pg=0,qg=null,rg=1,sg=\"\";function tg(a,b){kg[lg++]=ng;kg[lg++]=mg;mg=a;ng=b}\nfunction ug(a,b,c){og[pg++]=rg;og[pg++]=sg;og[pg++]=qg;qg=a;var d=rg;a=sg;var e=32-oc(d)-1;d&=~(1<<e);c+=1;var f=32-oc(b)+e;if(30<f){var g=e-e%5;f=(d&(1<<g)-1).toString(32);d>>=g;e-=g;rg=1<<32-oc(b)+e|c<<e|d;sg=f+a}else rg=1<<f|c<<e|d,sg=a}function vg(a){null!==a.return&&(tg(a,1),ug(a,1,0))}function wg(a){for(;a===mg;)mg=kg[--lg],kg[lg]=null,ng=kg[--lg],kg[lg]=null;for(;a===qg;)qg=og[--pg],og[pg]=null,sg=og[--pg],og[pg]=null,rg=og[--pg],og[pg]=null}var xg=null,yg=null,I=!1,zg=null;\nfunction Ag(a,b){var c=Bg(5,null,null,0);c.elementType=\"DELETED\";c.stateNode=b;c.return=a;b=a.deletions;null===b?(a.deletions=[c],a.flags|=16):b.push(c)}\nfunction Cg(a,b){switch(a.tag){case 5:var c=a.type;b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b;return null!==b?(a.stateNode=b,xg=a,yg=Lf(b.firstChild),!0):!1;case 6:return b=\"\"===a.pendingProps||3!==b.nodeType?null:b,null!==b?(a.stateNode=b,xg=a,yg=null,!0):!1;case 13:return b=8!==b.nodeType?null:b,null!==b?(c=null!==qg?{id:rg,overflow:sg}:null,a.memoizedState={dehydrated:b,treeContext:c,retryLane:1073741824},c=Bg(18,null,null,0),c.stateNode=b,c.return=a,a.child=c,xg=a,yg=\nnull,!0):!1;default:return!1}}function Dg(a){return 0!==(a.mode&1)&&0===(a.flags&128)}function Eg(a){if(I){var b=yg;if(b){var c=b;if(!Cg(a,b)){if(Dg(a))throw Error(p(418));b=Lf(c.nextSibling);var d=xg;b&&Cg(a,b)?Ag(d,c):(a.flags=a.flags&-4097|2,I=!1,xg=a)}}else{if(Dg(a))throw Error(p(418));a.flags=a.flags&-4097|2;I=!1;xg=a}}}function Fg(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&13!==a.tag;)a=a.return;xg=a}\nfunction Gg(a){if(a!==xg)return!1;if(!I)return Fg(a),I=!0,!1;var b;(b=3!==a.tag)&&!(b=5!==a.tag)&&(b=a.type,b=\"head\"!==b&&\"body\"!==b&&!Ef(a.type,a.memoizedProps));if(b&&(b=yg)){if(Dg(a))throw Hg(),Error(p(418));for(;b;)Ag(a,b),b=Lf(b.nextSibling)}Fg(a);if(13===a.tag){a=a.memoizedState;a=null!==a?a.dehydrated:null;if(!a)throw Error(p(317));a:{a=a.nextSibling;for(b=0;a;){if(8===a.nodeType){var c=a.data;if(\"/$\"===c){if(0===b){yg=Lf(a.nextSibling);break a}b--}else\"$\"!==c&&\"$!\"!==c&&\"$?\"!==c||b++}a=a.nextSibling}yg=\nnull}}else yg=xg?Lf(a.stateNode.nextSibling):null;return!0}function Hg(){for(var a=yg;a;)a=Lf(a.nextSibling)}function Ig(){yg=xg=null;I=!1}function Jg(a){null===zg?zg=[a]:zg.push(a)}var Kg=ua.ReactCurrentBatchConfig;function Lg(a,b){if(a&&a.defaultProps){b=A({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c]);return b}return b}var Mg=Uf(null),Ng=null,Og=null,Pg=null;function Qg(){Pg=Og=Ng=null}function Rg(a){var b=Mg.current;E(Mg);a._currentValue=b}\nfunction Sg(a,b,c){for(;null!==a;){var d=a.alternate;(a.childLanes&b)!==b?(a.childLanes|=b,null!==d&&(d.childLanes|=b)):null!==d&&(d.childLanes&b)!==b&&(d.childLanes|=b);if(a===c)break;a=a.return}}function Tg(a,b){Ng=a;Pg=Og=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(0!==(a.lanes&b)&&(Ug=!0),a.firstContext=null)}\nfunction Vg(a){var b=a._currentValue;if(Pg!==a)if(a={context:a,memoizedValue:b,next:null},null===Og){if(null===Ng)throw Error(p(308));Og=a;Ng.dependencies={lanes:0,firstContext:a}}else Og=Og.next=a;return b}var Wg=null;function Xg(a){null===Wg?Wg=[a]:Wg.push(a)}function Yg(a,b,c,d){var e=b.interleaved;null===e?(c.next=c,Xg(b)):(c.next=e.next,e.next=c);b.interleaved=c;return Zg(a,d)}\nfunction Zg(a,b){a.lanes|=b;var c=a.alternate;null!==c&&(c.lanes|=b);c=a;for(a=a.return;null!==a;)a.childLanes|=b,c=a.alternate,null!==c&&(c.childLanes|=b),c=a,a=a.return;return 3===c.tag?c.stateNode:null}var $g=!1;function ah(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}\nfunction bh(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function ch(a,b){return{eventTime:a,lane:b,tag:0,payload:null,callback:null,next:null}}\nfunction dh(a,b,c){var d=a.updateQueue;if(null===d)return null;d=d.shared;if(0!==(K&2)){var e=d.pending;null===e?b.next=b:(b.next=e.next,e.next=b);d.pending=b;return Zg(a,c)}e=d.interleaved;null===e?(b.next=b,Xg(d)):(b.next=e.next,e.next=b);d.interleaved=b;return Zg(a,c)}function eh(a,b,c){b=b.updateQueue;if(null!==b&&(b=b.shared,0!==(c&4194240))){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nfunction fh(a,b){var c=a.updateQueue,d=a.alternate;if(null!==d&&(d=d.updateQueue,c===d)){var e=null,f=null;c=c.firstBaseUpdate;if(null!==c){do{var g={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};null===f?e=f=g:f=f.next=g;c=c.next}while(null!==c);null===f?e=f=b:f=f.next=b}else e=f=b;c={baseState:d.baseState,firstBaseUpdate:e,lastBaseUpdate:f,shared:d.shared,effects:d.effects};a.updateQueue=c;return}a=c.lastBaseUpdate;null===a?c.firstBaseUpdate=b:a.next=\nb;c.lastBaseUpdate=b}\nfunction gh(a,b,c,d){var e=a.updateQueue;$g=!1;var f=e.firstBaseUpdate,g=e.lastBaseUpdate,h=e.shared.pending;if(null!==h){e.shared.pending=null;var k=h,l=k.next;k.next=null;null===g?f=l:g.next=l;g=k;var m=a.alternate;null!==m&&(m=m.updateQueue,h=m.lastBaseUpdate,h!==g&&(null===h?m.firstBaseUpdate=l:h.next=l,m.lastBaseUpdate=k))}if(null!==f){var q=e.baseState;g=0;m=l=k=null;h=f;do{var r=h.lane,y=h.eventTime;if((d&r)===r){null!==m&&(m=m.next={eventTime:y,lane:0,tag:h.tag,payload:h.payload,callback:h.callback,\nnext:null});a:{var n=a,t=h;r=b;y=c;switch(t.tag){case 1:n=t.payload;if(\"function\"===typeof n){q=n.call(y,q,r);break a}q=n;break a;case 3:n.flags=n.flags&-65537|128;case 0:n=t.payload;r=\"function\"===typeof n?n.call(y,q,r):n;if(null===r||void 0===r)break a;q=A({},q,r);break a;case 2:$g=!0}}null!==h.callback&&0!==h.lane&&(a.flags|=64,r=e.effects,null===r?e.effects=[h]:r.push(h))}else y={eventTime:y,lane:r,tag:h.tag,payload:h.payload,callback:h.callback,next:null},null===m?(l=m=y,k=q):m=m.next=y,g|=r;\nh=h.next;if(null===h)if(h=e.shared.pending,null===h)break;else r=h,h=r.next,r.next=null,e.lastBaseUpdate=r,e.shared.pending=null}while(1);null===m&&(k=q);e.baseState=k;e.firstBaseUpdate=l;e.lastBaseUpdate=m;b=e.shared.interleaved;if(null!==b){e=b;do g|=e.lane,e=e.next;while(e!==b)}else null===f&&(e.shared.lanes=0);hh|=g;a.lanes=g;a.memoizedState=q}}\nfunction ih(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;b<a.length;b++){var d=a[b],e=d.callback;if(null!==e){d.callback=null;d=c;if(\"function\"!==typeof e)throw Error(p(191,e));e.call(d)}}}var jh=(new aa.Component).refs;function kh(a,b,c,d){b=a.memoizedState;c=c(d,b);c=null===c||void 0===c?b:A({},b,c);a.memoizedState=c;0===a.lanes&&(a.updateQueue.baseState=c)}\nvar nh={isMounted:function(a){return(a=a._reactInternals)?Vb(a)===a:!1},enqueueSetState:function(a,b,c){a=a._reactInternals;var d=L(),e=lh(a),f=ch(d,e);f.payload=b;void 0!==c&&null!==c&&(f.callback=c);b=dh(a,f,e);null!==b&&(mh(b,a,e,d),eh(b,a,e))},enqueueReplaceState:function(a,b,c){a=a._reactInternals;var d=L(),e=lh(a),f=ch(d,e);f.tag=1;f.payload=b;void 0!==c&&null!==c&&(f.callback=c);b=dh(a,f,e);null!==b&&(mh(b,a,e,d),eh(b,a,e))},enqueueForceUpdate:function(a,b){a=a._reactInternals;var c=L(),d=\nlh(a),e=ch(c,d);e.tag=2;void 0!==b&&null!==b&&(e.callback=b);b=dh(a,e,d);null!==b&&(mh(b,a,d,c),eh(b,a,d))}};function oh(a,b,c,d,e,f,g){a=a.stateNode;return\"function\"===typeof a.shouldComponentUpdate?a.shouldComponentUpdate(d,f,g):b.prototype&&b.prototype.isPureReactComponent?!Ie(c,d)||!Ie(e,f):!0}\nfunction ph(a,b,c){var d=!1,e=Vf;var f=b.contextType;\"object\"===typeof f&&null!==f?f=Vg(f):(e=Zf(b)?Xf:H.current,d=b.contextTypes,f=(d=null!==d&&void 0!==d)?Yf(a,e):Vf);b=new b(c,f);a.memoizedState=null!==b.state&&void 0!==b.state?b.state:null;b.updater=nh;a.stateNode=b;b._reactInternals=a;d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=e,a.__reactInternalMemoizedMaskedChildContext=f);return b}\nfunction qh(a,b,c,d){a=b.state;\"function\"===typeof b.componentWillReceiveProps&&b.componentWillReceiveProps(c,d);\"function\"===typeof b.UNSAFE_componentWillReceiveProps&&b.UNSAFE_componentWillReceiveProps(c,d);b.state!==a&&nh.enqueueReplaceState(b,b.state,null)}\nfunction rh(a,b,c,d){var e=a.stateNode;e.props=c;e.state=a.memoizedState;e.refs=jh;ah(a);var f=b.contextType;\"object\"===typeof f&&null!==f?e.context=Vg(f):(f=Zf(b)?Xf:H.current,e.context=Yf(a,f));e.state=a.memoizedState;f=b.getDerivedStateFromProps;\"function\"===typeof f&&(kh(a,b,f,c),e.state=a.memoizedState);\"function\"===typeof b.getDerivedStateFromProps||\"function\"===typeof e.getSnapshotBeforeUpdate||\"function\"!==typeof e.UNSAFE_componentWillMount&&\"function\"!==typeof e.componentWillMount||(b=e.state,\n\"function\"===typeof e.componentWillMount&&e.componentWillMount(),\"function\"===typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),b!==e.state&&nh.enqueueReplaceState(e,e.state,null),gh(a,c,e,d),e.state=a.memoizedState);\"function\"===typeof e.componentDidMount&&(a.flags|=4194308)}\nfunction sh(a,b,c){a=c.ref;if(null!==a&&\"function\"!==typeof a&&\"object\"!==typeof a){if(c._owner){c=c._owner;if(c){if(1!==c.tag)throw Error(p(309));var d=c.stateNode}if(!d)throw Error(p(147,a));var e=d,f=\"\"+a;if(null!==b&&null!==b.ref&&\"function\"===typeof b.ref&&b.ref._stringRef===f)return b.ref;b=function(a){var b=e.refs;b===jh&&(b=e.refs={});null===a?delete b[f]:b[f]=a};b._stringRef=f;return b}if(\"string\"!==typeof a)throw Error(p(284));if(!c._owner)throw Error(p(290,a));}return a}\nfunction th(a,b){a=Object.prototype.toString.call(b);throw Error(p(31,\"[object Object]\"===a?\"object with keys {\"+Object.keys(b).join(\", \")+\"}\":a));}function uh(a){var b=a._init;return b(a._payload)}\nfunction vh(a){function b(b,c){if(a){var d=b.deletions;null===d?(b.deletions=[c],b.flags|=16):d.push(c)}}function c(c,d){if(!a)return null;for(;null!==d;)b(c,d),d=d.sibling;return null}function d(a,b){for(a=new Map;null!==b;)null!==b.key?a.set(b.key,b):a.set(b.index,b),b=b.sibling;return a}function e(a,b){a=wh(a,b);a.index=0;a.sibling=null;return a}function f(b,c,d){b.index=d;if(!a)return b.flags|=1048576,c;d=b.alternate;if(null!==d)return d=d.index,d<c?(b.flags|=2,c):d;b.flags|=2;return c}function g(b){a&&\nnull===b.alternate&&(b.flags|=2);return b}function h(a,b,c,d){if(null===b||6!==b.tag)return b=xh(c,a.mode,d),b.return=a,b;b=e(b,c);b.return=a;return b}function k(a,b,c,d){var f=c.type;if(f===ya)return m(a,b,c.props.children,d,c.key);if(null!==b&&(b.elementType===f||\"object\"===typeof f&&null!==f&&f.$$typeof===Ha&&uh(f)===b.type))return d=e(b,c.props),d.ref=sh(a,b,c),d.return=a,d;d=yh(c.type,c.key,c.props,null,a.mode,d);d.ref=sh(a,b,c);d.return=a;return d}function l(a,b,c,d){if(null===b||4!==b.tag||\nb.stateNode.containerInfo!==c.containerInfo||b.stateNode.implementation!==c.implementation)return b=zh(c,a.mode,d),b.return=a,b;b=e(b,c.children||[]);b.return=a;return b}function m(a,b,c,d,f){if(null===b||7!==b.tag)return b=Ah(c,a.mode,d,f),b.return=a,b;b=e(b,c);b.return=a;return b}function q(a,b,c){if(\"string\"===typeof b&&\"\"!==b||\"number\"===typeof b)return b=xh(\"\"+b,a.mode,c),b.return=a,b;if(\"object\"===typeof b&&null!==b){switch(b.$$typeof){case va:return c=yh(b.type,b.key,b.props,null,a.mode,c),\nc.ref=sh(a,null,b),c.return=a,c;case wa:return b=zh(b,a.mode,c),b.return=a,b;case Ha:var d=b._init;return q(a,d(b._payload),c)}if(eb(b)||Ka(b))return b=Ah(b,a.mode,c,null),b.return=a,b;th(a,b)}return null}function r(a,b,c,d){var e=null!==b?b.key:null;if(\"string\"===typeof c&&\"\"!==c||\"number\"===typeof c)return null!==e?null:h(a,b,\"\"+c,d);if(\"object\"===typeof c&&null!==c){switch(c.$$typeof){case va:return c.key===e?k(a,b,c,d):null;case wa:return c.key===e?l(a,b,c,d):null;case Ha:return e=c._init,r(a,\nb,e(c._payload),d)}if(eb(c)||Ka(c))return null!==e?null:m(a,b,c,d,null);th(a,c)}return null}function y(a,b,c,d,e){if(\"string\"===typeof d&&\"\"!==d||\"number\"===typeof d)return a=a.get(c)||null,h(b,a,\"\"+d,e);if(\"object\"===typeof d&&null!==d){switch(d.$$typeof){case va:return a=a.get(null===d.key?c:d.key)||null,k(b,a,d,e);case wa:return a=a.get(null===d.key?c:d.key)||null,l(b,a,d,e);case Ha:var f=d._init;return y(a,b,c,f(d._payload),e)}if(eb(d)||Ka(d))return a=a.get(c)||null,m(b,a,d,e,null);th(b,d)}return null}\nfunction n(e,g,h,k){for(var l=null,m=null,u=g,w=g=0,x=null;null!==u&&w<h.length;w++){u.index>w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;w<h.length;w++)u=q(e,h[w],k),null!==u&&(g=f(u,g,w),null===m?l=u:m.sibling=u,m=u);I&&tg(e,w);return l}for(u=d(e,u);w<h.length;w++)x=y(u,e,w,h[w],k),null!==x&&(a&&null!==x.alternate&&u.delete(null===\nx.key?w:x.key),g=f(x,g,w),null===m?l=x:m.sibling=x,m=x);a&&u.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function t(e,g,h,k){var l=Ka(h);if(\"function\"!==typeof l)throw Error(p(150));h=l.call(h);if(null==h)throw Error(p(151));for(var u=l=null,m=g,w=g=0,x=null,n=h.next();null!==m&&!n.done;w++,n=h.next()){m.index>w?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,\nm),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){\"object\"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if(\"object\"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=\nf.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||\"object\"===typeof k&&null!==k&&k.$$typeof===Ha&&uh(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=sh(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Ah(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=yh(f.type,f.key,f.props,null,a.mode,h),h.ref=sh(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!==\nd;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=zh(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);th(a,f)}return\"string\"===typeof f&&\"\"!==f||\"number\"===typeof f?(f=\"\"+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):\n(c(a,d),d=xh(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Bh=vh(!0),Ch=vh(!1),Dh={},Eh=Uf(Dh),Fh=Uf(Dh),Gh=Uf(Dh);function Hh(a){if(a===Dh)throw Error(p(174));return a}function Ih(a,b){G(Gh,b);G(Fh,a);G(Eh,Dh);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:lb(null,\"\");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=lb(b,a)}E(Eh);G(Eh,b)}function Jh(){E(Eh);E(Fh);E(Gh)}\nfunction Kh(a){Hh(Gh.current);var b=Hh(Eh.current);var c=lb(b,a.type);b!==c&&(G(Fh,a),G(Eh,c))}function Lh(a){Fh.current===a&&(E(Eh),E(Fh))}var M=Uf(0);\nfunction Mh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||\"$?\"===c.data||\"$!\"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}var Nh=[];\nfunction Oh(){for(var a=0;a<Nh.length;a++)Nh[a]._workInProgressVersionPrimary=null;Nh.length=0}var Ph=ua.ReactCurrentDispatcher,Qh=ua.ReactCurrentBatchConfig,Rh=0,N=null,O=null,P=null,Sh=!1,Th=!1,Uh=0,Vh=0;function Q(){throw Error(p(321));}function Wh(a,b){if(null===b)return!1;for(var c=0;c<b.length&&c<a.length;c++)if(!He(a[c],b[c]))return!1;return!0}\nfunction Xh(a,b,c,d,e,f){Rh=f;N=b;b.memoizedState=null;b.updateQueue=null;b.lanes=0;Ph.current=null===a||null===a.memoizedState?Yh:Zh;a=c(d,e);if(Th){f=0;do{Th=!1;Uh=0;if(25<=f)throw Error(p(301));f+=1;P=O=null;b.updateQueue=null;Ph.current=$h;a=c(d,e)}while(Th)}Ph.current=ai;b=null!==O&&null!==O.next;Rh=0;P=O=N=null;Sh=!1;if(b)throw Error(p(300));return a}function bi(){var a=0!==Uh;Uh=0;return a}\nfunction ci(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};null===P?N.memoizedState=P=a:P=P.next=a;return P}function di(){if(null===O){var a=N.alternate;a=null!==a?a.memoizedState:null}else a=O.next;var b=null===P?N.memoizedState:P.next;if(null!==b)P=b,O=a;else{if(null===a)throw Error(p(310));O=a;a={memoizedState:O.memoizedState,baseState:O.baseState,baseQueue:O.baseQueue,queue:O.queue,next:null};null===P?N.memoizedState=P=a:P=P.next=a}return P}\nfunction ei(a,b){return\"function\"===typeof b?b(a):b}\nfunction fi(a){var b=di(),c=b.queue;if(null===c)throw Error(p(311));c.lastRenderedReducer=a;var d=O,e=d.baseQueue,f=c.pending;if(null!==f){if(null!==e){var g=e.next;e.next=f.next;f.next=g}d.baseQueue=e=f;c.pending=null}if(null!==e){f=e.next;d=d.baseState;var h=g=null,k=null,l=f;do{var m=l.lane;if((Rh&m)===m)null!==k&&(k=k.next={lane:0,action:l.action,hasEagerState:l.hasEagerState,eagerState:l.eagerState,next:null}),d=l.hasEagerState?l.eagerState:a(d,l.action);else{var q={lane:m,action:l.action,hasEagerState:l.hasEagerState,\neagerState:l.eagerState,next:null};null===k?(h=k=q,g=d):k=k.next=q;N.lanes|=m;hh|=m}l=l.next}while(null!==l&&l!==f);null===k?g=d:k.next=h;He(d,b.memoizedState)||(Ug=!0);b.memoizedState=d;b.baseState=g;b.baseQueue=k;c.lastRenderedState=d}a=c.interleaved;if(null!==a){e=a;do f=e.lane,N.lanes|=f,hh|=f,e=e.next;while(e!==a)}else null===e&&(c.lanes=0);return[b.memoizedState,c.dispatch]}\nfunction gi(a){var b=di(),c=b.queue;if(null===c)throw Error(p(311));c.lastRenderedReducer=a;var d=c.dispatch,e=c.pending,f=b.memoizedState;if(null!==e){c.pending=null;var g=e=e.next;do f=a(f,g.action),g=g.next;while(g!==e);He(f,b.memoizedState)||(Ug=!0);b.memoizedState=f;null===b.baseQueue&&(b.baseState=f);c.lastRenderedState=f}return[f,d]}function hi(){}\nfunction ii(a,b){var c=N,d=di(),e=b(),f=!He(d.memoizedState,e);f&&(d.memoizedState=e,Ug=!0);d=d.queue;ji(ki.bind(null,c,d,a),[a]);if(d.getSnapshot!==b||f||null!==P&&P.memoizedState.tag&1){c.flags|=2048;li(9,mi.bind(null,c,d,e,b),void 0,null);if(null===R)throw Error(p(349));0!==(Rh&30)||ni(c,b,e)}return e}function ni(a,b,c){a.flags|=16384;a={getSnapshot:b,value:c};b=N.updateQueue;null===b?(b={lastEffect:null,stores:null},N.updateQueue=b,b.stores=[a]):(c=b.stores,null===c?b.stores=[a]:c.push(a))}\nfunction mi(a,b,c,d){b.value=c;b.getSnapshot=d;oi(b)&&pi(a)}function ki(a,b,c){return c(function(){oi(b)&&pi(a)})}function oi(a){var b=a.getSnapshot;a=a.value;try{var c=b();return!He(a,c)}catch(d){return!0}}function pi(a){var b=Zg(a,1);null!==b&&mh(b,a,1,-1)}\nfunction qi(a){var b=ci();\"function\"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:ei,lastRenderedState:a};b.queue=a;a=a.dispatch=ri.bind(null,N,a);return[b.memoizedState,a]}\nfunction li(a,b,c,d){a={tag:a,create:b,destroy:c,deps:d,next:null};b=N.updateQueue;null===b?(b={lastEffect:null,stores:null},N.updateQueue=b,b.lastEffect=a.next=a):(c=b.lastEffect,null===c?b.lastEffect=a.next=a:(d=c.next,c.next=a,a.next=d,b.lastEffect=a));return a}function si(){return di().memoizedState}function ti(a,b,c,d){var e=ci();N.flags|=a;e.memoizedState=li(1|b,c,void 0,void 0===d?null:d)}\nfunction ui(a,b,c,d){var e=di();d=void 0===d?null:d;var f=void 0;if(null!==O){var g=O.memoizedState;f=g.destroy;if(null!==d&&Wh(d,g.deps)){e.memoizedState=li(b,c,f,d);return}}N.flags|=a;e.memoizedState=li(1|b,c,f,d)}function vi(a,b){return ti(8390656,8,a,b)}function ji(a,b){return ui(2048,8,a,b)}function wi(a,b){return ui(4,2,a,b)}function xi(a,b){return ui(4,4,a,b)}\nfunction yi(a,b){if(\"function\"===typeof b)return a=a(),b(a),function(){b(null)};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null}}function zi(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ui(4,4,yi.bind(null,b,a),c)}function Ai(){}function Bi(a,b){var c=di();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Wh(b,d[1]))return d[0];c.memoizedState=[a,b];return a}\nfunction Ci(a,b){var c=di();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Wh(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a}function Di(a,b,c){if(0===(Rh&21))return a.baseState&&(a.baseState=!1,Ug=!0),a.memoizedState=c;He(c,b)||(c=yc(),N.lanes|=c,hh|=c,a.baseState=!0);return b}function Ei(a,b){var c=C;C=0!==c&&4>c?c:4;a(!0);var d=Qh.transition;Qh.transition={};try{a(!1),b()}finally{C=c,Qh.transition=d}}function Fi(){return di().memoizedState}\nfunction Gi(a,b,c){var d=lh(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,c);else if(c=Yg(a,b,c,d),null!==c){var e=L();mh(c,a,d,e);Ji(c,b,d)}}\nfunction ri(a,b,c){var d=lh(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,Xg(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=Yg(a,b,e,d);null!==c&&(e=L(),mh(c,a,d,e),Ji(c,b,d))}}\nfunction Hi(a){var b=a.alternate;return a===N||null!==b&&b===N}function Ii(a,b){Th=Sh=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Ji(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nvar ai={readContext:Vg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useInsertionEffect:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useDeferredValue:Q,useTransition:Q,useMutableSource:Q,useSyncExternalStore:Q,useId:Q,unstable_isNewReconciler:!1},Yh={readContext:Vg,useCallback:function(a,b){ci().memoizedState=[a,void 0===b?null:b];return a},useContext:Vg,useEffect:vi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ti(4194308,\n4,yi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ti(4194308,4,a,b)},useInsertionEffect:function(a,b){return ti(4,2,a,b)},useMemo:function(a,b){var c=ci();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=ci();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=Gi.bind(null,N,a);return[d.memoizedState,a]},useRef:function(a){var b=\nci();a={current:a};return b.memoizedState=a},useState:qi,useDebugValue:Ai,useDeferredValue:function(a){return ci().memoizedState=a},useTransition:function(){var a=qi(!1),b=a[0];a=Ei.bind(null,a[1]);ci().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=N,e=ci();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===R)throw Error(p(349));0!==(Rh&30)||ni(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;vi(ki.bind(null,d,\nf,a),[a]);d.flags|=2048;li(9,mi.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=ci(),b=R.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=\":\"+b+\"R\"+c;c=Uh++;0<c&&(b+=\"H\"+c.toString(32));b+=\":\"}else c=Vh++,b=\":\"+b+\"r\"+c.toString(32)+\":\";return a.memoizedState=b},unstable_isNewReconciler:!1},Zh={readContext:Vg,useCallback:Bi,useContext:Vg,useEffect:ji,useImperativeHandle:zi,useInsertionEffect:wi,useLayoutEffect:xi,useMemo:Ci,useReducer:fi,useRef:si,useState:function(){return fi(ei)},\nuseDebugValue:Ai,useDeferredValue:function(a){var b=di();return Di(b,O.memoizedState,a)},useTransition:function(){var a=fi(ei)[0],b=di().memoizedState;return[a,b]},useMutableSource:hi,useSyncExternalStore:ii,useId:Fi,unstable_isNewReconciler:!1},$h={readContext:Vg,useCallback:Bi,useContext:Vg,useEffect:ji,useImperativeHandle:zi,useInsertionEffect:wi,useLayoutEffect:xi,useMemo:Ci,useReducer:gi,useRef:si,useState:function(){return gi(ei)},useDebugValue:Ai,useDeferredValue:function(a){var b=di();return null===\nO?b.memoizedState=a:Di(b,O.memoizedState,a)},useTransition:function(){var a=gi(ei)[0],b=di().memoizedState;return[a,b]},useMutableSource:hi,useSyncExternalStore:ii,useId:Fi,unstable_isNewReconciler:!1};function Ki(a,b){try{var c=\"\",d=b;do c+=Pa(d),d=d.return;while(d);var e=c}catch(f){e=\"\\nError generating stack: \"+f.message+\"\\n\"+f.stack}return{value:a,source:b,stack:e,digest:null}}function Li(a,b,c){return{value:a,source:null,stack:null!=c?c:null,digest:null!=b?b:null}}\nfunction Mi(a,b){try{console.error(b.value)}catch(c){setTimeout(function(){throw c;})}}var Ni=\"function\"===typeof WeakMap?WeakMap:Map;function Oi(a,b,c){c=ch(-1,c);c.tag=3;c.payload={element:null};var d=b.value;c.callback=function(){Pi||(Pi=!0,Qi=d);Mi(a,b)};return c}\nfunction Ri(a,b,c){c=ch(-1,c);c.tag=3;var d=a.type.getDerivedStateFromError;if(\"function\"===typeof d){var e=b.value;c.payload=function(){return d(e)};c.callback=function(){Mi(a,b)}}var f=a.stateNode;null!==f&&\"function\"===typeof f.componentDidCatch&&(c.callback=function(){Mi(a,b);\"function\"!==typeof d&&(null===Si?Si=new Set([this]):Si.add(this));var c=b.stack;this.componentDidCatch(b.value,{componentStack:null!==c?c:\"\"})});return c}\nfunction Ti(a,b,c){var d=a.pingCache;if(null===d){d=a.pingCache=new Ni;var e=new Set;d.set(b,e)}else e=d.get(b),void 0===e&&(e=new Set,d.set(b,e));e.has(c)||(e.add(c),a=Ui.bind(null,a,b,c),b.then(a,a))}function Vi(a){do{var b;if(b=13===a.tag)b=a.memoizedState,b=null!==b?null!==b.dehydrated?!0:!1:!0;if(b)return a;a=a.return}while(null!==a);return null}\nfunction Wi(a,b,c,d,e){if(0===(a.mode&1))return a===b?a.flags|=65536:(a.flags|=128,c.flags|=131072,c.flags&=-52805,1===c.tag&&(null===c.alternate?c.tag=17:(b=ch(-1,1),b.tag=2,dh(c,b,1))),c.lanes|=1),a;a.flags|=65536;a.lanes=e;return a}var Xi=ua.ReactCurrentOwner,Ug=!1;function Yi(a,b,c,d){b.child=null===a?Ch(b,null,c,d):Bh(b,a.child,c,d)}\nfunction Zi(a,b,c,d,e){c=c.render;var f=b.ref;Tg(b,e);d=Xh(a,b,c,d,f,e);c=bi();if(null!==a&&!Ug)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,$i(a,b,e);I&&c&&vg(b);b.flags|=1;Yi(a,b,d,e);return b.child}\nfunction aj(a,b,c,d,e){if(null===a){var f=c.type;if(\"function\"===typeof f&&!bj(f)&&void 0===f.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=f,cj(a,b,f,d,e);a=yh(c.type,null,d,b,b.mode,e);a.ref=b.ref;a.return=b;return b.child=a}f=a.child;if(0===(a.lanes&e)){var g=f.memoizedProps;c=c.compare;c=null!==c?c:Ie;if(c(g,d)&&a.ref===b.ref)return $i(a,b,e)}b.flags|=1;a=wh(f,d);a.ref=b.ref;a.return=b;return b.child=a}\nfunction cj(a,b,c,d,e){if(null!==a){var f=a.memoizedProps;if(Ie(f,d)&&a.ref===b.ref)if(Ug=!1,b.pendingProps=d=f,0!==(a.lanes&e))0!==(a.flags&131072)&&(Ug=!0);else return b.lanes=a.lanes,$i(a,b,e)}return dj(a,b,c,d,e)}\nfunction ej(a,b,c){var d=b.pendingProps,e=d.children,f=null!==a?a.memoizedState:null;if(\"hidden\"===d.mode)if(0===(b.mode&1))b.memoizedState={baseLanes:0,cachePool:null,transitions:null},G(fj,gj),gj|=c;else{if(0===(c&1073741824))return a=null!==f?f.baseLanes|c:c,b.lanes=b.childLanes=1073741824,b.memoizedState={baseLanes:a,cachePool:null,transitions:null},b.updateQueue=null,G(fj,gj),gj|=a,null;b.memoizedState={baseLanes:0,cachePool:null,transitions:null};d=null!==f?f.baseLanes:c;G(fj,gj);gj|=d}else null!==\nf?(d=f.baseLanes|c,b.memoizedState=null):d=c,G(fj,gj),gj|=d;Yi(a,b,e,c);return b.child}function hj(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.flags|=512,b.flags|=2097152}function dj(a,b,c,d,e){var f=Zf(c)?Xf:H.current;f=Yf(b,f);Tg(b,e);c=Xh(a,b,c,d,f,e);d=bi();if(null!==a&&!Ug)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,$i(a,b,e);I&&d&&vg(b);b.flags|=1;Yi(a,b,c,e);return b.child}\nfunction ij(a,b,c,d,e){if(Zf(c)){var f=!0;cg(b)}else f=!1;Tg(b,e);if(null===b.stateNode)jj(a,b),ph(b,c,d),rh(b,c,d,e),d=!0;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var k=g.context,l=c.contextType;\"object\"===typeof l&&null!==l?l=Vg(l):(l=Zf(c)?Xf:H.current,l=Yf(b,l));var m=c.getDerivedStateFromProps,q=\"function\"===typeof m||\"function\"===typeof g.getSnapshotBeforeUpdate;q||\"function\"!==typeof g.UNSAFE_componentWillReceiveProps&&\"function\"!==typeof g.componentWillReceiveProps||\n(h!==d||k!==l)&&qh(b,g,d,l);$g=!1;var r=b.memoizedState;g.state=r;gh(b,d,g,e);k=b.memoizedState;h!==d||r!==k||Wf.current||$g?(\"function\"===typeof m&&(kh(b,c,m,d),k=b.memoizedState),(h=$g||oh(b,c,h,d,r,k,l))?(q||\"function\"!==typeof g.UNSAFE_componentWillMount&&\"function\"!==typeof g.componentWillMount||(\"function\"===typeof g.componentWillMount&&g.componentWillMount(),\"function\"===typeof g.UNSAFE_componentWillMount&&g.UNSAFE_componentWillMount()),\"function\"===typeof g.componentDidMount&&(b.flags|=4194308)):\n(\"function\"===typeof g.componentDidMount&&(b.flags|=4194308),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=l,d=h):(\"function\"===typeof g.componentDidMount&&(b.flags|=4194308),d=!1)}else{g=b.stateNode;bh(a,b);h=b.memoizedProps;l=b.type===b.elementType?h:Lg(b.type,h);g.props=l;q=b.pendingProps;r=g.context;k=c.contextType;\"object\"===typeof k&&null!==k?k=Vg(k):(k=Zf(c)?Xf:H.current,k=Yf(b,k));var y=c.getDerivedStateFromProps;(m=\"function\"===typeof y||\"function\"===typeof g.getSnapshotBeforeUpdate)||\n\"function\"!==typeof g.UNSAFE_componentWillReceiveProps&&\"function\"!==typeof g.componentWillReceiveProps||(h!==q||r!==k)&&qh(b,g,d,k);$g=!1;r=b.memoizedState;g.state=r;gh(b,d,g,e);var n=b.memoizedState;h!==q||r!==n||Wf.current||$g?(\"function\"===typeof y&&(kh(b,c,y,d),n=b.memoizedState),(l=$g||oh(b,c,l,d,r,n,k)||!1)?(m||\"function\"!==typeof g.UNSAFE_componentWillUpdate&&\"function\"!==typeof g.componentWillUpdate||(\"function\"===typeof g.componentWillUpdate&&g.componentWillUpdate(d,n,k),\"function\"===typeof g.UNSAFE_componentWillUpdate&&\ng.UNSAFE_componentWillUpdate(d,n,k)),\"function\"===typeof g.componentDidUpdate&&(b.flags|=4),\"function\"===typeof g.getSnapshotBeforeUpdate&&(b.flags|=1024)):(\"function\"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=4),\"function\"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),b.memoizedProps=d,b.memoizedState=n),g.props=d,g.state=n,g.context=k,d=l):(\"function\"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===\na.memoizedState||(b.flags|=4),\"function\"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),d=!1)}return kj(a,b,c,d,f,e)}\nfunction kj(a,b,c,d,e,f){hj(a,b);var g=0!==(b.flags&128);if(!d&&!g)return e&&dg(b,c,!1),$i(a,b,f);d=b.stateNode;Xi.current=b;var h=g&&\"function\"!==typeof c.getDerivedStateFromError?null:d.render();b.flags|=1;null!==a&&g?(b.child=Bh(b,a.child,null,f),b.child=Bh(b,null,h,f)):Yi(a,b,h,f);b.memoizedState=d.state;e&&dg(b,c,!0);return b.child}function lj(a){var b=a.stateNode;b.pendingContext?ag(a,b.pendingContext,b.pendingContext!==b.context):b.context&&ag(a,b.context,!1);Ih(a,b.containerInfo)}\nfunction mj(a,b,c,d,e){Ig();Jg(e);b.flags|=256;Yi(a,b,c,d);return b.child}var nj={dehydrated:null,treeContext:null,retryLane:0};function oj(a){return{baseLanes:a,cachePool:null,transitions:null}}\nfunction pj(a,b,c){var d=b.pendingProps,e=M.current,f=!1,g=0!==(b.flags&128),h;(h=g)||(h=null!==a&&null===a.memoizedState?!1:0!==(e&2));if(h)f=!0,b.flags&=-129;else if(null===a||null!==a.memoizedState)e|=1;G(M,e&1);if(null===a){Eg(b);a=b.memoizedState;if(null!==a&&(a=a.dehydrated,null!==a))return 0===(b.mode&1)?b.lanes=1:\"$!\"===a.data?b.lanes=8:b.lanes=1073741824,null;g=d.children;a=d.fallback;return f?(d=b.mode,f=b.child,g={mode:\"hidden\",children:g},0===(d&1)&&null!==f?(f.childLanes=0,f.pendingProps=\ng):f=qj(g,d,0,null),a=Ah(a,d,c,null),f.return=b,a.return=b,f.sibling=a,b.child=f,b.child.memoizedState=oj(c),b.memoizedState=nj,a):rj(b,g)}e=a.memoizedState;if(null!==e&&(h=e.dehydrated,null!==h))return sj(a,b,g,d,h,e,c);if(f){f=d.fallback;g=b.mode;e=a.child;h=e.sibling;var k={mode:\"hidden\",children:d.children};0===(g&1)&&b.child!==e?(d=b.child,d.childLanes=0,d.pendingProps=k,b.deletions=null):(d=wh(e,k),d.subtreeFlags=e.subtreeFlags&14680064);null!==h?f=wh(h,f):(f=Ah(f,g,c,null),f.flags|=2);f.return=\nb;d.return=b;d.sibling=f;b.child=d;d=f;f=b.child;g=a.child.memoizedState;g=null===g?oj(c):{baseLanes:g.baseLanes|c,cachePool:null,transitions:g.transitions};f.memoizedState=g;f.childLanes=a.childLanes&~c;b.memoizedState=nj;return d}f=a.child;a=f.sibling;d=wh(f,{mode:\"visible\",children:d.children});0===(b.mode&1)&&(d.lanes=c);d.return=b;d.sibling=null;null!==a&&(c=b.deletions,null===c?(b.deletions=[a],b.flags|=16):c.push(a));b.child=d;b.memoizedState=null;return d}\nfunction rj(a,b){b=qj({mode:\"visible\",children:b},a.mode,0,null);b.return=a;return a.child=b}function tj(a,b,c,d){null!==d&&Jg(d);Bh(b,a.child,null,c);a=rj(b,b.pendingProps.children);a.flags|=2;b.memoizedState=null;return a}\nfunction sj(a,b,c,d,e,f,g){if(c){if(b.flags&256)return b.flags&=-257,d=Li(Error(p(422))),tj(a,b,g,d);if(null!==b.memoizedState)return b.child=a.child,b.flags|=128,null;f=d.fallback;e=b.mode;d=qj({mode:\"visible\",children:d.children},e,0,null);f=Ah(f,e,g,null);f.flags|=2;d.return=b;f.return=b;d.sibling=f;b.child=d;0!==(b.mode&1)&&Bh(b,a.child,null,g);b.child.memoizedState=oj(g);b.memoizedState=nj;return f}if(0===(b.mode&1))return tj(a,b,g,null);if(\"$!\"===e.data){d=e.nextSibling&&e.nextSibling.dataset;\nif(d)var h=d.dgst;d=h;f=Error(p(419));d=Li(f,d,void 0);return tj(a,b,g,d)}h=0!==(g&a.childLanes);if(Ug||h){d=R;if(null!==d){switch(g&-g){case 4:e=2;break;case 16:e=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:e=32;break;case 536870912:e=268435456;break;default:e=0}e=0!==(e&(d.suspendedLanes|g))?0:e;\n0!==e&&e!==f.retryLane&&(f.retryLane=e,Zg(a,e),mh(d,a,e,-1))}uj();d=Li(Error(p(421)));return tj(a,b,g,d)}if(\"$?\"===e.data)return b.flags|=128,b.child=a.child,b=vj.bind(null,a),e._reactRetry=b,null;a=f.treeContext;yg=Lf(e.nextSibling);xg=b;I=!0;zg=null;null!==a&&(og[pg++]=rg,og[pg++]=sg,og[pg++]=qg,rg=a.id,sg=a.overflow,qg=b);b=rj(b,d.children);b.flags|=4096;return b}function wj(a,b,c){a.lanes|=b;var d=a.alternate;null!==d&&(d.lanes|=b);Sg(a.return,b,c)}\nfunction xj(a,b,c,d,e){var f=a.memoizedState;null===f?a.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:d,tail:c,tailMode:e}:(f.isBackwards=b,f.rendering=null,f.renderingStartTime=0,f.last=d,f.tail=c,f.tailMode=e)}\nfunction yj(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;Yi(a,b,d.children,c);d=M.current;if(0!==(d&2))d=d&1|2,b.flags|=128;else{if(null!==a&&0!==(a.flags&128))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&wj(a,c,b);else if(19===a.tag)wj(a,c,b);else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===b)break a;for(;null===a.sibling;){if(null===a.return||a.return===b)break a;a=a.return}a.sibling.return=a.return;a=a.sibling}d&=1}G(M,d);if(0===(b.mode&1))b.memoizedState=\nnull;else switch(e){case \"forwards\":c=b.child;for(e=null;null!==c;)a=c.alternate,null!==a&&null===Mh(a)&&(e=c),c=c.sibling;c=e;null===c?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null);xj(b,!1,e,c,f);break;case \"backwards\":c=null;e=b.child;for(b.child=null;null!==e;){a=e.alternate;if(null!==a&&null===Mh(a)){b.child=e;break}a=e.sibling;e.sibling=c;c=e;e=a}xj(b,!0,c,null,f);break;case \"together\":xj(b,!1,null,null,void 0);break;default:b.memoizedState=null}return b.child}\nfunction jj(a,b){0===(b.mode&1)&&null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2)}function $i(a,b,c){null!==a&&(b.dependencies=a.dependencies);hh|=b.lanes;if(0===(c&b.childLanes))return null;if(null!==a&&b.child!==a.child)throw Error(p(153));if(null!==b.child){a=b.child;c=wh(a,a.pendingProps);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=wh(a,a.pendingProps),c.return=b;c.sibling=null}return b.child}\nfunction zj(a,b,c){switch(b.tag){case 3:lj(b);Ig();break;case 5:Kh(b);break;case 1:Zf(b.type)&&cg(b);break;case 4:Ih(b,b.stateNode.containerInfo);break;case 10:var d=b.type._context,e=b.memoizedProps.value;G(Mg,d._currentValue);d._currentValue=e;break;case 13:d=b.memoizedState;if(null!==d){if(null!==d.dehydrated)return G(M,M.current&1),b.flags|=128,null;if(0!==(c&b.child.childLanes))return pj(a,b,c);G(M,M.current&1);a=$i(a,b,c);return null!==a?a.sibling:null}G(M,M.current&1);break;case 19:d=0!==(c&\nb.childLanes);if(0!==(a.flags&128)){if(d)return yj(a,b,c);b.flags|=128}e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null,e.lastEffect=null);G(M,M.current);if(d)break;else return null;case 22:case 23:return b.lanes=0,ej(a,b,c)}return $i(a,b,c)}var Aj,Bj,Cj,Dj;\nAj=function(a,b){for(var c=b.child;null!==c;){if(5===c.tag||6===c.tag)a.appendChild(c.stateNode);else if(4!==c.tag&&null!==c.child){c.child.return=c;c=c.child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return}c.sibling.return=c.return;c=c.sibling}};Bj=function(){};\nCj=function(a,b,c,d){var e=a.memoizedProps;if(e!==d){a=b.stateNode;Hh(Eh.current);var f=null;switch(c){case \"input\":e=Ya(a,e);d=Ya(a,d);f=[];break;case \"select\":e=A({},e,{value:void 0});d=A({},d,{value:void 0});f=[];break;case \"textarea\":e=gb(a,e);d=gb(a,d);f=[];break;default:\"function\"!==typeof e.onClick&&\"function\"===typeof d.onClick&&(a.onclick=Bf)}ub(c,d);var g;c=null;for(l in e)if(!d.hasOwnProperty(l)&&e.hasOwnProperty(l)&&null!=e[l])if(\"style\"===l){var h=e[l];for(g in h)h.hasOwnProperty(g)&&\n(c||(c={}),c[g]=\"\")}else\"dangerouslySetInnerHTML\"!==l&&\"children\"!==l&&\"suppressContentEditableWarning\"!==l&&\"suppressHydrationWarning\"!==l&&\"autoFocus\"!==l&&(ea.hasOwnProperty(l)?f||(f=[]):(f=f||[]).push(l,null));for(l in d){var k=d[l];h=null!=e?e[l]:void 0;if(d.hasOwnProperty(l)&&k!==h&&(null!=k||null!=h))if(\"style\"===l)if(h){for(g in h)!h.hasOwnProperty(g)||k&&k.hasOwnProperty(g)||(c||(c={}),c[g]=\"\");for(g in k)k.hasOwnProperty(g)&&h[g]!==k[g]&&(c||(c={}),c[g]=k[g])}else c||(f||(f=[]),f.push(l,\nc)),c=k;else\"dangerouslySetInnerHTML\"===l?(k=k?k.__html:void 0,h=h?h.__html:void 0,null!=k&&h!==k&&(f=f||[]).push(l,k)):\"children\"===l?\"string\"!==typeof k&&\"number\"!==typeof k||(f=f||[]).push(l,\"\"+k):\"suppressContentEditableWarning\"!==l&&\"suppressHydrationWarning\"!==l&&(ea.hasOwnProperty(l)?(null!=k&&\"onScroll\"===l&&D(\"scroll\",a),f||h===k||(f=[])):(f=f||[]).push(l,k))}c&&(f=f||[]).push(\"style\",c);var l=f;if(b.updateQueue=l)b.flags|=4}};Dj=function(a,b,c,d){c!==d&&(b.flags|=4)};\nfunction Ej(a,b){if(!I)switch(a.tailMode){case \"hidden\":b=a.tail;for(var c=null;null!==b;)null!==b.alternate&&(c=b),b=b.sibling;null===c?a.tail=null:c.sibling=null;break;case \"collapsed\":c=a.tail;for(var d=null;null!==c;)null!==c.alternate&&(d=c),c=c.sibling;null===d?b||null===a.tail?a.tail=null:a.tail.sibling=null:d.sibling=null}}\nfunction S(a){var b=null!==a.alternate&&a.alternate.child===a.child,c=0,d=0;if(b)for(var e=a.child;null!==e;)c|=e.lanes|e.childLanes,d|=e.subtreeFlags&14680064,d|=e.flags&14680064,e.return=a,e=e.sibling;else for(e=a.child;null!==e;)c|=e.lanes|e.childLanes,d|=e.subtreeFlags,d|=e.flags,e.return=a,e=e.sibling;a.subtreeFlags|=d;a.childLanes=c;return b}\nfunction Fj(a,b,c){var d=b.pendingProps;wg(b);switch(b.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return S(b),null;case 1:return Zf(b.type)&&$f(),S(b),null;case 3:d=b.stateNode;Jh();E(Wf);E(H);Oh();d.pendingContext&&(d.context=d.pendingContext,d.pendingContext=null);if(null===a||null===a.child)Gg(b)?b.flags|=4:null===a||a.memoizedState.isDehydrated&&0===(b.flags&256)||(b.flags|=1024,null!==zg&&(Gj(zg),zg=null));Bj(a,b);S(b);return null;case 5:Lh(b);var e=Hh(Gh.current);\nc=b.type;if(null!==a&&null!=b.stateNode)Cj(a,b,c,d,e),a.ref!==b.ref&&(b.flags|=512,b.flags|=2097152);else{if(!d){if(null===b.stateNode)throw Error(p(166));S(b);return null}a=Hh(Eh.current);if(Gg(b)){d=b.stateNode;c=b.type;var f=b.memoizedProps;d[Of]=b;d[Pf]=f;a=0!==(b.mode&1);switch(c){case \"dialog\":D(\"cancel\",d);D(\"close\",d);break;case \"iframe\":case \"object\":case \"embed\":D(\"load\",d);break;case \"video\":case \"audio\":for(e=0;e<lf.length;e++)D(lf[e],d);break;case \"source\":D(\"error\",d);break;case \"img\":case \"image\":case \"link\":D(\"error\",\nd);D(\"load\",d);break;case \"details\":D(\"toggle\",d);break;case \"input\":Za(d,f);D(\"invalid\",d);break;case \"select\":d._wrapperState={wasMultiple:!!f.multiple};D(\"invalid\",d);break;case \"textarea\":hb(d,f),D(\"invalid\",d)}ub(c,f);e=null;for(var g in f)if(f.hasOwnProperty(g)){var h=f[g];\"children\"===g?\"string\"===typeof h?d.textContent!==h&&(!0!==f.suppressHydrationWarning&&Af(d.textContent,h,a),e=[\"children\",h]):\"number\"===typeof h&&d.textContent!==\"\"+h&&(!0!==f.suppressHydrationWarning&&Af(d.textContent,\nh,a),e=[\"children\",\"\"+h]):ea.hasOwnProperty(g)&&null!=h&&\"onScroll\"===g&&D(\"scroll\",d)}switch(c){case \"input\":Va(d);db(d,f,!0);break;case \"textarea\":Va(d);jb(d);break;case \"select\":case \"option\":break;default:\"function\"===typeof f.onClick&&(d.onclick=Bf)}d=e;b.updateQueue=d;null!==d&&(b.flags|=4)}else{g=9===e.nodeType?e:e.ownerDocument;\"http://www.w3.org/1999/xhtml\"===a&&(a=kb(c));\"http://www.w3.org/1999/xhtml\"===a?\"script\"===c?(a=g.createElement(\"div\"),a.innerHTML=\"<script>\\x3c/script>\",a=a.removeChild(a.firstChild)):\n\"string\"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),\"select\"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;Aj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case \"dialog\":D(\"cancel\",a);D(\"close\",a);e=d;break;case \"iframe\":case \"object\":case \"embed\":D(\"load\",a);e=d;break;case \"video\":case \"audio\":for(e=0;e<lf.length;e++)D(lf[e],a);e=d;break;case \"source\":D(\"error\",a);e=d;break;case \"img\":case \"image\":case \"link\":D(\"error\",\na);D(\"load\",a);e=d;break;case \"details\":D(\"toggle\",a);e=d;break;case \"input\":Za(a,d);e=Ya(a,d);D(\"invalid\",a);break;case \"option\":e=d;break;case \"select\":a._wrapperState={wasMultiple:!!d.multiple};e=A({},d,{value:void 0});D(\"invalid\",a);break;case \"textarea\":hb(a,d);e=gb(a,d);D(\"invalid\",a);break;default:e=d}ub(c,e);h=e;for(f in h)if(h.hasOwnProperty(f)){var k=h[f];\"style\"===f?sb(a,k):\"dangerouslySetInnerHTML\"===f?(k=k?k.__html:void 0,null!=k&&nb(a,k)):\"children\"===f?\"string\"===typeof k?(\"textarea\"!==\nc||\"\"!==k)&&ob(a,k):\"number\"===typeof k&&ob(a,\"\"+k):\"suppressContentEditableWarning\"!==f&&\"suppressHydrationWarning\"!==f&&\"autoFocus\"!==f&&(ea.hasOwnProperty(f)?null!=k&&\"onScroll\"===f&&D(\"scroll\",a):null!=k&&ta(a,f,k,g))}switch(c){case \"input\":Va(a);db(a,d,!1);break;case \"textarea\":Va(a);jb(a);break;case \"option\":null!=d.value&&a.setAttribute(\"value\",\"\"+Sa(d.value));break;case \"select\":a.multiple=!!d.multiple;f=d.value;null!=f?fb(a,!!d.multiple,f,!1):null!=d.defaultValue&&fb(a,!!d.multiple,d.defaultValue,\n!0);break;default:\"function\"===typeof e.onClick&&(a.onclick=Bf)}switch(c){case \"button\":case \"input\":case \"select\":case \"textarea\":d=!!d.autoFocus;break a;case \"img\":d=!0;break a;default:d=!1}}d&&(b.flags|=4)}null!==b.ref&&(b.flags|=512,b.flags|=2097152)}S(b);return null;case 6:if(a&&null!=b.stateNode)Dj(a,b,a.memoizedProps,d);else{if(\"string\"!==typeof d&&null===b.stateNode)throw Error(p(166));c=Hh(Gh.current);Hh(Eh.current);if(Gg(b)){d=b.stateNode;c=b.memoizedProps;d[Of]=b;if(f=d.nodeValue!==c)if(a=\nxg,null!==a)switch(a.tag){case 3:Af(d.nodeValue,c,0!==(a.mode&1));break;case 5:!0!==a.memoizedProps.suppressHydrationWarning&&Af(d.nodeValue,c,0!==(a.mode&1))}f&&(b.flags|=4)}else d=(9===c.nodeType?c:c.ownerDocument).createTextNode(d),d[Of]=b,b.stateNode=d}S(b);return null;case 13:E(M);d=b.memoizedState;if(null===a||null!==a.memoizedState&&null!==a.memoizedState.dehydrated){if(I&&null!==yg&&0!==(b.mode&1)&&0===(b.flags&128))Hg(),Ig(),b.flags|=98560,f=!1;else if(f=Gg(b),null!==d&&null!==d.dehydrated){if(null===\na){if(!f)throw Error(p(318));f=b.memoizedState;f=null!==f?f.dehydrated:null;if(!f)throw Error(p(317));f[Of]=b}else Ig(),0===(b.flags&128)&&(b.memoizedState=null),b.flags|=4;S(b);f=!1}else null!==zg&&(Gj(zg),zg=null),f=!0;if(!f)return b.flags&65536?b:null}if(0!==(b.flags&128))return b.lanes=c,b;d=null!==d;d!==(null!==a&&null!==a.memoizedState)&&d&&(b.child.flags|=8192,0!==(b.mode&1)&&(null===a||0!==(M.current&1)?0===T&&(T=3):uj()));null!==b.updateQueue&&(b.flags|=4);S(b);return null;case 4:return Jh(),\nBj(a,b),null===a&&sf(b.stateNode.containerInfo),S(b),null;case 10:return Rg(b.type._context),S(b),null;case 17:return Zf(b.type)&&$f(),S(b),null;case 19:E(M);f=b.memoizedState;if(null===f)return S(b),null;d=0!==(b.flags&128);g=f.rendering;if(null===g)if(d)Ej(f,!1);else{if(0!==T||null!==a&&0!==(a.flags&128))for(a=b.child;null!==a;){g=Mh(a);if(null!==g){b.flags|=128;Ej(f,!1);d=g.updateQueue;null!==d&&(b.updateQueue=d,b.flags|=4);b.subtreeFlags=0;d=c;for(c=b.child;null!==c;)f=c,a=d,f.flags&=14680066,\ng=f.alternate,null===g?(f.childLanes=0,f.lanes=a,f.child=null,f.subtreeFlags=0,f.memoizedProps=null,f.memoizedState=null,f.updateQueue=null,f.dependencies=null,f.stateNode=null):(f.childLanes=g.childLanes,f.lanes=g.lanes,f.child=g.child,f.subtreeFlags=0,f.deletions=null,f.memoizedProps=g.memoizedProps,f.memoizedState=g.memoizedState,f.updateQueue=g.updateQueue,f.type=g.type,a=g.dependencies,f.dependencies=null===a?null:{lanes:a.lanes,firstContext:a.firstContext}),c=c.sibling;G(M,M.current&1|2);return b.child}a=\na.sibling}null!==f.tail&&B()>Hj&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304)}else{if(!d)if(a=Mh(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Ej(f,!0),null===f.tail&&\"hidden\"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Hj&&1073741824!==c&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=\nb,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=M.current,G(M,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Ij(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(gj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}\nfunction Jj(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return Jh(),E(Wf),E(H),Oh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Lh(b),null;case 13:E(M);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(M),null;case 4:return Jh(),null;case 10:return Rg(b.type._context),null;case 22:case 23:return Ij(),\nnull;case 24:return null;default:return null}}var Kj=!1,U=!1,Lj=\"function\"===typeof WeakSet?WeakSet:Set,V=null;function Mj(a,b){var c=a.ref;if(null!==c)if(\"function\"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Nj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Oj=!1;\nfunction Pj(a,b){Cf=dd;a=Me();if(Ne(a)){if(\"selectionStart\"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=\nq.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;\ncase 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Lg(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent=\"\":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Oj;Oj=!1;return n}\nfunction Qj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Nj(b,c,f)}e=e.next}while(e!==d)}}function Rj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Sj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}\"function\"===typeof b?b(a):b.current=a}}\nfunction Tj(a){var b=a.alternate;null!==b&&(a.alternate=null,Tj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Uj(a){return 5===a.tag||3===a.tag||4===a.tag}\nfunction Vj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Uj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}\nfunction Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling}\nfunction Xj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Xj(a,b,c),a=a.sibling;null!==a;)Xj(a,b,c),a=a.sibling}var X=null,Yj=!1;function Zj(a,b,c){for(c=c.child;null!==c;)ak(a,b,c),c=c.sibling}\nfunction ak(a,b,c){if(lc&&\"function\"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Mj(c,b);case 6:var d=X,e=Yj;X=null;Zj(a,b,c);X=d;Yj=e;null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Yj;X=c.stateNode.containerInfo;Yj=!0;\nZj(a,b,c);X=d;Yj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Nj(c,b,g):0!==(f&4)&&Nj(c,b,g));e=e.next}while(e!==d)}Zj(a,b,c);break;case 1:if(!U&&(Mj(c,b),d=c.stateNode,\"function\"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Zj(a,b,c);break;case 21:Zj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==\nc.memoizedState,Zj(a,b,c),U=d):Zj(a,b,c);break;default:Zj(a,b,c)}}function bk(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Lj);b.forEach(function(b){var d=ck.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}\nfunction dk(a,b){var c=b.deletions;if(null!==c)for(var d=0;d<c.length;d++){var e=c[d];try{var f=a,g=b,h=g;a:for(;null!==h;){switch(h.tag){case 5:X=h.stateNode;Yj=!1;break a;case 3:X=h.stateNode.containerInfo;Yj=!0;break a;case 4:X=h.stateNode.containerInfo;Yj=!0;break a}h=h.return}if(null===X)throw Error(p(160));ak(f,g,e);X=null;Yj=!1;var k=e.alternate;null!==k&&(k.return=null);e.return=null}catch(l){W(e,b,l)}}if(b.subtreeFlags&12854)for(b=b.child;null!==b;)ek(b,a),b=b.sibling}\nfunction ek(a,b){var c=a.alternate,d=a.flags;switch(a.tag){case 0:case 11:case 14:case 15:dk(b,a);fk(a);if(d&4){try{Qj(3,a,a.return),Rj(3,a)}catch(t){W(a,a.return,t)}try{Qj(5,a,a.return)}catch(t){W(a,a.return,t)}}break;case 1:dk(b,a);fk(a);d&512&&null!==c&&Mj(c,c.return);break;case 5:dk(b,a);fk(a);d&512&&null!==c&&Mj(c,c.return);if(a.flags&32){var e=a.stateNode;try{ob(e,\"\")}catch(t){W(a,a.return,t)}}if(d&4&&(e=a.stateNode,null!=e)){var f=a.memoizedProps,g=null!==c?c.memoizedProps:f,h=a.type,k=a.updateQueue;\na.updateQueue=null;if(null!==k)try{\"input\"===h&&\"radio\"===f.type&&null!=f.name&&ab(e,f);vb(h,g);var l=vb(h,f);for(g=0;g<k.length;g+=2){var m=k[g],q=k[g+1];\"style\"===m?sb(e,q):\"dangerouslySetInnerHTML\"===m?nb(e,q):\"children\"===m?ob(e,q):ta(e,m,q,l)}switch(h){case \"input\":bb(e,f);break;case \"textarea\":ib(e,f);break;case \"select\":var r=e._wrapperState.wasMultiple;e._wrapperState.wasMultiple=!!f.multiple;var y=f.value;null!=y?fb(e,!!f.multiple,y,!1):r!==!!f.multiple&&(null!=f.defaultValue?fb(e,!!f.multiple,\nf.defaultValue,!0):fb(e,!!f.multiple,f.multiple?[]:\"\",!1))}e[Pf]=f}catch(t){W(a,a.return,t)}}break;case 6:dk(b,a);fk(a);if(d&4){if(null===a.stateNode)throw Error(p(162));e=a.stateNode;f=a.memoizedProps;try{e.nodeValue=f}catch(t){W(a,a.return,t)}}break;case 3:dk(b,a);fk(a);if(d&4&&null!==c&&c.memoizedState.isDehydrated)try{bd(b.containerInfo)}catch(t){W(a,a.return,t)}break;case 4:dk(b,a);fk(a);break;case 13:dk(b,a);fk(a);e=a.child;e.flags&8192&&(f=null!==e.memoizedState,e.stateNode.isHidden=f,!f||\nnull!==e.alternate&&null!==e.alternate.memoizedState||(gk=B()));d&4&&bk(a);break;case 22:m=null!==c&&null!==c.memoizedState;a.mode&1?(U=(l=U)||m,dk(b,a),U=l):dk(b,a);fk(a);if(d&8192){l=null!==a.memoizedState;if((a.stateNode.isHidden=l)&&!m&&0!==(a.mode&1))for(V=a,m=a.child;null!==m;){for(q=V=m;null!==V;){r=V;y=r.child;switch(r.tag){case 0:case 11:case 14:case 15:Qj(4,r,r.return);break;case 1:Mj(r,r.return);var n=r.stateNode;if(\"function\"===typeof n.componentWillUnmount){d=r;c=r.return;try{b=d,n.props=\nb.memoizedProps,n.state=b.memoizedState,n.componentWillUnmount()}catch(t){W(d,c,t)}}break;case 5:Mj(r,r.return);break;case 22:if(null!==r.memoizedState){hk(q);continue}}null!==y?(y.return=r,V=y):hk(q)}m=m.sibling}a:for(m=null,q=a;;){if(5===q.tag){if(null===m){m=q;try{e=q.stateNode,l?(f=e.style,\"function\"===typeof f.setProperty?f.setProperty(\"display\",\"none\",\"important\"):f.display=\"none\"):(h=q.stateNode,k=q.memoizedProps.style,g=void 0!==k&&null!==k&&k.hasOwnProperty(\"display\")?k.display:null,h.style.display=\nrb(\"display\",g))}catch(t){W(a,a.return,t)}}}else if(6===q.tag){if(null===m)try{q.stateNode.nodeValue=l?\"\":q.memoizedProps}catch(t){W(a,a.return,t)}}else if((22!==q.tag&&23!==q.tag||null===q.memoizedState||q===a)&&null!==q.child){q.child.return=q;q=q.child;continue}if(q===a)break a;for(;null===q.sibling;){if(null===q.return||q.return===a)break a;m===q&&(m=null);q=q.return}m===q&&(m=null);q.sibling.return=q.return;q=q.sibling}}break;case 19:dk(b,a);fk(a);d&4&&bk(a);break;case 21:break;default:dk(b,\na),fk(a)}}function fk(a){var b=a.flags;if(b&2){try{a:{for(var c=a.return;null!==c;){if(Uj(c)){var d=c;break a}c=c.return}throw Error(p(160));}switch(d.tag){case 5:var e=d.stateNode;d.flags&32&&(ob(e,\"\"),d.flags&=-33);var f=Vj(a);Xj(a,f,e);break;case 3:case 4:var g=d.stateNode.containerInfo,h=Vj(a);Wj(a,h,g);break;default:throw Error(p(161));}}catch(k){W(a,a.return,k)}a.flags&=-3}b&4096&&(a.flags&=-4097)}function ik(a,b,c){V=a;jk(a,b,c)}\nfunction jk(a,b,c){for(var d=0!==(a.mode&1);null!==V;){var e=V,f=e.child;if(22===e.tag&&d){var g=null!==e.memoizedState||Kj;if(!g){var h=e.alternate,k=null!==h&&null!==h.memoizedState||U;h=Kj;var l=U;Kj=g;if((U=k)&&!l)for(V=e;null!==V;)g=V,k=g.child,22===g.tag&&null!==g.memoizedState?kk(e):null!==k?(k.return=g,V=k):kk(e);for(;null!==f;)V=f,jk(f,b,c),f=f.sibling;V=e;Kj=h;U=l}lk(a,b,c)}else 0!==(e.subtreeFlags&8772)&&null!==f?(f.return=e,V=f):lk(a,b,c)}}\nfunction lk(a){for(;null!==V;){var b=V;if(0!==(b.flags&8772)){var c=b.alternate;try{if(0!==(b.flags&8772))switch(b.tag){case 0:case 11:case 15:U||Rj(5,b);break;case 1:var d=b.stateNode;if(b.flags&4&&!U)if(null===c)d.componentDidMount();else{var e=b.elementType===b.type?c.memoizedProps:Lg(b.type,c.memoizedProps);d.componentDidUpdate(e,c.memoizedState,d.__reactInternalSnapshotBeforeUpdate)}var f=b.updateQueue;null!==f&&ih(b,f,d);break;case 3:var g=b.updateQueue;if(null!==g){c=null;if(null!==b.child)switch(b.child.tag){case 5:c=\nb.child.stateNode;break;case 1:c=b.child.stateNode}ih(b,g,c)}break;case 5:var h=b.stateNode;if(null===c&&b.flags&4){c=h;var k=b.memoizedProps;switch(b.type){case \"button\":case \"input\":case \"select\":case \"textarea\":k.autoFocus&&c.focus();break;case \"img\":k.src&&(c.src=k.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(null===b.memoizedState){var l=b.alternate;if(null!==l){var m=l.memoizedState;if(null!==m){var q=m.dehydrated;null!==q&&bd(q)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;\ndefault:throw Error(p(163));}U||b.flags&512&&Sj(b)}catch(r){W(b,b.return,r)}}if(b===a){V=null;break}c=b.sibling;if(null!==c){c.return=b.return;V=c;break}V=b.return}}function hk(a){for(;null!==V;){var b=V;if(b===a){V=null;break}var c=b.sibling;if(null!==c){c.return=b.return;V=c;break}V=b.return}}\nfunction kk(a){for(;null!==V;){var b=V;try{switch(b.tag){case 0:case 11:case 15:var c=b.return;try{Rj(4,b)}catch(k){W(b,c,k)}break;case 1:var d=b.stateNode;if(\"function\"===typeof d.componentDidMount){var e=b.return;try{d.componentDidMount()}catch(k){W(b,e,k)}}var f=b.return;try{Sj(b)}catch(k){W(b,f,k)}break;case 5:var g=b.return;try{Sj(b)}catch(k){W(b,g,k)}}}catch(k){W(b,b.return,k)}if(b===a){V=null;break}var h=b.sibling;if(null!==h){h.return=b.return;V=h;break}V=b.return}}\nvar mk=Math.ceil,nk=ua.ReactCurrentDispatcher,ok=ua.ReactCurrentOwner,pk=ua.ReactCurrentBatchConfig,K=0,R=null,Y=null,Z=0,gj=0,fj=Uf(0),T=0,qk=null,hh=0,rk=0,sk=0,tk=null,uk=null,gk=0,Hj=Infinity,vk=null,Pi=!1,Qi=null,Si=null,wk=!1,xk=null,yk=0,zk=0,Ak=null,Bk=-1,Ck=0;function L(){return 0!==(K&6)?B():-1!==Bk?Bk:Bk=B()}\nfunction lh(a){if(0===(a.mode&1))return 1;if(0!==(K&2)&&0!==Z)return Z&-Z;if(null!==Kg.transition)return 0===Ck&&(Ck=yc()),Ck;a=C;if(0!==a)return a;a=window.event;a=void 0===a?16:jd(a.type);return a}function mh(a,b,c,d){if(50<zk)throw zk=0,Ak=null,Error(p(185));Ac(a,c,d);if(0===(K&2)||a!==R)a===R&&(0===(K&2)&&(rk|=c),4===T&&Dk(a,Z)),Ek(a,d),1===c&&0===K&&0===(b.mode&1)&&(Hj=B()+500,fg&&jg())}\nfunction Ek(a,b){var c=a.callbackNode;wc(a,b);var d=uc(a,a===R?Z:0);if(0===d)null!==c&&bc(c),a.callbackNode=null,a.callbackPriority=0;else if(b=d&-d,a.callbackPriority!==b){null!=c&&bc(c);if(1===b)0===a.tag?ig(Fk.bind(null,a)):hg(Fk.bind(null,a)),Jf(function(){0===(K&6)&&jg()}),c=null;else{switch(Dc(d)){case 1:c=fc;break;case 4:c=gc;break;case 16:c=hc;break;case 536870912:c=jc;break;default:c=hc}c=Gk(c,Hk.bind(null,a))}a.callbackPriority=b;a.callbackNode=c}}\nfunction Hk(a,b){Bk=-1;Ck=0;if(0!==(K&6))throw Error(p(327));var c=a.callbackNode;if(Ik()&&a.callbackNode!==c)return null;var d=uc(a,a===R?Z:0);if(0===d)return null;if(0!==(d&30)||0!==(d&a.expiredLanes)||b)b=Jk(a,d);else{b=d;var e=K;K|=2;var f=Kk();if(R!==a||Z!==b)vk=null,Hj=B()+500,Lk(a,b);do try{Mk();break}catch(h){Nk(a,h)}while(1);Qg();nk.current=f;K=e;null!==Y?b=0:(R=null,Z=0,b=T)}if(0!==b){2===b&&(e=xc(a),0!==e&&(d=e,b=Ok(a,e)));if(1===b)throw c=qk,Lk(a,0),Dk(a,d),Ek(a,B()),c;if(6===b)Dk(a,d);\nelse{e=a.current.alternate;if(0===(d&30)&&!Pk(e)&&(b=Jk(a,d),2===b&&(f=xc(a),0!==f&&(d=f,b=Ok(a,f))),1===b))throw c=qk,Lk(a,0),Dk(a,d),Ek(a,B()),c;a.finishedWork=e;a.finishedLanes=d;switch(b){case 0:case 1:throw Error(p(345));case 2:Qk(a,uk,vk);break;case 3:Dk(a,d);if((d&130023424)===d&&(b=gk+500-B(),10<b)){if(0!==uc(a,0))break;e=a.suspendedLanes;if((e&d)!==d){L();a.pingedLanes|=a.suspendedLanes&e;break}a.timeoutHandle=Ff(Qk.bind(null,a,uk,vk),b);break}Qk(a,uk,vk);break;case 4:Dk(a,d);if((d&4194240)===\nd)break;b=a.eventTimes;for(e=-1;0<d;){var g=31-oc(d);f=1<<g;g=b[g];g>e&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*mk(d/1960))-d;if(10<d){a.timeoutHandle=Ff(Qk.bind(null,a,uk,vk),d);break}Qk(a,uk,vk);break;case 5:Qk(a,uk,vk);break;default:throw Error(p(329));}}}Ek(a,B());return a.callbackNode===c?Hk.bind(null,a):null}\nfunction Ok(a,b){var c=tk;a.current.memoizedState.isDehydrated&&(Lk(a,b).flags|=256);a=Jk(a,b);2!==a&&(b=uk,uk=c,null!==b&&Gj(b));return a}function Gj(a){null===uk?uk=a:uk.push.apply(uk,a)}\nfunction Pk(a){for(var b=a;;){if(b.flags&16384){var c=b.updateQueue;if(null!==c&&(c=c.stores,null!==c))for(var d=0;d<c.length;d++){var e=c[d],f=e.getSnapshot;e=e.value;try{if(!He(f(),e))return!1}catch(g){return!1}}}c=b.child;if(b.subtreeFlags&16384&&null!==c)c.return=b,b=c;else{if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return!0;b=b.return}b.sibling.return=b.return;b=b.sibling}}return!0}\nfunction Dk(a,b){b&=~sk;b&=~rk;a.suspendedLanes|=b;a.pingedLanes&=~b;for(a=a.expirationTimes;0<b;){var c=31-oc(b),d=1<<c;a[c]=-1;b&=~d}}function Fk(a){if(0!==(K&6))throw Error(p(327));Ik();var b=uc(a,0);if(0===(b&1))return Ek(a,B()),null;var c=Jk(a,b);if(0!==a.tag&&2===c){var d=xc(a);0!==d&&(b=d,c=Ok(a,d))}if(1===c)throw c=qk,Lk(a,0),Dk(a,b),Ek(a,B()),c;if(6===c)throw Error(p(345));a.finishedWork=a.current.alternate;a.finishedLanes=b;Qk(a,uk,vk);Ek(a,B());return null}\nfunction Rk(a,b){var c=K;K|=1;try{return a(b)}finally{K=c,0===K&&(Hj=B()+500,fg&&jg())}}function Sk(a){null!==xk&&0===xk.tag&&0===(K&6)&&Ik();var b=K;K|=1;var c=pk.transition,d=C;try{if(pk.transition=null,C=1,a)return a()}finally{C=d,pk.transition=c,K=b,0===(K&6)&&jg()}}function Ij(){gj=fj.current;E(fj)}\nfunction Lk(a,b){a.finishedWork=null;a.finishedLanes=0;var c=a.timeoutHandle;-1!==c&&(a.timeoutHandle=-1,Gf(c));if(null!==Y)for(c=Y.return;null!==c;){var d=c;wg(d);switch(d.tag){case 1:d=d.type.childContextTypes;null!==d&&void 0!==d&&$f();break;case 3:Jh();E(Wf);E(H);Oh();break;case 5:Lh(d);break;case 4:Jh();break;case 13:E(M);break;case 19:E(M);break;case 10:Rg(d.type._context);break;case 22:case 23:Ij()}c=c.return}R=a;Y=a=wh(a.current,null);Z=gj=b;T=0;qk=null;sk=rk=hh=0;uk=tk=null;if(null!==Wg){for(b=\n0;b<Wg.length;b++)if(c=Wg[b],d=c.interleaved,null!==d){c.interleaved=null;var e=d.next,f=c.pending;if(null!==f){var g=f.next;f.next=e;d.next=g}c.pending=d}Wg=null}return a}\nfunction Nk(a,b){do{var c=Y;try{Qg();Ph.current=ai;if(Sh){for(var d=N.memoizedState;null!==d;){var e=d.queue;null!==e&&(e.pending=null);d=d.next}Sh=!1}Rh=0;P=O=N=null;Th=!1;Uh=0;ok.current=null;if(null===c||null===c.return){T=1;qk=b;Y=null;break}a:{var f=a,g=c.return,h=c,k=b;b=Z;h.flags|=32768;if(null!==k&&\"object\"===typeof k&&\"function\"===typeof k.then){var l=k,m=h,q=m.tag;if(0===(m.mode&1)&&(0===q||11===q||15===q)){var r=m.alternate;r?(m.updateQueue=r.updateQueue,m.memoizedState=r.memoizedState,\nm.lanes=r.lanes):(m.updateQueue=null,m.memoizedState=null)}var y=Vi(g);if(null!==y){y.flags&=-257;Wi(y,g,h,f,b);y.mode&1&&Ti(f,l,b);b=y;k=l;var n=b.updateQueue;if(null===n){var t=new Set;t.add(k);b.updateQueue=t}else n.add(k);break a}else{if(0===(b&1)){Ti(f,l,b);uj();break a}k=Error(p(426))}}else if(I&&h.mode&1){var J=Vi(g);if(null!==J){0===(J.flags&65536)&&(J.flags|=256);Wi(J,g,h,f,b);Jg(Ki(k,h));break a}}f=k=Ki(k,h);4!==T&&(T=2);null===tk?tk=[f]:tk.push(f);f=g;do{switch(f.tag){case 3:f.flags|=65536;\nb&=-b;f.lanes|=b;var x=Oi(f,k,b);fh(f,x);break a;case 1:h=k;var w=f.type,u=f.stateNode;if(0===(f.flags&128)&&(\"function\"===typeof w.getDerivedStateFromError||null!==u&&\"function\"===typeof u.componentDidCatch&&(null===Si||!Si.has(u)))){f.flags|=65536;b&=-b;f.lanes|=b;var F=Ri(f,h,b);fh(f,F);break a}}f=f.return}while(null!==f)}Tk(c)}catch(na){b=na;Y===c&&null!==c&&(Y=c=c.return);continue}break}while(1)}function Kk(){var a=nk.current;nk.current=ai;return null===a?ai:a}\nfunction uj(){if(0===T||3===T||2===T)T=4;null===R||0===(hh&268435455)&&0===(rk&268435455)||Dk(R,Z)}function Jk(a,b){var c=K;K|=2;var d=Kk();if(R!==a||Z!==b)vk=null,Lk(a,b);do try{Uk();break}catch(e){Nk(a,e)}while(1);Qg();K=c;nk.current=d;if(null!==Y)throw Error(p(261));R=null;Z=0;return T}function Uk(){for(;null!==Y;)Vk(Y)}function Mk(){for(;null!==Y&&!cc();)Vk(Y)}function Vk(a){var b=Wk(a.alternate,a,gj);a.memoizedProps=a.pendingProps;null===b?Tk(a):Y=b;ok.current=null}\nfunction Tk(a){var b=a;do{var c=b.alternate;a=b.return;if(0===(b.flags&32768)){if(c=Fj(c,b,gj),null!==c){Y=c;return}}else{c=Jj(c,b);if(null!==c){c.flags&=32767;Y=c;return}if(null!==a)a.flags|=32768,a.subtreeFlags=0,a.deletions=null;else{T=6;Y=null;return}}b=b.sibling;if(null!==b){Y=b;return}Y=b=a}while(null!==b);0===T&&(T=5)}function Qk(a,b,c){var d=C,e=pk.transition;try{pk.transition=null,C=1,Xk(a,b,c,d)}finally{pk.transition=e,C=d}return null}\nfunction Xk(a,b,c,d){do Ik();while(null!==xk);if(0!==(K&6))throw Error(p(327));c=a.finishedWork;var e=a.finishedLanes;if(null===c)return null;a.finishedWork=null;a.finishedLanes=0;if(c===a.current)throw Error(p(177));a.callbackNode=null;a.callbackPriority=0;var f=c.lanes|c.childLanes;Bc(a,f);a===R&&(Y=R=null,Z=0);0===(c.subtreeFlags&2064)&&0===(c.flags&2064)||wk||(wk=!0,Gk(hc,function(){Ik();return null}));f=0!==(c.flags&15990);if(0!==(c.subtreeFlags&15990)||f){f=pk.transition;pk.transition=null;\nvar g=C;C=1;var h=K;K|=4;ok.current=null;Pj(a,c);ek(c,a);Oe(Df);dd=!!Cf;Df=Cf=null;a.current=c;ik(c,a,e);dc();K=h;C=g;pk.transition=f}else a.current=c;wk&&(wk=!1,xk=a,yk=e);f=a.pendingLanes;0===f&&(Si=null);mc(c.stateNode,d);Ek(a,B());if(null!==b)for(d=a.onRecoverableError,c=0;c<b.length;c++)e=b[c],d(e.value,{componentStack:e.stack,digest:e.digest});if(Pi)throw Pi=!1,a=Qi,Qi=null,a;0!==(yk&1)&&0!==a.tag&&Ik();f=a.pendingLanes;0!==(f&1)?a===Ak?zk++:(zk=0,Ak=a):zk=0;jg();return null}\nfunction Ik(){if(null!==xk){var a=Dc(yk),b=pk.transition,c=C;try{pk.transition=null;C=16>a?16:a;if(null===xk)var d=!1;else{a=xk;xk=null;yk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;k<h.length;k++){var l=h[k];for(V=l;null!==V;){var m=V;switch(m.tag){case 0:case 11:case 15:Qj(8,m,f)}var q=m.child;if(null!==q)q.return=m,V=q;else for(;null!==V;){m=V;var r=m.sibling,y=m.return;Tj(m);if(m===\nl){V=null;break}if(null!==r){r.return=y;V=r;break}V=y}}}var n=f.alternate;if(null!==n){var t=n.child;if(null!==t){n.child=null;do{var J=t.sibling;t.sibling=null;t=J}while(null!==t)}}V=f}}if(0!==(f.subtreeFlags&2064)&&null!==g)g.return=f,V=g;else b:for(;null!==V;){f=V;if(0!==(f.flags&2048))switch(f.tag){case 0:case 11:case 15:Qj(9,f,f.return)}var x=f.sibling;if(null!==x){x.return=f.return;V=x;break b}V=f.return}}var w=a.current;for(V=w;null!==V;){g=V;var u=g.child;if(0!==(g.subtreeFlags&2064)&&null!==\nu)u.return=g,V=u;else b:for(g=w;null!==V;){h=V;if(0!==(h.flags&2048))try{switch(h.tag){case 0:case 11:case 15:Rj(9,h)}}catch(na){W(h,h.return,na)}if(h===g){V=null;break b}var F=h.sibling;if(null!==F){F.return=h.return;V=F;break b}V=h.return}}K=e;jg();if(lc&&\"function\"===typeof lc.onPostCommitFiberRoot)try{lc.onPostCommitFiberRoot(kc,a)}catch(na){}d=!0}return d}finally{C=c,pk.transition=b}}return!1}function Yk(a,b,c){b=Ki(c,b);b=Oi(a,b,1);a=dh(a,b,1);b=L();null!==a&&(Ac(a,1,b),Ek(a,b))}\nfunction W(a,b,c){if(3===a.tag)Yk(a,a,c);else for(;null!==b;){if(3===b.tag){Yk(b,a,c);break}else if(1===b.tag){var d=b.stateNode;if(\"function\"===typeof b.type.getDerivedStateFromError||\"function\"===typeof d.componentDidCatch&&(null===Si||!Si.has(d))){a=Ki(c,a);a=Ri(b,a,1);b=dh(b,a,1);a=L();null!==b&&(Ac(b,1,a),Ek(b,a));break}}b=b.return}}\nfunction Ui(a,b,c){var d=a.pingCache;null!==d&&d.delete(b);b=L();a.pingedLanes|=a.suspendedLanes&c;R===a&&(Z&c)===c&&(4===T||3===T&&(Z&130023424)===Z&&500>B()-gk?Lk(a,0):sk|=c);Ek(a,b)}function Zk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=L();a=Zg(a,b);null!==a&&(Ac(a,b,c),Ek(a,c))}function vj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Zk(a,c)}\nfunction ck(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Zk(a,c)}var Wk;\nWk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)Ug=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return Ug=!1,zj(a,b,c);Ug=0!==(a.flags&131072)?!0:!1}else Ug=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;jj(a,b);a=b.pendingProps;var e=Yf(b,H.current);Tg(b,c);e=Xh(null,b,d,a,e,c);var f=bi();b.flags|=1;\"object\"===typeof e&&null!==e&&\"function\"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=\nnull,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,ah(b),e.updater=nh,b.stateNode=e,e._reactInternals=b,rh(b,d,a,c),b=kj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Yi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{jj(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=$k(d);a=Lg(d,a);switch(e){case 0:b=dj(null,b,d,a,c);break a;case 1:b=ij(null,b,d,a,c);break a;case 11:b=Zi(null,b,d,a,c);break a;case 14:b=aj(null,b,d,Lg(d.type,a),c);break a}throw Error(p(306,\nd,\"\"));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),dj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),ij(a,b,d,e,c);case 3:a:{lj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;bh(a,b);gh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=\nf,b.memoizedState=f,b.flags&256){e=Ki(Error(p(423)),b);b=mj(a,b,d,c,e);break a}else if(d!==e){e=Ki(Error(p(424)),b);b=mj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Ch(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=$i(a,b,c);break a}Yi(a,b,d,c)}b=b.child}return b;case 5:return Kh(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),\nhj(a,b),Yi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return pj(a,b,c);case 4:return Ih(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Bh(b,null,d,c):Yi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),Zi(a,b,d,e,c);case 7:return Yi(a,b,b.pendingProps,c),b.child;case 8:return Yi(a,b,b.pendingProps.children,c),b.child;case 12:return Yi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;\ng=e.value;G(Mg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=$i(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=ch(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);Sg(f.return,\nc,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);Sg(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Yi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,Tg(b,c),e=Vg(e),d=d(e),b.flags|=1,Yi(a,b,d,c),\nb.child;case 14:return d=b.type,e=Lg(d,b.pendingProps),e=Lg(d.type,e),aj(a,b,d,e,c);case 15:return cj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),jj(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,Tg(b,c),ph(b,d,e),rh(b,d,e,c),kj(null,b,d,!0,a,c);case 19:return yj(a,b,c);case 22:return ej(a,b,c)}throw Error(p(156,b.tag));};function Gk(a,b){return ac(a,b)}\nfunction al(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new al(a,b,c,d)}function bj(a){a=a.prototype;return!(!a||!a.isReactComponent)}\nfunction $k(a){if(\"function\"===typeof a)return bj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}\nfunction wh(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};\nc.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}\nfunction yh(a,b,c,d,e,f){var g=2;d=a;if(\"function\"===typeof a)bj(a)&&(g=1);else if(\"string\"===typeof a)g=5;else a:switch(a){case ya:return Ah(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return qj(c,e,f,b);default:if(\"object\"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;\nbreak a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,\"\"));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Ah(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function qj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function xh(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}\nfunction zh(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}\nfunction bl(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=\nnull}function cl(a,b,c,d,e,f,g,h,k){a=new bl(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};ah(f);return a}function dl(a,b,c){var d=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:wa,key:null==d?null:\"\"+d,children:a,containerInfo:b,implementation:c}}\nfunction el(a){if(!a)return Vf;a=a._reactInternals;a:{if(Vb(a)!==a||1!==a.tag)throw Error(p(170));var b=a;do{switch(b.tag){case 3:b=b.stateNode.context;break a;case 1:if(Zf(b.type)){b=b.stateNode.__reactInternalMemoizedMergedChildContext;break a}}b=b.return}while(null!==b);throw Error(p(171));}if(1===a.tag){var c=a.type;if(Zf(c))return bg(a,c,b)}return b}\nfunction fl(a,b,c,d,e,f,g,h,k){a=cl(c,d,!0,a,e,f,g,h,k);a.context=el(null);c=a.current;d=L();e=lh(c);f=ch(d,e);f.callback=void 0!==b&&null!==b?b:null;dh(c,f,e);a.current.lanes=e;Ac(a,e,d);Ek(a,d);return a}function gl(a,b,c,d){var e=b.current,f=L(),g=lh(e);c=el(c);null===b.context?b.context=c:b.pendingContext=c;b=ch(f,g);b.payload={element:a};d=void 0===d?null:d;null!==d&&(b.callback=d);a=dh(e,b,g);null!==a&&(mh(a,e,g,f),eh(a,e,g));return g}\nfunction hl(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function il(a,b){a=a.memoizedState;if(null!==a&&null!==a.dehydrated){var c=a.retryLane;a.retryLane=0!==c&&c<b?c:b}}function jl(a,b){il(a,b);(a=a.alternate)&&il(a,b)}function kl(){return null}var ll=\"function\"===typeof reportError?reportError:function(a){console.error(a)};function ml(a){this._internalRoot=a}\nnl.prototype.render=ml.prototype.render=function(a){var b=this._internalRoot;if(null===b)throw Error(p(409));gl(a,b,null,null)};nl.prototype.unmount=ml.prototype.unmount=function(){var a=this._internalRoot;if(null!==a){this._internalRoot=null;var b=a.containerInfo;Sk(function(){gl(null,a,null,null)});b[uf]=null}};function nl(a){this._internalRoot=a}\nnl.prototype.unstable_scheduleHydration=function(a){if(a){var b=Hc();a={blockedOn:null,target:a,priority:b};for(var c=0;c<Qc.length&&0!==b&&b<Qc[c].priority;c++);Qc.splice(c,0,a);0===c&&Vc(a)}};function ol(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType)}function pl(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType&&(8!==a.nodeType||\" react-mount-point-unstable \"!==a.nodeValue))}function ql(){}\nfunction rl(a,b,c,d,e){if(e){if(\"function\"===typeof d){var f=d;d=function(){var a=hl(g);f.call(a)}}var g=fl(b,d,a,0,null,!1,!1,\"\",ql);a._reactRootContainer=g;a[uf]=g.current;sf(8===a.nodeType?a.parentNode:a);Sk();return g}for(;e=a.lastChild;)a.removeChild(e);if(\"function\"===typeof d){var h=d;d=function(){var a=hl(k);h.call(a)}}var k=cl(a,0,!1,null,null,!1,!1,\"\",ql);a._reactRootContainer=k;a[uf]=k.current;sf(8===a.nodeType?a.parentNode:a);Sk(function(){gl(b,k,c,d)});return k}\nfunction sl(a,b,c,d,e){var f=c._reactRootContainer;if(f){var g=f;if(\"function\"===typeof e){var h=e;e=function(){var a=hl(g);h.call(a)}}gl(b,g,a,e)}else g=rl(c,b,a,e,d);return hl(g)}Ec=function(a){switch(a.tag){case 3:var b=a.stateNode;if(b.current.memoizedState.isDehydrated){var c=tc(b.pendingLanes);0!==c&&(Cc(b,c|1),Ek(b,B()),0===(K&6)&&(Hj=B()+500,jg()))}break;case 13:Sk(function(){var b=Zg(a,1);if(null!==b){var c=L();mh(b,a,1,c)}}),jl(a,1)}};\nFc=function(a){if(13===a.tag){var b=Zg(a,134217728);if(null!==b){var c=L();mh(b,a,134217728,c)}jl(a,134217728)}};Gc=function(a){if(13===a.tag){var b=lh(a),c=Zg(a,b);if(null!==c){var d=L();mh(c,a,b,d)}jl(a,b)}};Hc=function(){return C};Ic=function(a,b){var c=C;try{return C=a,b()}finally{C=c}};\nyb=function(a,b,c){switch(b){case \"input\":bb(a,c);b=c.name;if(\"radio\"===c.type&&null!=b){for(c=a;c.parentNode;)c=c.parentNode;c=c.querySelectorAll(\"input[name=\"+JSON.stringify(\"\"+b)+'][type=\"radio\"]');for(b=0;b<c.length;b++){var d=c[b];if(d!==a&&d.form===a.form){var e=Db(d);if(!e)throw Error(p(90));Wa(d);bb(d,e)}}}break;case \"textarea\":ib(a,c);break;case \"select\":b=c.value,null!=b&&fb(a,!!c.multiple,b,!1)}};Gb=Rk;Hb=Sk;\nvar tl={usingClientEntryPoint:!1,Events:[Cb,ue,Db,Eb,Fb,Rk]},ul={findFiberByHostInstance:Wc,bundleType:0,version:\"18.2.0\",rendererPackageName:\"react-dom\"};\nvar vl={bundleType:ul.bundleType,version:ul.version,rendererPackageName:ul.rendererPackageName,rendererConfig:ul.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:ua.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){a=Zb(a);return null===a?null:a.stateNode},findFiberByHostInstance:ul.findFiberByHostInstance||\nkl,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:\"18.2.0-next-9e3b772b8-20220608\"};if(\"undefined\"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__){var wl=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!wl.isDisabled&&wl.supportsFiber)try{kc=wl.inject(vl),lc=wl}catch(a){}}exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=tl;\nexports.createPortal=function(a,b){var c=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!ol(b))throw Error(p(200));return dl(a,b,null,c)};exports.createRoot=function(a,b){if(!ol(a))throw Error(p(299));var c=!1,d=\"\",e=ll;null!==b&&void 0!==b&&(!0===b.unstable_strictMode&&(c=!0),void 0!==b.identifierPrefix&&(d=b.identifierPrefix),void 0!==b.onRecoverableError&&(e=b.onRecoverableError));b=cl(a,1,!1,null,null,c,!1,d,e);a[uf]=b.current;sf(8===a.nodeType?a.parentNode:a);return new ml(b)};\nexports.findDOMNode=function(a){if(null==a)return null;if(1===a.nodeType)return a;var b=a._reactInternals;if(void 0===b){if(\"function\"===typeof a.render)throw Error(p(188));a=Object.keys(a).join(\",\");throw Error(p(268,a));}a=Zb(b);a=null===a?null:a.stateNode;return a};exports.flushSync=function(a){return Sk(a)};exports.hydrate=function(a,b,c){if(!pl(b))throw Error(p(200));return sl(null,a,b,!0,c)};\nexports.hydrateRoot=function(a,b,c){if(!ol(a))throw Error(p(405));var d=null!=c&&c.hydratedSources||null,e=!1,f=\"\",g=ll;null!==c&&void 0!==c&&(!0===c.unstable_strictMode&&(e=!0),void 0!==c.identifierPrefix&&(f=c.identifierPrefix),void 0!==c.onRecoverableError&&(g=c.onRecoverableError));b=fl(b,null,a,1,null!=c?c:null,e,!1,f,g);a[uf]=b.current;sf(a);if(d)for(a=0;a<d.length;a++)c=d[a],e=c._getVersion,e=e(c._source),null==b.mutableSourceEagerHydrationData?b.mutableSourceEagerHydrationData=[c,e]:b.mutableSourceEagerHydrationData.push(c,\ne);return new nl(b)};exports.render=function(a,b,c){if(!pl(b))throw Error(p(200));return sl(null,a,b,!1,c)};exports.unmountComponentAtNode=function(a){if(!pl(a))throw Error(p(40));return a._reactRootContainer?(Sk(function(){sl(null,null,a,!1,function(){a._reactRootContainer=null;a[uf]=null})}),!0):!1};exports.unstable_batchedUpdates=Rk;\nexports.unstable_renderSubtreeIntoContainer=function(a,b,c,d){if(!pl(c))throw Error(p(200));if(null==a||void 0===a._reactInternals)throw Error(p(38));return sl(a,b,c,!1,d)};exports.version=\"18.2.0-next-9e3b772b8-20220608\";\n","'use strict';\n\nvar m = require('react-dom');\nif (process.env.NODE_ENV === 'production') {\n exports.createRoot = m.createRoot;\n exports.hydrateRoot = m.hydrateRoot;\n} else {\n var i = m.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n exports.createRoot = function(c, o) {\n i.usingClientEntryPoint = true;\n try {\n return m.createRoot(c, o);\n } finally {\n i.usingClientEntryPoint = false;\n }\n };\n exports.hydrateRoot = function(c, h, o) {\n i.usingClientEntryPoint = true;\n try {\n return m.hydrateRoot(c, h, o);\n } finally {\n i.usingClientEntryPoint = false;\n }\n };\n}\n","'use strict';\n\nfunction checkDCE() {\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\n if (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'\n ) {\n return;\n }\n if (process.env.NODE_ENV !== 'production') {\n // This branch is unreachable because this function is only called\n // in production, but the condition is true only in development.\n // Therefore if the branch is still here, dead code elimination wasn't\n // properly applied.\n // Don't change the message. React DevTools relies on it. Also make sure\n // this message doesn't occur elsewhere in this function, or it will cause\n // a false positive.\n throw new Error('^_^');\n }\n try {\n // Verify that the code above has been dead code eliminated (DCE'd).\n __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);\n } catch (err) {\n // DevTools shouldn't crash React, no matter what.\n // We should still report in case we break this code.\n console.error(err);\n }\n}\n\nif (process.env.NODE_ENV === 'production') {\n // DCE check should happen before ReactDOM bundle executes so that\n // DevTools can report bad minification during injection.\n checkDCE();\n module.exports = require('./cjs/react-dom.production.min.js');\n} else {\n module.exports = require('./cjs/react-dom.development.js');\n}\n","/**\n * @license React\n * react-jsx-runtime.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var f=require(\"react\"),k=Symbol.for(\"react.element\"),l=Symbol.for(\"react.fragment\"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};\nfunction q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=\"\"+g);void 0!==a.key&&(e=\"\"+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}exports.Fragment=l;exports.jsx=q;exports.jsxs=q;\n","/**\n * @license React\n * react.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var l=Symbol.for(\"react.element\"),n=Symbol.for(\"react.portal\"),p=Symbol.for(\"react.fragment\"),q=Symbol.for(\"react.strict_mode\"),r=Symbol.for(\"react.profiler\"),t=Symbol.for(\"react.provider\"),u=Symbol.for(\"react.context\"),v=Symbol.for(\"react.forward_ref\"),w=Symbol.for(\"react.suspense\"),x=Symbol.for(\"react.memo\"),y=Symbol.for(\"react.lazy\"),z=Symbol.iterator;function A(a){if(null===a||\"object\"!==typeof a)return null;a=z&&a[z]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}\nvar B={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}E.prototype.isReactComponent={};\nE.prototype.setState=function(a,b){if(\"object\"!==typeof a&&\"function\"!==typeof a&&null!=a)throw Error(\"setState(...): takes an object of state variables to update or a function which returns an object of state variables.\");this.updater.enqueueSetState(this,a,b,\"setState\")};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,\"forceUpdate\")};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}var H=G.prototype=new F;\nH.constructor=G;C(H,E.prototype);H.isPureReactComponent=!0;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:!0,ref:!0,__self:!0,__source:!0};\nfunction M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=\"\"+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1<g){for(var f=Array(g),m=0;m<g;m++)f[m]=arguments[m+2];c.children=f}if(a&&a.defaultProps)for(d in g=a.defaultProps,g)void 0===c[d]&&(c[d]=g[d]);return{$$typeof:l,type:a,key:k,ref:h,props:c,_owner:K.current}}\nfunction N(a,b){return{$$typeof:l,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}function O(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===l}function escape(a){var b={\"=\":\"=0\",\":\":\"=2\"};return\"$\"+a.replace(/[=:]/g,function(a){return b[a]})}var P=/\\/+/g;function Q(a,b){return\"object\"===typeof a&&null!==a&&null!=a.key?escape(\"\"+a.key):b.toString(36)}\nfunction R(a,b,e,d,c){var k=typeof a;if(\"undefined\"===k||\"boolean\"===k)a=null;var h=!1;if(null===a)h=!0;else switch(k){case \"string\":case \"number\":h=!0;break;case \"object\":switch(a.$$typeof){case l:case n:h=!0}}if(h)return h=a,c=c(h),a=\"\"===d?\".\"+Q(h,0):d,I(c)?(e=\"\",null!=a&&(e=a.replace(P,\"$&/\")+\"/\"),R(c,b,e,\"\",function(a){return a})):null!=c&&(O(c)&&(c=N(c,e+(!c.key||h&&h.key===c.key?\"\":(\"\"+c.key).replace(P,\"$&/\")+\"/\")+a)),b.push(c)),1;h=0;d=\"\"===d?\".\":d+\":\";if(I(a))for(var g=0;g<a.length;g++){k=\na[g];var f=d+Q(k,g);h+=R(k,b,e,f,c)}else if(f=A(a),\"function\"===typeof f)for(a=f.call(a),g=0;!(k=a.next()).done;)k=k.value,f=d+Q(k,g++),h+=R(k,b,e,f,c);else if(\"object\"===k)throw b=String(a),Error(\"Objects are not valid as a React child (found: \"+(\"[object Object]\"===b?\"object with keys {\"+Object.keys(a).join(\", \")+\"}\":b)+\"). If you meant to render a collection of children, use an array instead.\");return h}\nfunction S(a,b,e){if(null==a)return a;var d=[],c=0;R(a,d,\"\",\"\",function(a){return b.call(e,a,c++)});return d}function T(a){if(-1===a._status){var b=a._result;b=b();b.then(function(b){if(0===a._status||-1===a._status)a._status=1,a._result=b},function(b){if(0===a._status||-1===a._status)a._status=2,a._result=b});-1===a._status&&(a._status=0,a._result=b)}if(1===a._status)return a._result.default;throw a._result;}\nvar U={current:null},V={transition:null},W={ReactCurrentDispatcher:U,ReactCurrentBatchConfig:V,ReactCurrentOwner:K};exports.Children={map:S,forEach:function(a,b,e){S(a,function(){b.apply(this,arguments)},e)},count:function(a){var b=0;S(a,function(){b++});return b},toArray:function(a){return S(a,function(a){return a})||[]},only:function(a){if(!O(a))throw Error(\"React.Children.only expected to receive a single React element child.\");return a}};exports.Component=E;exports.Fragment=p;\nexports.Profiler=r;exports.PureComponent=G;exports.StrictMode=q;exports.Suspense=w;exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=W;\nexports.cloneElement=function(a,b,e){if(null===a||void 0===a)throw Error(\"React.cloneElement(...): The argument must be a React element, but you passed \"+a+\".\");var d=C({},a.props),c=a.key,k=a.ref,h=a._owner;if(null!=b){void 0!==b.ref&&(k=b.ref,h=K.current);void 0!==b.key&&(c=\"\"+b.key);if(a.type&&a.type.defaultProps)var g=a.type.defaultProps;for(f in b)J.call(b,f)&&!L.hasOwnProperty(f)&&(d[f]=void 0===b[f]&&void 0!==g?g[f]:b[f])}var f=arguments.length-2;if(1===f)d.children=e;else if(1<f){g=Array(f);\nfor(var m=0;m<f;m++)g[m]=arguments[m+2];d.children=g}return{$$typeof:l,type:a.type,key:c,ref:k,props:d,_owner:h}};exports.createContext=function(a){a={$$typeof:u,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};a.Provider={$$typeof:t,_context:a};return a.Consumer=a};exports.createElement=M;exports.createFactory=function(a){var b=M.bind(null,a);b.type=a;return b};exports.createRef=function(){return{current:null}};\nexports.forwardRef=function(a){return{$$typeof:v,render:a}};exports.isValidElement=O;exports.lazy=function(a){return{$$typeof:y,_payload:{_status:-1,_result:a},_init:T}};exports.memo=function(a,b){return{$$typeof:x,type:a,compare:void 0===b?null:b}};exports.startTransition=function(a){var b=V.transition;V.transition={};try{a()}finally{V.transition=b}};exports.unstable_act=function(){throw Error(\"act(...) is not supported in production builds of React.\");};\nexports.useCallback=function(a,b){return U.current.useCallback(a,b)};exports.useContext=function(a){return U.current.useContext(a)};exports.useDebugValue=function(){};exports.useDeferredValue=function(a){return U.current.useDeferredValue(a)};exports.useEffect=function(a,b){return U.current.useEffect(a,b)};exports.useId=function(){return U.current.useId()};exports.useImperativeHandle=function(a,b,e){return U.current.useImperativeHandle(a,b,e)};\nexports.useInsertionEffect=function(a,b){return U.current.useInsertionEffect(a,b)};exports.useLayoutEffect=function(a,b){return U.current.useLayoutEffect(a,b)};exports.useMemo=function(a,b){return U.current.useMemo(a,b)};exports.useReducer=function(a,b,e){return U.current.useReducer(a,b,e)};exports.useRef=function(a){return U.current.useRef(a)};exports.useState=function(a){return U.current.useState(a)};exports.useSyncExternalStore=function(a,b,e){return U.current.useSyncExternalStore(a,b,e)};\nexports.useTransition=function(){return U.current.useTransition()};exports.version=\"18.2.0\";\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react.production.min.js');\n} else {\n module.exports = require('./cjs/react.development.js');\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.min.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","/**\n * @license React\n * scheduler.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';function f(a,b){var c=a.length;a.push(b);a:for(;0<c;){var d=c-1>>>1,e=a[d];if(0<g(e,b))a[d]=b,a[c]=e,c=d;else break a}}function h(a){return 0===a.length?null:a[0]}function k(a){if(0===a.length)return null;var b=a[0],c=a.pop();if(c!==b){a[0]=c;a:for(var d=0,e=a.length,w=e>>>1;d<w;){var m=2*(d+1)-1,C=a[m],n=m+1,x=a[n];if(0>g(C,c))n<e&&0>g(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(n<e&&0>g(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}\nfunction g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if(\"object\"===typeof performance&&\"function\"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D=\"function\"===typeof setTimeout?setTimeout:null,E=\"function\"===typeof clearTimeout?clearTimeout:null,F=\"undefined\"!==typeof setImmediate?setImmediate:null;\n\"undefined\"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}\nfunction J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if(\"function\"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;\nfunction M(){return exports.unstable_now()-Q<P?!1:!0}function R(){if(null!==O){var a=exports.unstable_now();Q=a;var b=!0;try{b=O(!0,a)}finally{b?S():(N=!1,O=null)}}else N=!1}var S;if(\"function\"===typeof F)S=function(){F(R)};else if(\"undefined\"!==typeof MessageChannel){var T=new MessageChannel,U=T.port2;T.port1.onmessage=R;S=function(){U.postMessage(null)}}else S=function(){D(R,0)};function I(a){O=a;N||(N=!0,S())}function K(a,b){L=D(function(){a(exports.unstable_now())},b)}\nexports.unstable_IdlePriority=5;exports.unstable_ImmediatePriority=1;exports.unstable_LowPriority=4;exports.unstable_NormalPriority=3;exports.unstable_Profiling=null;exports.unstable_UserBlockingPriority=2;exports.unstable_cancelCallback=function(a){a.callback=null};exports.unstable_continueExecution=function(){A||z||(A=!0,I(J))};\nexports.unstable_forceFrameRate=function(a){0>a||125<a?console.error(\"forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported\"):P=0<a?Math.floor(1E3/a):5};exports.unstable_getCurrentPriorityLevel=function(){return y};exports.unstable_getFirstCallbackNode=function(){return h(r)};exports.unstable_next=function(a){switch(y){case 1:case 2:case 3:var b=3;break;default:b=y}var c=y;y=b;try{return a()}finally{y=c}};exports.unstable_pauseExecution=function(){};\nexports.unstable_requestPaint=function(){};exports.unstable_runWithPriority=function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=y;y=a;try{return b()}finally{y=c}};\nexports.unstable_scheduleCallback=function(a,b,c){var d=exports.unstable_now();\"object\"===typeof c&&null!==c?(c=c.delay,c=\"number\"===typeof c&&0<c?d+c:d):c=d;switch(a){case 1:var e=-1;break;case 2:e=250;break;case 5:e=1073741823;break;case 4:e=1E4;break;default:e=5E3}e=c+e;a={id:u++,callback:b,priorityLevel:a,startTime:c,expirationTime:e,sortIndex:-1};c>d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};\nexports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"static/js/\" + chunkId + \".\" + \"7e4c938d\" + \".chunk.js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","var inProgress = {};\nvar dataWebpackPrefix = \"friendlybetting:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tscript.timeout = 120;\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.p = \"/Friendly-Betting/\";","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t179: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n// no on chunks loaded\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar chunkIds = data[0];\n\tvar moreModules = data[1];\n\tvar runtime = data[2];\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkfriendlybetting\"] = self[\"webpackChunkfriendlybetting\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\n */\n\nexport const CONSTANTS = {\n /**\n * @define {boolean} Whether this is the client Node.js SDK.\n */\n NODE_CLIENT: false,\n /**\n * @define {boolean} Whether this is the Admin Node.js SDK.\n */\n NODE_ADMIN: false,\n\n /**\n * Firebase SDK Version\n */\n SDK_VERSION: '${JSCORE_VERSION}'\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst stringToByteArray = function (str: string): number[] {\n // TODO(user): Use native implementations if/when available\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (\n (c & 0xfc00) === 0xd800 &&\n i + 1 < str.length &&\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n ) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes: number[]): string {\n // TODO(user): Use native implementations if/when available\n const out: string[] = [];\n let pos = 0,\n c = 0;\n while (pos < bytes.length) {\n const c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n } else if (c1 > 191 && c1 < 224) {\n const c2 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n } else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n const c4 = bytes[pos++];\n const u =\n (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n 0x10000;\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n } else {\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n out[c++] = String.fromCharCode(\n ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n );\n }\n }\n return out.join('');\n};\n\ninterface Base64 {\n byteToCharMap_: { [key: number]: string } | null;\n charToByteMap_: { [key: string]: number } | null;\n byteToCharMapWebSafe_: { [key: number]: string } | null;\n charToByteMapWebSafe_: { [key: string]: number } | null;\n ENCODED_VALS_BASE: string;\n readonly ENCODED_VALS: string;\n readonly ENCODED_VALS_WEBSAFE: string;\n HAS_NATIVE_SUPPORT: boolean;\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n encodeString(input: string, webSafe?: boolean): string;\n decodeString(input: string, webSafe: boolean): string;\n decodeStringToByteArray(input: string, webSafe: boolean): number[];\n init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\nexport const base64: Base64 = {\n /**\n * Maps bytes to characters.\n */\n byteToCharMap_: null,\n\n /**\n * Maps characters to bytes.\n */\n charToByteMap_: null,\n\n /**\n * Maps bytes to websafe characters.\n * @private\n */\n byteToCharMapWebSafe_: null,\n\n /**\n * Maps websafe characters to bytes.\n * @private\n */\n charToByteMapWebSafe_: null,\n\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n */\n ENCODED_VALS_BASE:\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n\n /**\n * Our websafe alphabet.\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n /**\n * Base64-encode an array of bytes.\n *\n * @param input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n\n this.init_();\n\n const byteToCharMap = webSafe\n ? this.byteToCharMapWebSafe_!\n : this.byteToCharMap_!;\n\n const output = [];\n\n for (let i = 0; i < input.length; i += 3) {\n const byte1 = input[i];\n const haveByte2 = i + 1 < input.length;\n const byte2 = haveByte2 ? input[i + 1] : 0;\n const haveByte3 = i + 2 < input.length;\n const byte3 = haveByte3 ? input[i + 2] : 0;\n\n const outByte1 = byte1 >> 2;\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n let outByte4 = byte3 & 0x3f;\n\n if (!haveByte3) {\n outByte4 = 64;\n\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n\n output.push(\n byteToCharMap[outByte1],\n byteToCharMap[outByte2],\n byteToCharMap[outByte3],\n byteToCharMap[outByte4]\n );\n }\n\n return output.join('');\n },\n\n /**\n * Base64-encode a string.\n *\n * @param input A string to encode.\n * @param webSafe If true, we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeString(input: string, webSafe?: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), webSafe);\n },\n\n /**\n * Base64-decode a string.\n *\n * @param input to decode.\n * @param webSafe True if we should use the\n * alternative alphabet.\n * @return string representing the decoded value.\n */\n decodeString(input: string, webSafe: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n },\n\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param input Input to decode.\n * @param webSafe True if we should use the web-safe alphabet.\n * @return bytes representing the decoded value.\n */\n decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n this.init_();\n\n const charToByteMap = webSafe\n ? this.charToByteMapWebSafe_!\n : this.charToByteMap_!;\n\n const output: number[] = [];\n\n for (let i = 0; i < input.length; ) {\n const byte1 = charToByteMap[input.charAt(i++)];\n\n const haveByte2 = i < input.length;\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n\n const haveByte3 = i < input.length;\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n const haveByte4 = i < input.length;\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw new DecodeBase64StringError();\n }\n\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n\n if (byte3 !== 64) {\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n\n if (byte4 !== 64) {\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n\n return output;\n },\n\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_() {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n\n // We want quick mappings back and forth, so we precompute two maps.\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class DecodeBase64StringError extends Error {\n readonly name = 'DecodeBase64StringError';\n}\n\n/**\n * URL-safe base64 encoding\n */\nexport const base64Encode = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n return base64.encodeByteArray(utf8Bytes, true);\n};\n\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n // Use base64url encoding and remove padding in the end (dot characters).\n return base64Encode(str).replace(/\\./g, '');\n};\n\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function (str: string): string | null {\n try {\n return base64.decodeString(str, true);\n } catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { getGlobal } from './global';\n\n/**\n * Keys for experimental properties on the `FirebaseDefaults` object.\n * @public\n */\nexport type ExperimentalKey = 'authTokenSyncURL' | 'authIdTokenMaxAge';\n\n/**\n * An object that can be injected into the environment as __FIREBASE_DEFAULTS__,\n * either as a property of globalThis, a shell environment variable, or a\n * cookie.\n *\n * This object can be used to automatically configure and initialize\n * a Firebase app as well as any emulators.\n *\n * @public\n */\nexport interface FirebaseDefaults {\n config?: Record<string, string>;\n emulatorHosts?: Record<string, string>;\n _authTokenSyncURL?: string;\n _authIdTokenMaxAge?: number;\n /**\n * Override Firebase's runtime environment detection and\n * force the SDK to act as if it were in the specified environment.\n */\n forceEnvironment?: 'browser' | 'node';\n [key: string]: unknown;\n}\n\ndeclare global {\n // Need `var` for this to work.\n // eslint-disable-next-line no-var\n var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined;\n}\n\nconst getDefaultsFromGlobal = (): FirebaseDefaults | undefined =>\n getGlobal().__FIREBASE_DEFAULTS__;\n\n/**\n * Attempt to read defaults from a JSON string provided to\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\n * The dots are in parens because certain compilers (Vite?) cannot\n * handle seeing that variable in comments.\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\n */\nconst getDefaultsFromEnvVariable = (): FirebaseDefaults | undefined => {\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\n return;\n }\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\n if (defaultsJsonString) {\n return JSON.parse(defaultsJsonString);\n }\n};\n\nconst getDefaultsFromCookie = (): FirebaseDefaults | undefined => {\n if (typeof document === 'undefined') {\n return;\n }\n let match;\n try {\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\n } catch (e) {\n // Some environments such as Angular Universal SSR have a\n // `document` object but error on accessing `document.cookie`.\n return;\n }\n const decoded = match && base64Decode(match[1]);\n return decoded && JSON.parse(decoded);\n};\n\n/**\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\n * (1) if such an object exists as a property of `globalThis`\n * (2) if such an object was provided on a shell environment variable\n * (3) if such an object exists in a cookie\n * @public\n */\nexport const getDefaults = (): FirebaseDefaults | undefined => {\n try {\n return (\n getDefaultsFromGlobal() ||\n getDefaultsFromEnvVariable() ||\n getDefaultsFromCookie()\n );\n } catch (e) {\n /**\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\n * to any environment case we have not accounted for. Log to\n * info instead of swallowing so we can find these unknown cases\n * and add paths for them if needed.\n */\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\n return;\n }\n};\n\n/**\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\n * @public\n */\nexport const getDefaultEmulatorHost = (\n productName: string\n): string | undefined => getDefaults()?.emulatorHosts?.[productName];\n\n/**\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\n * @public\n */\nexport const getDefaultEmulatorHostnameAndPort = (\n productName: string\n): [hostname: string, port: number] | undefined => {\n const host = getDefaultEmulatorHost(productName);\n if (!host) {\n return undefined;\n }\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\n }\n // eslint-disable-next-line no-restricted-globals\n const port = parseInt(host.substring(separatorIndex + 1), 10);\n if (host[0] === '[') {\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\n return [host.substring(1, separatorIndex - 1), port];\n } else {\n return [host.substring(0, separatorIndex), port];\n }\n};\n\n/**\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\n * @public\n */\nexport const getDefaultAppConfig = (): Record<string, string> | undefined =>\n getDefaults()?.config;\n\n/**\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\n * prefixed by \"_\")\n * @public\n */\nexport const getExperimentalSetting = <T extends ExperimentalKey>(\n name: T\n): FirebaseDefaults[`_${T}`] =>\n getDefaults()?.[`_${name}`] as FirebaseDefaults[`_${T}`];\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Polyfill for `globalThis` object.\n * @returns the `globalThis` object for the given environment.\n * @public\n */\nexport function getGlobal(): typeof globalThis {\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('Unable to locate global object.');\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<R> {\n promise: Promise<R>;\n reject: (value?: unknown) => void = () => {};\n resolve: (value?: unknown) => void = () => {};\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve as (value?: unknown) => void;\n this.reject = reject as (value?: unknown) => void;\n });\n }\n\n /**\n * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\n */\n wrapCallback(\n callback?: (error?: unknown, value?: unknown) => void\n ): (error: unknown, value?: unknown) => void {\n return (error, value?) => {\n if (error) {\n this.reject(error);\n } else {\n this.resolve(value);\n }\n if (typeof callback === 'function') {\n // Attaching noop handler just in case developer wasn't expecting\n // promises\n this.promise.catch(() => {});\n\n // Some of our callbacks don't expect a value and our own tests\n // assert that the parameter length is 1\n if (callback.length === 1) {\n callback(error);\n } else {\n callback(error, value);\n }\n }\n };\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './constants';\nimport { getDefaults } from './defaults';\n\n/**\n * Returns navigator.userAgent string or '' if it's not defined.\n * @return user agent string\n */\nexport function getUA(): string {\n if (\n typeof navigator !== 'undefined' &&\n typeof navigator['userAgent'] === 'string'\n ) {\n return navigator['userAgent'];\n } else {\n return '';\n }\n}\n\n/**\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\n *\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\n * wait for a callback.\n */\nexport function isMobileCordova(): boolean {\n return (\n typeof window !== 'undefined' &&\n // @ts-ignore Setting up an broadly applicable index signature for Window\n // just to deal with this case would probably be a bad idea.\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())\n );\n}\n\n/**\n * Detect Node.js.\n *\n * @return true if Node.js environment is detected or specified.\n */\n// Node detection logic from: https://github.com/iliakan/detect-node/\nexport function isNode(): boolean {\n const forceEnvironment = getDefaults()?.forceEnvironment;\n if (forceEnvironment === 'node') {\n return true;\n } else if (forceEnvironment === 'browser') {\n return false;\n }\n\n try {\n return (\n Object.prototype.toString.call(global.process) === '[object process]'\n );\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Detect Browser Environment\n */\nexport function isBrowser(): boolean {\n return typeof self === 'object' && self.self === self;\n}\n\n/**\n * Detect browser extensions (Chrome and Firefox at least).\n */\ninterface BrowserRuntime {\n id?: unknown;\n}\ndeclare const chrome: { runtime?: BrowserRuntime };\ndeclare const browser: { runtime?: BrowserRuntime };\nexport function isBrowserExtension(): boolean {\n const runtime =\n typeof chrome === 'object'\n ? chrome.runtime\n : typeof browser === 'object'\n ? browser.runtime\n : undefined;\n return typeof runtime === 'object' && runtime.id !== undefined;\n}\n\n/**\n * Detect React Native.\n *\n * @return true if ReactNative environment is detected.\n */\nexport function isReactNative(): boolean {\n return (\n typeof navigator === 'object' && navigator['product'] === 'ReactNative'\n );\n}\n\n/** Detects Electron apps. */\nexport function isElectron(): boolean {\n return getUA().indexOf('Electron/') >= 0;\n}\n\n/** Detects Internet Explorer. */\nexport function isIE(): boolean {\n const ua = getUA();\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\n}\n\n/** Detects Universal Windows Platform apps. */\nexport function isUWP(): boolean {\n return getUA().indexOf('MSAppHost/') >= 0;\n}\n\n/**\n * Detect whether the current SDK build is the Node version.\n *\n * @return true if it's the Node SDK build.\n */\nexport function isNodeSdk(): boolean {\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\n}\n\n/** Returns true if we are running in Safari. */\nexport function isSafari(): boolean {\n return (\n !isNode() &&\n navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome')\n );\n}\n\n/**\n * This method checks if indexedDB is supported by current browser/service worker context\n * @return true if indexedDB is supported by current browser/service worker context\n */\nexport function isIndexedDBAvailable(): boolean {\n try {\n return typeof indexedDB === 'object';\n } catch (e) {\n return false;\n }\n}\n\n/**\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\n * if errors occur during the database open operation.\n *\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\n * private browsing)\n */\nexport function validateIndexedDBOpenable(): Promise<boolean> {\n return new Promise((resolve, reject) => {\n try {\n let preExist: boolean = true;\n const DB_CHECK_NAME =\n 'validate-browser-context-for-indexeddb-analytics-module';\n const request = self.indexedDB.open(DB_CHECK_NAME);\n request.onsuccess = () => {\n request.result.close();\n // delete database only when it doesn't pre-exist\n if (!preExist) {\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\n }\n resolve(true);\n };\n request.onupgradeneeded = () => {\n preExist = false;\n };\n\n request.onerror = () => {\n reject(request.error?.message || '');\n };\n } catch (error) {\n reject(error);\n }\n });\n}\n\n/**\n *\n * This method checks whether cookie is enabled within current browser\n * @return true if cookie is enabled within current browser\n */\nexport function areCookiesEnabled(): boolean {\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\n return false;\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n * // Typescript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map<Err, string> = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory<Err>('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\n\nexport type ErrorMap<ErrorCode extends string> = {\n readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n toString(): string;\n}\n\nexport interface ErrorData {\n [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n /** The custom name for all FirebaseErrors. */\n readonly name: string = ERROR_NAME;\n\n constructor(\n /** The error code for this error. */\n readonly code: string,\n message: string,\n /** Custom data for this error. */\n public customData?: Record<string, unknown>\n ) {\n super(message);\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, FirebaseError.prototype);\n\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\n\nexport class ErrorFactory<\n ErrorCode extends string,\n ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n constructor(\n private readonly service: string,\n private readonly serviceName: string,\n private readonly errors: ErrorMap<ErrorCode>\n ) {}\n\n create<K extends ErrorCode>(\n code: K,\n ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n ): FirebaseError {\n const customData = (data[0] as ErrorData) || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n const error = new FirebaseError(fullCode, fullMessage, customData);\n\n return error;\n }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n return template.replace(PATTERN, (_, key) => {\n const value = data[key];\n return value != null ? String(value) : `<${key}?>`;\n });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function contains<T extends object>(obj: T, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function safeGet<T extends object, K extends keyof T>(\n obj: T,\n key: K\n): T[K] | undefined {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return obj[key];\n } else {\n return undefined;\n }\n}\n\nexport function isEmpty(obj: object): obj is {} {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n\nexport function map<K extends string, V, U>(\n obj: { [key in K]: V },\n fn: (value: V, key: K, obj: { [key in K]: V }) => U,\n contextObj?: unknown\n): { [key in K]: U } {\n const res: Partial<{ [key in K]: U }> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n res[key] = fn.call(contextObj, obj[key], key, obj);\n }\n }\n return res as { [key in K]: U };\n}\n\n/**\n * Deep equal two objects. Support Arrays and Objects.\n */\nexport function deepEqual(a: object, b: object): boolean {\n if (a === b) {\n return true;\n }\n\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n for (const k of aKeys) {\n if (!bKeys.includes(k)) {\n return false;\n }\n\n const aProp = (a as Record<string, unknown>)[k];\n const bProp = (b as Record<string, unknown>)[k];\n if (isObject(aProp) && isObject(bProp)) {\n if (!deepEqual(aProp, bProp)) {\n return false;\n }\n } else if (aProp !== bProp) {\n return false;\n }\n }\n\n for (const k of bKeys) {\n if (!aKeys.includes(k)) {\n return false;\n }\n }\n return true;\n}\n\nfunction isObject(thing: unknown): thing is object {\n return thing !== null && typeof thing === 'object';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\n * params object (e.g. {arg: 'val', arg2: 'val2'})\n * Note: You must prepend it with ? when adding it to a URL.\n */\nexport function querystring(querystringParams: {\n [key: string]: string | number;\n}): string {\n const params = [];\n for (const [key, value] of Object.entries(querystringParams)) {\n if (Array.isArray(value)) {\n value.forEach(arrayVal => {\n params.push(\n encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal)\n );\n });\n } else {\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n }\n }\n return params.length ? '&' + params.join('&') : '';\n}\n\n/**\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\n * (e.g. {arg: 'val', arg2: 'val2'})\n */\nexport function querystringDecode(querystring: string): Record<string, string> {\n const obj: Record<string, string> = {};\n const tokens = querystring.replace(/^\\?/, '').split('&');\n\n tokens.forEach(token => {\n if (token) {\n const [key, value] = token.split('=');\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\n }\n });\n return obj;\n}\n\n/**\n * Extract the query string part of a URL, including the leading question mark (if present).\n */\nexport function extractQuerystring(url: string): string {\n const queryStart = url.indexOf('?');\n if (!queryStart) {\n return '';\n }\n const fragmentStart = url.indexOf('#', queryStart);\n return url.substring(\n queryStart,\n fragmentStart > 0 ? fragmentStart : undefined\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport type NextFn<T> = (value: T) => void;\nexport type ErrorFn = (error: Error) => void;\nexport type CompleteFn = () => void;\n\nexport interface Observer<T> {\n // Called once for each value in a stream of values.\n next: NextFn<T>;\n\n // A stream terminates by a single call to EITHER error() or complete().\n error: ErrorFn;\n\n // No events will be sent to next() once complete() is called.\n complete: CompleteFn;\n}\n\nexport type PartialObserver<T> = Partial<Observer<T>>;\n\n// TODO: Support also Unsubscribe.unsubscribe?\nexport type Unsubscribe = () => void;\n\n/**\n * The Subscribe interface has two forms - passing the inline function\n * callbacks, or a object interface with callback properties.\n */\nexport interface Subscribe<T> {\n (next?: NextFn<T>, error?: ErrorFn, complete?: CompleteFn): Unsubscribe;\n (observer: PartialObserver<T>): Unsubscribe;\n}\n\nexport interface Observable<T> {\n // Subscribe method\n subscribe: Subscribe<T>;\n}\n\nexport type Executor<T> = (observer: Observer<T>) => void;\n\n/**\n * Helper to make a Subscribe function (just like Promise helps make a\n * Thenable).\n *\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\nexport function createSubscribe<T>(\n executor: Executor<T>,\n onNoObservers?: Executor<T>\n): Subscribe<T> {\n const proxy = new ObserverProxy<T>(executor, onNoObservers);\n return proxy.subscribe.bind(proxy);\n}\n\n/**\n * Implement fan-out for any number of Observers attached via a subscribe\n * function.\n */\nclass ObserverProxy<T> implements Observer<T> {\n private observers: Array<Observer<T>> | undefined = [];\n private unsubscribes: Unsubscribe[] = [];\n private onNoObservers: Executor<T> | undefined;\n private observerCount = 0;\n // Micro-task scheduling by calling task.then().\n private task = Promise.resolve();\n private finalized = false;\n private finalError?: Error;\n\n /**\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\n constructor(executor: Executor<T>, onNoObservers?: Executor<T>) {\n this.onNoObservers = onNoObservers;\n // Call the executor asynchronously so subscribers that are called\n // synchronously after the creation of the subscribe function\n // can still receive the very first value generated in the executor.\n this.task\n .then(() => {\n executor(this);\n })\n .catch(e => {\n this.error(e);\n });\n }\n\n next(value: T): void {\n this.forEachObserver((observer: Observer<T>) => {\n observer.next(value);\n });\n }\n\n error(error: Error): void {\n this.forEachObserver((observer: Observer<T>) => {\n observer.error(error);\n });\n this.close(error);\n }\n\n complete(): void {\n this.forEachObserver((observer: Observer<T>) => {\n observer.complete();\n });\n this.close();\n }\n\n /**\n * Subscribe function that can be used to add an Observer to the fan-out list.\n *\n * - We require that no event is sent to a subscriber sychronously to their\n * call to subscribe().\n */\n subscribe(\n nextOrObserver?: NextFn<T> | PartialObserver<T>,\n error?: ErrorFn,\n complete?: CompleteFn\n ): Unsubscribe {\n let observer: Observer<T>;\n\n if (\n nextOrObserver === undefined &&\n error === undefined &&\n complete === undefined\n ) {\n throw new Error('Missing Observer.');\n }\n\n // Assemble an Observer object when passed as callback functions.\n if (\n implementsAnyMethods(nextOrObserver as { [key: string]: unknown }, [\n 'next',\n 'error',\n 'complete'\n ])\n ) {\n observer = nextOrObserver as Observer<T>;\n } else {\n observer = {\n next: nextOrObserver as NextFn<T>,\n error,\n complete\n } as Observer<T>;\n }\n\n if (observer.next === undefined) {\n observer.next = noop as NextFn<T>;\n }\n if (observer.error === undefined) {\n observer.error = noop as ErrorFn;\n }\n if (observer.complete === undefined) {\n observer.complete = noop as CompleteFn;\n }\n\n const unsub = this.unsubscribeOne.bind(this, this.observers!.length);\n\n // Attempt to subscribe to a terminated Observable - we\n // just respond to the Observer with the final error or complete\n // event.\n if (this.finalized) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n try {\n if (this.finalError) {\n observer.error(this.finalError);\n } else {\n observer.complete();\n }\n } catch (e) {\n // nothing\n }\n return;\n });\n }\n\n this.observers!.push(observer as Observer<T>);\n\n return unsub;\n }\n\n // Unsubscribe is synchronous - we guarantee that no events are sent to\n // any unsubscribed Observer.\n private unsubscribeOne(i: number): void {\n if (this.observers === undefined || this.observers[i] === undefined) {\n return;\n }\n\n delete this.observers[i];\n\n this.observerCount -= 1;\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\n this.onNoObservers(this);\n }\n }\n\n private forEachObserver(fn: (observer: Observer<T>) => void): void {\n if (this.finalized) {\n // Already closed by previous event....just eat the additional values.\n return;\n }\n\n // Since sendOne calls asynchronously - there is no chance that\n // this.observers will become undefined.\n for (let i = 0; i < this.observers!.length; i++) {\n this.sendOne(i, fn);\n }\n }\n\n // Call the Observer via one of it's callback function. We are careful to\n // confirm that the observe has not been unsubscribed since this asynchronous\n // function had been queued.\n private sendOne(i: number, fn: (observer: Observer<T>) => void): void {\n // Execute the callback asynchronously\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n if (this.observers !== undefined && this.observers[i] !== undefined) {\n try {\n fn(this.observers[i]);\n } catch (e) {\n // Ignore exceptions raised in Observers or missing methods of an\n // Observer.\n // Log error to console. b/31404806\n if (typeof console !== 'undefined' && console.error) {\n console.error(e);\n }\n }\n }\n });\n }\n\n private close(err?: Error): void {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n if (err !== undefined) {\n this.finalError = err;\n }\n // Proxy is no longer needed - garbage collect references\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n this.observers = undefined;\n this.onNoObservers = undefined;\n });\n }\n}\n\n/** Turn synchronous function into one called asynchronously. */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function async(fn: Function, onError?: ErrorFn): Function {\n return (...args: unknown[]) => {\n Promise.resolve(true)\n .then(() => {\n fn(...args);\n })\n .catch((error: Error) => {\n if (onError) {\n onError(error);\n }\n });\n };\n}\n\n/**\n * Return true if the object passed in implements any of the named methods.\n */\nfunction implementsAnyMethods(\n obj: { [key: string]: unknown },\n methods: string[]\n): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n for (const method of methods) {\n if (method in obj && typeof obj[method] === 'function') {\n return true;\n }\n }\n\n return false;\n}\n\nfunction noop(): void {\n // do nothing\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from './assert';\n\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\n// so it's been modified.\n\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\n// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\n// pair).\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\n\n/**\n * @param {string} str\n * @return {Array}\n */\nexport const stringToByteArray = function (str: string): number[] {\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n\n // Is this the lead surrogate in a surrogate pair?\n if (c >= 0xd800 && c <= 0xdbff) {\n const high = c - 0xd800; // the high 10 bits.\n i++;\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\n c = 0x10000 + (high << 10) + low;\n }\n\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (c < 65536) {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Calculate length without actually converting; useful for doing cheaper validation.\n * @param {string} str\n * @return {number}\n */\nexport const stringLength = function (str: string): number {\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n const c = str.charCodeAt(i);\n if (c < 128) {\n p++;\n } else if (c < 2048) {\n p += 2;\n } else if (c >= 0xd800 && c <= 0xdbff) {\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\n p += 4;\n i++; // skip trail surrogate.\n } else {\n p += 3;\n }\n }\n return p;\n};\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The amount of milliseconds to exponentially increase.\n */\nconst DEFAULT_INTERVAL_MILLIS = 1000;\n\n/**\n * The factor to backoff by.\n * Should be a number greater than 1.\n */\nconst DEFAULT_BACKOFF_FACTOR = 2;\n\n/**\n * The maximum milliseconds to increase to.\n *\n * <p>Visible for testing\n */\nexport const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\n\n/**\n * The percentage of backoff time to randomize by.\n * See\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\n * for context.\n *\n * <p>Visible for testing\n */\nexport const RANDOM_FACTOR = 0.5;\n\n/**\n * Based on the backoff method from\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\n */\nexport function calculateBackoffMillis(\n backoffCount: number,\n intervalMillis: number = DEFAULT_INTERVAL_MILLIS,\n backoffFactor: number = DEFAULT_BACKOFF_FACTOR\n): number {\n // Calculates an exponentially increasing value.\n // Deviation: calculates value from count and a constant interval, so we only need to save value\n // and count to restore state.\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\n\n // A random \"fuzz\" to avoid waves of retries.\n // Deviation: randomFactor is required.\n const randomWait = Math.round(\n // A fraction of the backoff value to add/subtract.\n // Deviation: changes multiplication order to improve readability.\n RANDOM_FACTOR *\n currBaseValue *\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\n // if we add or subtract.\n (Math.random() - 0.5) *\n 2\n );\n\n // Limits backoff to max to avoid effectively permanent backoff.\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Compat<T> {\n _delegate: T;\n}\n\nexport function getModularInstance<ExpService>(\n service: Compat<ExpService> | ExpService\n): ExpService {\n if (service && (service as Compat<ExpService>)._delegate) {\n return (service as Compat<ExpService>)._delegate;\n } else {\n return service as ExpService;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n InstantiationMode,\n InstanceFactory,\n ComponentType,\n Dictionary,\n Name,\n onInstanceCreatedCallback\n} from './types';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nexport class Component<T extends Name = Name> {\n multipleInstances = false;\n /**\n * Properties to be added to the service namespace\n */\n serviceProps: Dictionary = {};\n\n instantiationMode = InstantiationMode.LAZY;\n\n onInstanceCreated: onInstanceCreatedCallback<T> | null = null;\n\n /**\n *\n * @param name The public service name, e.g. app, auth, firestore, database\n * @param instanceFactory Service factory responsible for creating the public interface\n * @param type whether the service provided by the component is public or private\n */\n constructor(\n readonly name: T,\n readonly instanceFactory: InstanceFactory<T>,\n readonly type: ComponentType\n ) {}\n\n setInstantiationMode(mode: InstantiationMode): this {\n this.instantiationMode = mode;\n return this;\n }\n\n setMultipleInstances(multipleInstances: boolean): this {\n this.multipleInstances = multipleInstances;\n return this;\n }\n\n setServiceProps(props: Dictionary): this {\n this.serviceProps = props;\n return this;\n }\n\n setInstanceCreatedCallback(callback: onInstanceCreatedCallback<T>): this {\n this.onInstanceCreated = callback;\n return this;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const DEFAULT_ENTRY_NAME = '[DEFAULT]';\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\nimport { ComponentContainer } from './component_container';\nimport { DEFAULT_ENTRY_NAME } from './constants';\nimport {\n InitializeOptions,\n InstantiationMode,\n Name,\n NameServiceMapping,\n OnInitCallBack\n} from './types';\nimport { Component } from './component';\n\n/**\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\n * NameServiceMapping[T] is an alias for the type of the instance\n */\nexport class Provider<T extends Name> {\n private component: Component<T> | null = null;\n private readonly instances: Map<string, NameServiceMapping[T]> = new Map();\n private readonly instancesDeferred: Map<\n string,\n Deferred<NameServiceMapping[T]>\n > = new Map();\n private readonly instancesOptions: Map<string, Record<string, unknown>> =\n new Map();\n private onInitCallbacks: Map<string, Set<OnInitCallBack<T>>> = new Map();\n\n constructor(\n private readonly name: T,\n private readonly container: ComponentContainer\n ) {}\n\n /**\n * @param identifier A provider can provide mulitple instances of a service\n * if this.component.multipleInstances is true.\n */\n get(identifier?: string): Promise<NameServiceMapping[T]> {\n // if multipleInstances is not supported, use the default name\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\n const deferred = new Deferred<NameServiceMapping[T]>();\n this.instancesDeferred.set(normalizedIdentifier, deferred);\n\n if (\n this.isInitialized(normalizedIdentifier) ||\n this.shouldAutoInitialize()\n ) {\n // initialize the service if it can be auto-initialized\n try {\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n });\n if (instance) {\n deferred.resolve(instance);\n }\n } catch (e) {\n // when the instance factory throws an exception during get(), it should not cause\n // a fatal error. We just return the unresolved promise in this case.\n }\n }\n }\n\n return this.instancesDeferred.get(normalizedIdentifier)!.promise;\n }\n\n /**\n *\n * @param options.identifier A provider can provide mulitple instances of a service\n * if this.component.multipleInstances is true.\n * @param options.optional If optional is false or not provided, the method throws an error when\n * the service is not immediately available.\n * If optional is true, the method returns null if the service is not immediately available.\n */\n getImmediate(options: {\n identifier?: string;\n optional: true;\n }): NameServiceMapping[T] | null;\n getImmediate(options?: {\n identifier?: string;\n optional?: false;\n }): NameServiceMapping[T];\n getImmediate(options?: {\n identifier?: string;\n optional?: boolean;\n }): NameServiceMapping[T] | null {\n // if multipleInstances is not supported, use the default name\n const normalizedIdentifier = this.normalizeInstanceIdentifier(\n options?.identifier\n );\n const optional = options?.optional ?? false;\n\n if (\n this.isInitialized(normalizedIdentifier) ||\n this.shouldAutoInitialize()\n ) {\n try {\n return this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n });\n } catch (e) {\n if (optional) {\n return null;\n } else {\n throw e;\n }\n }\n } else {\n // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw\n if (optional) {\n return null;\n } else {\n throw Error(`Service ${this.name} is not available`);\n }\n }\n }\n\n getComponent(): Component<T> | null {\n return this.component;\n }\n\n setComponent(component: Component<T>): void {\n if (component.name !== this.name) {\n throw Error(\n `Mismatching Component ${component.name} for Provider ${this.name}.`\n );\n }\n\n if (this.component) {\n throw Error(`Component for ${this.name} has already been provided`);\n }\n\n this.component = component;\n\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\n if (!this.shouldAutoInitialize()) {\n return;\n }\n\n // if the service is eager, initialize the default instance\n if (isComponentEager(component)) {\n try {\n this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\n } catch (e) {\n // when the instance factory for an eager Component throws an exception during the eager\n // initialization, it should not cause a fatal error.\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\n // a fatal error in this case?\n }\n }\n\n // Create service instances for the pending promises and resolve them\n // NOTE: if this.multipleInstances is false, only the default instance will be created\n // and all promises with resolve with it regardless of the identifier.\n for (const [\n instanceIdentifier,\n instanceDeferred\n ] of this.instancesDeferred.entries()) {\n const normalizedIdentifier =\n this.normalizeInstanceIdentifier(instanceIdentifier);\n\n try {\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n })!;\n instanceDeferred.resolve(instance);\n } catch (e) {\n // when the instance factory throws an exception, it should not cause\n // a fatal error. We just leave the promise unresolved.\n }\n }\n }\n\n clearInstance(identifier: string = DEFAULT_ENTRY_NAME): void {\n this.instancesDeferred.delete(identifier);\n this.instancesOptions.delete(identifier);\n this.instances.delete(identifier);\n }\n\n // app.delete() will call this method on every provider to delete the services\n // TODO: should we mark the provider as deleted?\n async delete(): Promise<void> {\n const services = Array.from(this.instances.values());\n\n await Promise.all([\n ...services\n .filter(service => 'INTERNAL' in service) // legacy services\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map(service => (service as any).INTERNAL!.delete()),\n ...services\n .filter(service => '_delete' in service) // modularized services\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map(service => (service as any)._delete())\n ]);\n }\n\n isComponentSet(): boolean {\n return this.component != null;\n }\n\n isInitialized(identifier: string = DEFAULT_ENTRY_NAME): boolean {\n return this.instances.has(identifier);\n }\n\n getOptions(identifier: string = DEFAULT_ENTRY_NAME): Record<string, unknown> {\n return this.instancesOptions.get(identifier) || {};\n }\n\n initialize(opts: InitializeOptions = {}): NameServiceMapping[T] {\n const { options = {} } = opts;\n const normalizedIdentifier = this.normalizeInstanceIdentifier(\n opts.instanceIdentifier\n );\n if (this.isInitialized(normalizedIdentifier)) {\n throw Error(\n `${this.name}(${normalizedIdentifier}) has already been initialized`\n );\n }\n\n if (!this.isComponentSet()) {\n throw Error(`Component ${this.name} has not been registered yet`);\n }\n\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier,\n options\n })!;\n\n // resolve any pending promise waiting for the service instance\n for (const [\n instanceIdentifier,\n instanceDeferred\n ] of this.instancesDeferred.entries()) {\n const normalizedDeferredIdentifier =\n this.normalizeInstanceIdentifier(instanceIdentifier);\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\n instanceDeferred.resolve(instance);\n }\n }\n\n return instance;\n }\n\n /**\n *\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\n *\n * @param identifier An optional instance identifier\n * @returns a function to unregister the callback\n */\n onInit(callback: OnInitCallBack<T>, identifier?: string): () => void {\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n const existingCallbacks =\n this.onInitCallbacks.get(normalizedIdentifier) ??\n new Set<OnInitCallBack<T>>();\n existingCallbacks.add(callback);\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\n\n const existingInstance = this.instances.get(normalizedIdentifier);\n if (existingInstance) {\n callback(existingInstance, normalizedIdentifier);\n }\n\n return () => {\n existingCallbacks.delete(callback);\n };\n }\n\n /**\n * Invoke onInit callbacks synchronously\n * @param instance the service instance`\n */\n private invokeOnInitCallbacks(\n instance: NameServiceMapping[T],\n identifier: string\n ): void {\n const callbacks = this.onInitCallbacks.get(identifier);\n if (!callbacks) {\n return;\n }\n for (const callback of callbacks) {\n try {\n callback(instance, identifier);\n } catch {\n // ignore errors in the onInit callback\n }\n }\n }\n\n private getOrInitializeService({\n instanceIdentifier,\n options = {}\n }: {\n instanceIdentifier: string;\n options?: Record<string, unknown>;\n }): NameServiceMapping[T] | null {\n let instance = this.instances.get(instanceIdentifier);\n if (!instance && this.component) {\n instance = this.component.instanceFactory(this.container, {\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\n options\n });\n this.instances.set(instanceIdentifier, instance);\n this.instancesOptions.set(instanceIdentifier, options);\n\n /**\n * Invoke onInit listeners.\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\n * while onInit listeners are registered by consumers of the provider.\n */\n this.invokeOnInitCallbacks(instance, instanceIdentifier);\n\n /**\n * Order is important\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\n * makes `isInitialized()` return true.\n */\n if (this.component.onInstanceCreated) {\n try {\n this.component.onInstanceCreated(\n this.container,\n instanceIdentifier,\n instance\n );\n } catch {\n // ignore errors in the onInstanceCreatedCallback\n }\n }\n }\n\n return instance || null;\n }\n\n private normalizeInstanceIdentifier(\n identifier: string = DEFAULT_ENTRY_NAME\n ): string {\n if (this.component) {\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\n } else {\n return identifier; // assume multiple instances are supported before the component is provided.\n }\n }\n\n private shouldAutoInitialize(): boolean {\n return (\n !!this.component &&\n this.component.instantiationMode !== InstantiationMode.EXPLICIT\n );\n }\n}\n\n// undefined should be passed to the service factory for the default instance\nfunction normalizeIdentifierForFactory(identifier: string): string | undefined {\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\n}\n\nfunction isComponentEager<T extends Name>(component: Component<T>): boolean {\n return component.instantiationMode === InstantiationMode.EAGER;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Provider } from './provider';\nimport { Component } from './component';\nimport { Name } from './types';\n\n/**\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\n */\nexport class ComponentContainer {\n private readonly providers = new Map<string, Provider<Name>>();\n\n constructor(private readonly name: string) {}\n\n /**\n *\n * @param component Component being added\n * @param overwrite When a component with the same name has already been registered,\n * if overwrite is true: overwrite the existing component with the new component and create a new\n * provider with the new component. It can be useful in tests where you want to use different mocks\n * for different tests.\n * if overwrite is false: throw an exception\n */\n addComponent<T extends Name>(component: Component<T>): void {\n const provider = this.getProvider(component.name);\n if (provider.isComponentSet()) {\n throw new Error(\n `Component ${component.name} has already been registered with ${this.name}`\n );\n }\n\n provider.setComponent(component);\n }\n\n addOrOverwriteComponent<T extends Name>(component: Component<T>): void {\n const provider = this.getProvider(component.name);\n if (provider.isComponentSet()) {\n // delete the existing provider from the container, so we can register the new component\n this.providers.delete(component.name);\n }\n\n this.addComponent(component);\n }\n\n /**\n * getProvider provides a type safe interface where it can only be called with a field name\n * present in NameServiceMapping interface.\n *\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\n * themselves.\n */\n getProvider<T extends Name>(name: T): Provider<T> {\n if (this.providers.has(name)) {\n return this.providers.get(name) as unknown as Provider<T>;\n }\n\n // create a Provider for a service that hasn't registered with Firebase\n const provider = new Provider<T>(name, this);\n this.providers.set(name, provider as unknown as Provider<Name>);\n\n return provider as Provider<T>;\n }\n\n getProviders(): Array<Provider<Name>> {\n return Array.from(this.providers.values());\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type LogLevelString =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'silent';\n\nexport interface LogOptions {\n level: LogLevelString;\n}\n\nexport type LogCallback = (callbackParams: LogCallbackParams) => void;\n\nexport interface LogCallbackParams {\n level: LogLevelString;\n message: string;\n args: unknown[];\n type: string;\n}\n\n/**\n * A container for all of the Logger instances\n */\nexport const instances: Logger[] = [];\n\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport enum LogLevel {\n DEBUG,\n VERBOSE,\n INFO,\n WARN,\n ERROR,\n SILENT\n}\n\nconst levelStringToEnum: { [key in LogLevelString]: LogLevel } = {\n 'debug': LogLevel.DEBUG,\n 'verbose': LogLevel.VERBOSE,\n 'info': LogLevel.INFO,\n 'warn': LogLevel.WARN,\n 'error': LogLevel.ERROR,\n 'silent': LogLevel.SILENT\n};\n\n/**\n * The default log level\n */\nconst defaultLogLevel: LogLevel = LogLevel.INFO;\n\n/**\n * We allow users the ability to pass their own log handler. We will pass the\n * type of log, the current log level, and any other arguments passed (i.e. the\n * messages that the user wants to log) to this function.\n */\nexport type LogHandler = (\n loggerInstance: Logger,\n logType: LogLevel,\n ...args: unknown[]\n) => void;\n\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n [LogLevel.DEBUG]: 'log',\n [LogLevel.VERBOSE]: 'log',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error'\n};\n\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler: LogHandler = (instance, logType, ...args): void => {\n if (logType < instance.logLevel) {\n return;\n }\n const now = new Date().toISOString();\n const method = ConsoleMethod[logType as keyof typeof ConsoleMethod];\n if (method) {\n console[method as 'log' | 'info' | 'warn' | 'error'](\n `[${now}] ${instance.name}:`,\n ...args\n );\n } else {\n throw new Error(\n `Attempted to log a message with an invalid logType (value: ${logType})`\n );\n }\n};\n\nexport class Logger {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n constructor(public name: string) {\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n\n /**\n * The log level of the given Logger instance.\n */\n private _logLevel = defaultLogLevel;\n\n get logLevel(): LogLevel {\n return this._logLevel;\n }\n\n set logLevel(val: LogLevel) {\n if (!(val in LogLevel)) {\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n }\n this._logLevel = val;\n }\n\n // Workaround for setter/getter having to be the same type.\n setLogLevel(val: LogLevel | LogLevelString): void {\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n }\n\n /**\n * The main (internal) log handler for the Logger instance.\n * Can be set to a new function in internal package code but not by user.\n */\n private _logHandler: LogHandler = defaultLogHandler;\n get logHandler(): LogHandler {\n return this._logHandler;\n }\n set logHandler(val: LogHandler) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n }\n\n /**\n * The optional, additional, user-defined log handler for the Logger instance.\n */\n private _userLogHandler: LogHandler | null = null;\n get userLogHandler(): LogHandler | null {\n return this._userLogHandler;\n }\n set userLogHandler(val: LogHandler | null) {\n this._userLogHandler = val;\n }\n\n /**\n * The functions below are all based on the `console` interface\n */\n\n debug(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n this._logHandler(this, LogLevel.DEBUG, ...args);\n }\n log(...args: unknown[]): void {\n this._userLogHandler &&\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n this._logHandler(this, LogLevel.VERBOSE, ...args);\n }\n info(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n this._logHandler(this, LogLevel.INFO, ...args);\n }\n warn(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n this._logHandler(this, LogLevel.WARN, ...args);\n }\n error(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n this._logHandler(this, LogLevel.ERROR, ...args);\n }\n}\n\nexport function setLogLevel(level: LogLevelString | LogLevel): void {\n instances.forEach(inst => {\n inst.setLogLevel(level);\n });\n}\n\nexport function setUserLogHandler(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n for (const instance of instances) {\n let customLogLevel: LogLevel | null = null;\n if (options && options.level) {\n customLogLevel = levelStringToEnum[options.level];\n }\n if (logCallback === null) {\n instance.userLogHandler = null;\n } else {\n instance.userLogHandler = (\n instance: Logger,\n level: LogLevel,\n ...args: unknown[]\n ) => {\n const message = args\n .map(arg => {\n if (arg == null) {\n return null;\n } else if (typeof arg === 'string') {\n return arg;\n } else if (typeof arg === 'number' || typeof arg === 'boolean') {\n return arg.toString();\n } else if (arg instanceof Error) {\n return arg.message;\n } else {\n try {\n return JSON.stringify(arg);\n } catch (ignored) {\n return null;\n }\n }\n })\n .filter(arg => arg)\n .join(' ');\n if (level >= (customLogLevel ?? instance.logLevel)) {\n logCallback({\n level: LogLevel[level].toLowerCase() as LogLevelString,\n message,\n args,\n type: instance.name\n });\n }\n };\n }\n }\n}\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n });\n }\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event.newVersion, event));\n }\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking) {\n db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n }\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event));\n }\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ComponentContainer,\n ComponentType,\n Provider,\n Name\n} from '@firebase/component';\nimport { PlatformLoggerService, VersionService } from './types';\n\nexport class PlatformLoggerServiceImpl implements PlatformLoggerService {\n constructor(private readonly container: ComponentContainer) {}\n // In initial implementation, this will be called by installations on\n // auth token refresh, and installations will send this string.\n getPlatformInfoString(): string {\n const providers = this.container.getProviders();\n // Loop through providers and get library/version pairs from any that are\n // version components.\n return providers\n .map(provider => {\n if (isVersionServiceProvider(provider)) {\n const service = provider.getImmediate() as VersionService;\n return `${service.library}/${service.version}`;\n } else {\n return null;\n }\n })\n .filter(logString => logString)\n .join(' ');\n }\n}\n/**\n *\n * @param provider check if this provider provides a VersionService\n *\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\n * provides VersionService. The provider is not necessarily a 'app-version'\n * provider.\n */\nfunction isVersionServiceProvider(provider: Provider<Name>): boolean {\n const component = provider.getComponent();\n return component?.type === ComponentType.VERSION;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/app');\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { name as appName } from '../package.json';\nimport { name as appCompatName } from '../../app-compat/package.json';\nimport { name as analyticsCompatName } from '../../../packages/analytics-compat/package.json';\nimport { name as analyticsName } from '../../../packages/analytics/package.json';\nimport { name as appCheckCompatName } from '../../../packages/app-check-compat/package.json';\nimport { name as appCheckName } from '../../../packages/app-check/package.json';\nimport { name as authName } from '../../../packages/auth/package.json';\nimport { name as authCompatName } from '../../../packages/auth-compat/package.json';\nimport { name as databaseName } from '../../../packages/database/package.json';\nimport { name as databaseCompatName } from '../../../packages/database-compat/package.json';\nimport { name as functionsName } from '../../../packages/functions/package.json';\nimport { name as functionsCompatName } from '../../../packages/functions-compat/package.json';\nimport { name as installationsName } from '../../../packages/installations/package.json';\nimport { name as installationsCompatName } from '../../../packages/installations-compat/package.json';\nimport { name as messagingName } from '../../../packages/messaging/package.json';\nimport { name as messagingCompatName } from '../../../packages/messaging-compat/package.json';\nimport { name as performanceName } from '../../../packages/performance/package.json';\nimport { name as performanceCompatName } from '../../../packages/performance-compat/package.json';\nimport { name as remoteConfigName } from '../../../packages/remote-config/package.json';\nimport { name as remoteConfigCompatName } from '../../../packages/remote-config-compat/package.json';\nimport { name as storageName } from '../../../packages/storage/package.json';\nimport { name as storageCompatName } from '../../../packages/storage-compat/package.json';\nimport { name as firestoreName } from '../../../packages/firestore/package.json';\nimport { name as firestoreCompatName } from '../../../packages/firestore-compat/package.json';\nimport { name as packageName } from '../../../packages/firebase/package.json';\n\n/**\n * The default app name\n *\n * @internal\n */\nexport const DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\nexport const PLATFORM_LOG_STRING = {\n [appName]: 'fire-core',\n [appCompatName]: 'fire-core-compat',\n [analyticsName]: 'fire-analytics',\n [analyticsCompatName]: 'fire-analytics-compat',\n [appCheckName]: 'fire-app-check',\n [appCheckCompatName]: 'fire-app-check-compat',\n [authName]: 'fire-auth',\n [authCompatName]: 'fire-auth-compat',\n [databaseName]: 'fire-rtdb',\n [databaseCompatName]: 'fire-rtdb-compat',\n [functionsName]: 'fire-fn',\n [functionsCompatName]: 'fire-fn-compat',\n [installationsName]: 'fire-iid',\n [installationsCompatName]: 'fire-iid-compat',\n [messagingName]: 'fire-fcm',\n [messagingCompatName]: 'fire-fcm-compat',\n [performanceName]: 'fire-perf',\n [performanceCompatName]: 'fire-perf-compat',\n [remoteConfigName]: 'fire-rc',\n [remoteConfigCompatName]: 'fire-rc-compat',\n [storageName]: 'fire-gcs',\n [storageCompatName]: 'fire-gcs-compat',\n [firestoreName]: 'fire-fst',\n [firestoreCompatName]: 'fire-fst-compat',\n 'fire-js': 'fire-js', // Platform identifier for JS SDK.\n [packageName]: 'fire-js-all'\n} as const;\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from './public-types';\nimport { Component, Provider, Name } from '@firebase/component';\nimport { logger } from './logger';\nimport { DEFAULT_ENTRY_NAME } from './constants';\nimport { FirebaseAppImpl } from './firebaseApp';\n\n/**\n * @internal\n */\nexport const _apps = new Map<string, FirebaseApp>();\n\n/**\n * Registered components.\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const _components = new Map<string, Component<any>>();\n\n/**\n * @param component - the component being added to this app's container\n *\n * @internal\n */\nexport function _addComponent<T extends Name>(\n app: FirebaseApp,\n component: Component<T>\n): void {\n try {\n (app as FirebaseAppImpl).container.addComponent(component);\n } catch (e) {\n logger.debug(\n `Component ${component.name} failed to register with FirebaseApp ${app.name}`,\n e\n );\n }\n}\n\n/**\n *\n * @internal\n */\nexport function _addOrOverwriteComponent(\n app: FirebaseApp,\n component: Component\n): void {\n (app as FirebaseAppImpl).container.addOrOverwriteComponent(component);\n}\n\n/**\n *\n * @param component - the component to register\n * @returns whether or not the component is registered successfully\n *\n * @internal\n */\nexport function _registerComponent<T extends Name>(\n component: Component<T>\n): boolean {\n const componentName = component.name;\n if (_components.has(componentName)) {\n logger.debug(\n `There were multiple attempts to register component ${componentName}.`\n );\n\n return false;\n }\n\n _components.set(componentName, component);\n\n // add the component to existing app instances\n for (const app of _apps.values()) {\n _addComponent(app as FirebaseAppImpl, component);\n }\n\n return true;\n}\n\n/**\n *\n * @param app - FirebaseApp instance\n * @param name - service name\n *\n * @returns the provider for the service with the matching name\n *\n * @internal\n */\nexport function _getProvider<T extends Name>(\n app: FirebaseApp,\n name: T\n): Provider<T> {\n const heartbeatController = (app as FirebaseAppImpl).container\n .getProvider('heartbeat')\n .getImmediate({ optional: true });\n if (heartbeatController) {\n void heartbeatController.triggerHeartbeat();\n }\n return (app as FirebaseAppImpl).container.getProvider(name);\n}\n\n/**\n *\n * @param app - FirebaseApp instance\n * @param name - service name\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\n *\n * @internal\n */\nexport function _removeServiceInstance<T extends Name>(\n app: FirebaseApp,\n name: T,\n instanceIdentifier: string = DEFAULT_ENTRY_NAME\n): void {\n _getProvider(app, name).clearInstance(instanceIdentifier);\n}\n\n/**\n * Test only\n *\n * @internal\n */\nexport function _clearComponents(): void {\n _components.clear();\n}\n\n/**\n * Exported in order to be used in app-compat package\n */\nexport { DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME };\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AppError {\n NO_APP = 'no-app',\n BAD_APP_NAME = 'bad-app-name',\n DUPLICATE_APP = 'duplicate-app',\n APP_DELETED = 'app-deleted',\n NO_OPTIONS = 'no-options',\n INVALID_APP_ARGUMENT = 'invalid-app-argument',\n INVALID_LOG_ARGUMENT = 'invalid-log-argument',\n IDB_OPEN = 'idb-open',\n IDB_GET = 'idb-get',\n IDB_WRITE = 'idb-set',\n IDB_DELETE = 'idb-delete'\n}\n\nconst ERRORS: ErrorMap<AppError> = {\n [AppError.NO_APP]:\n \"No Firebase App '{$appName}' has been created - \" +\n 'call initializeApp() first',\n [AppError.BAD_APP_NAME]: \"Illegal App name: '{$appName}\",\n [AppError.DUPLICATE_APP]:\n \"Firebase App named '{$appName}' already exists with different options or config\",\n [AppError.APP_DELETED]: \"Firebase App named '{$appName}' already deleted\",\n [AppError.NO_OPTIONS]:\n 'Need to provide options, when not being deployed to hosting via source.',\n [AppError.INVALID_APP_ARGUMENT]:\n 'firebase.{$appName}() takes either no argument or a ' +\n 'Firebase App instance.',\n [AppError.INVALID_LOG_ARGUMENT]:\n 'First argument to `onLog` must be null or a function.',\n [AppError.IDB_OPEN]:\n 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_GET]:\n 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_WRITE]:\n 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_DELETE]:\n 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.'\n};\n\ninterface ErrorParams {\n [AppError.NO_APP]: { appName: string };\n [AppError.BAD_APP_NAME]: { appName: string };\n [AppError.DUPLICATE_APP]: { appName: string };\n [AppError.APP_DELETED]: { appName: string };\n [AppError.INVALID_APP_ARGUMENT]: { appName: string };\n [AppError.IDB_OPEN]: { originalErrorMessage?: string };\n [AppError.IDB_GET]: { originalErrorMessage?: string };\n [AppError.IDB_WRITE]: { originalErrorMessage?: string };\n [AppError.IDB_DELETE]: { originalErrorMessage?: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<AppError, ErrorParams>(\n 'app',\n 'Firebase',\n ERRORS\n);\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseApp,\n FirebaseOptions,\n FirebaseAppSettings\n} from './public-types';\nimport {\n ComponentContainer,\n Component,\n ComponentType\n} from '@firebase/component';\nimport { ERROR_FACTORY, AppError } from './errors';\n\nexport class FirebaseAppImpl implements FirebaseApp {\n private readonly _options: FirebaseOptions;\n private readonly _name: string;\n /**\n * Original config values passed in as a constructor parameter.\n * It is only used to compare with another config object to support idempotent initializeApp().\n *\n * Updating automaticDataCollectionEnabled on the App instance will not change its value in _config.\n */\n private readonly _config: Required<FirebaseAppSettings>;\n private _automaticDataCollectionEnabled: boolean;\n private _isDeleted = false;\n private readonly _container: ComponentContainer;\n\n constructor(\n options: FirebaseOptions,\n config: Required<FirebaseAppSettings>,\n container: ComponentContainer\n ) {\n this._options = { ...options };\n this._config = { ...config };\n this._name = config.name;\n this._automaticDataCollectionEnabled =\n config.automaticDataCollectionEnabled;\n this._container = container;\n this.container.addComponent(\n new Component('app', () => this, ComponentType.PUBLIC)\n );\n }\n\n get automaticDataCollectionEnabled(): boolean {\n this.checkDestroyed();\n return this._automaticDataCollectionEnabled;\n }\n\n set automaticDataCollectionEnabled(val: boolean) {\n this.checkDestroyed();\n this._automaticDataCollectionEnabled = val;\n }\n\n get name(): string {\n this.checkDestroyed();\n return this._name;\n }\n\n get options(): FirebaseOptions {\n this.checkDestroyed();\n return this._options;\n }\n\n get config(): Required<FirebaseAppSettings> {\n this.checkDestroyed();\n return this._config;\n }\n\n get container(): ComponentContainer {\n return this._container;\n }\n\n get isDeleted(): boolean {\n return this._isDeleted;\n }\n\n set isDeleted(val: boolean) {\n this._isDeleted = val;\n }\n\n /**\n * This function will throw an Error if the App has already been deleted -\n * use before performing API actions on the App.\n */\n private checkDestroyed(): void {\n if (this.isDeleted) {\n throw ERROR_FACTORY.create(AppError.APP_DELETED, { appName: this._name });\n }\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseApp,\n FirebaseOptions,\n FirebaseAppSettings\n} from './public-types';\nimport { DEFAULT_ENTRY_NAME, PLATFORM_LOG_STRING } from './constants';\nimport { ERROR_FACTORY, AppError } from './errors';\nimport {\n ComponentContainer,\n Component,\n Name,\n ComponentType\n} from '@firebase/component';\nimport { version } from '../../firebase/package.json';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { _apps, _components, _registerComponent } from './internal';\nimport { logger } from './logger';\nimport {\n LogLevelString,\n setLogLevel as setLogLevelImpl,\n LogCallback,\n LogOptions,\n setUserLogHandler\n} from '@firebase/logger';\nimport { deepEqual, getDefaultAppConfig } from '@firebase/util';\n\nexport { FirebaseError } from '@firebase/util';\n\n/**\n * The current SDK version.\n *\n * @public\n */\nexport const SDK_VERSION = version;\n\n/**\n * Creates and initializes a {@link @firebase/app#FirebaseApp} instance.\n *\n * See\n * {@link\n * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app\n * | Add Firebase to your app} and\n * {@link\n * https://firebase.google.com/docs/web/setup#multiple-projects\n * | Initialize multiple projects} for detailed documentation.\n *\n * @example\n * ```javascript\n *\n * // Initialize default app\n * // Retrieve your own options values by adding a web app on\n * // https://console.firebase.google.com\n * initializeApp({\n * apiKey: \"AIza....\", // Auth / General Use\n * authDomain: \"YOUR_APP.firebaseapp.com\", // Auth with popup/redirect\n * databaseURL: \"https://YOUR_APP.firebaseio.com\", // Realtime Database\n * storageBucket: \"YOUR_APP.appspot.com\", // Storage\n * messagingSenderId: \"123456789\" // Cloud Messaging\n * });\n * ```\n *\n * @example\n * ```javascript\n *\n * // Initialize another app\n * const otherApp = initializeApp({\n * databaseURL: \"https://<OTHER_DATABASE_NAME>.firebaseio.com\",\n * storageBucket: \"<OTHER_STORAGE_BUCKET>.appspot.com\"\n * }, \"otherApp\");\n * ```\n *\n * @param options - Options to configure the app's services.\n * @param name - Optional name of the app to initialize. If no name\n * is provided, the default is `\"[DEFAULT]\"`.\n *\n * @returns The initialized app.\n *\n * @public\n */\nexport function initializeApp(\n options: FirebaseOptions,\n name?: string\n): FirebaseApp;\n/**\n * Creates and initializes a FirebaseApp instance.\n *\n * @param options - Options to configure the app's services.\n * @param config - FirebaseApp Configuration\n *\n * @public\n */\nexport function initializeApp(\n options: FirebaseOptions,\n config?: FirebaseAppSettings\n): FirebaseApp;\n/**\n * Creates and initializes a FirebaseApp instance.\n *\n * @public\n */\nexport function initializeApp(): FirebaseApp;\nexport function initializeApp(\n _options?: FirebaseOptions,\n rawConfig = {}\n): FirebaseApp {\n let options = _options;\n\n if (typeof rawConfig !== 'object') {\n const name = rawConfig;\n rawConfig = { name };\n }\n\n const config: Required<FirebaseAppSettings> = {\n name: DEFAULT_ENTRY_NAME,\n automaticDataCollectionEnabled: false,\n ...rawConfig\n };\n const name = config.name;\n\n if (typeof name !== 'string' || !name) {\n throw ERROR_FACTORY.create(AppError.BAD_APP_NAME, {\n appName: String(name)\n });\n }\n\n options ||= getDefaultAppConfig();\n\n if (!options) {\n throw ERROR_FACTORY.create(AppError.NO_OPTIONS);\n }\n\n const existingApp = _apps.get(name) as FirebaseAppImpl;\n if (existingApp) {\n // return the existing app if options and config deep equal the ones in the existing app.\n if (\n deepEqual(options, existingApp.options) &&\n deepEqual(config, existingApp.config)\n ) {\n return existingApp;\n } else {\n throw ERROR_FACTORY.create(AppError.DUPLICATE_APP, { appName: name });\n }\n }\n\n const container = new ComponentContainer(name);\n for (const component of _components.values()) {\n container.addComponent(component);\n }\n\n const newApp = new FirebaseAppImpl(options, config, container);\n\n _apps.set(name, newApp);\n\n return newApp;\n}\n\n/**\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\n *\n * When called with no arguments, the default app is returned. When an app name\n * is provided, the app corresponding to that name is returned.\n *\n * An exception is thrown if the app being retrieved has not yet been\n * initialized.\n *\n * @example\n * ```javascript\n * // Return the default app\n * const app = getApp();\n * ```\n *\n * @example\n * ```javascript\n * // Return a named app\n * const otherApp = getApp(\"otherApp\");\n * ```\n *\n * @param name - Optional name of the app to return. If no name is\n * provided, the default is `\"[DEFAULT]\"`.\n *\n * @returns The app corresponding to the provided app name.\n * If no app name is provided, the default app is returned.\n *\n * @public\n */\nexport function getApp(name: string = DEFAULT_ENTRY_NAME): FirebaseApp {\n const app = _apps.get(name);\n if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {\n return initializeApp();\n }\n if (!app) {\n throw ERROR_FACTORY.create(AppError.NO_APP, { appName: name });\n }\n\n return app;\n}\n\n/**\n * A (read-only) array of all initialized apps.\n * @public\n */\nexport function getApps(): FirebaseApp[] {\n return Array.from(_apps.values());\n}\n\n/**\n * Renders this app unusable and frees the resources of all associated\n * services.\n *\n * @example\n * ```javascript\n * deleteApp(app)\n * .then(function() {\n * console.log(\"App deleted successfully\");\n * })\n * .catch(function(error) {\n * console.log(\"Error deleting app:\", error);\n * });\n * ```\n *\n * @public\n */\nexport async function deleteApp(app: FirebaseApp): Promise<void> {\n const name = app.name;\n if (_apps.has(name)) {\n _apps.delete(name);\n await Promise.all(\n (app as FirebaseAppImpl).container\n .getProviders()\n .map(provider => provider.delete())\n );\n (app as FirebaseAppImpl).isDeleted = true;\n }\n}\n\n/**\n * Registers a library's name and version for platform logging purposes.\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\n * @param version - Current version of that library.\n * @param variant - Bundle variant, e.g., node, rn, etc.\n *\n * @public\n */\nexport function registerVersion(\n libraryKeyOrName: string,\n version: string,\n variant?: string\n): void {\n // TODO: We can use this check to whitelist strings when/if we set up\n // a good whitelist system.\n let library = PLATFORM_LOG_STRING[libraryKeyOrName] ?? libraryKeyOrName;\n if (variant) {\n library += `-${variant}`;\n }\n const libraryMismatch = library.match(/\\s|\\//);\n const versionMismatch = version.match(/\\s|\\//);\n if (libraryMismatch || versionMismatch) {\n const warning = [\n `Unable to register library \"${library}\" with version \"${version}\":`\n ];\n if (libraryMismatch) {\n warning.push(\n `library name \"${library}\" contains illegal characters (whitespace or \"/\")`\n );\n }\n if (libraryMismatch && versionMismatch) {\n warning.push('and');\n }\n if (versionMismatch) {\n warning.push(\n `version name \"${version}\" contains illegal characters (whitespace or \"/\")`\n );\n }\n logger.warn(warning.join(' '));\n return;\n }\n _registerComponent(\n new Component(\n `${library}-version` as Name,\n () => ({ library, version }),\n ComponentType.VERSION\n )\n );\n}\n\n/**\n * Sets log handler for all Firebase SDKs.\n * @param logCallback - An optional custom log handler that executes user code whenever\n * the Firebase SDK makes a logging call.\n *\n * @public\n */\nexport function onLog(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n if (logCallback !== null && typeof logCallback !== 'function') {\n throw ERROR_FACTORY.create(AppError.INVALID_LOG_ARGUMENT);\n }\n setUserLogHandler(logCallback, options);\n}\n\n/**\n * Sets log level for all Firebase SDKs.\n *\n * All of the log types above the current log level are captured (i.e. if\n * you set the log level to `info`, errors are logged, but `debug` and\n * `verbose` logs are not).\n *\n * @public\n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n setLogLevelImpl(logLevel);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { DBSchema, openDB, IDBPDatabase } from 'idb';\nimport { AppError, ERROR_FACTORY } from './errors';\nimport { FirebaseApp } from './public-types';\nimport { HeartbeatsInIndexedDB } from './types';\nimport { logger } from './logger';\n\nconst DB_NAME = 'firebase-heartbeat-database';\nconst DB_VERSION = 1;\nconst STORE_NAME = 'firebase-heartbeat-store';\n\ninterface AppDB extends DBSchema {\n 'firebase-heartbeat-store': {\n key: string;\n value: HeartbeatsInIndexedDB;\n };\n}\n\nlet dbPromise: Promise<IDBPDatabase<AppDB>> | null = null;\nfunction getDbPromise(): Promise<IDBPDatabase<AppDB>> {\n if (!dbPromise) {\n dbPromise = openDB<AppDB>(DB_NAME, DB_VERSION, {\n upgrade: (db, oldVersion) => {\n // We don't use 'break' in this switch statement, the fall-through\n // behavior is what we want, because if there are multiple versions between\n // the old version and the current version, we want ALL the migrations\n // that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (oldVersion) {\n case 0:\n db.createObjectStore(STORE_NAME);\n }\n }\n }).catch(e => {\n throw ERROR_FACTORY.create(AppError.IDB_OPEN, {\n originalErrorMessage: e.message\n });\n });\n }\n return dbPromise;\n}\n\nexport async function readHeartbeatsFromIndexedDB(\n app: FirebaseApp\n): Promise<HeartbeatsInIndexedDB | undefined> {\n try {\n const db = await getDbPromise();\n const result = await db\n .transaction(STORE_NAME)\n .objectStore(STORE_NAME)\n .get(computeKey(app));\n return result;\n } catch (e) {\n if (e instanceof FirebaseError) {\n logger.warn(e.message);\n } else {\n const idbGetError = ERROR_FACTORY.create(AppError.IDB_GET, {\n originalErrorMessage: (e as Error)?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\n\nexport async function writeHeartbeatsToIndexedDB(\n app: FirebaseApp,\n heartbeatObject: HeartbeatsInIndexedDB\n): Promise<void> {\n try {\n const db = await getDbPromise();\n const tx = db.transaction(STORE_NAME, 'readwrite');\n const objectStore = tx.objectStore(STORE_NAME);\n await objectStore.put(heartbeatObject, computeKey(app));\n await tx.done;\n } catch (e) {\n if (e instanceof FirebaseError) {\n logger.warn(e.message);\n } else {\n const idbGetError = ERROR_FACTORY.create(AppError.IDB_WRITE, {\n originalErrorMessage: (e as Error)?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\n\nfunction computeKey(app: FirebaseApp): string {\n return `${app.name}!${app.options.appId}`;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ComponentContainer } from '@firebase/component';\nimport {\n base64urlEncodeWithoutPadding,\n isIndexedDBAvailable,\n validateIndexedDBOpenable\n} from '@firebase/util';\nimport {\n readHeartbeatsFromIndexedDB,\n writeHeartbeatsToIndexedDB\n} from './indexeddb';\nimport { FirebaseApp } from './public-types';\nimport {\n HeartbeatsByUserAgent,\n HeartbeatService,\n HeartbeatsInIndexedDB,\n HeartbeatStorage,\n SingleDateHeartbeat\n} from './types';\n\nconst MAX_HEADER_BYTES = 1024;\n// 30 days\nconst STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;\n\nexport class HeartbeatServiceImpl implements HeartbeatService {\n /**\n * The persistence layer for heartbeats\n * Leave public for easier testing.\n */\n _storage: HeartbeatStorageImpl;\n\n /**\n * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\n * the header string.\n * Stores one record per date. This will be consolidated into the standard\n * format of one record per user agent string before being sent as a header.\n * Populated from indexedDB when the controller is instantiated and should\n * be kept in sync with indexedDB.\n * Leave public for easier testing.\n */\n _heartbeatsCache: HeartbeatsInIndexedDB | null = null;\n\n /**\n * the initialization promise for populating heartbeatCache.\n * If getHeartbeatsHeader() is called before the promise resolves\n * (hearbeatsCache == null), it should wait for this promise\n * Leave public for easier testing.\n */\n _heartbeatsCachePromise: Promise<HeartbeatsInIndexedDB>;\n constructor(private readonly container: ComponentContainer) {\n const app = this.container.getProvider('app').getImmediate();\n this._storage = new HeartbeatStorageImpl(app);\n this._heartbeatsCachePromise = this._storage.read().then(result => {\n this._heartbeatsCache = result;\n return result;\n });\n }\n\n /**\n * Called to report a heartbeat. The function will generate\n * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\n * to IndexedDB.\n * Note that we only store one heartbeat per day. So if a heartbeat for today is\n * already logged, subsequent calls to this function in the same day will be ignored.\n */\n async triggerHeartbeat(): Promise<void> {\n const platformLogger = this.container\n .getProvider('platform-logger')\n .getImmediate();\n\n // This is the \"Firebase user agent\" string from the platform logger\n // service, not the browser user agent.\n const agent = platformLogger.getPlatformInfoString();\n const date = getUTCDateString();\n if (this._heartbeatsCache?.heartbeats == null) {\n this._heartbeatsCache = await this._heartbeatsCachePromise;\n }\n // Do not store a heartbeat if one is already stored for this day\n // or if a header has already been sent today.\n if (\n this._heartbeatsCache.lastSentHeartbeatDate === date ||\n this._heartbeatsCache.heartbeats.some(\n singleDateHeartbeat => singleDateHeartbeat.date === date\n )\n ) {\n return;\n } else {\n // There is no entry for this date. Create one.\n this._heartbeatsCache.heartbeats.push({ date, agent });\n }\n // Remove entries older than 30 days.\n this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(\n singleDateHeartbeat => {\n const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\n const now = Date.now();\n return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\n }\n );\n return this._storage.overwrite(this._heartbeatsCache);\n }\n\n /**\n * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\n * It also clears all heartbeats from memory as well as in IndexedDB.\n *\n * NOTE: Consuming product SDKs should not send the header if this method\n * returns an empty string.\n */\n async getHeartbeatsHeader(): Promise<string> {\n if (this._heartbeatsCache === null) {\n await this._heartbeatsCachePromise;\n }\n // If it's still null or the array is empty, there is no data to send.\n if (\n this._heartbeatsCache?.heartbeats == null ||\n this._heartbeatsCache.heartbeats.length === 0\n ) {\n return '';\n }\n const date = getUTCDateString();\n // Extract as many heartbeats from the cache as will fit under the size limit.\n const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(\n this._heartbeatsCache.heartbeats\n );\n const headerString = base64urlEncodeWithoutPadding(\n JSON.stringify({ version: 2, heartbeats: heartbeatsToSend })\n );\n // Store last sent date to prevent another being logged/sent for the same day.\n this._heartbeatsCache.lastSentHeartbeatDate = date;\n if (unsentEntries.length > 0) {\n // Store any unsent entries if they exist.\n this._heartbeatsCache.heartbeats = unsentEntries;\n // This seems more likely than emptying the array (below) to lead to some odd state\n // since the cache isn't empty and this will be called again on the next request,\n // and is probably safest if we await it.\n await this._storage.overwrite(this._heartbeatsCache);\n } else {\n this._heartbeatsCache.heartbeats = [];\n // Do not wait for this, to reduce latency.\n void this._storage.overwrite(this._heartbeatsCache);\n }\n return headerString;\n }\n}\n\nfunction getUTCDateString(): string {\n const today = new Date();\n // Returns date format 'YYYY-MM-DD'\n return today.toISOString().substring(0, 10);\n}\n\nexport function extractHeartbeatsForHeader(\n heartbeatsCache: SingleDateHeartbeat[],\n maxSize = MAX_HEADER_BYTES\n): {\n heartbeatsToSend: HeartbeatsByUserAgent[];\n unsentEntries: SingleDateHeartbeat[];\n} {\n // Heartbeats grouped by user agent in the standard format to be sent in\n // the header.\n const heartbeatsToSend: HeartbeatsByUserAgent[] = [];\n // Single date format heartbeats that are not sent.\n let unsentEntries = heartbeatsCache.slice();\n for (const singleDateHeartbeat of heartbeatsCache) {\n // Look for an existing entry with the same user agent.\n const heartbeatEntry = heartbeatsToSend.find(\n hb => hb.agent === singleDateHeartbeat.agent\n );\n if (!heartbeatEntry) {\n // If no entry for this user agent exists, create one.\n heartbeatsToSend.push({\n agent: singleDateHeartbeat.agent,\n dates: [singleDateHeartbeat.date]\n });\n if (countBytes(heartbeatsToSend) > maxSize) {\n // If the header would exceed max size, remove the added heartbeat\n // entry and stop adding to the header.\n heartbeatsToSend.pop();\n break;\n }\n } else {\n heartbeatEntry.dates.push(singleDateHeartbeat.date);\n // If the header would exceed max size, remove the added date\n // and stop adding to the header.\n if (countBytes(heartbeatsToSend) > maxSize) {\n heartbeatEntry.dates.pop();\n break;\n }\n }\n // Pop unsent entry from queue. (Skipped if adding the entry exceeded\n // quota and the loop breaks early.)\n unsentEntries = unsentEntries.slice(1);\n }\n return {\n heartbeatsToSend,\n unsentEntries\n };\n}\n\nexport class HeartbeatStorageImpl implements HeartbeatStorage {\n private _canUseIndexedDBPromise: Promise<boolean>;\n constructor(public app: FirebaseApp) {\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\n }\n async runIndexedDBEnvironmentCheck(): Promise<boolean> {\n if (!isIndexedDBAvailable()) {\n return false;\n } else {\n return validateIndexedDBOpenable()\n .then(() => true)\n .catch(() => false);\n }\n }\n /**\n * Read all heartbeats.\n */\n async read(): Promise<HeartbeatsInIndexedDB> {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return { heartbeats: [] };\n } else {\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\n return idbHeartbeatObject || { heartbeats: [] };\n }\n }\n // overwrite the storage with the provided heartbeats\n async overwrite(heartbeatsObject: HeartbeatsInIndexedDB): Promise<void> {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n } else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate:\n heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: heartbeatsObject.heartbeats\n });\n }\n }\n // add heartbeats\n async add(heartbeatsObject: HeartbeatsInIndexedDB): Promise<void> {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n } else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate:\n heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: [\n ...existingHeartbeatsObject.heartbeats,\n ...heartbeatsObject.heartbeats\n ]\n });\n }\n }\n}\n\n/**\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\n * in a platform logging header JSON object, stringified, and converted\n * to base 64.\n */\nexport function countBytes(heartbeatsCache: HeartbeatsByUserAgent[]): number {\n // base64 has a restricted set of characters, all of which should be 1 byte.\n return base64urlEncodeWithoutPadding(\n // heartbeatsCache wrapper properties\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })\n ).length;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Component, ComponentType } from '@firebase/component';\nimport { PlatformLoggerServiceImpl } from './platformLoggerService';\nimport { name, version } from '../package.json';\nimport { _registerComponent } from './internal';\nimport { registerVersion } from './api';\nimport { HeartbeatServiceImpl } from './heartbeatService';\n\nexport function registerCoreComponents(variant?: string): void {\n _registerComponent(\n new Component(\n 'platform-logger',\n container => new PlatformLoggerServiceImpl(container),\n ComponentType.PRIVATE\n )\n );\n _registerComponent(\n new Component(\n 'heartbeat',\n container => new HeartbeatServiceImpl(container),\n ComponentType.PRIVATE\n )\n );\n\n // Register `app` package.\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n // Register platform SDK identifier (no version).\n registerVersion('fire-js', '');\n}\n","/**\n * Firebase App\n *\n * @remarks This package coordinates the communication between the different Firebase components\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerCoreComponents } from './registerCoreComponents';\n\nexport * from './api';\nexport * from './internal';\nexport * from './public-types';\n\nregisterCoreComponents('__RUNTIME_ENV__');\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { registerVersion } from '@firebase/app';\nimport { name, version } from '../package.json';\n\nregisterVersion(name, version, 'app');\nexport * from '@firebase/app';\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));\n });\n }\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking)\n db.addEventListener('versionchange', () => blocking());\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { version } from '../../package.json';\n\nexport const PENDING_TIMEOUT_MS = 10000;\n\nexport const PACKAGE_VERSION = `w:${version}`;\nexport const INTERNAL_AUTH_VERSION = 'FIS_v2';\n\nexport const INSTALLATIONS_API_URL =\n 'https://firebaseinstallations.googleapis.com/v1';\n\nexport const TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour\n\nexport const SERVICE = 'installations';\nexport const SERVICE_NAME = 'Installations';\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { SERVICE, SERVICE_NAME } from './constants';\n\nexport const enum ErrorCode {\n MISSING_APP_CONFIG_VALUES = 'missing-app-config-values',\n NOT_REGISTERED = 'not-registered',\n INSTALLATION_NOT_FOUND = 'installation-not-found',\n REQUEST_FAILED = 'request-failed',\n APP_OFFLINE = 'app-offline',\n DELETE_PENDING_REGISTRATION = 'delete-pending-registration'\n}\n\nconst ERROR_DESCRIPTION_MAP: { readonly [key in ErrorCode]: string } = {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]:\n 'Missing App configuration value: \"{$valueName}\"',\n [ErrorCode.NOT_REGISTERED]: 'Firebase Installation is not registered.',\n [ErrorCode.INSTALLATION_NOT_FOUND]: 'Firebase Installation not found.',\n [ErrorCode.REQUEST_FAILED]:\n '{$requestName} request failed with error \"{$serverCode} {$serverStatus}: {$serverMessage}\"',\n [ErrorCode.APP_OFFLINE]: 'Could not process request. Application offline.',\n [ErrorCode.DELETE_PENDING_REGISTRATION]:\n \"Can't delete installation while there is a pending registration request.\"\n};\n\ninterface ErrorParams {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]: {\n valueName: string;\n };\n [ErrorCode.REQUEST_FAILED]: {\n requestName: string;\n [index: string]: string | number; // to make Typescript 3.8 happy\n } & ServerErrorData;\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<ErrorCode, ErrorParams>(\n SERVICE,\n SERVICE_NAME,\n ERROR_DESCRIPTION_MAP\n);\n\nexport interface ServerErrorData {\n serverCode: number;\n serverMessage: string;\n serverStatus: string;\n}\n\nexport type ServerError = FirebaseError & { customData: ServerErrorData };\n\n/** Returns true if error is a FirebaseError that is based on an error from the server. */\nexport function isServerError(error: unknown): error is ServerError {\n return (\n error instanceof FirebaseError &&\n error.code.includes(ErrorCode.REQUEST_FAILED)\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { GenerateAuthTokenResponse } from '../interfaces/api-response';\nimport {\n CompletedAuthToken,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport {\n INSTALLATIONS_API_URL,\n INTERNAL_AUTH_VERSION\n} from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport { AppConfig } from '../interfaces/installation-impl';\n\nexport function getInstallationsEndpoint({ projectId }: AppConfig): string {\n return `${INSTALLATIONS_API_URL}/projects/${projectId}/installations`;\n}\n\nexport function extractAuthTokenInfoFromResponse(\n response: GenerateAuthTokenResponse\n): CompletedAuthToken {\n return {\n token: response.token,\n requestStatus: RequestStatus.COMPLETED,\n expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),\n creationTime: Date.now()\n };\n}\n\nexport async function getErrorFromResponse(\n requestName: string,\n response: Response\n): Promise<FirebaseError> {\n const responseJson: ErrorResponse = await response.json();\n const errorData = responseJson.error;\n return ERROR_FACTORY.create(ErrorCode.REQUEST_FAILED, {\n requestName,\n serverCode: errorData.code,\n serverMessage: errorData.message,\n serverStatus: errorData.status\n });\n}\n\nexport function getHeaders({ apiKey }: AppConfig): Headers {\n return new Headers({\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'x-goog-api-key': apiKey\n });\n}\n\nexport function getHeadersWithAuth(\n appConfig: AppConfig,\n { refreshToken }: RegisteredInstallationEntry\n): Headers {\n const headers = getHeaders(appConfig);\n headers.append('Authorization', getAuthorizationHeader(refreshToken));\n return headers;\n}\n\nexport interface ErrorResponse {\n error: {\n code: number;\n message: string;\n status: string;\n };\n}\n\n/**\n * Calls the passed in fetch wrapper and returns the response.\n * If the returned response has a status of 5xx, re-runs the function once and\n * returns the response.\n */\nexport async function retryIfServerError(\n fn: () => Promise<Response>\n): Promise<Response> {\n const result = await fn();\n\n if (result.status >= 500 && result.status < 600) {\n // Internal Server Error. Retry request.\n return fn();\n }\n\n return result;\n}\n\nfunction getExpiresInFromResponseExpiresIn(responseExpiresIn: string): number {\n // This works because the server will never respond with fractions of a second.\n return Number(responseExpiresIn.replace('s', '000'));\n}\n\nfunction getAuthorizationHeader(refreshToken: string): string {\n return `${INTERNAL_AUTH_VERSION} ${refreshToken}`;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Returns a promise that resolves after given time passes. */\nexport function sleep(ms: number): Promise<void> {\n return new Promise<void>(resolve => {\n setTimeout(resolve, ms);\n });\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bufferToBase64UrlSafe } from './buffer-to-base64-url-safe';\n\nexport const VALID_FID_PATTERN = /^[cdef][\\w-]{21}$/;\nexport const INVALID_FID = '';\n\n/**\n * Generates a new FID using random values from Web Crypto API.\n * Returns an empty string if FID generation fails for any reason.\n */\nexport function generateFid(): string {\n try {\n // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5\n // bytes. our implementation generates a 17 byte array instead.\n const fidByteArray = new Uint8Array(17);\n const crypto =\n self.crypto || (self as unknown as { msCrypto: Crypto }).msCrypto;\n crypto.getRandomValues(fidByteArray);\n\n // Replace the first 4 random bits with the constant FID header of 0b0111.\n fidByteArray[0] = 0b01110000 + (fidByteArray[0] % 0b00010000);\n\n const fid = encode(fidByteArray);\n\n return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;\n } catch {\n // FID generation errored\n return INVALID_FID;\n }\n}\n\n/** Converts a FID Uint8Array to a base64 string representation. */\nfunction encode(fidByteArray: Uint8Array): string {\n const b64String = bufferToBase64UrlSafe(fidByteArray);\n\n // Remove the 23rd character that was added because of the extra 4 bits at the\n // end of our 17 byte array, and the '=' padding.\n return b64String.substr(0, 22);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function bufferToBase64UrlSafe(array: Uint8Array): string {\n const b64 = btoa(String.fromCharCode(...array));\n return b64.replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppConfig } from '../interfaces/installation-impl';\n\n/** Returns a string key that can be used to identify the app. */\nexport function getKey(appConfig: AppConfig): string {\n return `${appConfig.appName}!${appConfig.appId}`;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getKey } from '../util/get-key';\nimport { AppConfig } from '../interfaces/installation-impl';\nimport { IdChangeCallbackFn } from '../api';\n\nconst fidChangeCallbacks: Map<string, Set<IdChangeCallbackFn>> = new Map();\n\n/**\n * Calls the onIdChange callbacks with the new FID value, and broadcasts the\n * change to other tabs.\n */\nexport function fidChanged(appConfig: AppConfig, fid: string): void {\n const key = getKey(appConfig);\n\n callFidChangeCallbacks(key, fid);\n broadcastFidChange(key, fid);\n}\n\nexport function addCallback(\n appConfig: AppConfig,\n callback: IdChangeCallbackFn\n): void {\n // Open the broadcast channel if it's not already open,\n // to be able to listen to change events from other tabs.\n getBroadcastChannel();\n\n const key = getKey(appConfig);\n\n let callbackSet = fidChangeCallbacks.get(key);\n if (!callbackSet) {\n callbackSet = new Set();\n fidChangeCallbacks.set(key, callbackSet);\n }\n callbackSet.add(callback);\n}\n\nexport function removeCallback(\n appConfig: AppConfig,\n callback: IdChangeCallbackFn\n): void {\n const key = getKey(appConfig);\n\n const callbackSet = fidChangeCallbacks.get(key);\n\n if (!callbackSet) {\n return;\n }\n\n callbackSet.delete(callback);\n if (callbackSet.size === 0) {\n fidChangeCallbacks.delete(key);\n }\n\n // Close broadcast channel if there are no more callbacks.\n closeBroadcastChannel();\n}\n\nfunction callFidChangeCallbacks(key: string, fid: string): void {\n const callbacks = fidChangeCallbacks.get(key);\n if (!callbacks) {\n return;\n }\n\n for (const callback of callbacks) {\n callback(fid);\n }\n}\n\nfunction broadcastFidChange(key: string, fid: string): void {\n const channel = getBroadcastChannel();\n if (channel) {\n channel.postMessage({ key, fid });\n }\n closeBroadcastChannel();\n}\n\nlet broadcastChannel: BroadcastChannel | null = null;\n/** Opens and returns a BroadcastChannel if it is supported by the browser. */\nfunction getBroadcastChannel(): BroadcastChannel | null {\n if (!broadcastChannel && 'BroadcastChannel' in self) {\n broadcastChannel = new BroadcastChannel('[Firebase] FID Change');\n broadcastChannel.onmessage = e => {\n callFidChangeCallbacks(e.data.key, e.data.fid);\n };\n }\n return broadcastChannel;\n}\n\nfunction closeBroadcastChannel(): void {\n if (fidChangeCallbacks.size === 0 && broadcastChannel) {\n broadcastChannel.close();\n broadcastChannel = null;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DBSchema, IDBPDatabase, openDB } from 'idb';\nimport { AppConfig } from '../interfaces/installation-impl';\nimport { InstallationEntry } from '../interfaces/installation-entry';\nimport { getKey } from '../util/get-key';\nimport { fidChanged } from './fid-changed';\n\nconst DATABASE_NAME = 'firebase-installations-database';\nconst DATABASE_VERSION = 1;\nconst OBJECT_STORE_NAME = 'firebase-installations-store';\n\ninterface InstallationsDB extends DBSchema {\n 'firebase-installations-store': {\n key: string;\n value: InstallationEntry | undefined;\n };\n}\n\nlet dbPromise: Promise<IDBPDatabase<InstallationsDB>> | null = null;\nfunction getDbPromise(): Promise<IDBPDatabase<InstallationsDB>> {\n if (!dbPromise) {\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\n upgrade: (db, oldVersion) => {\n // We don't use 'break' in this switch statement, the fall-through\n // behavior is what we want, because if there are multiple versions between\n // the old version and the current version, we want ALL the migrations\n // that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (oldVersion) {\n case 0:\n db.createObjectStore(OBJECT_STORE_NAME);\n }\n }\n });\n }\n return dbPromise;\n}\n\n/** Gets record(s) from the objectStore that match the given key. */\nexport async function get(\n appConfig: AppConfig\n): Promise<InstallationEntry | undefined> {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n return db\n .transaction(OBJECT_STORE_NAME)\n .objectStore(OBJECT_STORE_NAME)\n .get(key) as Promise<InstallationEntry>;\n}\n\n/** Assigns or overwrites the record for the given key with the given value. */\nexport async function set<ValueType extends InstallationEntry>(\n appConfig: AppConfig,\n value: ValueType\n): Promise<ValueType> {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n const objectStore = tx.objectStore(OBJECT_STORE_NAME);\n const oldValue = (await objectStore.get(key)) as InstallationEntry;\n await objectStore.put(value, key);\n await tx.done;\n\n if (!oldValue || oldValue.fid !== value.fid) {\n fidChanged(appConfig, value.fid);\n }\n\n return value;\n}\n\n/** Removes record(s) from the objectStore that match the given key. */\nexport async function remove(appConfig: AppConfig): Promise<void> {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\n await tx.done;\n}\n\n/**\n * Atomically updates a record with the result of updateFn, which gets\n * called with the current value. If newValue is undefined, the record is\n * deleted instead.\n * @return Updated value\n */\nexport async function update<ValueType extends InstallationEntry | undefined>(\n appConfig: AppConfig,\n updateFn: (previousValue: InstallationEntry | undefined) => ValueType\n): Promise<ValueType> {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n const store = tx.objectStore(OBJECT_STORE_NAME);\n const oldValue: InstallationEntry | undefined = (await store.get(\n key\n )) as InstallationEntry;\n const newValue = updateFn(oldValue);\n\n if (newValue === undefined) {\n await store.delete(key);\n } else {\n await store.put(newValue, key);\n }\n await tx.done;\n\n if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {\n fidChanged(appConfig, newValue.fid);\n }\n\n return newValue;\n}\n\nexport async function clear(): Promise<void> {\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n await tx.objectStore(OBJECT_STORE_NAME).clear();\n await tx.done;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createInstallationRequest } from '../functions/create-installation-request';\nimport {\n AppConfig,\n FirebaseInstallationsImpl\n} from '../interfaces/installation-impl';\nimport {\n InProgressInstallationEntry,\n InstallationEntry,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport { PENDING_TIMEOUT_MS } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode, isServerError } from '../util/errors';\nimport { sleep } from '../util/sleep';\nimport { generateFid, INVALID_FID } from './generate-fid';\nimport { remove, set, update } from './idb-manager';\n\nexport interface InstallationEntryWithRegistrationPromise {\n installationEntry: InstallationEntry;\n /** Exist iff the installationEntry is not registered. */\n registrationPromise?: Promise<RegisteredInstallationEntry>;\n}\n\n/**\n * Updates and returns the InstallationEntry from the database.\n * Also triggers a registration request if it is necessary and possible.\n */\nexport async function getInstallationEntry(\n installations: FirebaseInstallationsImpl\n): Promise<InstallationEntryWithRegistrationPromise> {\n let registrationPromise: Promise<RegisteredInstallationEntry> | undefined;\n\n const installationEntry = await update(installations.appConfig, oldEntry => {\n const installationEntry = updateOrCreateInstallationEntry(oldEntry);\n const entryWithPromise = triggerRegistrationIfNecessary(\n installations,\n installationEntry\n );\n registrationPromise = entryWithPromise.registrationPromise;\n return entryWithPromise.installationEntry;\n });\n\n if (installationEntry.fid === INVALID_FID) {\n // FID generation failed. Waiting for the FID from the server.\n return { installationEntry: await registrationPromise! };\n }\n\n return {\n installationEntry,\n registrationPromise\n };\n}\n\n/**\n * Creates a new Installation Entry if one does not exist.\n * Also clears timed out pending requests.\n */\nfunction updateOrCreateInstallationEntry(\n oldEntry: InstallationEntry | undefined\n): InstallationEntry {\n const entry: InstallationEntry = oldEntry || {\n fid: generateFid(),\n registrationStatus: RequestStatus.NOT_STARTED\n };\n\n return clearTimedOutRequest(entry);\n}\n\n/**\n * If the Firebase Installation is not registered yet, this will trigger the\n * registration and return an InProgressInstallationEntry.\n *\n * If registrationPromise does not exist, the installationEntry is guaranteed\n * to be registered.\n */\nfunction triggerRegistrationIfNecessary(\n installations: FirebaseInstallationsImpl,\n installationEntry: InstallationEntry\n): InstallationEntryWithRegistrationPromise {\n if (installationEntry.registrationStatus === RequestStatus.NOT_STARTED) {\n if (!navigator.onLine) {\n // Registration required but app is offline.\n const registrationPromiseWithError = Promise.reject(\n ERROR_FACTORY.create(ErrorCode.APP_OFFLINE)\n );\n return {\n installationEntry,\n registrationPromise: registrationPromiseWithError\n };\n }\n\n // Try registering. Change status to IN_PROGRESS.\n const inProgressEntry: InProgressInstallationEntry = {\n fid: installationEntry.fid,\n registrationStatus: RequestStatus.IN_PROGRESS,\n registrationTime: Date.now()\n };\n const registrationPromise = registerInstallation(\n installations,\n inProgressEntry\n );\n return { installationEntry: inProgressEntry, registrationPromise };\n } else if (\n installationEntry.registrationStatus === RequestStatus.IN_PROGRESS\n ) {\n return {\n installationEntry,\n registrationPromise: waitUntilFidRegistration(installations)\n };\n } else {\n return { installationEntry };\n }\n}\n\n/** This will be executed only once for each new Firebase Installation. */\nasync function registerInstallation(\n installations: FirebaseInstallationsImpl,\n installationEntry: InProgressInstallationEntry\n): Promise<RegisteredInstallationEntry> {\n try {\n const registeredInstallationEntry = await createInstallationRequest(\n installations,\n installationEntry\n );\n return set(installations.appConfig, registeredInstallationEntry);\n } catch (e) {\n if (isServerError(e) && e.customData.serverCode === 409) {\n // Server returned a \"FID can not be used\" error.\n // Generate a new ID next time.\n await remove(installations.appConfig);\n } else {\n // Registration failed. Set FID as not registered.\n await set(installations.appConfig, {\n fid: installationEntry.fid,\n registrationStatus: RequestStatus.NOT_STARTED\n });\n }\n throw e;\n }\n}\n\n/** Call if FID registration is pending in another request. */\nasync function waitUntilFidRegistration(\n installations: FirebaseInstallationsImpl\n): Promise<RegisteredInstallationEntry> {\n // Unfortunately, there is no way of reliably observing when a value in\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\n // so we need to poll.\n\n let entry: InstallationEntry = await updateInstallationRequest(\n installations.appConfig\n );\n while (entry.registrationStatus === RequestStatus.IN_PROGRESS) {\n // createInstallation request still in progress.\n await sleep(100);\n\n entry = await updateInstallationRequest(installations.appConfig);\n }\n\n if (entry.registrationStatus === RequestStatus.NOT_STARTED) {\n // The request timed out or failed in a different call. Try again.\n const { installationEntry, registrationPromise } =\n await getInstallationEntry(installations);\n\n if (registrationPromise) {\n return registrationPromise;\n } else {\n // if there is no registrationPromise, entry is registered.\n return installationEntry as RegisteredInstallationEntry;\n }\n }\n\n return entry;\n}\n\n/**\n * Called only if there is a CreateInstallation request in progress.\n *\n * Updates the InstallationEntry in the DB based on the status of the\n * CreateInstallation request.\n *\n * Returns the updated InstallationEntry.\n */\nfunction updateInstallationRequest(\n appConfig: AppConfig\n): Promise<InstallationEntry> {\n return update(appConfig, oldEntry => {\n if (!oldEntry) {\n throw ERROR_FACTORY.create(ErrorCode.INSTALLATION_NOT_FOUND);\n }\n return clearTimedOutRequest(oldEntry);\n });\n}\n\nfunction clearTimedOutRequest(entry: InstallationEntry): InstallationEntry {\n if (hasInstallationRequestTimedOut(entry)) {\n return {\n fid: entry.fid,\n registrationStatus: RequestStatus.NOT_STARTED\n };\n }\n\n return entry;\n}\n\nfunction hasInstallationRequestTimedOut(\n installationEntry: InstallationEntry\n): boolean {\n return (\n installationEntry.registrationStatus === RequestStatus.IN_PROGRESS &&\n installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now()\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CreateInstallationResponse } from '../interfaces/api-response';\nimport {\n InProgressInstallationEntry,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport { INTERNAL_AUTH_VERSION, PACKAGE_VERSION } from '../util/constants';\nimport {\n extractAuthTokenInfoFromResponse,\n getErrorFromResponse,\n getHeaders,\n getInstallationsEndpoint,\n retryIfServerError\n} from './common';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\n\nexport async function createInstallationRequest(\n { appConfig, heartbeatServiceProvider }: FirebaseInstallationsImpl,\n { fid }: InProgressInstallationEntry\n): Promise<RegisteredInstallationEntry> {\n const endpoint = getInstallationsEndpoint(appConfig);\n\n const headers = getHeaders(appConfig);\n\n // If heartbeat service exists, add the heartbeat string to the header.\n const heartbeatService = heartbeatServiceProvider.getImmediate({\n optional: true\n });\n if (heartbeatService) {\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers.append('x-firebase-client', heartbeatsHeader);\n }\n }\n\n const body = {\n fid,\n authVersion: INTERNAL_AUTH_VERSION,\n appId: appConfig.appId,\n sdkVersion: PACKAGE_VERSION\n };\n\n const request: RequestInit = {\n method: 'POST',\n headers,\n body: JSON.stringify(body)\n };\n\n const response = await retryIfServerError(() => fetch(endpoint, request));\n if (response.ok) {\n const responseValue: CreateInstallationResponse = await response.json();\n const registeredInstallationEntry: RegisteredInstallationEntry = {\n fid: responseValue.fid || fid,\n registrationStatus: RequestStatus.COMPLETED,\n refreshToken: responseValue.refreshToken,\n authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)\n };\n return registeredInstallationEntry;\n } else {\n throw await getErrorFromResponse('Create Installation', response);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GenerateAuthTokenResponse } from '../interfaces/api-response';\nimport {\n CompletedAuthToken,\n RegisteredInstallationEntry\n} from '../interfaces/installation-entry';\nimport { PACKAGE_VERSION } from '../util/constants';\nimport {\n extractAuthTokenInfoFromResponse,\n getErrorFromResponse,\n getHeadersWithAuth,\n getInstallationsEndpoint,\n retryIfServerError\n} from './common';\nimport {\n FirebaseInstallationsImpl,\n AppConfig\n} from '../interfaces/installation-impl';\n\nexport async function generateAuthTokenRequest(\n { appConfig, heartbeatServiceProvider }: FirebaseInstallationsImpl,\n installationEntry: RegisteredInstallationEntry\n): Promise<CompletedAuthToken> {\n const endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);\n\n const headers = getHeadersWithAuth(appConfig, installationEntry);\n\n // If heartbeat service exists, add the heartbeat string to the header.\n const heartbeatService = heartbeatServiceProvider.getImmediate({\n optional: true\n });\n if (heartbeatService) {\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers.append('x-firebase-client', heartbeatsHeader);\n }\n }\n\n const body = {\n installation: {\n sdkVersion: PACKAGE_VERSION,\n appId: appConfig.appId\n }\n };\n\n const request: RequestInit = {\n method: 'POST',\n headers,\n body: JSON.stringify(body)\n };\n\n const response = await retryIfServerError(() => fetch(endpoint, request));\n if (response.ok) {\n const responseValue: GenerateAuthTokenResponse = await response.json();\n const completedAuthToken: CompletedAuthToken =\n extractAuthTokenInfoFromResponse(responseValue);\n return completedAuthToken;\n } else {\n throw await getErrorFromResponse('Generate Auth Token', response);\n }\n}\n\nfunction getGenerateAuthTokenEndpoint(\n appConfig: AppConfig,\n { fid }: RegisteredInstallationEntry\n): string {\n return `${getInstallationsEndpoint(appConfig)}/${fid}/authTokens:generate`;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { generateAuthTokenRequest } from '../functions/generate-auth-token-request';\nimport {\n AppConfig,\n FirebaseInstallationsImpl\n} from '../interfaces/installation-impl';\nimport {\n AuthToken,\n CompletedAuthToken,\n InProgressAuthToken,\n InstallationEntry,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport { PENDING_TIMEOUT_MS, TOKEN_EXPIRATION_BUFFER } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode, isServerError } from '../util/errors';\nimport { sleep } from '../util/sleep';\nimport { remove, set, update } from './idb-manager';\n\n/**\n * Returns a valid authentication token for the installation. Generates a new\n * token if one doesn't exist, is expired or about to expire.\n *\n * Should only be called if the Firebase Installation is registered.\n */\nexport async function refreshAuthToken(\n installations: FirebaseInstallationsImpl,\n forceRefresh = false\n): Promise<CompletedAuthToken> {\n let tokenPromise: Promise<CompletedAuthToken> | undefined;\n const entry = await update(installations.appConfig, oldEntry => {\n if (!isEntryRegistered(oldEntry)) {\n throw ERROR_FACTORY.create(ErrorCode.NOT_REGISTERED);\n }\n\n const oldAuthToken = oldEntry.authToken;\n if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {\n // There is a valid token in the DB.\n return oldEntry;\n } else if (oldAuthToken.requestStatus === RequestStatus.IN_PROGRESS) {\n // There already is a token request in progress.\n tokenPromise = waitUntilAuthTokenRequest(installations, forceRefresh);\n return oldEntry;\n } else {\n // No token or token expired.\n if (!navigator.onLine) {\n throw ERROR_FACTORY.create(ErrorCode.APP_OFFLINE);\n }\n\n const inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);\n tokenPromise = fetchAuthTokenFromServer(installations, inProgressEntry);\n return inProgressEntry;\n }\n });\n\n const authToken = tokenPromise\n ? await tokenPromise\n : (entry.authToken as CompletedAuthToken);\n return authToken;\n}\n\n/**\n * Call only if FID is registered and Auth Token request is in progress.\n *\n * Waits until the current pending request finishes. If the request times out,\n * tries once in this thread as well.\n */\nasync function waitUntilAuthTokenRequest(\n installations: FirebaseInstallationsImpl,\n forceRefresh: boolean\n): Promise<CompletedAuthToken> {\n // Unfortunately, there is no way of reliably observing when a value in\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\n // so we need to poll.\n\n let entry = await updateAuthTokenRequest(installations.appConfig);\n while (entry.authToken.requestStatus === RequestStatus.IN_PROGRESS) {\n // generateAuthToken still in progress.\n await sleep(100);\n\n entry = await updateAuthTokenRequest(installations.appConfig);\n }\n\n const authToken = entry.authToken;\n if (authToken.requestStatus === RequestStatus.NOT_STARTED) {\n // The request timed out or failed in a different call. Try again.\n return refreshAuthToken(installations, forceRefresh);\n } else {\n return authToken;\n }\n}\n\n/**\n * Called only if there is a GenerateAuthToken request in progress.\n *\n * Updates the InstallationEntry in the DB based on the status of the\n * GenerateAuthToken request.\n *\n * Returns the updated InstallationEntry.\n */\nfunction updateAuthTokenRequest(\n appConfig: AppConfig\n): Promise<RegisteredInstallationEntry> {\n return update(appConfig, oldEntry => {\n if (!isEntryRegistered(oldEntry)) {\n throw ERROR_FACTORY.create(ErrorCode.NOT_REGISTERED);\n }\n\n const oldAuthToken = oldEntry.authToken;\n if (hasAuthTokenRequestTimedOut(oldAuthToken)) {\n return {\n ...oldEntry,\n authToken: { requestStatus: RequestStatus.NOT_STARTED }\n };\n }\n\n return oldEntry;\n });\n}\n\nasync function fetchAuthTokenFromServer(\n installations: FirebaseInstallationsImpl,\n installationEntry: RegisteredInstallationEntry\n): Promise<CompletedAuthToken> {\n try {\n const authToken = await generateAuthTokenRequest(\n installations,\n installationEntry\n );\n const updatedInstallationEntry: RegisteredInstallationEntry = {\n ...installationEntry,\n authToken\n };\n await set(installations.appConfig, updatedInstallationEntry);\n return authToken;\n } catch (e) {\n if (\n isServerError(e) &&\n (e.customData.serverCode === 401 || e.customData.serverCode === 404)\n ) {\n // Server returned a \"FID not found\" or a \"Invalid authentication\" error.\n // Generate a new ID next time.\n await remove(installations.appConfig);\n } else {\n const updatedInstallationEntry: RegisteredInstallationEntry = {\n ...installationEntry,\n authToken: { requestStatus: RequestStatus.NOT_STARTED }\n };\n await set(installations.appConfig, updatedInstallationEntry);\n }\n throw e;\n }\n}\n\nfunction isEntryRegistered(\n installationEntry: InstallationEntry | undefined\n): installationEntry is RegisteredInstallationEntry {\n return (\n installationEntry !== undefined &&\n installationEntry.registrationStatus === RequestStatus.COMPLETED\n );\n}\n\nfunction isAuthTokenValid(authToken: AuthToken): boolean {\n return (\n authToken.requestStatus === RequestStatus.COMPLETED &&\n !isAuthTokenExpired(authToken)\n );\n}\n\nfunction isAuthTokenExpired(authToken: CompletedAuthToken): boolean {\n const now = Date.now();\n return (\n now < authToken.creationTime ||\n authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER\n );\n}\n\n/** Returns an updated InstallationEntry with an InProgressAuthToken. */\nfunction makeAuthTokenRequestInProgressEntry(\n oldEntry: RegisteredInstallationEntry\n): RegisteredInstallationEntry {\n const inProgressAuthToken: InProgressAuthToken = {\n requestStatus: RequestStatus.IN_PROGRESS,\n requestTime: Date.now()\n };\n return {\n ...oldEntry,\n authToken: inProgressAuthToken\n };\n}\n\nfunction hasAuthTokenRequestTimedOut(authToken: AuthToken): boolean {\n return (\n authToken.requestStatus === RequestStatus.IN_PROGRESS &&\n authToken.requestTime + PENDING_TIMEOUT_MS < Date.now()\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getInstallationEntry } from '../helpers/get-installation-entry';\nimport { refreshAuthToken } from '../helpers/refresh-auth-token';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { Installations } from '../interfaces/public-types';\n\n/**\n * Returns a Firebase Installations auth token, identifying the current\n * Firebase Installation.\n * @param installations - The `Installations` instance.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport async function getToken(\n installations: Installations,\n forceRefresh = false\n): Promise<string> {\n const installationsImpl = installations as FirebaseInstallationsImpl;\n await completeInstallationRegistration(installationsImpl);\n\n // At this point we either have a Registered Installation in the DB, or we've\n // already thrown an error.\n const authToken = await refreshAuthToken(installationsImpl, forceRefresh);\n return authToken.token;\n}\n\nasync function completeInstallationRegistration(\n installations: FirebaseInstallationsImpl\n): Promise<void> {\n const { registrationPromise } = await getInstallationEntry(installations);\n\n if (registrationPromise) {\n // A createInstallation request is in progress. Wait until it finishes.\n await registrationPromise;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, FirebaseOptions } from '@firebase/app';\nimport { FirebaseError } from '@firebase/util';\nimport { AppConfig } from '../interfaces/installation-impl';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nexport function extractAppConfig(app: FirebaseApp): AppConfig {\n if (!app || !app.options) {\n throw getMissingValueError('App Configuration');\n }\n\n if (!app.name) {\n throw getMissingValueError('App Name');\n }\n\n // Required app config keys\n const configKeys: Array<keyof FirebaseOptions> = [\n 'projectId',\n 'apiKey',\n 'appId'\n ];\n\n for (const keyName of configKeys) {\n if (!app.options[keyName]) {\n throw getMissingValueError(keyName);\n }\n }\n\n return {\n appName: app.name,\n projectId: app.options.projectId!,\n apiKey: app.options.apiKey!,\n appId: app.options.appId!\n };\n}\n\nfunction getMissingValueError(valueName: string): FirebaseError {\n return ERROR_FACTORY.create(ErrorCode.MISSING_APP_CONFIG_VALUES, {\n valueName\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _registerComponent, _getProvider } from '@firebase/app';\nimport {\n Component,\n ComponentType,\n InstanceFactory,\n ComponentContainer\n} from '@firebase/component';\nimport { getId, getToken } from '../api/index';\nimport { _FirebaseInstallationsInternal } from '../interfaces/public-types';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { extractAppConfig } from '../helpers/extract-app-config';\n\nconst INSTALLATIONS_NAME = 'installations';\nconst INSTALLATIONS_NAME_INTERNAL = 'installations-internal';\n\nconst publicFactory: InstanceFactory<'installations'> = (\n container: ComponentContainer\n) => {\n const app = container.getProvider('app').getImmediate();\n // Throws if app isn't configured properly.\n const appConfig = extractAppConfig(app);\n const heartbeatServiceProvider = _getProvider(app, 'heartbeat');\n\n const installationsImpl: FirebaseInstallationsImpl = {\n app,\n appConfig,\n heartbeatServiceProvider,\n _delete: () => Promise.resolve()\n };\n return installationsImpl;\n};\n\nconst internalFactory: InstanceFactory<'installations-internal'> = (\n container: ComponentContainer\n) => {\n const app = container.getProvider('app').getImmediate();\n // Internal FIS instance relies on public FIS instance.\n const installations = _getProvider(app, INSTALLATIONS_NAME).getImmediate();\n\n const installationsInternal: _FirebaseInstallationsInternal = {\n getId: () => getId(installations),\n getToken: (forceRefresh?: boolean) => getToken(installations, forceRefresh)\n };\n return installationsInternal;\n};\n\nexport function registerInstallations(): void {\n _registerComponent(\n new Component(INSTALLATIONS_NAME, publicFactory, ComponentType.PUBLIC)\n );\n _registerComponent(\n new Component(\n INSTALLATIONS_NAME_INTERNAL,\n internalFactory,\n ComponentType.PRIVATE\n )\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getInstallationEntry } from '../helpers/get-installation-entry';\nimport { refreshAuthToken } from '../helpers/refresh-auth-token';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { Installations } from '../interfaces/public-types';\n\n/**\n * Creates a Firebase Installation if there isn't one for the app and\n * returns the Installation ID.\n * @param installations - The `Installations` instance.\n *\n * @public\n */\nexport async function getId(installations: Installations): Promise<string> {\n const installationsImpl = installations as FirebaseInstallationsImpl;\n const { installationEntry, registrationPromise } = await getInstallationEntry(\n installationsImpl\n );\n\n if (registrationPromise) {\n registrationPromise.catch(console.error);\n } else {\n // If the installation is already registered, update the authentication\n // token if needed.\n refreshAuthToken(installationsImpl).catch(console.error);\n }\n\n return installationEntry.fid;\n}\n","/**\n * Firebase Installations\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerInstallations } from './functions/config';\nimport { registerVersion } from '@firebase/app';\nimport { name, version } from '../package.json';\n\nexport * from './api';\nexport * from './interfaces/public-types';\n\nregisterInstallations();\nregisterVersion(name, version);\n// BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\nregisterVersion(name, version, '__BUILD_TARGET__');\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Type constant for Firebase Analytics.\n */\nexport const ANALYTICS_TYPE = 'analytics';\n\n// Key to attach FID to in gtag params.\nexport const GA_FID_KEY = 'firebase_id';\nexport const ORIGIN_KEY = 'origin';\n\nexport const FETCH_TIMEOUT_MILLIS = 60 * 1000;\n\nexport const DYNAMIC_CONFIG_URL =\n 'https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig';\n\nexport const GTAG_URL = 'https://www.googletagmanager.com/gtag/js';\n\nexport const enum GtagCommand {\n EVENT = 'event',\n SET = 'set',\n CONFIG = 'config',\n CONSENT = 'consent',\n GET = 'get'\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/analytics');\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AnalyticsError {\n ALREADY_EXISTS = 'already-exists',\n ALREADY_INITIALIZED = 'already-initialized',\n ALREADY_INITIALIZED_SETTINGS = 'already-initialized-settings',\n INTEROP_COMPONENT_REG_FAILED = 'interop-component-reg-failed',\n INVALID_ANALYTICS_CONTEXT = 'invalid-analytics-context',\n INDEXEDDB_UNAVAILABLE = 'indexeddb-unavailable',\n FETCH_THROTTLE = 'fetch-throttle',\n CONFIG_FETCH_FAILED = 'config-fetch-failed',\n NO_API_KEY = 'no-api-key',\n NO_APP_ID = 'no-app-id',\n NO_CLIENT_ID = 'no-client-id',\n INVALID_GTAG_RESOURCE = 'invalid-gtag-resource'\n}\n\nconst ERRORS: ErrorMap<AnalyticsError> = {\n [AnalyticsError.ALREADY_EXISTS]:\n 'A Firebase Analytics instance with the appId {$id} ' +\n ' already exists. ' +\n 'Only one Firebase Analytics instance can be created for each appId.',\n [AnalyticsError.ALREADY_INITIALIZED]:\n 'initializeAnalytics() cannot be called again with different options than those ' +\n 'it was initially called with. It can be called again with the same options to ' +\n 'return the existing instance, or getAnalytics() can be used ' +\n 'to get a reference to the already-intialized instance.',\n [AnalyticsError.ALREADY_INITIALIZED_SETTINGS]:\n 'Firebase Analytics has already been initialized.' +\n 'settings() must be called before initializing any Analytics instance' +\n 'or it will have no effect.',\n [AnalyticsError.INTEROP_COMPONENT_REG_FAILED]:\n 'Firebase Analytics Interop Component failed to instantiate: {$reason}',\n [AnalyticsError.INVALID_ANALYTICS_CONTEXT]:\n 'Firebase Analytics is not supported in this environment. ' +\n 'Wrap initialization of analytics in analytics.isSupported() ' +\n 'to prevent initialization in unsupported environments. Details: {$errorInfo}',\n [AnalyticsError.INDEXEDDB_UNAVAILABLE]:\n 'IndexedDB unavailable or restricted in this environment. ' +\n 'Wrap initialization of analytics in analytics.isSupported() ' +\n 'to prevent initialization in unsupported environments. Details: {$errorInfo}',\n [AnalyticsError.FETCH_THROTTLE]:\n 'The config fetch request timed out while in an exponential backoff state.' +\n ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',\n [AnalyticsError.CONFIG_FETCH_FAILED]:\n 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}',\n [AnalyticsError.NO_API_KEY]:\n 'The \"apiKey\" field is empty in the local Firebase config. Firebase Analytics requires this field to' +\n 'contain a valid API key.',\n [AnalyticsError.NO_APP_ID]:\n 'The \"appId\" field is empty in the local Firebase config. Firebase Analytics requires this field to' +\n 'contain a valid app ID.',\n [AnalyticsError.NO_CLIENT_ID]: 'The \"client_id\" field is empty.',\n [AnalyticsError.INVALID_GTAG_RESOURCE]:\n 'Trusted Types detected an invalid gtag resource: {$gtagURL}.'\n};\n\ninterface ErrorParams {\n [AnalyticsError.ALREADY_EXISTS]: { id: string };\n [AnalyticsError.INTEROP_COMPONENT_REG_FAILED]: { reason: Error };\n [AnalyticsError.FETCH_THROTTLE]: { throttleEndTimeMillis: number };\n [AnalyticsError.CONFIG_FETCH_FAILED]: {\n httpStatus: number;\n responseMessage: string;\n };\n [AnalyticsError.INVALID_ANALYTICS_CONTEXT]: { errorInfo: string };\n [AnalyticsError.INDEXEDDB_UNAVAILABLE]: { errorInfo: string };\n [AnalyticsError.INVALID_GTAG_RESOURCE]: { gtagURL: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<AnalyticsError, ErrorParams>(\n 'analytics',\n 'Analytics',\n ERRORS\n);\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CustomParams,\n ControlParams,\n EventParams,\n ConsentSettings\n} from './public-types';\nimport { DynamicConfig, DataLayer, Gtag, MinimalDynamicConfig } from './types';\nimport { GtagCommand, GTAG_URL } from './constants';\nimport { logger } from './logger';\nimport { AnalyticsError, ERROR_FACTORY } from './errors';\n\n// Possible parameter types for gtag 'event' and 'config' commands\ntype GtagConfigOrEventParams = ControlParams & EventParams & CustomParams;\n\n/**\n * Verifies and creates a TrustedScriptURL.\n */\nexport function createGtagTrustedTypesScriptURL(url: string): string {\n if (!url.startsWith(GTAG_URL)) {\n const err = ERROR_FACTORY.create(AnalyticsError.INVALID_GTAG_RESOURCE, {\n gtagURL: url\n });\n logger.warn(err.message);\n return '';\n }\n return url;\n}\n\n/**\n * Makeshift polyfill for Promise.allSettled(). Resolves when all promises\n * have either resolved or rejected.\n *\n * @param promises Array of promises to wait for.\n */\nexport function promiseAllSettled<T>(\n promises: Array<Promise<T>>\n): Promise<T[]> {\n return Promise.all(promises.map(promise => promise.catch(e => e)));\n}\n\n/**\n * Creates a TrustedTypePolicy object that implements the rules passed as policyOptions.\n *\n * @param policyName A string containing the name of the policy\n * @param policyOptions Object containing implementations of instance methods for TrustedTypesPolicy, see {@link https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicy#instance_methods\n * | the TrustedTypePolicy reference documentation}.\n */\nexport function createTrustedTypesPolicy(\n policyName: string,\n policyOptions: Partial<TrustedTypePolicyOptions>\n): Partial<TrustedTypePolicy> | undefined {\n // Create a TrustedTypes policy that we can use for updating src\n // properties\n let trustedTypesPolicy: Partial<TrustedTypePolicy> | undefined;\n if (window.trustedTypes) {\n trustedTypesPolicy = window.trustedTypes.createPolicy(\n policyName,\n policyOptions\n );\n }\n return trustedTypesPolicy;\n}\n\n/**\n * Inserts gtag script tag into the page to asynchronously download gtag.\n * @param dataLayerName Name of datalayer (most often the default, \"_dataLayer\").\n */\nexport function insertScriptTag(\n dataLayerName: string,\n measurementId: string\n): void {\n const trustedTypesPolicy = createTrustedTypesPolicy(\n 'firebase-js-sdk-policy',\n {\n createScriptURL: createGtagTrustedTypesScriptURL\n }\n );\n\n const script = document.createElement('script');\n // We are not providing an analyticsId in the URL because it would trigger a `page_view`\n // without fid. We will initialize ga-id using gtag (config) command together with fid.\n\n const gtagScriptURL = `${GTAG_URL}?l=${dataLayerName}&id=${measurementId}`;\n (script.src as string | TrustedScriptURL) = trustedTypesPolicy\n ? (trustedTypesPolicy as TrustedTypePolicy)?.createScriptURL(gtagScriptURL)\n : gtagScriptURL;\n\n script.async = true;\n document.head.appendChild(script);\n}\n\n/**\n * Get reference to, or create, global datalayer.\n * @param dataLayerName Name of datalayer (most often the default, \"_dataLayer\").\n */\nexport function getOrCreateDataLayer(dataLayerName: string): DataLayer {\n // Check for existing dataLayer and create if needed.\n let dataLayer: DataLayer = [];\n if (Array.isArray(window[dataLayerName])) {\n dataLayer = window[dataLayerName] as DataLayer;\n } else {\n window[dataLayerName] = dataLayer;\n }\n return dataLayer;\n}\n\n/**\n * Wrapped gtag logic when gtag is called with 'config' command.\n *\n * @param gtagCore Basic gtag function that just appends to dataLayer.\n * @param initializationPromisesMap Map of appIds to their initialization promises.\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\n * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.\n * @param measurementId GA Measurement ID to set config for.\n * @param gtagParams Gtag config params to set.\n */\nasync function gtagOnConfig(\n gtagCore: Gtag,\n initializationPromisesMap: { [appId: string]: Promise<string> },\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n measurementIdToAppId: { [measurementId: string]: string },\n measurementId: string,\n gtagParams?: ControlParams & EventParams & CustomParams\n): Promise<void> {\n // If config is already fetched, we know the appId and can use it to look up what FID promise we\n /// are waiting for, and wait only on that one.\n const correspondingAppId = measurementIdToAppId[measurementId as string];\n try {\n if (correspondingAppId) {\n await initializationPromisesMap[correspondingAppId];\n } else {\n // If config is not fetched yet, wait for all configs (we don't know which one we need) and\n // find the appId (if any) corresponding to this measurementId. If there is one, wait on\n // that appId's initialization promise. If there is none, promise resolves and gtag\n // call goes through.\n const dynamicConfigResults = await promiseAllSettled(\n dynamicConfigPromisesList\n );\n const foundConfig = dynamicConfigResults.find(\n config => config.measurementId === measurementId\n );\n if (foundConfig) {\n await initializationPromisesMap[foundConfig.appId];\n }\n }\n } catch (e) {\n logger.error(e);\n }\n gtagCore(GtagCommand.CONFIG, measurementId, gtagParams);\n}\n\n/**\n * Wrapped gtag logic when gtag is called with 'event' command.\n *\n * @param gtagCore Basic gtag function that just appends to dataLayer.\n * @param initializationPromisesMap Map of appIds to their initialization promises.\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\n * @param measurementId GA Measurement ID to log event to.\n * @param gtagParams Params to log with this event.\n */\nasync function gtagOnEvent(\n gtagCore: Gtag,\n initializationPromisesMap: { [appId: string]: Promise<string> },\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n measurementId: string,\n gtagParams?: ControlParams & EventParams & CustomParams\n): Promise<void> {\n try {\n let initializationPromisesToWaitFor: Array<Promise<string>> = [];\n\n // If there's a 'send_to' param, check if any ID specified matches\n // an initializeIds() promise we are waiting for.\n if (gtagParams && gtagParams['send_to']) {\n let gaSendToList: string | string[] = gtagParams['send_to'];\n // Make it an array if is isn't, so it can be dealt with the same way.\n if (!Array.isArray(gaSendToList)) {\n gaSendToList = [gaSendToList];\n }\n // Checking 'send_to' fields requires having all measurement ID results back from\n // the dynamic config fetch.\n const dynamicConfigResults = await promiseAllSettled(\n dynamicConfigPromisesList\n );\n for (const sendToId of gaSendToList) {\n // Any fetched dynamic measurement ID that matches this 'send_to' ID\n const foundConfig = dynamicConfigResults.find(\n config => config.measurementId === sendToId\n );\n const initializationPromise =\n foundConfig && initializationPromisesMap[foundConfig.appId];\n if (initializationPromise) {\n initializationPromisesToWaitFor.push(initializationPromise);\n } else {\n // Found an item in 'send_to' that is not associated\n // directly with an FID, possibly a group. Empty this array,\n // exit the loop early, and let it get populated below.\n initializationPromisesToWaitFor = [];\n break;\n }\n }\n }\n\n // This will be unpopulated if there was no 'send_to' field , or\n // if not all entries in the 'send_to' field could be mapped to\n // a FID. In these cases, wait on all pending initialization promises.\n if (initializationPromisesToWaitFor.length === 0) {\n initializationPromisesToWaitFor = Object.values(\n initializationPromisesMap\n );\n }\n\n // Run core gtag function with args after all relevant initialization\n // promises have been resolved.\n await Promise.all(initializationPromisesToWaitFor);\n // Workaround for http://b/141370449 - third argument cannot be undefined.\n gtagCore(GtagCommand.EVENT, measurementId, gtagParams || {});\n } catch (e) {\n logger.error(e);\n }\n}\n\n/**\n * Wraps a standard gtag function with extra code to wait for completion of\n * relevant initialization promises before sending requests.\n *\n * @param gtagCore Basic gtag function that just appends to dataLayer.\n * @param initializationPromisesMap Map of appIds to their initialization promises.\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\n * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.\n */\nfunction wrapGtag(\n gtagCore: Gtag,\n /**\n * Allows wrapped gtag calls to wait on whichever intialization promises are required,\n * depending on the contents of the gtag params' `send_to` field, if any.\n */\n initializationPromisesMap: { [appId: string]: Promise<string> },\n /**\n * Wrapped gtag calls sometimes require all dynamic config fetches to have returned\n * before determining what initialization promises (which include FIDs) to wait for.\n */\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n /**\n * Wrapped gtag config calls can narrow down which initialization promise (with FID)\n * to wait for if the measurementId is already fetched, by getting the corresponding appId,\n * which is the key for the initialization promises map.\n */\n measurementIdToAppId: { [measurementId: string]: string }\n): Gtag {\n /**\n * Wrapper around gtag that ensures FID is sent with gtag calls.\n * @param command Gtag command type.\n * @param idOrNameOrParams Measurement ID if command is EVENT/CONFIG, params if command is SET.\n * @param gtagParams Params if event is EVENT/CONFIG.\n */\n async function gtagWrapper(\n command: 'config' | 'set' | 'event' | 'consent' | 'get' | string,\n ...args: unknown[]\n ): Promise<void> {\n try {\n // If event, check that relevant initialization promises have completed.\n if (command === GtagCommand.EVENT) {\n const [measurementId, gtagParams] = args;\n // If EVENT, second arg must be measurementId.\n await gtagOnEvent(\n gtagCore,\n initializationPromisesMap,\n dynamicConfigPromisesList,\n measurementId as string,\n gtagParams as GtagConfigOrEventParams\n );\n } else if (command === GtagCommand.CONFIG) {\n const [measurementId, gtagParams] = args;\n // If CONFIG, second arg must be measurementId.\n await gtagOnConfig(\n gtagCore,\n initializationPromisesMap,\n dynamicConfigPromisesList,\n measurementIdToAppId,\n measurementId as string,\n gtagParams as GtagConfigOrEventParams\n );\n } else if (command === GtagCommand.CONSENT) {\n const [gtagParams] = args;\n gtagCore(GtagCommand.CONSENT, 'update', gtagParams as ConsentSettings);\n } else if (command === GtagCommand.GET) {\n const [measurementId, fieldName, callback] = args;\n gtagCore(\n GtagCommand.GET,\n measurementId as string,\n fieldName as string,\n callback as (...args: unknown[]) => void\n );\n } else if (command === GtagCommand.SET) {\n const [customParams] = args;\n // If SET, second arg must be params.\n gtagCore(GtagCommand.SET, customParams as CustomParams);\n } else {\n gtagCore(command, ...args);\n }\n } catch (e) {\n logger.error(e);\n }\n }\n return gtagWrapper as Gtag;\n}\n\n/**\n * Creates global gtag function or wraps existing one if found.\n * This wrapped function attaches Firebase instance ID (FID) to gtag 'config' and\n * 'event' calls that belong to the GAID associated with this Firebase instance.\n *\n * @param initializationPromisesMap Map of appIds to their initialization promises.\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\n * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.\n * @param dataLayerName Name of global GA datalayer array.\n * @param gtagFunctionName Name of global gtag function (\"gtag\" if not user-specified).\n */\nexport function wrapOrCreateGtag(\n initializationPromisesMap: { [appId: string]: Promise<string> },\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n measurementIdToAppId: { [measurementId: string]: string },\n dataLayerName: string,\n gtagFunctionName: string\n): {\n gtagCore: Gtag;\n wrappedGtag: Gtag;\n} {\n // Create a basic core gtag function\n let gtagCore: Gtag = function (..._args: unknown[]) {\n // Must push IArguments object, not an array.\n (window[dataLayerName] as DataLayer).push(arguments);\n };\n\n // Replace it with existing one if found\n if (\n window[gtagFunctionName] &&\n typeof window[gtagFunctionName] === 'function'\n ) {\n // @ts-ignore\n gtagCore = window[gtagFunctionName];\n }\n\n window[gtagFunctionName] = wrapGtag(\n gtagCore,\n initializationPromisesMap,\n dynamicConfigPromisesList,\n measurementIdToAppId\n );\n\n return {\n gtagCore,\n wrappedGtag: window[gtagFunctionName] as Gtag\n };\n}\n\n/**\n * Returns the script tag in the DOM matching both the gtag url pattern\n * and the provided data layer name.\n */\nexport function findGtagScriptOnPage(\n dataLayerName: string\n): HTMLScriptElement | null {\n const scriptTags = window.document.getElementsByTagName('script');\n for (const tag of Object.values(scriptTags)) {\n if (\n tag.src &&\n tag.src.includes(GTAG_URL) &&\n tag.src.includes(dataLayerName)\n ) {\n return tag;\n }\n }\n return null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Most logic is copied from packages/remote-config/src/client/retrying_client.ts\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { DynamicConfig, ThrottleMetadata, MinimalDynamicConfig } from './types';\nimport { FirebaseError, calculateBackoffMillis } from '@firebase/util';\nimport { AnalyticsError, ERROR_FACTORY } from './errors';\nimport { DYNAMIC_CONFIG_URL, FETCH_TIMEOUT_MILLIS } from './constants';\nimport { logger } from './logger';\n\n// App config fields needed by analytics.\nexport interface AppFields {\n appId: string;\n apiKey: string;\n measurementId?: string;\n}\n\n/**\n * Backoff factor for 503 errors, which we want to be conservative about\n * to avoid overloading servers. Each retry interval will be\n * BASE_INTERVAL_MILLIS * LONG_RETRY_FACTOR ^ retryCount, so the second one\n * will be ~30 seconds (with fuzzing).\n */\nexport const LONG_RETRY_FACTOR = 30;\n\n/**\n * Base wait interval to multiplied by backoffFactor^backoffCount.\n */\nconst BASE_INTERVAL_MILLIS = 1000;\n\n/**\n * Stubbable retry data storage class.\n */\nclass RetryData {\n constructor(\n public throttleMetadata: { [appId: string]: ThrottleMetadata } = {},\n public intervalMillis: number = BASE_INTERVAL_MILLIS\n ) {}\n\n getThrottleMetadata(appId: string): ThrottleMetadata {\n return this.throttleMetadata[appId];\n }\n\n setThrottleMetadata(appId: string, metadata: ThrottleMetadata): void {\n this.throttleMetadata[appId] = metadata;\n }\n\n deleteThrottleMetadata(appId: string): void {\n delete this.throttleMetadata[appId];\n }\n}\n\nconst defaultRetryData = new RetryData();\n\n/**\n * Set GET request headers.\n * @param apiKey App API key.\n */\nfunction getHeaders(apiKey: string): Headers {\n return new Headers({\n Accept: 'application/json',\n 'x-goog-api-key': apiKey\n });\n}\n\n/**\n * Fetches dynamic config from backend.\n * @param app Firebase app to fetch config for.\n */\nexport async function fetchDynamicConfig(\n appFields: AppFields\n): Promise<DynamicConfig> {\n const { appId, apiKey } = appFields;\n const request: RequestInit = {\n method: 'GET',\n headers: getHeaders(apiKey)\n };\n const appUrl = DYNAMIC_CONFIG_URL.replace('{app-id}', appId);\n const response = await fetch(appUrl, request);\n if (response.status !== 200 && response.status !== 304) {\n let errorMessage = '';\n try {\n // Try to get any error message text from server response.\n const jsonResponse = (await response.json()) as {\n error?: { message?: string };\n };\n if (jsonResponse.error?.message) {\n errorMessage = jsonResponse.error.message;\n }\n } catch (_ignored) {}\n throw ERROR_FACTORY.create(AnalyticsError.CONFIG_FETCH_FAILED, {\n httpStatus: response.status,\n responseMessage: errorMessage\n });\n }\n return response.json();\n}\n\n/**\n * Fetches dynamic config from backend, retrying if failed.\n * @param app Firebase app to fetch config for.\n */\nexport async function fetchDynamicConfigWithRetry(\n app: FirebaseApp,\n // retryData and timeoutMillis are parameterized to allow passing a different value for testing.\n retryData: RetryData = defaultRetryData,\n timeoutMillis?: number\n): Promise<DynamicConfig | MinimalDynamicConfig> {\n const { appId, apiKey, measurementId } = app.options;\n\n if (!appId) {\n throw ERROR_FACTORY.create(AnalyticsError.NO_APP_ID);\n }\n\n if (!apiKey) {\n if (measurementId) {\n return {\n measurementId,\n appId\n };\n }\n throw ERROR_FACTORY.create(AnalyticsError.NO_API_KEY);\n }\n\n const throttleMetadata: ThrottleMetadata = retryData.getThrottleMetadata(\n appId\n ) || {\n backoffCount: 0,\n throttleEndTimeMillis: Date.now()\n };\n\n const signal = new AnalyticsAbortSignal();\n\n setTimeout(\n async () => {\n // Note a very low delay, eg < 10ms, can elapse before listeners are initialized.\n signal.abort();\n },\n timeoutMillis !== undefined ? timeoutMillis : FETCH_TIMEOUT_MILLIS\n );\n\n return attemptFetchDynamicConfigWithRetry(\n { appId, apiKey, measurementId },\n throttleMetadata,\n signal,\n retryData\n );\n}\n\n/**\n * Runs one retry attempt.\n * @param appFields Necessary app config fields.\n * @param throttleMetadata Ongoing metadata to determine throttling times.\n * @param signal Abort signal.\n */\nasync function attemptFetchDynamicConfigWithRetry(\n appFields: AppFields,\n { throttleEndTimeMillis, backoffCount }: ThrottleMetadata,\n signal: AnalyticsAbortSignal,\n retryData: RetryData = defaultRetryData // for testing\n): Promise<DynamicConfig | MinimalDynamicConfig> {\n const { appId, measurementId } = appFields;\n // Starts with a (potentially zero) timeout to support resumption from stored state.\n // Ensures the throttle end time is honored if the last attempt timed out.\n // Note the SDK will never make a request if the fetch timeout expires at this point.\n try {\n await setAbortableTimeout(signal, throttleEndTimeMillis);\n } catch (e) {\n if (measurementId) {\n logger.warn(\n `Timed out fetching this Firebase app's measurement ID from the server.` +\n ` Falling back to the measurement ID ${measurementId}` +\n ` provided in the \"measurementId\" field in the local Firebase config. [${\n (e as Error)?.message\n }]`\n );\n return { appId, measurementId };\n }\n throw e;\n }\n\n try {\n const response = await fetchDynamicConfig(appFields);\n\n // Note the SDK only clears throttle state if response is success or non-retriable.\n retryData.deleteThrottleMetadata(appId);\n\n return response;\n } catch (e) {\n const error = e as Error;\n if (!isRetriableError(error)) {\n retryData.deleteThrottleMetadata(appId);\n if (measurementId) {\n logger.warn(\n `Failed to fetch this Firebase app's measurement ID from the server.` +\n ` Falling back to the measurement ID ${measurementId}` +\n ` provided in the \"measurementId\" field in the local Firebase config. [${error?.message}]`\n );\n return { appId, measurementId };\n } else {\n throw e;\n }\n }\n\n const backoffMillis =\n Number(error?.customData?.httpStatus) === 503\n ? calculateBackoffMillis(\n backoffCount,\n retryData.intervalMillis,\n LONG_RETRY_FACTOR\n )\n : calculateBackoffMillis(backoffCount, retryData.intervalMillis);\n\n // Increments backoff state.\n const throttleMetadata = {\n throttleEndTimeMillis: Date.now() + backoffMillis,\n backoffCount: backoffCount + 1\n };\n\n // Persists state.\n retryData.setThrottleMetadata(appId, throttleMetadata);\n logger.debug(`Calling attemptFetch again in ${backoffMillis} millis`);\n\n return attemptFetchDynamicConfigWithRetry(\n appFields,\n throttleMetadata,\n signal,\n retryData\n );\n }\n}\n\n/**\n * Supports waiting on a backoff by:\n *\n * <ul>\n * <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li>\n * <li>Listening on a signal bus for abort events, just like the Fetch API</li>\n * <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled\n * request appear the same.</li>\n * </ul>\n *\n * <p>Visible for testing.\n */\nfunction setAbortableTimeout(\n signal: AnalyticsAbortSignal,\n throttleEndTimeMillis: number\n): Promise<void> {\n return new Promise((resolve, reject) => {\n // Derives backoff from given end time, normalizing negative numbers to zero.\n const backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0);\n\n const timeout = setTimeout(resolve, backoffMillis);\n\n // Adds listener, rather than sets onabort, because signal is a shared object.\n signal.addEventListener(() => {\n clearTimeout(timeout);\n // If the request completes before this timeout, the rejection has no effect.\n reject(\n ERROR_FACTORY.create(AnalyticsError.FETCH_THROTTLE, {\n throttleEndTimeMillis\n })\n );\n });\n });\n}\n\ntype RetriableError = FirebaseError & { customData: { httpStatus: string } };\n\n/**\n * Returns true if the {@link Error} indicates a fetch request may succeed later.\n */\nfunction isRetriableError(e: Error): e is RetriableError {\n if (!(e instanceof FirebaseError) || !e.customData) {\n return false;\n }\n\n // Uses string index defined by ErrorData, which FirebaseError implements.\n const httpStatus = Number(e.customData['httpStatus']);\n\n return (\n httpStatus === 429 ||\n httpStatus === 500 ||\n httpStatus === 503 ||\n httpStatus === 504\n );\n}\n\n/**\n * Shims a minimal AbortSignal (copied from Remote Config).\n *\n * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects\n * of networking, such as retries. Firebase doesn't use AbortController enough to justify a\n * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be\n * swapped out if/when we do.\n */\nexport class AnalyticsAbortSignal {\n listeners: Array<() => void> = [];\n addEventListener(listener: () => void): void {\n this.listeners.push(listener);\n }\n abort(): void {\n this.listeners.forEach(listener => listener());\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AnalyticsCallOptions,\n CustomParams,\n ControlParams,\n EventParams,\n ConsentSettings\n} from './public-types';\nimport { Gtag } from './types';\nimport { GtagCommand } from './constants';\nimport { AnalyticsError, ERROR_FACTORY } from './errors';\n\n/**\n * Event parameters to set on 'gtag' during initialization.\n */\nexport let defaultEventParametersForInit: CustomParams | undefined;\n\n/**\n * Logs an analytics event through the Firebase SDK.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n * @param eventName Google Analytics event name, choose from standard list or use a custom string.\n * @param eventParams Analytics event parameters.\n */\nexport async function logEvent(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>,\n eventName: string,\n eventParams?: EventParams,\n options?: AnalyticsCallOptions\n): Promise<void> {\n if (options && options.global) {\n gtagFunction(GtagCommand.EVENT, eventName, eventParams);\n return;\n } else {\n const measurementId = await initializationPromise;\n const params: EventParams | ControlParams = {\n ...eventParams,\n 'send_to': measurementId\n };\n gtagFunction(GtagCommand.EVENT, eventName, params);\n }\n}\n\n/**\n * Set screen_name parameter for this Google Analytics ID.\n *\n * @deprecated Use {@link logEvent} with `eventName` as 'screen_view' and add relevant `eventParams`.\n * See {@link https://firebase.google.com/docs/analytics/screenviews | Track Screenviews}.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n * @param screenName Screen name string to set.\n */\nexport async function setCurrentScreen(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>,\n screenName: string | null,\n options?: AnalyticsCallOptions\n): Promise<void> {\n if (options && options.global) {\n gtagFunction(GtagCommand.SET, { 'screen_name': screenName });\n return Promise.resolve();\n } else {\n const measurementId = await initializationPromise;\n gtagFunction(GtagCommand.CONFIG, measurementId, {\n update: true,\n 'screen_name': screenName\n });\n }\n}\n\n/**\n * Set user_id parameter for this Google Analytics ID.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n * @param id User ID string to set\n */\nexport async function setUserId(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>,\n id: string | null,\n options?: AnalyticsCallOptions\n): Promise<void> {\n if (options && options.global) {\n gtagFunction(GtagCommand.SET, { 'user_id': id });\n return Promise.resolve();\n } else {\n const measurementId = await initializationPromise;\n gtagFunction(GtagCommand.CONFIG, measurementId, {\n update: true,\n 'user_id': id\n });\n }\n}\n\n/**\n * Set all other user properties other than user_id and screen_name.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n * @param properties Map of user properties to set\n */\nexport async function setUserProperties(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>,\n properties: CustomParams,\n options?: AnalyticsCallOptions\n): Promise<void> {\n if (options && options.global) {\n const flatProperties: { [key: string]: unknown } = {};\n for (const key of Object.keys(properties)) {\n // use dot notation for merge behavior in gtag.js\n flatProperties[`user_properties.${key}`] = properties[key];\n }\n gtagFunction(GtagCommand.SET, flatProperties);\n return Promise.resolve();\n } else {\n const measurementId = await initializationPromise;\n gtagFunction(GtagCommand.CONFIG, measurementId, {\n update: true,\n 'user_properties': properties\n });\n }\n}\n\n/**\n * Retrieves a unique Google Analytics identifier for the web client.\n * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n */\nexport async function internalGetGoogleAnalyticsClientId(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>\n): Promise<string> {\n const measurementId = await initializationPromise;\n return new Promise((resolve, reject) => {\n gtagFunction(\n GtagCommand.GET,\n measurementId,\n 'client_id',\n (clientId: string) => {\n if (!clientId) {\n reject(ERROR_FACTORY.create(AnalyticsError.NO_CLIENT_ID));\n }\n resolve(clientId);\n }\n );\n });\n}\n\n/**\n * Set whether collection is enabled for this ID.\n *\n * @param enabled If true, collection is enabled for this ID.\n */\nexport async function setAnalyticsCollectionEnabled(\n initializationPromise: Promise<string>,\n enabled: boolean\n): Promise<void> {\n const measurementId = await initializationPromise;\n window[`ga-disable-${measurementId}`] = !enabled;\n}\n\n/**\n * Consent parameters to default to during 'gtag' initialization.\n */\nexport let defaultConsentSettingsForInit: ConsentSettings | undefined;\n\n/**\n * Sets the variable {@link defaultConsentSettingsForInit} for use in the initialization of\n * analytics.\n *\n * @param consentSettings Maps the applicable end user consent state for gtag.js.\n */\nexport function _setConsentDefaultForInit(\n consentSettings?: ConsentSettings\n): void {\n defaultConsentSettingsForInit = consentSettings;\n}\n\n/**\n * Sets the variable `defaultEventParametersForInit` for use in the initialization of\n * analytics.\n *\n * @param customParams Any custom params the user may pass to gtag.js.\n */\nexport function _setDefaultEventParametersForInit(\n customParams?: CustomParams\n): void {\n defaultEventParametersForInit = customParams;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DynamicConfig, Gtag, MinimalDynamicConfig } from './types';\nimport { GtagCommand, GA_FID_KEY, ORIGIN_KEY } from './constants';\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\nimport { fetchDynamicConfigWithRetry } from './get-config';\nimport { logger } from './logger';\nimport { FirebaseApp } from '@firebase/app';\nimport {\n isIndexedDBAvailable,\n validateIndexedDBOpenable\n} from '@firebase/util';\nimport { ERROR_FACTORY, AnalyticsError } from './errors';\nimport { findGtagScriptOnPage, insertScriptTag } from './helpers';\nimport { AnalyticsSettings } from './public-types';\nimport {\n defaultConsentSettingsForInit,\n _setConsentDefaultForInit,\n defaultEventParametersForInit,\n _setDefaultEventParametersForInit\n} from './functions';\n\nasync function validateIndexedDB(): Promise<boolean> {\n if (!isIndexedDBAvailable()) {\n logger.warn(\n ERROR_FACTORY.create(AnalyticsError.INDEXEDDB_UNAVAILABLE, {\n errorInfo: 'IndexedDB is not available in this environment.'\n }).message\n );\n return false;\n } else {\n try {\n await validateIndexedDBOpenable();\n } catch (e) {\n logger.warn(\n ERROR_FACTORY.create(AnalyticsError.INDEXEDDB_UNAVAILABLE, {\n errorInfo: (e as Error)?.toString()\n }).message\n );\n return false;\n }\n }\n return true;\n}\n\n/**\n * Initialize the analytics instance in gtag.js by calling config command with fid.\n *\n * NOTE: We combine analytics initialization and setting fid together because we want fid to be\n * part of the `page_view` event that's sent during the initialization\n * @param app Firebase app\n * @param gtagCore The gtag function that's not wrapped.\n * @param dynamicConfigPromisesList Array of all dynamic config promises.\n * @param measurementIdToAppId Maps measurementID to appID.\n * @param installations _FirebaseInstallationsInternal instance.\n *\n * @returns Measurement ID.\n */\nexport async function _initializeAnalytics(\n app: FirebaseApp,\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n measurementIdToAppId: { [key: string]: string },\n installations: _FirebaseInstallationsInternal,\n gtagCore: Gtag,\n dataLayerName: string,\n options?: AnalyticsSettings\n): Promise<string> {\n const dynamicConfigPromise = fetchDynamicConfigWithRetry(app);\n // Once fetched, map measurementIds to appId, for ease of lookup in wrapped gtag function.\n dynamicConfigPromise\n .then(config => {\n measurementIdToAppId[config.measurementId] = config.appId;\n if (\n app.options.measurementId &&\n config.measurementId !== app.options.measurementId\n ) {\n logger.warn(\n `The measurement ID in the local Firebase config (${app.options.measurementId})` +\n ` does not match the measurement ID fetched from the server (${config.measurementId}).` +\n ` To ensure analytics events are always sent to the correct Analytics property,` +\n ` update the` +\n ` measurement ID field in the local config or remove it from the local config.`\n );\n }\n })\n .catch(e => logger.error(e));\n // Add to list to track state of all dynamic config promises.\n dynamicConfigPromisesList.push(dynamicConfigPromise);\n\n const fidPromise: Promise<string | undefined> = validateIndexedDB().then(\n envIsValid => {\n if (envIsValid) {\n return installations.getId();\n } else {\n return undefined;\n }\n }\n );\n\n const [dynamicConfig, fid] = await Promise.all([\n dynamicConfigPromise,\n fidPromise\n ]);\n\n // Detect if user has already put the gtag <script> tag on this page with the passed in\n // data layer name.\n if (!findGtagScriptOnPage(dataLayerName)) {\n insertScriptTag(dataLayerName, dynamicConfig.measurementId);\n }\n\n // Detects if there are consent settings that need to be configured.\n if (defaultConsentSettingsForInit) {\n gtagCore(GtagCommand.CONSENT, 'default', defaultConsentSettingsForInit);\n _setConsentDefaultForInit(undefined);\n }\n\n // This command initializes gtag.js and only needs to be called once for the entire web app,\n // but since it is idempotent, we can call it multiple times.\n // We keep it together with other initialization logic for better code structure.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (gtagCore as any)('js', new Date());\n // User config added first. We don't want users to accidentally overwrite\n // base Firebase config properties.\n const configProperties: Record<string, unknown> = options?.config ?? {};\n\n // guard against developers accidentally setting properties with prefix `firebase_`\n configProperties[ORIGIN_KEY] = 'firebase';\n configProperties.update = true;\n\n if (fid != null) {\n configProperties[GA_FID_KEY] = fid;\n }\n\n // It should be the first config command called on this GA-ID\n // Initialize this GA-ID and set FID on it using the gtag config API.\n // Note: This will trigger a page_view event unless 'send_page_view' is set to false in\n // `configProperties`.\n gtagCore(GtagCommand.CONFIG, dynamicConfig.measurementId, configProperties);\n\n // Detects if there is data that will be set on every event logged from the SDK.\n if (defaultEventParametersForInit) {\n gtagCore(GtagCommand.SET, defaultEventParametersForInit);\n _setDefaultEventParametersForInit(undefined);\n }\n\n return dynamicConfig.measurementId;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SettingsOptions, Analytics, AnalyticsSettings } from './public-types';\nimport { Gtag, DynamicConfig, MinimalDynamicConfig } from './types';\nimport { getOrCreateDataLayer, wrapOrCreateGtag } from './helpers';\nimport { AnalyticsError, ERROR_FACTORY } from './errors';\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\nimport { areCookiesEnabled, isBrowserExtension } from '@firebase/util';\nimport { _initializeAnalytics } from './initialize-analytics';\nimport { logger } from './logger';\nimport { FirebaseApp, _FirebaseService } from '@firebase/app';\n\n/**\n * Analytics Service class.\n */\nexport class AnalyticsService implements Analytics, _FirebaseService {\n constructor(public app: FirebaseApp) {}\n _delete(): Promise<void> {\n delete initializationPromisesMap[this.app.options.appId!];\n return Promise.resolve();\n }\n}\n\n/**\n * Maps appId to full initialization promise. Wrapped gtag calls must wait on\n * all or some of these, depending on the call's `send_to` param and the status\n * of the dynamic config fetches (see below).\n */\nexport let initializationPromisesMap: {\n [appId: string]: Promise<string>; // Promise contains measurement ID string.\n} = {};\n\n/**\n * List of dynamic config fetch promises. In certain cases, wrapped gtag calls\n * wait on all these to be complete in order to determine if it can selectively\n * wait for only certain initialization (FID) promises or if it must wait for all.\n */\nlet dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n> = [];\n\n/**\n * Maps fetched measurementIds to appId. Populated when the app's dynamic config\n * fetch completes. If already populated, gtag config calls can use this to\n * selectively wait for only this app's initialization promise (FID) instead of all\n * initialization promises.\n */\nconst measurementIdToAppId: { [measurementId: string]: string } = {};\n\n/**\n * Name for window global data layer array used by GA: defaults to 'dataLayer'.\n */\nlet dataLayerName: string = 'dataLayer';\n\n/**\n * Name for window global gtag function used by GA: defaults to 'gtag'.\n */\nlet gtagName: string = 'gtag';\n\n/**\n * Reproduction of standard gtag function or reference to existing\n * gtag function on window object.\n */\nlet gtagCoreFunction: Gtag;\n\n/**\n * Wrapper around gtag function that ensures FID is sent with all\n * relevant event and config calls.\n */\nexport let wrappedGtagFunction: Gtag;\n\n/**\n * Flag to ensure page initialization steps (creation or wrapping of\n * dataLayer and gtag script) are only run once per page load.\n */\nlet globalInitDone: boolean = false;\n\n/**\n * For testing\n * @internal\n */\nexport function resetGlobalVars(\n newGlobalInitDone = false,\n newInitializationPromisesMap = {},\n newDynamicPromises = []\n): void {\n globalInitDone = newGlobalInitDone;\n initializationPromisesMap = newInitializationPromisesMap;\n dynamicConfigPromisesList = newDynamicPromises;\n dataLayerName = 'dataLayer';\n gtagName = 'gtag';\n}\n\n/**\n * For testing\n * @internal\n */\nexport function getGlobalVars(): {\n initializationPromisesMap: { [appId: string]: Promise<string> };\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >;\n} {\n return {\n initializationPromisesMap,\n dynamicConfigPromisesList\n };\n}\n\n/**\n * Configures Firebase Analytics to use custom `gtag` or `dataLayer` names.\n * Intended to be used if `gtag.js` script has been installed on\n * this page independently of Firebase Analytics, and is using non-default\n * names for either the `gtag` function or for `dataLayer`.\n * Must be called before calling `getAnalytics()` or it won't\n * have any effect.\n *\n * @public\n *\n * @param options - Custom gtag and dataLayer names.\n */\nexport function settings(options: SettingsOptions): void {\n if (globalInitDone) {\n throw ERROR_FACTORY.create(AnalyticsError.ALREADY_INITIALIZED);\n }\n if (options.dataLayerName) {\n dataLayerName = options.dataLayerName;\n }\n if (options.gtagName) {\n gtagName = options.gtagName;\n }\n}\n\n/**\n * Returns true if no environment mismatch is found.\n * If environment mismatches are found, throws an INVALID_ANALYTICS_CONTEXT\n * error that also lists details for each mismatch found.\n */\nfunction warnOnBrowserContextMismatch(): void {\n const mismatchedEnvMessages = [];\n if (isBrowserExtension()) {\n mismatchedEnvMessages.push('This is a browser extension environment.');\n }\n if (!areCookiesEnabled()) {\n mismatchedEnvMessages.push('Cookies are not available.');\n }\n if (mismatchedEnvMessages.length > 0) {\n const details = mismatchedEnvMessages\n .map((message, index) => `(${index + 1}) ${message}`)\n .join(' ');\n const err = ERROR_FACTORY.create(AnalyticsError.INVALID_ANALYTICS_CONTEXT, {\n errorInfo: details\n });\n logger.warn(err.message);\n }\n}\n\n/**\n * Analytics instance factory.\n * @internal\n */\nexport function factory(\n app: FirebaseApp,\n installations: _FirebaseInstallationsInternal,\n options?: AnalyticsSettings\n): AnalyticsService {\n warnOnBrowserContextMismatch();\n const appId = app.options.appId;\n if (!appId) {\n throw ERROR_FACTORY.create(AnalyticsError.NO_APP_ID);\n }\n if (!app.options.apiKey) {\n if (app.options.measurementId) {\n logger.warn(\n `The \"apiKey\" field is empty in the local Firebase config. This is needed to fetch the latest` +\n ` measurement ID for this Firebase app. Falling back to the measurement ID ${app.options.measurementId}` +\n ` provided in the \"measurementId\" field in the local Firebase config.`\n );\n } else {\n throw ERROR_FACTORY.create(AnalyticsError.NO_API_KEY);\n }\n }\n if (initializationPromisesMap[appId] != null) {\n throw ERROR_FACTORY.create(AnalyticsError.ALREADY_EXISTS, {\n id: appId\n });\n }\n\n if (!globalInitDone) {\n // Steps here should only be done once per page: creation or wrapping\n // of dataLayer and global gtag function.\n\n getOrCreateDataLayer(dataLayerName);\n\n const { wrappedGtag, gtagCore } = wrapOrCreateGtag(\n initializationPromisesMap,\n dynamicConfigPromisesList,\n measurementIdToAppId,\n dataLayerName,\n gtagName\n );\n wrappedGtagFunction = wrappedGtag;\n gtagCoreFunction = gtagCore;\n\n globalInitDone = true;\n }\n // Async but non-blocking.\n // This map reflects the completion state of all promises for each appId.\n initializationPromisesMap[appId] = _initializeAnalytics(\n app,\n dynamicConfigPromisesList,\n measurementIdToAppId,\n installations,\n gtagCoreFunction,\n dataLayerName,\n options\n );\n\n const analyticsInstance: AnalyticsService = new AnalyticsService(app);\n\n return analyticsInstance;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable camelcase */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProvider, FirebaseApp, getApp } from '@firebase/app';\nimport {\n Analytics,\n AnalyticsCallOptions,\n AnalyticsSettings,\n ConsentSettings,\n CustomParams,\n EventNameString,\n EventParams\n} from './public-types';\nimport { Provider } from '@firebase/component';\nimport {\n isIndexedDBAvailable,\n validateIndexedDBOpenable,\n areCookiesEnabled,\n isBrowserExtension,\n getModularInstance,\n deepEqual\n} from '@firebase/util';\nimport { ANALYTICS_TYPE, GtagCommand } from './constants';\nimport {\n AnalyticsService,\n initializationPromisesMap,\n wrappedGtagFunction\n} from './factory';\nimport { logger } from './logger';\nimport {\n logEvent as internalLogEvent,\n setCurrentScreen as internalSetCurrentScreen,\n setUserId as internalSetUserId,\n setUserProperties as internalSetUserProperties,\n setAnalyticsCollectionEnabled as internalSetAnalyticsCollectionEnabled,\n _setConsentDefaultForInit,\n _setDefaultEventParametersForInit,\n internalGetGoogleAnalyticsClientId\n} from './functions';\nimport { ERROR_FACTORY, AnalyticsError } from './errors';\n\nexport { settings } from './factory';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n [ANALYTICS_TYPE]: AnalyticsService;\n }\n}\n\n/**\n * Returns an {@link Analytics} instance for the given app.\n *\n * @public\n *\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n */\nexport function getAnalytics(app: FirebaseApp = getApp()): Analytics {\n app = getModularInstance(app);\n // Dependencies\n const analyticsProvider: Provider<'analytics'> = _getProvider(\n app,\n ANALYTICS_TYPE\n );\n\n if (analyticsProvider.isInitialized()) {\n return analyticsProvider.getImmediate();\n }\n\n return initializeAnalytics(app);\n}\n\n/**\n * Returns an {@link Analytics} instance for the given app.\n *\n * @public\n *\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n */\nexport function initializeAnalytics(\n app: FirebaseApp,\n options: AnalyticsSettings = {}\n): Analytics {\n // Dependencies\n const analyticsProvider: Provider<'analytics'> = _getProvider(\n app,\n ANALYTICS_TYPE\n );\n if (analyticsProvider.isInitialized()) {\n const existingInstance = analyticsProvider.getImmediate();\n if (deepEqual(options, analyticsProvider.getOptions())) {\n return existingInstance;\n } else {\n throw ERROR_FACTORY.create(AnalyticsError.ALREADY_INITIALIZED);\n }\n }\n const analyticsInstance = analyticsProvider.initialize({ options });\n return analyticsInstance;\n}\n\n/**\n * This is a public static method provided to users that wraps four different checks:\n *\n * 1. Check if it's not a browser extension environment.\n * 2. Check if cookies are enabled in current browser.\n * 3. Check if IndexedDB is supported by the browser environment.\n * 4. Check if the current browser context is valid for using `IndexedDB.open()`.\n *\n * @public\n *\n */\nexport async function isSupported(): Promise<boolean> {\n if (isBrowserExtension()) {\n return false;\n }\n if (!areCookiesEnabled()) {\n return false;\n }\n if (!isIndexedDBAvailable()) {\n return false;\n }\n\n try {\n const isDBOpenable: boolean = await validateIndexedDBOpenable();\n return isDBOpenable;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Use gtag `config` command to set `screen_name`.\n *\n * @public\n *\n * @deprecated Use {@link logEvent} with `eventName` as 'screen_view' and add relevant `eventParams`.\n * See {@link https://firebase.google.com/docs/analytics/screenviews | Track Screenviews}.\n *\n * @param analyticsInstance - The {@link Analytics} instance.\n * @param screenName - Screen name to set.\n */\nexport function setCurrentScreen(\n analyticsInstance: Analytics,\n screenName: string,\n options?: AnalyticsCallOptions\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalSetCurrentScreen(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n screenName,\n options\n ).catch(e => logger.error(e));\n}\n\n/**\n * Retrieves a unique Google Analytics identifier for the web client.\n * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.\n *\n * @public\n *\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n */\nexport async function getGoogleAnalyticsClientId(\n analyticsInstance: Analytics\n): Promise<string> {\n analyticsInstance = getModularInstance(analyticsInstance);\n return internalGetGoogleAnalyticsClientId(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!]\n );\n}\n\n/**\n * Use gtag `config` command to set `user_id`.\n *\n * @public\n *\n * @param analyticsInstance - The {@link Analytics} instance.\n * @param id - User ID to set.\n */\nexport function setUserId(\n analyticsInstance: Analytics,\n id: string | null,\n options?: AnalyticsCallOptions\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalSetUserId(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n id,\n options\n ).catch(e => logger.error(e));\n}\n\n/**\n * Use gtag `config` command to set all params specified.\n *\n * @public\n */\nexport function setUserProperties(\n analyticsInstance: Analytics,\n properties: CustomParams,\n options?: AnalyticsCallOptions\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalSetUserProperties(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n properties,\n options\n ).catch(e => logger.error(e));\n}\n\n/**\n * Sets whether Google Analytics collection is enabled for this app on this device.\n * Sets global `window['ga-disable-analyticsId'] = true;`\n *\n * @public\n *\n * @param analyticsInstance - The {@link Analytics} instance.\n * @param enabled - If true, enables collection, if false, disables it.\n */\nexport function setAnalyticsCollectionEnabled(\n analyticsInstance: Analytics,\n enabled: boolean\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalSetAnalyticsCollectionEnabled(\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n enabled\n ).catch(e => logger.error(e));\n}\n\n/**\n * Adds data that will be set on every event logged from the SDK, including automatic ones.\n * With gtag's \"set\" command, the values passed persist on the current page and are passed with\n * all subsequent events.\n * @public\n * @param customParams - Any custom params the user may pass to gtag.js.\n */\nexport function setDefaultEventParameters(customParams: CustomParams): void {\n // Check if reference to existing gtag function on window object exists\n if (wrappedGtagFunction) {\n wrappedGtagFunction(GtagCommand.SET, customParams);\n } else {\n _setDefaultEventParametersForInit(customParams);\n }\n}\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'add_payment_info',\n eventParams?: {\n coupon?: EventParams['coupon'];\n currency?: EventParams['currency'];\n items?: EventParams['items'];\n payment_type?: EventParams['payment_type'];\n value?: EventParams['value'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'add_shipping_info',\n eventParams?: {\n coupon?: EventParams['coupon'];\n currency?: EventParams['currency'];\n items?: EventParams['items'];\n shipping_tier?: EventParams['shipping_tier'];\n value?: EventParams['value'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'add_to_cart' | 'add_to_wishlist' | 'remove_from_cart',\n eventParams?: {\n currency?: EventParams['currency'];\n value?: EventParams['value'];\n items?: EventParams['items'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'begin_checkout',\n eventParams?: {\n currency?: EventParams['currency'];\n coupon?: EventParams['coupon'];\n value?: EventParams['value'];\n items?: EventParams['items'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'checkout_progress',\n eventParams?: {\n currency?: EventParams['currency'];\n coupon?: EventParams['coupon'];\n value?: EventParams['value'];\n items?: EventParams['items'];\n checkout_step?: EventParams['checkout_step'];\n checkout_option?: EventParams['checkout_option'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * See\n * {@link https://developers.google.com/analytics/devguides/collection/ga4/exceptions\n * | Measure exceptions}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'exception',\n eventParams?: {\n description?: EventParams['description'];\n fatal?: EventParams['fatal'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'generate_lead',\n eventParams?: {\n value?: EventParams['value'];\n currency?: EventParams['currency'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'login',\n eventParams?: {\n method?: EventParams['method'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * See\n * {@link https://developers.google.com/analytics/devguides/collection/ga4/page-view\n * | Page views}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'page_view',\n eventParams?: {\n page_title?: string;\n page_location?: string;\n page_path?: string;\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'purchase' | 'refund',\n eventParams?: {\n value?: EventParams['value'];\n currency?: EventParams['currency'];\n transaction_id: EventParams['transaction_id'];\n tax?: EventParams['tax'];\n shipping?: EventParams['shipping'];\n items?: EventParams['items'];\n coupon?: EventParams['coupon'];\n affiliation?: EventParams['affiliation'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * See {@link https://firebase.google.com/docs/analytics/screenviews\n * | Track Screenviews}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'screen_view',\n eventParams?: {\n firebase_screen: EventParams['firebase_screen'];\n firebase_screen_class: EventParams['firebase_screen_class'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'search' | 'view_search_results',\n eventParams?: {\n search_term?: EventParams['search_term'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'select_content',\n eventParams?: {\n content_type?: EventParams['content_type'];\n item_id?: EventParams['item_id'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'select_item',\n eventParams?: {\n items?: EventParams['items'];\n item_list_name?: EventParams['item_list_name'];\n item_list_id?: EventParams['item_list_id'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'select_promotion' | 'view_promotion',\n eventParams?: {\n items?: EventParams['items'];\n promotion_id?: EventParams['promotion_id'];\n promotion_name?: EventParams['promotion_name'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'set_checkout_option',\n eventParams?: {\n checkout_step?: EventParams['checkout_step'];\n checkout_option?: EventParams['checkout_option'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'share',\n eventParams?: {\n method?: EventParams['method'];\n content_type?: EventParams['content_type'];\n item_id?: EventParams['item_id'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'sign_up',\n eventParams?: {\n method?: EventParams['method'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'timing_complete',\n eventParams?: {\n name: string;\n value: number;\n event_category?: string;\n event_label?: string;\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'view_cart' | 'view_item',\n eventParams?: {\n currency?: EventParams['currency'];\n items?: EventParams['items'];\n value?: EventParams['value'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'view_item_list',\n eventParams?: {\n items?: EventParams['items'];\n item_list_name?: EventParams['item_list_name'];\n item_list_id?: EventParams['item_list_id'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent<T extends string>(\n analyticsInstance: Analytics,\n eventName: CustomEventName<T>,\n eventParams?: { [key: string]: any },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * List of official event parameters can be found in the gtag.js\n * reference documentation:\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n *\n * @public\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: string,\n eventParams?: EventParams,\n options?: AnalyticsCallOptions\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalLogEvent(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n eventName,\n eventParams,\n options\n ).catch(e => logger.error(e));\n}\n\n/**\n * Any custom event name string not in the standard list of recommended\n * event names.\n * @public\n */\nexport type CustomEventName<T> = T extends EventNameString ? never : T;\n\n/**\n * Sets the applicable end user consent state for this web app across all gtag references once\n * Firebase Analytics is initialized.\n *\n * Use the {@link ConsentSettings} to specify individual consent type values. By default consent\n * types are set to \"granted\".\n * @public\n * @param consentSettings - Maps the applicable end user consent state for gtag.js.\n */\nexport function setConsent(consentSettings: ConsentSettings): void {\n // Check if reference to existing gtag function on window object exists\n if (wrappedGtagFunction) {\n wrappedGtagFunction(GtagCommand.CONSENT, 'update', consentSettings);\n } else {\n _setConsentDefaultForInit(consentSettings);\n }\n}\n","/**\n * Firebase Analytics\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerVersion, _registerComponent } from '@firebase/app';\nimport { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types';\nimport { factory } from './factory';\nimport { ANALYTICS_TYPE } from './constants';\nimport {\n Component,\n ComponentType,\n ComponentContainer,\n InstanceFactoryOptions\n} from '@firebase/component';\nimport { ERROR_FACTORY, AnalyticsError } from './errors';\nimport { logEvent } from './api';\nimport { name, version } from '../package.json';\nimport { AnalyticsCallOptions } from './public-types';\nimport '@firebase/installations';\n\ndeclare global {\n interface Window {\n [key: string]: unknown;\n }\n}\n\nfunction registerAnalytics(): void {\n _registerComponent(\n new Component(\n ANALYTICS_TYPE,\n (container, { options: analyticsOptions }: InstanceFactoryOptions) => {\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app').getImmediate();\n const installations = container\n .getProvider('installations-internal')\n .getImmediate();\n\n return factory(app, installations, analyticsOptions);\n },\n ComponentType.PUBLIC\n )\n );\n\n _registerComponent(\n new Component('analytics-internal', internalFactory, ComponentType.PRIVATE)\n );\n\n registerVersion(name, version);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n\n function internalFactory(\n container: ComponentContainer\n ): FirebaseAnalyticsInternal {\n try {\n const analytics = container.getProvider(ANALYTICS_TYPE).getImmediate();\n return {\n logEvent: (\n eventName: string,\n eventParams?: { [key: string]: unknown },\n options?: AnalyticsCallOptions\n ) => logEvent(analytics, eventName, eventParams, options)\n };\n } catch (e) {\n throw ERROR_FACTORY.create(AnalyticsError.INTEROP_COMPONENT_REG_FAILED, {\n reason: e as Error\n });\n }\n }\n}\n\nregisterAnalytics();\n\nexport * from './api';\nexport * from './public-types';\n","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n function next() {\n while (env.stack.length) {\n var rec = env.stack.pop();\n try {\n var result = rec.dispose && rec.dispose.call(rec.value);\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n catch (e) {\n fail(e);\n }\n }\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorMap, User } from '../model/public_types';\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nimport { IdTokenMfaResponse } from '../api/authentication/mfa';\nimport { AppName } from '../model/auth';\nimport { AuthCredential } from './credentials';\n\n/**\n * Enumeration of Firebase Auth error codes.\n *\n * @internal\n */\nexport const enum AuthErrorCode {\n ADMIN_ONLY_OPERATION = 'admin-restricted-operation',\n ARGUMENT_ERROR = 'argument-error',\n APP_NOT_AUTHORIZED = 'app-not-authorized',\n APP_NOT_INSTALLED = 'app-not-installed',\n CAPTCHA_CHECK_FAILED = 'captcha-check-failed',\n CODE_EXPIRED = 'code-expired',\n CORDOVA_NOT_READY = 'cordova-not-ready',\n CORS_UNSUPPORTED = 'cors-unsupported',\n CREDENTIAL_ALREADY_IN_USE = 'credential-already-in-use',\n CREDENTIAL_MISMATCH = 'custom-token-mismatch',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN = 'requires-recent-login',\n DEPENDENT_SDK_INIT_BEFORE_AUTH = 'dependent-sdk-initialized-before-auth',\n DYNAMIC_LINK_NOT_ACTIVATED = 'dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION = 'email-change-needs-verification',\n EMAIL_EXISTS = 'email-already-in-use',\n EMULATOR_CONFIG_FAILED = 'emulator-config-failed',\n EXPIRED_OOB_CODE = 'expired-action-code',\n EXPIRED_POPUP_REQUEST = 'cancelled-popup-request',\n INTERNAL_ERROR = 'internal-error',\n INVALID_API_KEY = 'invalid-api-key',\n INVALID_APP_CREDENTIAL = 'invalid-app-credential',\n INVALID_APP_ID = 'invalid-app-id',\n INVALID_AUTH = 'invalid-user-token',\n INVALID_AUTH_EVENT = 'invalid-auth-event',\n INVALID_CERT_HASH = 'invalid-cert-hash',\n INVALID_CODE = 'invalid-verification-code',\n INVALID_CONTINUE_URI = 'invalid-continue-uri',\n INVALID_CORDOVA_CONFIGURATION = 'invalid-cordova-configuration',\n INVALID_CUSTOM_TOKEN = 'invalid-custom-token',\n INVALID_DYNAMIC_LINK_DOMAIN = 'invalid-dynamic-link-domain',\n INVALID_EMAIL = 'invalid-email',\n INVALID_EMULATOR_SCHEME = 'invalid-emulator-scheme',\n INVALID_IDP_RESPONSE = 'invalid-credential',\n INVALID_MESSAGE_PAYLOAD = 'invalid-message-payload',\n INVALID_MFA_SESSION = 'invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID = 'invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER = 'invalid-oauth-provider',\n INVALID_OOB_CODE = 'invalid-action-code',\n INVALID_ORIGIN = 'unauthorized-domain',\n INVALID_PASSWORD = 'wrong-password',\n INVALID_PERSISTENCE = 'invalid-persistence-type',\n INVALID_PHONE_NUMBER = 'invalid-phone-number',\n INVALID_PROVIDER_ID = 'invalid-provider-id',\n INVALID_RECIPIENT_EMAIL = 'invalid-recipient-email',\n INVALID_SENDER = 'invalid-sender',\n INVALID_SESSION_INFO = 'invalid-verification-id',\n INVALID_TENANT_ID = 'invalid-tenant-id',\n LOGIN_BLOCKED = 'login-blocked',\n MFA_INFO_NOT_FOUND = 'multi-factor-info-not-found',\n MFA_REQUIRED = 'multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME = 'missing-android-pkg-name',\n MISSING_APP_CREDENTIAL = 'missing-app-credential',\n MISSING_AUTH_DOMAIN = 'auth-domain-config-required',\n MISSING_CODE = 'missing-verification-code',\n MISSING_CONTINUE_URI = 'missing-continue-uri',\n MISSING_IFRAME_START = 'missing-iframe-start',\n MISSING_IOS_BUNDLE_ID = 'missing-ios-bundle-id',\n MISSING_OR_INVALID_NONCE = 'missing-or-invalid-nonce',\n MISSING_MFA_INFO = 'missing-multi-factor-info',\n MISSING_MFA_SESSION = 'missing-multi-factor-session',\n MISSING_PHONE_NUMBER = 'missing-phone-number',\n MISSING_PASSWORD = 'missing-password',\n MISSING_SESSION_INFO = 'missing-verification-id',\n MODULE_DESTROYED = 'app-deleted',\n NEED_CONFIRMATION = 'account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED = 'network-request-failed',\n NULL_USER = 'null-user',\n NO_AUTH_EVENT = 'no-auth-event',\n NO_SUCH_PROVIDER = 'no-such-provider',\n OPERATION_NOT_ALLOWED = 'operation-not-allowed',\n OPERATION_NOT_SUPPORTED = 'operation-not-supported-in-this-environment',\n POPUP_BLOCKED = 'popup-blocked',\n POPUP_CLOSED_BY_USER = 'popup-closed-by-user',\n PROVIDER_ALREADY_LINKED = 'provider-already-linked',\n QUOTA_EXCEEDED = 'quota-exceeded',\n REDIRECT_CANCELLED_BY_USER = 'redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING = 'redirect-operation-pending',\n REJECTED_CREDENTIAL = 'rejected-credential',\n SECOND_FACTOR_ALREADY_ENROLLED = 'second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED = 'maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH = 'tenant-id-mismatch',\n TIMEOUT = 'timeout',\n TOKEN_EXPIRED = 'user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER = 'too-many-requests',\n UNAUTHORIZED_DOMAIN = 'unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR = 'unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE = 'unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION = 'unsupported-tenant-operation',\n UNVERIFIED_EMAIL = 'unverified-email',\n USER_CANCELLED = 'user-cancelled',\n USER_DELETED = 'user-not-found',\n USER_DISABLED = 'user-disabled',\n USER_MISMATCH = 'user-mismatch',\n USER_SIGNED_OUT = 'user-signed-out',\n WEAK_PASSWORD = 'weak-password',\n WEB_STORAGE_UNSUPPORTED = 'web-storage-unsupported',\n ALREADY_INITIALIZED = 'already-initialized',\n RECAPTCHA_NOT_ENABLED = 'recaptcha-not-enabled',\n MISSING_RECAPTCHA_TOKEN = 'missing-recaptcha-token',\n INVALID_RECAPTCHA_TOKEN = 'invalid-recaptcha-token',\n INVALID_RECAPTCHA_ACTION = 'invalid-recaptcha-action',\n MISSING_CLIENT_TYPE = 'missing-client-type',\n MISSING_RECAPTCHA_VERSION = 'missing-recaptcha-version',\n INVALID_RECAPTCHA_VERSION = 'invalid-recaptcha-version',\n INVALID_REQ_TYPE = 'invalid-req-type',\n UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION = 'unsupported-password-policy-schema-version',\n PASSWORD_DOES_NOT_MEET_REQUIREMENTS = 'password-does-not-meet-requirements'\n}\n\nfunction _debugErrorMap(): ErrorMap<AuthErrorCode> {\n return {\n [AuthErrorCode.ADMIN_ONLY_OPERATION]:\n 'This operation is restricted to administrators only.',\n [AuthErrorCode.ARGUMENT_ERROR]: '',\n [AuthErrorCode.APP_NOT_AUTHORIZED]:\n \"This app, identified by the domain where it's hosted, is not \" +\n 'authorized to use Firebase Authentication with the provided API key. ' +\n 'Review your key configuration in the Google API console.',\n [AuthErrorCode.APP_NOT_INSTALLED]:\n 'The requested mobile application corresponding to the identifier (' +\n 'Android package name or iOS bundle ID) provided is not installed on ' +\n 'this device.',\n [AuthErrorCode.CAPTCHA_CHECK_FAILED]:\n 'The reCAPTCHA response token provided is either invalid, expired, ' +\n 'already used or the domain associated with it does not match the list ' +\n 'of whitelisted domains.',\n [AuthErrorCode.CODE_EXPIRED]:\n 'The SMS code has expired. Please re-send the verification code to try ' +\n 'again.',\n [AuthErrorCode.CORDOVA_NOT_READY]: 'Cordova framework is not ready.',\n [AuthErrorCode.CORS_UNSUPPORTED]: 'This browser is not supported.',\n [AuthErrorCode.CREDENTIAL_ALREADY_IN_USE]:\n 'This credential is already associated with a different user account.',\n [AuthErrorCode.CREDENTIAL_MISMATCH]:\n 'The custom token corresponds to a different audience.',\n [AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN]:\n 'This operation is sensitive and requires recent authentication. Log in ' +\n 'again before retrying this request.',\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]:\n 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.',\n [AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED]:\n 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +\n 'conditions.',\n [AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION]:\n 'Multi-factor users must always have a verified email.',\n [AuthErrorCode.EMAIL_EXISTS]:\n 'The email address is already in use by another account.',\n [AuthErrorCode.EMULATOR_CONFIG_FAILED]:\n 'Auth instance has already been used to make a network call. Auth can ' +\n 'no longer be configured to use the emulator. Try calling ' +\n '\"connectAuthEmulator()\" sooner.',\n [AuthErrorCode.EXPIRED_OOB_CODE]: 'The action code has expired.',\n [AuthErrorCode.EXPIRED_POPUP_REQUEST]:\n 'This operation has been cancelled due to another conflicting popup being opened.',\n [AuthErrorCode.INTERNAL_ERROR]: 'An internal AuthError has occurred.',\n [AuthErrorCode.INVALID_APP_CREDENTIAL]:\n 'The phone verification request contains an invalid application verifier.' +\n ' The reCAPTCHA token response is either invalid or expired.',\n [AuthErrorCode.INVALID_APP_ID]:\n 'The mobile app identifier is not registed for the current project.',\n [AuthErrorCode.INVALID_AUTH]:\n \"This user's credential isn't valid for this project. This can happen \" +\n \"if the user's token has been tampered with, or if the user isn't for \" +\n 'the project associated with this API key.',\n [AuthErrorCode.INVALID_AUTH_EVENT]: 'An internal AuthError has occurred.',\n [AuthErrorCode.INVALID_CODE]:\n 'The SMS verification code used to create the phone auth credential is ' +\n 'invalid. Please resend the verification code sms and be sure to use the ' +\n 'verification code provided by the user.',\n [AuthErrorCode.INVALID_CONTINUE_URI]:\n 'The continue URL provided in the request is invalid.',\n [AuthErrorCode.INVALID_CORDOVA_CONFIGURATION]:\n 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +\n 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +\n 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +\n 'cordova-plugin-customurlscheme.',\n [AuthErrorCode.INVALID_CUSTOM_TOKEN]:\n 'The custom token format is incorrect. Please check the documentation.',\n [AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN]:\n 'The provided dynamic link domain is not configured or authorized for the current project.',\n [AuthErrorCode.INVALID_EMAIL]: 'The email address is badly formatted.',\n [AuthErrorCode.INVALID_EMULATOR_SCHEME]:\n 'Emulator URL must start with a valid scheme (http:// or https://).',\n [AuthErrorCode.INVALID_API_KEY]:\n 'Your API key is invalid, please check you have copied it correctly.',\n [AuthErrorCode.INVALID_CERT_HASH]:\n 'The SHA-1 certificate hash provided is invalid.',\n [AuthErrorCode.INVALID_IDP_RESPONSE]:\n 'The supplied auth credential is malformed or has expired.',\n [AuthErrorCode.INVALID_MESSAGE_PAYLOAD]:\n 'The email template corresponding to this action contains invalid characters in its message. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [AuthErrorCode.INVALID_MFA_SESSION]:\n 'The request does not contain a valid proof of first factor successful sign-in.',\n [AuthErrorCode.INVALID_OAUTH_PROVIDER]:\n 'EmailAuthProvider is not supported for this operation. This operation ' +\n 'only supports OAuth providers.',\n [AuthErrorCode.INVALID_OAUTH_CLIENT_ID]:\n 'The OAuth client ID provided is either invalid or does not match the ' +\n 'specified API key.',\n [AuthErrorCode.INVALID_ORIGIN]:\n 'This domain is not authorized for OAuth operations for your Firebase ' +\n 'project. Edit the list of authorized domains from the Firebase console.',\n [AuthErrorCode.INVALID_OOB_CODE]:\n 'The action code is invalid. This can happen if the code is malformed, ' +\n 'expired, or has already been used.',\n [AuthErrorCode.INVALID_PASSWORD]:\n 'The password is invalid or the user does not have a password.',\n [AuthErrorCode.INVALID_PERSISTENCE]:\n 'The specified persistence type is invalid. It can only be local, session or none.',\n [AuthErrorCode.INVALID_PHONE_NUMBER]:\n 'The format of the phone number provided is incorrect. Please enter the ' +\n 'phone number in a format that can be parsed into E.164 format. E.164 ' +\n 'phone numbers are written in the format [+][country code][subscriber ' +\n 'number including area code].',\n [AuthErrorCode.INVALID_PROVIDER_ID]:\n 'The specified provider ID is invalid.',\n [AuthErrorCode.INVALID_RECIPIENT_EMAIL]:\n 'The email corresponding to this action failed to send as the provided ' +\n 'recipient email address is invalid.',\n [AuthErrorCode.INVALID_SENDER]:\n 'The email template corresponding to this action contains an invalid sender email or name. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [AuthErrorCode.INVALID_SESSION_INFO]:\n 'The verification ID used to create the phone auth credential is invalid.',\n [AuthErrorCode.INVALID_TENANT_ID]:\n \"The Auth instance's tenant ID is invalid.\",\n [AuthErrorCode.LOGIN_BLOCKED]:\n 'Login blocked by user-provided method: {$originalMessage}',\n [AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME]:\n 'An Android Package Name must be provided if the Android App is required to be installed.',\n [AuthErrorCode.MISSING_AUTH_DOMAIN]:\n 'Be sure to include authDomain when calling firebase.initializeApp(), ' +\n 'by following the instructions in the Firebase console.',\n [AuthErrorCode.MISSING_APP_CREDENTIAL]:\n 'The phone verification request is missing an application verifier ' +\n 'assertion. A reCAPTCHA response token needs to be provided.',\n [AuthErrorCode.MISSING_CODE]:\n 'The phone auth credential was created with an empty SMS verification code.',\n [AuthErrorCode.MISSING_CONTINUE_URI]:\n 'A continue URL must be provided in the request.',\n [AuthErrorCode.MISSING_IFRAME_START]: 'An internal AuthError has occurred.',\n [AuthErrorCode.MISSING_IOS_BUNDLE_ID]:\n 'An iOS Bundle ID must be provided if an App Store ID is provided.',\n [AuthErrorCode.MISSING_OR_INVALID_NONCE]:\n 'The request does not contain a valid nonce. This can occur if the ' +\n 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +\n 'in the ID token payload.',\n [AuthErrorCode.MISSING_PASSWORD]: 'A non-empty password must be provided',\n [AuthErrorCode.MISSING_MFA_INFO]:\n 'No second factor identifier is provided.',\n [AuthErrorCode.MISSING_MFA_SESSION]:\n 'The request is missing proof of first factor successful sign-in.',\n [AuthErrorCode.MISSING_PHONE_NUMBER]:\n 'To send verification codes, provide a phone number for the recipient.',\n [AuthErrorCode.MISSING_SESSION_INFO]:\n 'The phone auth credential was created with an empty verification ID.',\n [AuthErrorCode.MODULE_DESTROYED]:\n 'This instance of FirebaseApp has been deleted.',\n [AuthErrorCode.MFA_INFO_NOT_FOUND]:\n 'The user does not have a second factor matching the identifier provided.',\n [AuthErrorCode.MFA_REQUIRED]:\n 'Proof of ownership of a second factor is required to complete sign-in.',\n [AuthErrorCode.NEED_CONFIRMATION]:\n 'An account already exists with the same email address but different ' +\n 'sign-in credentials. Sign in using a provider associated with this ' +\n 'email address.',\n [AuthErrorCode.NETWORK_REQUEST_FAILED]:\n 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',\n [AuthErrorCode.NO_AUTH_EVENT]: 'An internal AuthError has occurred.',\n [AuthErrorCode.NO_SUCH_PROVIDER]:\n 'User was not linked to an account with the given provider.',\n [AuthErrorCode.NULL_USER]:\n 'A null user object was provided as the argument for an operation which ' +\n 'requires a non-null user object.',\n [AuthErrorCode.OPERATION_NOT_ALLOWED]:\n 'The given sign-in provider is disabled for this Firebase project. ' +\n 'Enable it in the Firebase console, under the sign-in method tab of the ' +\n 'Auth section.',\n [AuthErrorCode.OPERATION_NOT_SUPPORTED]:\n 'This operation is not supported in the environment this application is ' +\n 'running on. \"location.protocol\" must be http, https or chrome-extension' +\n ' and web storage must be enabled.',\n [AuthErrorCode.POPUP_BLOCKED]:\n 'Unable to establish a connection with the popup. It may have been blocked by the browser.',\n [AuthErrorCode.POPUP_CLOSED_BY_USER]:\n 'The popup has been closed by the user before finalizing the operation.',\n [AuthErrorCode.PROVIDER_ALREADY_LINKED]:\n 'User can only be linked to one identity for the given provider.',\n [AuthErrorCode.QUOTA_EXCEEDED]:\n \"The project's quota for this operation has been exceeded.\",\n [AuthErrorCode.REDIRECT_CANCELLED_BY_USER]:\n 'The redirect operation has been cancelled by the user before finalizing.',\n [AuthErrorCode.REDIRECT_OPERATION_PENDING]:\n 'A redirect sign-in operation is already pending.',\n [AuthErrorCode.REJECTED_CREDENTIAL]:\n 'The request contains malformed or mismatching credentials.',\n [AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED]:\n 'The second factor is already enrolled on this account.',\n [AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED]:\n 'The maximum allowed number of second factors on a user has been exceeded.',\n [AuthErrorCode.TENANT_ID_MISMATCH]:\n \"The provided tenant ID does not match the Auth instance's tenant ID\",\n [AuthErrorCode.TIMEOUT]: 'The operation has timed out.',\n [AuthErrorCode.TOKEN_EXPIRED]:\n \"The user's credential is no longer valid. The user must sign in again.\",\n [AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER]:\n 'We have blocked all requests from this device due to unusual activity. ' +\n 'Try again later.',\n [AuthErrorCode.UNAUTHORIZED_DOMAIN]:\n 'The domain of the continue URL is not whitelisted. Please whitelist ' +\n 'the domain in the Firebase console.',\n [AuthErrorCode.UNSUPPORTED_FIRST_FACTOR]:\n 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',\n [AuthErrorCode.UNSUPPORTED_PERSISTENCE]:\n 'The current environment does not support the specified persistence type.',\n [AuthErrorCode.UNSUPPORTED_TENANT_OPERATION]:\n 'This operation is not supported in a multi-tenant context.',\n [AuthErrorCode.UNVERIFIED_EMAIL]:\n 'The operation requires a verified email.',\n [AuthErrorCode.USER_CANCELLED]:\n 'The user did not grant your application the permissions it requested.',\n [AuthErrorCode.USER_DELETED]:\n 'There is no user record corresponding to this identifier. The user may ' +\n 'have been deleted.',\n [AuthErrorCode.USER_DISABLED]:\n 'The user account has been disabled by an administrator.',\n [AuthErrorCode.USER_MISMATCH]:\n 'The supplied credentials do not correspond to the previously signed in user.',\n [AuthErrorCode.USER_SIGNED_OUT]: '',\n [AuthErrorCode.WEAK_PASSWORD]:\n 'The password must be 6 characters long or more.',\n [AuthErrorCode.WEB_STORAGE_UNSUPPORTED]:\n 'This browser is not supported or 3rd party cookies and data may be disabled.',\n [AuthErrorCode.ALREADY_INITIALIZED]:\n 'initializeAuth() has already been called with ' +\n 'different options. To avoid this error, call initializeAuth() with the ' +\n 'same options as when it was originally called, or call getAuth() to return the' +\n ' already initialized instance.',\n [AuthErrorCode.MISSING_RECAPTCHA_TOKEN]:\n 'The reCAPTCHA token is missing when sending request to the backend.',\n [AuthErrorCode.INVALID_RECAPTCHA_TOKEN]:\n 'The reCAPTCHA token is invalid when sending request to the backend.',\n [AuthErrorCode.INVALID_RECAPTCHA_ACTION]:\n 'The reCAPTCHA action is invalid when sending request to the backend.',\n [AuthErrorCode.RECAPTCHA_NOT_ENABLED]:\n 'reCAPTCHA Enterprise integration is not enabled for this project.',\n [AuthErrorCode.MISSING_CLIENT_TYPE]:\n 'The reCAPTCHA client type is missing when sending request to the backend.',\n [AuthErrorCode.MISSING_RECAPTCHA_VERSION]:\n 'The reCAPTCHA version is missing when sending request to the backend.',\n [AuthErrorCode.INVALID_REQ_TYPE]: 'Invalid request parameters.',\n [AuthErrorCode.INVALID_RECAPTCHA_VERSION]:\n 'The reCAPTCHA version is invalid when sending request to the backend.',\n [AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION]:\n 'The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.',\n [AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS]:\n 'The password does not meet the requirements.'\n };\n}\n\nexport interface ErrorMapRetriever extends AuthErrorMap {\n (): ErrorMap<AuthErrorCode>;\n}\n\nfunction _prodErrorMap(): ErrorMap<AuthErrorCode> {\n // We will include this one message in the prod error map since by the very\n // nature of this error, developers will never be able to see the message\n // using the debugErrorMap (which is installed during auth initialization).\n return {\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]:\n 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.'\n } as ErrorMap<AuthErrorCode>;\n}\n\n/**\n * A verbose error map with detailed descriptions for most error codes.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nexport const debugErrorMap: AuthErrorMap = _debugErrorMap;\n\n/**\n * A minimal error map with all verbose error messages stripped.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nexport const prodErrorMap: AuthErrorMap = _prodErrorMap;\n\nexport interface NamedErrorParams {\n appName: AppName;\n credential?: AuthCredential;\n email?: string;\n phoneNumber?: string;\n tenantId?: string;\n user?: User;\n _serverResponse?: object;\n}\n\n/**\n * @internal\n */\ntype GenericAuthErrorParams = {\n [key in Exclude<\n AuthErrorCode,\n | AuthErrorCode.ARGUMENT_ERROR\n | AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH\n | AuthErrorCode.INTERNAL_ERROR\n | AuthErrorCode.MFA_REQUIRED\n | AuthErrorCode.NO_AUTH_EVENT\n | AuthErrorCode.OPERATION_NOT_SUPPORTED\n >]: {\n appName?: AppName;\n email?: string;\n phoneNumber?: string;\n message?: string;\n };\n};\n\n/**\n * @internal\n */\nexport interface AuthErrorParams extends GenericAuthErrorParams {\n [AuthErrorCode.ARGUMENT_ERROR]: { appName?: AppName };\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]: { appName?: AppName };\n [AuthErrorCode.INTERNAL_ERROR]: { appName?: AppName };\n [AuthErrorCode.LOGIN_BLOCKED]: {\n appName?: AppName;\n originalMessage?: string;\n };\n [AuthErrorCode.OPERATION_NOT_SUPPORTED]: { appName?: AppName };\n [AuthErrorCode.NO_AUTH_EVENT]: { appName?: AppName };\n [AuthErrorCode.MFA_REQUIRED]: {\n appName: AppName;\n _serverResponse: IdTokenMfaResponse;\n };\n [AuthErrorCode.INVALID_CORDOVA_CONFIGURATION]: {\n appName: AppName;\n missingPlugin?: string;\n };\n}\n\nexport const _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory<\n AuthErrorCode,\n AuthErrorParams\n>('auth', 'Firebase', _prodErrorMap());\n\n/**\n * A map of potential `Auth` error codes, for easier comparison with errors\n * thrown by the SDK.\n *\n * @remarks\n * Note that you can't tree-shake individual keys\n * in the map, so by using the map you might substantially increase your\n * bundle size.\n *\n * @public\n */\nexport const AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {\n ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',\n ARGUMENT_ERROR: 'auth/argument-error',\n APP_NOT_AUTHORIZED: 'auth/app-not-authorized',\n APP_NOT_INSTALLED: 'auth/app-not-installed',\n CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',\n CODE_EXPIRED: 'auth/code-expired',\n CORDOVA_NOT_READY: 'auth/cordova-not-ready',\n CORS_UNSUPPORTED: 'auth/cors-unsupported',\n CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',\n CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',\n DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',\n DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',\n EMAIL_EXISTS: 'auth/email-already-in-use',\n EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',\n EXPIRED_OOB_CODE: 'auth/expired-action-code',\n EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',\n INTERNAL_ERROR: 'auth/internal-error',\n INVALID_API_KEY: 'auth/invalid-api-key',\n INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',\n INVALID_APP_ID: 'auth/invalid-app-id',\n INVALID_AUTH: 'auth/invalid-user-token',\n INVALID_AUTH_EVENT: 'auth/invalid-auth-event',\n INVALID_CERT_HASH: 'auth/invalid-cert-hash',\n INVALID_CODE: 'auth/invalid-verification-code',\n INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',\n INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',\n INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',\n INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',\n INVALID_EMAIL: 'auth/invalid-email',\n INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',\n INVALID_IDP_RESPONSE: 'auth/invalid-credential',\n INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',\n INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',\n INVALID_OOB_CODE: 'auth/invalid-action-code',\n INVALID_ORIGIN: 'auth/unauthorized-domain',\n INVALID_PASSWORD: 'auth/wrong-password',\n INVALID_PERSISTENCE: 'auth/invalid-persistence-type',\n INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',\n INVALID_PROVIDER_ID: 'auth/invalid-provider-id',\n INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',\n INVALID_SENDER: 'auth/invalid-sender',\n INVALID_SESSION_INFO: 'auth/invalid-verification-id',\n INVALID_TENANT_ID: 'auth/invalid-tenant-id',\n MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',\n MFA_REQUIRED: 'auth/multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',\n MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',\n MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',\n MISSING_CODE: 'auth/missing-verification-code',\n MISSING_CONTINUE_URI: 'auth/missing-continue-uri',\n MISSING_IFRAME_START: 'auth/missing-iframe-start',\n MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',\n MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',\n MISSING_MFA_INFO: 'auth/missing-multi-factor-info',\n MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',\n MISSING_PHONE_NUMBER: 'auth/missing-phone-number',\n MISSING_SESSION_INFO: 'auth/missing-verification-id',\n MODULE_DESTROYED: 'auth/app-deleted',\n NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED: 'auth/network-request-failed',\n NULL_USER: 'auth/null-user',\n NO_AUTH_EVENT: 'auth/no-auth-event',\n NO_SUCH_PROVIDER: 'auth/no-such-provider',\n OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',\n OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',\n POPUP_BLOCKED: 'auth/popup-blocked',\n POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',\n PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',\n QUOTA_EXCEEDED: 'auth/quota-exceeded',\n REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',\n REJECTED_CREDENTIAL: 'auth/rejected-credential',\n SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',\n TIMEOUT: 'auth/timeout',\n TOKEN_EXPIRED: 'auth/user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',\n UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',\n UNVERIFIED_EMAIL: 'auth/unverified-email',\n USER_CANCELLED: 'auth/user-cancelled',\n USER_DELETED: 'auth/user-not-found',\n USER_DISABLED: 'auth/user-disabled',\n USER_MISMATCH: 'auth/user-mismatch',\n USER_SIGNED_OUT: 'auth/user-signed-out',\n WEAK_PASSWORD: 'auth/weak-password',\n WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',\n ALREADY_INITIALIZED: 'auth/already-initialized',\n RECAPTCHA_NOT_ENABLED: 'auth/recaptcha-not-enabled',\n MISSING_RECAPTCHA_TOKEN: 'auth/missing-recaptcha-token',\n INVALID_RECAPTCHA_TOKEN: 'auth/invalid-recaptcha-token',\n INVALID_RECAPTCHA_ACTION: 'auth/invalid-recaptcha-action',\n MISSING_CLIENT_TYPE: 'auth/missing-client-type',\n MISSING_RECAPTCHA_VERSION: 'auth/missing-recaptcha-version',\n INVALID_RECAPTCHA_VERSION: 'auth/invalid-recaptcha-version',\n INVALID_REQ_TYPE: 'auth/invalid-req-type'\n} as const;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { SDK_VERSION } from '@firebase/app';\n\nexport { LogLevel };\n\nconst logClient = new Logger('@firebase/auth');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function _getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\nexport function _setLogLevel(newLevel: LogLevel): void {\n logClient.logLevel = newLevel;\n}\n\nexport function _logDebug(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n logClient.debug(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function _logWarn(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n logClient.warn(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function _logError(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth } from '../../model/public_types';\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { AuthInternal } from '../../model/auth';\nimport {\n _DEFAULT_AUTH_ERROR_FACTORY,\n AuthErrorCode,\n AuthErrorParams,\n prodErrorMap,\n ErrorMapRetriever\n} from '../errors';\nimport { _logError } from './log';\n\ntype AuthErrorListParams<K> = K extends keyof AuthErrorParams\n ? [AuthErrorParams[K]]\n : [];\ntype LessAppName<K extends AuthErrorCode> = Omit<AuthErrorParams[K], 'appName'>;\n\n/**\n * Unconditionally fails, throwing a developer facing INTERNAL_ERROR\n *\n * @example\n * ```javascript\n * fail(auth, AuthErrorCode.MFA_REQUIRED); // Error: the MFA_REQUIRED error needs more params than appName\n * fail(auth, AuthErrorCode.MFA_REQUIRED, {serverResponse}); // Compiles\n * fail(AuthErrorCode.INTERNAL_ERROR); // Compiles; internal error does not need appName\n * fail(AuthErrorCode.USER_DELETED); // Error: USER_DELETED requires app name\n * fail(auth, AuthErrorCode.USER_DELETED); // Compiles; USER_DELETED _only_ needs app name\n * ```\n *\n * @param appName App name for tagging the error\n * @throws FirebaseError\n */\nexport function _fail<K extends AuthErrorCode>(\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): never;\nexport function _fail<K extends AuthErrorCode>(\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName<K> ? [LessAppName<K>?] : [LessAppName<K>]\n): never;\nexport function _fail<K extends AuthErrorCode>(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): never {\n throw createErrorInternal(authOrCode, ...rest);\n}\n\nexport function _createError<K extends AuthErrorCode>(\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): FirebaseError;\nexport function _createError<K extends AuthErrorCode>(\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName<K> ? [LessAppName<K>?] : [LessAppName<K>]\n): FirebaseError;\nexport function _createError<K extends AuthErrorCode>(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): FirebaseError {\n return createErrorInternal(authOrCode, ...rest);\n}\n\nexport function _errorWithCustomMessage(\n auth: Auth,\n code: AuthErrorCode,\n message: string\n): FirebaseError {\n const errorMap = {\n ...(prodErrorMap as ErrorMapRetriever)(),\n [code]: message\n };\n const factory = new ErrorFactory<AuthErrorCode, AuthErrorParams>(\n 'auth',\n 'Firebase',\n errorMap\n );\n return factory.create(code, {\n appName: auth.name\n });\n}\n\nexport function _assertInstanceOf(\n auth: Auth,\n object: object,\n instance: unknown\n): void {\n const constructorInstance = instance as { new (...args: unknown[]): unknown };\n if (!(object instanceof constructorInstance)) {\n if (constructorInstance.name !== object.constructor.name) {\n _fail(auth, AuthErrorCode.ARGUMENT_ERROR);\n }\n\n throw _errorWithCustomMessage(\n auth,\n AuthErrorCode.ARGUMENT_ERROR,\n `Type of ${object.constructor.name} does not match expected instance.` +\n `Did you pass a reference from a different Auth SDK?`\n );\n }\n}\n\nfunction createErrorInternal<K extends AuthErrorCode>(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): FirebaseError {\n if (typeof authOrCode !== 'string') {\n const code = rest[0] as K;\n const fullParams = [...rest.slice(1)] as AuthErrorListParams<K>;\n if (fullParams[0]) {\n fullParams[0].appName = authOrCode.name;\n }\n\n return (authOrCode as AuthInternal)._errorFactory.create(\n code,\n ...fullParams\n );\n }\n\n return _DEFAULT_AUTH_ERROR_FACTORY.create(\n authOrCode,\n ...(rest as AuthErrorListParams<K>)\n );\n}\n\nexport function _assert<K extends AuthErrorCode>(\n assertion: unknown,\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): asserts assertion;\nexport function _assert<K extends AuthErrorCode>(\n assertion: unknown,\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName<K> ? [LessAppName<K>?] : [LessAppName<K>]\n): asserts assertion;\nexport function _assert<K extends AuthErrorCode>(\n assertion: unknown,\n authOrCode: Auth | K,\n ...rest: unknown[]\n): asserts assertion {\n if (!assertion) {\n throw createErrorInternal(authOrCode, ...rest);\n }\n}\n\n// We really do want to accept literally any function type here\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype TypeExpectation = Function | string | MapType;\n\ninterface MapType extends Record<string, TypeExpectation | Optional> {}\n\nclass Optional {\n constructor(readonly type: TypeExpectation) {}\n}\n\nexport function opt(type: TypeExpectation): Optional {\n return new Optional(type);\n}\n\n/**\n * Asserts the runtime types of arguments. The 'expected' field can be one of\n * a class, a string (representing a \"typeof\" call), or a record map of name\n * to type. Furthermore, the opt() function can be used to mark a field as\n * optional. For example:\n *\n * function foo(auth: Auth, profile: {displayName?: string}, update = false) {\n * assertTypes(arguments, [AuthImpl, {displayName: opt('string')}, opt('boolean')]);\n * }\n *\n * opt() can be used for any type:\n * function foo(auth?: Auth) {\n * assertTypes(arguments, [opt(AuthImpl)]);\n * }\n *\n * The string types can be or'd together, and you can use \"null\" as well (note\n * that typeof null === 'object'; this is an edge case). For example:\n *\n * function foo(profile: {displayName?: string | null}) {\n * assertTypes(arguments, [{displayName: opt('string|null')}]);\n * }\n *\n * @param args\n * @param expected\n */\nexport function assertTypes(\n args: Omit<IArguments, 'callee'>,\n ...expected: Array<TypeExpectation | Optional>\n): void {\n if (args.length > expected.length) {\n _fail(AuthErrorCode.ARGUMENT_ERROR, {});\n }\n\n for (let i = 0; i < expected.length; i++) {\n let expect = expected[i];\n const arg = args[i];\n\n if (expect instanceof Optional) {\n // If the arg is undefined, then it matches \"optional\" and we can move to\n // the next arg\n if (typeof arg === 'undefined') {\n continue;\n }\n expect = expect.type;\n }\n\n if (typeof expect === 'string') {\n // Handle the edge case for null because typeof null === 'object'\n if (expect.includes('null') && arg === null) {\n continue;\n }\n\n const required = expect.split('|');\n _assert(required.includes(typeof arg), AuthErrorCode.ARGUMENT_ERROR, {});\n } else if (typeof expect === 'object') {\n // Recursively check record arguments\n const record = arg as Record<string, unknown>;\n const map = expect as MapType;\n const keys = Object.keys(expect);\n\n assertTypes(\n keys.map(k => record[k]),\n ...keys.map(k => map[k])\n );\n } else {\n _assert(arg instanceof expect, AuthErrorCode.ARGUMENT_ERROR, {});\n }\n }\n}\n\n/**\n * Unconditionally fails, throwing an internal error with the given message.\n *\n * @param failure type of failure encountered\n * @throws Error\n */\nexport function debugFail(failure: string): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const message = `INTERNAL ASSERTION FAILED: ` + failure;\n _logError(message);\n\n // NOTE: We don't use FirebaseError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * @param assertion\n * @param message\n */\nexport function debugAssert(\n assertion: unknown,\n message: string\n): asserts assertion {\n if (!assertion) {\n debugFail(message);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function _getCurrentUrl(): string {\n return (typeof self !== 'undefined' && self.location?.href) || '';\n}\n\nexport function _isHttpOrHttps(): boolean {\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\n}\n\nexport function _getCurrentScheme(): string | null {\n return (typeof self !== 'undefined' && self.location?.protocol) || null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isMobileCordova, isReactNative } from '@firebase/util';\nimport { _isOnline } from './navigator';\nimport { debugAssert } from './assert';\n\nexport const enum DelayMin {\n OFFLINE = 5000\n}\n\n/**\n * A structure to help pick between a range of long and short delay durations\n * depending on the current environment. In general, the long delay is used for\n * mobile environments whereas short delays are used for desktop environments.\n */\nexport class Delay {\n // The default value for the offline delay timeout in ms.\n\n private readonly isMobile: boolean;\n constructor(\n private readonly shortDelay: number,\n private readonly longDelay: number\n ) {\n // Internal error when improperly initialized.\n debugAssert(\n longDelay > shortDelay,\n 'Short delay should be less than long delay!'\n );\n this.isMobile = isMobileCordova() || isReactNative();\n }\n\n get(): number {\n if (!_isOnline()) {\n // Pick the shorter timeout.\n return Math.min(DelayMin.OFFLINE, this.shortDelay);\n }\n // If running in a mobile environment, return the long delay, otherwise\n // return the short delay.\n // This could be improved in the future to dynamically change based on other\n // variables instead of just reading the current environment.\n return this.isMobile ? this.longDelay : this.shortDelay;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isBrowserExtension } from '@firebase/util';\nimport { _isHttpOrHttps } from './location';\n\n/**\n * Determine whether the browser is working online\n */\nexport function _isOnline(): boolean {\n if (\n typeof navigator !== 'undefined' &&\n navigator &&\n 'onLine' in navigator &&\n typeof navigator.onLine === 'boolean' &&\n // Apply only for traditional web apps and Chrome extensions.\n // This is especially true for Cordova apps which have unreliable\n // navigator.onLine behavior unless cordova-plugin-network-information is\n // installed which overwrites the native navigator.onLine value and\n // defines navigator.connection.\n (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)\n ) {\n return navigator.onLine;\n }\n // If we can't determine the state, assume it is online.\n return true;\n}\n\nexport function _getUserLanguage(): string | null {\n if (typeof navigator === 'undefined') {\n return null;\n }\n const navigatorLanguage: NavigatorLanguage = navigator;\n return (\n // Most reliable, but only supported in Chrome/Firefox.\n (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\n // Supported in most browsers, but returns the language of the browser\n // UI, not the language set in browser settings.\n navigatorLanguage.language ||\n // Couldn't determine language.\n null\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ConfigInternal } from '../../model/auth';\nimport { debugAssert } from './assert';\n\nexport function _emulatorUrl(config: ConfigInternal, path?: string): string {\n debugAssert(config.emulator, 'Emulator should always be set here');\n const { url } = config.emulator;\n\n if (!path) {\n return url;\n }\n\n return `${url}${path.startsWith('/') ? path.slice(1) : path}`;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugFail } from './assert';\n\nexport class FetchProvider {\n private static fetchImpl: typeof fetch | null;\n private static headersImpl: typeof Headers | null;\n private static responseImpl: typeof Response | null;\n\n static initialize(\n fetchImpl: typeof fetch,\n headersImpl?: typeof Headers,\n responseImpl?: typeof Response\n ): void {\n this.fetchImpl = fetchImpl;\n if (headersImpl) {\n this.headersImpl = headersImpl;\n }\n if (responseImpl) {\n this.responseImpl = responseImpl;\n }\n }\n\n static fetch(): typeof fetch {\n if (this.fetchImpl) {\n return this.fetchImpl;\n }\n if (typeof self !== 'undefined' && 'fetch' in self) {\n return self.fetch;\n }\n if (typeof globalThis !== 'undefined' && globalThis.fetch) {\n return globalThis.fetch;\n }\n if (typeof fetch !== 'undefined') {\n return fetch;\n }\n debugFail(\n 'Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n\n static headers(): typeof Headers {\n if (this.headersImpl) {\n return this.headersImpl;\n }\n if (typeof self !== 'undefined' && 'Headers' in self) {\n return self.Headers;\n }\n if (typeof globalThis !== 'undefined' && globalThis.Headers) {\n return globalThis.Headers;\n }\n if (typeof Headers !== 'undefined') {\n return Headers;\n }\n debugFail(\n 'Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n\n static response(): typeof Response {\n if (this.responseImpl) {\n return this.responseImpl;\n }\n if (typeof self !== 'undefined' && 'Response' in self) {\n return self.Response;\n }\n if (typeof globalThis !== 'undefined' && globalThis.Response) {\n return globalThis.Response;\n }\n if (typeof Response !== 'undefined') {\n return Response;\n }\n debugFail(\n 'Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../core/errors';\n\n/**\n * Errors that can be returned by the backend\n */\nexport const enum ServerError {\n ADMIN_ONLY_OPERATION = 'ADMIN_ONLY_OPERATION',\n BLOCKING_FUNCTION_ERROR_RESPONSE = 'BLOCKING_FUNCTION_ERROR_RESPONSE',\n CAPTCHA_CHECK_FAILED = 'CAPTCHA_CHECK_FAILED',\n CORS_UNSUPPORTED = 'CORS_UNSUPPORTED',\n CREDENTIAL_MISMATCH = 'CREDENTIAL_MISMATCH',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN = 'CREDENTIAL_TOO_OLD_LOGIN_AGAIN',\n DYNAMIC_LINK_NOT_ACTIVATED = 'DYNAMIC_LINK_NOT_ACTIVATED',\n EMAIL_CHANGE_NEEDS_VERIFICATION = 'EMAIL_CHANGE_NEEDS_VERIFICATION',\n EMAIL_EXISTS = 'EMAIL_EXISTS',\n EMAIL_NOT_FOUND = 'EMAIL_NOT_FOUND',\n EXPIRED_OOB_CODE = 'EXPIRED_OOB_CODE',\n FEDERATED_USER_ID_ALREADY_LINKED = 'FEDERATED_USER_ID_ALREADY_LINKED',\n INVALID_APP_CREDENTIAL = 'INVALID_APP_CREDENTIAL',\n INVALID_APP_ID = 'INVALID_APP_ID',\n INVALID_CERT_HASH = 'INVALID_CERT_HASH',\n INVALID_CODE = 'INVALID_CODE',\n INVALID_CONTINUE_URI = 'INVALID_CONTINUE_URI',\n INVALID_CUSTOM_TOKEN = 'INVALID_CUSTOM_TOKEN',\n INVALID_DYNAMIC_LINK_DOMAIN = 'INVALID_DYNAMIC_LINK_DOMAIN',\n INVALID_EMAIL = 'INVALID_EMAIL',\n INVALID_ID_TOKEN = 'INVALID_ID_TOKEN',\n INVALID_IDP_RESPONSE = 'INVALID_IDP_RESPONSE',\n INVALID_IDENTIFIER = 'INVALID_IDENTIFIER',\n INVALID_MESSAGE_PAYLOAD = 'INVALID_MESSAGE_PAYLOAD',\n INVALID_MFA_PENDING_CREDENTIAL = 'INVALID_MFA_PENDING_CREDENTIAL',\n INVALID_OAUTH_CLIENT_ID = 'INVALID_OAUTH_CLIENT_ID',\n INVALID_OOB_CODE = 'INVALID_OOB_CODE',\n INVALID_PASSWORD = 'INVALID_PASSWORD',\n INVALID_PENDING_TOKEN = 'INVALID_PENDING_TOKEN',\n INVALID_PHONE_NUMBER = 'INVALID_PHONE_NUMBER',\n INVALID_PROVIDER_ID = 'INVALID_PROVIDER_ID',\n INVALID_RECIPIENT_EMAIL = 'INVALID_RECIPIENT_EMAIL',\n INVALID_SENDER = 'INVALID_SENDER',\n INVALID_SESSION_INFO = 'INVALID_SESSION_INFO',\n INVALID_TEMPORARY_PROOF = 'INVALID_TEMPORARY_PROOF',\n INVALID_TENANT_ID = 'INVALID_TENANT_ID',\n MFA_ENROLLMENT_NOT_FOUND = 'MFA_ENROLLMENT_NOT_FOUND',\n MISSING_ANDROID_PACKAGE_NAME = 'MISSING_ANDROID_PACKAGE_NAME',\n MISSING_APP_CREDENTIAL = 'MISSING_APP_CREDENTIAL',\n MISSING_CODE = 'MISSING_CODE',\n MISSING_CONTINUE_URI = 'MISSING_CONTINUE_URI',\n MISSING_CUSTOM_TOKEN = 'MISSING_CUSTOM_TOKEN',\n MISSING_IOS_BUNDLE_ID = 'MISSING_IOS_BUNDLE_ID',\n MISSING_MFA_ENROLLMENT_ID = 'MISSING_MFA_ENROLLMENT_ID',\n MISSING_MFA_PENDING_CREDENTIAL = 'MISSING_MFA_PENDING_CREDENTIAL',\n MISSING_OOB_CODE = 'MISSING_OOB_CODE',\n MISSING_OR_INVALID_NONCE = 'MISSING_OR_INVALID_NONCE',\n MISSING_PASSWORD = 'MISSING_PASSWORD',\n MISSING_REQ_TYPE = 'MISSING_REQ_TYPE',\n MISSING_PHONE_NUMBER = 'MISSING_PHONE_NUMBER',\n MISSING_SESSION_INFO = 'MISSING_SESSION_INFO',\n OPERATION_NOT_ALLOWED = 'OPERATION_NOT_ALLOWED',\n PASSWORD_LOGIN_DISABLED = 'PASSWORD_LOGIN_DISABLED',\n QUOTA_EXCEEDED = 'QUOTA_EXCEEDED',\n RESET_PASSWORD_EXCEED_LIMIT = 'RESET_PASSWORD_EXCEED_LIMIT',\n REJECTED_CREDENTIAL = 'REJECTED_CREDENTIAL',\n SECOND_FACTOR_EXISTS = 'SECOND_FACTOR_EXISTS',\n SECOND_FACTOR_LIMIT_EXCEEDED = 'SECOND_FACTOR_LIMIT_EXCEEDED',\n SESSION_EXPIRED = 'SESSION_EXPIRED',\n TENANT_ID_MISMATCH = 'TENANT_ID_MISMATCH',\n TOKEN_EXPIRED = 'TOKEN_EXPIRED',\n TOO_MANY_ATTEMPTS_TRY_LATER = 'TOO_MANY_ATTEMPTS_TRY_LATER',\n UNSUPPORTED_FIRST_FACTOR = 'UNSUPPORTED_FIRST_FACTOR',\n UNSUPPORTED_TENANT_OPERATION = 'UNSUPPORTED_TENANT_OPERATION',\n UNAUTHORIZED_DOMAIN = 'UNAUTHORIZED_DOMAIN',\n UNVERIFIED_EMAIL = 'UNVERIFIED_EMAIL',\n USER_CANCELLED = 'USER_CANCELLED',\n USER_DISABLED = 'USER_DISABLED',\n USER_NOT_FOUND = 'USER_NOT_FOUND',\n WEAK_PASSWORD = 'WEAK_PASSWORD',\n RECAPTCHA_NOT_ENABLED = 'RECAPTCHA_NOT_ENABLED',\n MISSING_RECAPTCHA_TOKEN = 'MISSING_RECAPTCHA_TOKEN',\n INVALID_RECAPTCHA_TOKEN = 'INVALID_RECAPTCHA_TOKEN',\n INVALID_RECAPTCHA_ACTION = 'INVALID_RECAPTCHA_ACTION',\n MISSING_CLIENT_TYPE = 'MISSING_CLIENT_TYPE',\n MISSING_RECAPTCHA_VERSION = 'MISSING_RECAPTCHA_VERSION',\n INVALID_RECAPTCHA_VERSION = 'INVALID_RECAPTCHA_VERSION',\n INVALID_REQ_TYPE = 'INVALID_REQ_TYPE',\n PASSWORD_DOES_NOT_MEET_REQUIREMENTS = 'PASSWORD_DOES_NOT_MEET_REQUIREMENTS'\n}\n\n/**\n * API Response in the event of an error\n */\nexport interface JsonError {\n error: {\n code: number;\n message: string;\n errors?: [\n {\n message: ServerError;\n domain: string;\n reason: string;\n }\n ];\n };\n}\n\n/**\n * Type definition for a map from server errors to developer visible errors\n */\nexport declare type ServerErrorMap<ApiError extends string> = {\n readonly [K in ApiError]: AuthErrorCode;\n};\n\n/**\n * Map from errors returned by the server to errors to developer visible errors\n */\nexport const SERVER_ERROR_MAP: Partial<ServerErrorMap<ServerError>> = {\n // Custom token errors.\n [ServerError.CREDENTIAL_MISMATCH]: AuthErrorCode.CREDENTIAL_MISMATCH,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_CUSTOM_TOKEN]: AuthErrorCode.INTERNAL_ERROR,\n\n // Create Auth URI errors.\n [ServerError.INVALID_IDENTIFIER]: AuthErrorCode.INVALID_EMAIL,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_CONTINUE_URI]: AuthErrorCode.INTERNAL_ERROR,\n\n // Sign in with email and password errors (some apply to sign up too).\n [ServerError.INVALID_PASSWORD]: AuthErrorCode.INVALID_PASSWORD,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_PASSWORD]: AuthErrorCode.MISSING_PASSWORD,\n\n // Sign up with email and password errors.\n [ServerError.EMAIL_EXISTS]: AuthErrorCode.EMAIL_EXISTS,\n [ServerError.PASSWORD_LOGIN_DISABLED]: AuthErrorCode.OPERATION_NOT_ALLOWED,\n\n // Verify assertion for sign in with credential errors:\n [ServerError.INVALID_IDP_RESPONSE]: AuthErrorCode.INVALID_IDP_RESPONSE,\n [ServerError.INVALID_PENDING_TOKEN]: AuthErrorCode.INVALID_IDP_RESPONSE,\n [ServerError.FEDERATED_USER_ID_ALREADY_LINKED]:\n AuthErrorCode.CREDENTIAL_ALREADY_IN_USE,\n\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_REQ_TYPE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Send Password reset email errors:\n [ServerError.EMAIL_NOT_FOUND]: AuthErrorCode.USER_DELETED,\n [ServerError.RESET_PASSWORD_EXCEED_LIMIT]:\n AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER,\n\n [ServerError.EXPIRED_OOB_CODE]: AuthErrorCode.EXPIRED_OOB_CODE,\n [ServerError.INVALID_OOB_CODE]: AuthErrorCode.INVALID_OOB_CODE,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_OOB_CODE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Operations that require ID token in request:\n [ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN]:\n AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN,\n [ServerError.INVALID_ID_TOKEN]: AuthErrorCode.INVALID_AUTH,\n [ServerError.TOKEN_EXPIRED]: AuthErrorCode.TOKEN_EXPIRED,\n [ServerError.USER_NOT_FOUND]: AuthErrorCode.TOKEN_EXPIRED,\n\n // Other errors.\n [ServerError.TOO_MANY_ATTEMPTS_TRY_LATER]:\n AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER,\n [ServerError.PASSWORD_DOES_NOT_MEET_REQUIREMENTS]:\n AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS,\n\n // Phone Auth related errors.\n [ServerError.INVALID_CODE]: AuthErrorCode.INVALID_CODE,\n [ServerError.INVALID_SESSION_INFO]: AuthErrorCode.INVALID_SESSION_INFO,\n [ServerError.INVALID_TEMPORARY_PROOF]: AuthErrorCode.INVALID_IDP_RESPONSE,\n [ServerError.MISSING_SESSION_INFO]: AuthErrorCode.MISSING_SESSION_INFO,\n [ServerError.SESSION_EXPIRED]: AuthErrorCode.CODE_EXPIRED,\n\n // Other action code errors when additional settings passed.\n // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.\n // This is OK as this error will be caught by client side validation.\n [ServerError.MISSING_ANDROID_PACKAGE_NAME]:\n AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME,\n [ServerError.UNAUTHORIZED_DOMAIN]: AuthErrorCode.UNAUTHORIZED_DOMAIN,\n\n // getProjectConfig errors when clientId is passed.\n [ServerError.INVALID_OAUTH_CLIENT_ID]: AuthErrorCode.INVALID_OAUTH_CLIENT_ID,\n\n // User actions (sign-up or deletion) disabled errors.\n [ServerError.ADMIN_ONLY_OPERATION]: AuthErrorCode.ADMIN_ONLY_OPERATION,\n\n // Multi factor related errors.\n [ServerError.INVALID_MFA_PENDING_CREDENTIAL]:\n AuthErrorCode.INVALID_MFA_SESSION,\n [ServerError.MFA_ENROLLMENT_NOT_FOUND]: AuthErrorCode.MFA_INFO_NOT_FOUND,\n [ServerError.MISSING_MFA_ENROLLMENT_ID]: AuthErrorCode.MISSING_MFA_INFO,\n [ServerError.MISSING_MFA_PENDING_CREDENTIAL]:\n AuthErrorCode.MISSING_MFA_SESSION,\n [ServerError.SECOND_FACTOR_EXISTS]:\n AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED,\n [ServerError.SECOND_FACTOR_LIMIT_EXCEEDED]:\n AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED,\n\n // Blocking functions related errors.\n [ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Recaptcha related errors.\n [ServerError.RECAPTCHA_NOT_ENABLED]: AuthErrorCode.RECAPTCHA_NOT_ENABLED,\n [ServerError.MISSING_RECAPTCHA_TOKEN]: AuthErrorCode.MISSING_RECAPTCHA_TOKEN,\n [ServerError.INVALID_RECAPTCHA_TOKEN]: AuthErrorCode.INVALID_RECAPTCHA_TOKEN,\n [ServerError.INVALID_RECAPTCHA_ACTION]:\n AuthErrorCode.INVALID_RECAPTCHA_ACTION,\n [ServerError.MISSING_CLIENT_TYPE]: AuthErrorCode.MISSING_CLIENT_TYPE,\n [ServerError.MISSING_RECAPTCHA_VERSION]:\n AuthErrorCode.MISSING_RECAPTCHA_VERSION,\n [ServerError.INVALID_RECAPTCHA_VERSION]:\n AuthErrorCode.INVALID_RECAPTCHA_VERSION,\n [ServerError.INVALID_REQ_TYPE]: AuthErrorCode.INVALID_REQ_TYPE\n};\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError, querystring } from '@firebase/util';\n\nimport { AuthErrorCode, NamedErrorParams } from '../core/errors';\nimport {\n _createError,\n _errorWithCustomMessage,\n _fail\n} from '../core/util/assert';\nimport { Delay } from '../core/util/delay';\nimport { _emulatorUrl } from '../core/util/emulator';\nimport { FetchProvider } from '../core/util/fetch_provider';\nimport { Auth } from '../model/public_types';\nimport { AuthInternal, ConfigInternal } from '../model/auth';\nimport { IdTokenResponse, TaggedWithTokenResponse } from '../model/id_token';\nimport { IdTokenMfaResponse } from './authentication/mfa';\nimport { SERVER_ERROR_MAP, ServerError, ServerErrorMap } from './errors';\n\nexport const enum HttpMethod {\n POST = 'POST',\n GET = 'GET'\n}\n\nexport const enum HttpHeader {\n CONTENT_TYPE = 'Content-Type',\n X_FIREBASE_LOCALE = 'X-Firebase-Locale',\n X_CLIENT_VERSION = 'X-Client-Version',\n X_FIREBASE_GMPID = 'X-Firebase-gmpid',\n X_FIREBASE_CLIENT = 'X-Firebase-Client',\n X_FIREBASE_APP_CHECK = 'X-Firebase-AppCheck'\n}\n\nexport const enum Endpoint {\n CREATE_AUTH_URI = '/v1/accounts:createAuthUri',\n DELETE_ACCOUNT = '/v1/accounts:delete',\n RESET_PASSWORD = '/v1/accounts:resetPassword',\n SIGN_UP = '/v1/accounts:signUp',\n SIGN_IN_WITH_CUSTOM_TOKEN = '/v1/accounts:signInWithCustomToken',\n SIGN_IN_WITH_EMAIL_LINK = '/v1/accounts:signInWithEmailLink',\n SIGN_IN_WITH_IDP = '/v1/accounts:signInWithIdp',\n SIGN_IN_WITH_PASSWORD = '/v1/accounts:signInWithPassword',\n SIGN_IN_WITH_PHONE_NUMBER = '/v1/accounts:signInWithPhoneNumber',\n SEND_VERIFICATION_CODE = '/v1/accounts:sendVerificationCode',\n SEND_OOB_CODE = '/v1/accounts:sendOobCode',\n SET_ACCOUNT_INFO = '/v1/accounts:update',\n GET_ACCOUNT_INFO = '/v1/accounts:lookup',\n GET_RECAPTCHA_PARAM = '/v1/recaptchaParams',\n START_MFA_ENROLLMENT = '/v2/accounts/mfaEnrollment:start',\n FINALIZE_MFA_ENROLLMENT = '/v2/accounts/mfaEnrollment:finalize',\n START_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:start',\n FINALIZE_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:finalize',\n WITHDRAW_MFA = '/v2/accounts/mfaEnrollment:withdraw',\n GET_PROJECT_CONFIG = '/v1/projects',\n GET_RECAPTCHA_CONFIG = '/v2/recaptchaConfig',\n GET_PASSWORD_POLICY = '/v2/passwordPolicy',\n TOKEN = '/v1/token',\n REVOKE_TOKEN = '/v2/accounts:revokeToken'\n}\n\nexport const enum RecaptchaClientType {\n WEB = 'CLIENT_TYPE_WEB',\n ANDROID = 'CLIENT_TYPE_ANDROID',\n IOS = 'CLIENT_TYPE_IOS'\n}\n\nexport const enum RecaptchaVersion {\n ENTERPRISE = 'RECAPTCHA_ENTERPRISE'\n}\n\nexport const enum RecaptchaActionName {\n SIGN_IN_WITH_PASSWORD = 'signInWithPassword',\n GET_OOB_CODE = 'getOobCode',\n SIGN_UP_PASSWORD = 'signUpPassword'\n}\n\nexport const enum EnforcementState {\n ENFORCE = 'ENFORCE',\n AUDIT = 'AUDIT',\n OFF = 'OFF',\n ENFORCEMENT_STATE_UNSPECIFIED = 'ENFORCEMENT_STATE_UNSPECIFIED'\n}\n\n// Providers that have reCAPTCHA Enterprise support.\nexport const enum RecaptchaProvider {\n EMAIL_PASSWORD_PROVIDER = 'EMAIL_PASSWORD_PROVIDER'\n}\n\nexport const DEFAULT_API_TIMEOUT_MS = new Delay(30_000, 60_000);\n\nexport function _addTidIfNecessary<T extends { tenantId?: string }>(\n auth: Auth,\n request: T\n): T {\n if (auth.tenantId && !request.tenantId) {\n return {\n ...request,\n tenantId: auth.tenantId\n };\n }\n return request;\n}\n\nexport async function _performApiRequest<T, V>(\n auth: Auth,\n method: HttpMethod,\n path: Endpoint,\n request?: T,\n customErrorMap: Partial<ServerErrorMap<ServerError>> = {}\n): Promise<V> {\n return _performFetchWithErrorHandling(auth, customErrorMap, async () => {\n let body = {};\n let params = {};\n if (request) {\n if (method === HttpMethod.GET) {\n params = request;\n } else {\n body = {\n body: JSON.stringify(request)\n };\n }\n }\n\n const query = querystring({\n key: auth.config.apiKey,\n ...params\n }).slice(1);\n\n const headers = await (auth as AuthInternal)._getAdditionalHeaders();\n headers[HttpHeader.CONTENT_TYPE] = 'application/json';\n\n if (auth.languageCode) {\n headers[HttpHeader.X_FIREBASE_LOCALE] = auth.languageCode;\n }\n\n return FetchProvider.fetch()(\n _getFinalTarget(auth, auth.config.apiHost, path, query),\n {\n method,\n headers,\n referrerPolicy: 'no-referrer',\n ...body\n }\n );\n });\n}\n\nexport async function _performFetchWithErrorHandling<V>(\n auth: Auth,\n customErrorMap: Partial<ServerErrorMap<ServerError>>,\n fetchFn: () => Promise<Response>\n): Promise<V> {\n (auth as AuthInternal)._canInitEmulator = false;\n const errorMap = { ...SERVER_ERROR_MAP, ...customErrorMap };\n try {\n const networkTimeout = new NetworkTimeout<Response>(auth);\n const response: Response = await Promise.race<Promise<Response>>([\n fetchFn(),\n networkTimeout.promise\n ]);\n\n // If we've reached this point, the fetch succeeded and the networkTimeout\n // didn't throw; clear the network timeout delay so that Node won't hang\n networkTimeout.clearNetworkTimeout();\n\n const json = await response.json();\n if ('needConfirmation' in json) {\n throw _makeTaggedError(auth, AuthErrorCode.NEED_CONFIRMATION, json);\n }\n\n if (response.ok && !('errorMessage' in json)) {\n return json;\n } else {\n const errorMessage = response.ok ? json.errorMessage : json.error.message;\n const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');\n if (serverErrorCode === ServerError.FEDERATED_USER_ID_ALREADY_LINKED) {\n throw _makeTaggedError(\n auth,\n AuthErrorCode.CREDENTIAL_ALREADY_IN_USE,\n json\n );\n } else if (serverErrorCode === ServerError.EMAIL_EXISTS) {\n throw _makeTaggedError(auth, AuthErrorCode.EMAIL_EXISTS, json);\n } else if (serverErrorCode === ServerError.USER_DISABLED) {\n throw _makeTaggedError(auth, AuthErrorCode.USER_DISABLED, json);\n }\n const authError =\n errorMap[serverErrorCode as ServerError] ||\n (serverErrorCode\n .toLowerCase()\n .replace(/[_\\s]+/g, '-') as unknown as AuthErrorCode);\n if (serverErrorMessage) {\n throw _errorWithCustomMessage(auth, authError, serverErrorMessage);\n } else {\n _fail(auth, authError);\n }\n }\n } catch (e) {\n if (e instanceof FirebaseError) {\n throw e;\n }\n // Changing this to a different error code will log user out when there is a network error\n // because we treat any error other than NETWORK_REQUEST_FAILED as token is invalid.\n // https://github.com/firebase/firebase-js-sdk/blob/4fbc73610d70be4e0852e7de63a39cb7897e8546/packages/auth/src/core/auth/auth_impl.ts#L309-L316\n _fail(auth, AuthErrorCode.NETWORK_REQUEST_FAILED, { 'message': String(e) });\n }\n}\n\nexport async function _performSignInRequest<T, V extends IdTokenResponse>(\n auth: Auth,\n method: HttpMethod,\n path: Endpoint,\n request?: T,\n customErrorMap: Partial<ServerErrorMap<ServerError>> = {}\n): Promise<V> {\n const serverResponse = (await _performApiRequest<T, V | IdTokenMfaResponse>(\n auth,\n method,\n path,\n request,\n customErrorMap\n )) as V;\n if ('mfaPendingCredential' in serverResponse) {\n _fail(auth, AuthErrorCode.MFA_REQUIRED, {\n _serverResponse: serverResponse\n });\n }\n\n return serverResponse;\n}\n\nexport function _getFinalTarget(\n auth: Auth,\n host: string,\n path: string,\n query: string\n): string {\n const base = `${host}${path}?${query}`;\n\n if (!(auth as AuthInternal).config.emulator) {\n return `${auth.config.apiScheme}://${base}`;\n }\n\n return _emulatorUrl(auth.config as ConfigInternal, base);\n}\n\nexport function _parseEnforcementState(\n enforcementStateStr: string\n): EnforcementState {\n switch (enforcementStateStr) {\n case 'ENFORCE':\n return EnforcementState.ENFORCE;\n case 'AUDIT':\n return EnforcementState.AUDIT;\n case 'OFF':\n return EnforcementState.OFF;\n default:\n return EnforcementState.ENFORCEMENT_STATE_UNSPECIFIED;\n }\n}\n\nclass NetworkTimeout<T> {\n // Node timers and browser timers are fundamentally incompatible, but we\n // don't care about the value here\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private timer: any | null = null;\n readonly promise = new Promise<T>((_, reject) => {\n this.timer = setTimeout(() => {\n return reject(\n _createError(this.auth, AuthErrorCode.NETWORK_REQUEST_FAILED)\n );\n }, DEFAULT_API_TIMEOUT_MS.get());\n });\n\n clearNetworkTimeout(): void {\n clearTimeout(this.timer);\n }\n\n constructor(private readonly auth: Auth) {}\n}\n\ninterface PotentialResponse extends IdTokenResponse {\n email?: string;\n phoneNumber?: string;\n}\n\nexport function _makeTaggedError(\n auth: Auth,\n code: AuthErrorCode,\n response: PotentialResponse\n): FirebaseError {\n const errorParams: NamedErrorParams = {\n appName: auth.name\n };\n\n if (response.email) {\n errorParams.email = response.email;\n }\n if (response.phoneNumber) {\n errorParams.phoneNumber = response.phoneNumber;\n }\n\n const error = _createError(auth, code, errorParams);\n\n // We know customData is defined on error because errorParams is defined\n (error.customData! as TaggedWithTokenResponse)._tokenResponse = response;\n return error;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RecaptchaParameters } from '../../model/public_types';\nimport {\n GetRecaptchaConfigResponse,\n RecaptchaEnforcementProviderState\n} from '../../api/authentication/recaptcha';\nimport { EnforcementState, _parseEnforcementState } from '../../api/index';\n\n// reCAPTCHA v2 interface\nexport interface Recaptcha {\n render: (container: HTMLElement, parameters: RecaptchaParameters) => number;\n getResponse: (id: number) => string;\n execute: (id: number) => unknown;\n reset: (id: number) => unknown;\n}\n\nexport function isV2(\n grecaptcha: Recaptcha | GreCAPTCHA | undefined\n): grecaptcha is Recaptcha {\n return (\n grecaptcha !== undefined &&\n (grecaptcha as Recaptcha).getResponse !== undefined\n );\n}\n\n// reCAPTCHA Enterprise & v3 shared interface\nexport interface GreCAPTCHATopLevel extends GreCAPTCHA {\n enterprise: GreCAPTCHA;\n}\n\n// reCAPTCHA Enterprise interface\nexport interface GreCAPTCHA {\n ready: (callback: () => void) => void;\n execute: (siteKey: string, options: { action: string }) => Promise<string>;\n render: (\n container: string | HTMLElement,\n parameters: GreCAPTCHARenderOption\n ) => string;\n}\n\nexport interface GreCAPTCHARenderOption {\n sitekey: string;\n size: 'invisible';\n}\n\nexport function isEnterprise(\n grecaptcha: Recaptcha | GreCAPTCHA | undefined\n): grecaptcha is GreCAPTCHATopLevel {\n return (\n grecaptcha !== undefined &&\n (grecaptcha as GreCAPTCHATopLevel).enterprise !== undefined\n );\n}\n\n// TODO(chuanr): Replace this with the AuthWindow after resolving the dependency issue in Node.js env.\ndeclare global {\n interface Window {\n grecaptcha?: Recaptcha | GreCAPTCHATopLevel;\n }\n}\n\nexport class RecaptchaConfig {\n /**\n * The reCAPTCHA site key.\n */\n siteKey: string = '';\n\n /**\n * The list of providers and their enablement status for reCAPTCHA Enterprise.\n */\n recaptchaEnforcementState: RecaptchaEnforcementProviderState[] = [];\n\n constructor(response: GetRecaptchaConfigResponse) {\n if (response.recaptchaKey === undefined) {\n throw new Error('recaptchaKey undefined');\n }\n // Example response.recaptchaKey: \"projects/proj123/keys/sitekey123\"\n this.siteKey = response.recaptchaKey.split('/')[3];\n this.recaptchaEnforcementState = response.recaptchaEnforcementState;\n }\n\n /**\n * Returns the reCAPTCHA Enterprise enforcement state for the given provider.\n *\n * @param providerStr - The provider whose enforcement state is to be returned.\n * @returns The reCAPTCHA Enterprise enforcement state for the given provider.\n */\n getProviderEnforcementState(providerStr: string): EnforcementState | null {\n if (\n !this.recaptchaEnforcementState ||\n this.recaptchaEnforcementState.length === 0\n ) {\n return null;\n }\n\n for (const recaptchaEnforcementState of this.recaptchaEnforcementState) {\n if (\n recaptchaEnforcementState.provider &&\n recaptchaEnforcementState.provider === providerStr\n ) {\n return _parseEnforcementState(\n recaptchaEnforcementState.enforcementState\n );\n }\n }\n return null;\n }\n\n /**\n * Returns true if the reCAPTCHA Enterprise enforcement state for the provider is set to ENFORCE or AUDIT.\n *\n * @param providerStr - The provider whose enablement state is to be returned.\n * @returns Whether or not reCAPTCHA Enterprise protection is enabled for the given provider.\n */\n isProviderEnabled(providerStr: string): boolean {\n return (\n this.getProviderEnforcementState(providerStr) ===\n EnforcementState.ENFORCE ||\n this.getProviderEnforcementState(providerStr) === EnforcementState.AUDIT\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _performApiRequest,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\ninterface GetRecaptchaParamResponse {\n recaptchaSiteKey?: string;\n}\n\nexport async function getRecaptchaParams(auth: Auth): Promise<string> {\n return (\n (\n await _performApiRequest<void, GetRecaptchaParamResponse>(\n auth,\n HttpMethod.GET,\n Endpoint.GET_RECAPTCHA_PARAM\n )\n ).recaptchaSiteKey || ''\n );\n}\n\n// The following functions are for reCAPTCHA enterprise integration.\ninterface GetRecaptchaConfigRequest {\n tenantId?: string;\n clientType?: RecaptchaClientType;\n version?: RecaptchaVersion;\n}\n\nexport interface RecaptchaEnforcementProviderState {\n provider: string;\n enforcementState: string;\n}\n\nexport interface GetRecaptchaConfigResponse {\n recaptchaKey: string;\n recaptchaEnforcementState: RecaptchaEnforcementProviderState[];\n}\n\nexport async function getRecaptchaConfig(\n auth: Auth,\n request: GetRecaptchaConfigRequest\n): Promise<GetRecaptchaConfigResponse> {\n return _performApiRequest<\n GetRecaptchaConfigRequest,\n GetRecaptchaConfigResponse\n >(\n auth,\n HttpMethod.GET,\n Endpoint.GET_RECAPTCHA_CONFIG,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function utcTimestampToDateString(\n utcTimestamp?: string | number\n): string | undefined {\n if (!utcTimestamp) {\n return undefined;\n }\n try {\n // Convert to date object.\n const date = new Date(Number(utcTimestamp));\n // Test date is valid.\n if (!isNaN(date.getTime())) {\n // Convert to UTC date string.\n return date.toUTCString();\n }\n } catch (e) {\n // Do nothing. undefined will be returned.\n }\n return undefined;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdTokenResult, ParsedToken, User } from '../../model/public_types';\nimport { base64Decode, getModularInstance } from '@firebase/util';\n\nimport { UserInternal } from '../../model/user';\nimport { _assert } from '../util/assert';\nimport { _logError } from '../util/log';\nimport { utcTimestampToDateString } from '../util/time';\nimport { AuthErrorCode } from '../errors';\n\n/**\n * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport function getIdToken(user: User, forceRefresh = false): Promise<string> {\n return getModularInstance(user).getIdToken(forceRefresh);\n}\n\n/**\n * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport async function getIdTokenResult(\n user: User,\n forceRefresh = false\n): Promise<IdTokenResult> {\n const userInternal = getModularInstance(user) as UserInternal;\n const token = await userInternal.getIdToken(forceRefresh);\n const claims = _parseToken(token);\n\n _assert(\n claims && claims.exp && claims.auth_time && claims.iat,\n userInternal.auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const firebase =\n typeof claims.firebase === 'object' ? claims.firebase : undefined;\n\n const signInProvider: string | undefined = firebase?.['sign_in_provider'];\n\n return {\n claims,\n token,\n authTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.auth_time)\n )!,\n issuedAtTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.iat)\n )!,\n expirationTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.exp)\n )!,\n signInProvider: signInProvider || null,\n signInSecondFactor: firebase?.['sign_in_second_factor'] || null\n };\n}\n\nfunction secondsStringToMilliseconds(seconds: string): number {\n return Number(seconds) * 1000;\n}\n\nexport function _parseToken(token: string): ParsedToken | null {\n const [algorithm, payload, signature] = token.split('.');\n if (\n algorithm === undefined ||\n payload === undefined ||\n signature === undefined\n ) {\n _logError('JWT malformed, contained fewer than 3 sections');\n return null;\n }\n\n try {\n const decoded = base64Decode(payload);\n if (!decoded) {\n _logError('Failed to decode base64 JWT payload');\n return null;\n }\n return JSON.parse(decoded);\n } catch (e) {\n _logError(\n 'Caught error parsing JWT payload as JSON',\n (e as Error)?.toString()\n );\n return null;\n }\n}\n\n/**\n * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.\n */\nexport function _tokenExpiresIn(token: string): number {\n const parsedToken = _parseToken(token);\n _assert(parsedToken, AuthErrorCode.INTERNAL_ERROR);\n _assert(typeof parsedToken.exp !== 'undefined', AuthErrorCode.INTERNAL_ERROR);\n _assert(typeof parsedToken.iat !== 'undefined', AuthErrorCode.INTERNAL_ERROR);\n return Number(parsedToken.exp) - Number(parsedToken.iat);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\n\nexport async function _logoutIfInvalidated<T>(\n user: UserInternal,\n promise: Promise<T>,\n bypassAuthState = false\n): Promise<T> {\n if (bypassAuthState) {\n return promise;\n }\n try {\n return await promise;\n } catch (e) {\n if (e instanceof FirebaseError && isUserInvalidated(e)) {\n if (user.auth.currentUser === user) {\n await user.auth.signOut();\n }\n }\n\n throw e;\n }\n}\n\nfunction isUserInvalidated({ code }: FirebaseError): boolean {\n return (\n code === `auth/${AuthErrorCode.USER_DISABLED}` ||\n code === `auth/${AuthErrorCode.TOKEN_EXPIRED}`\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\n\n// Refresh the token five minutes before expiration\nexport const enum Duration {\n OFFSET = 5 * 1000 * 60,\n RETRY_BACKOFF_MIN = 30 * 1000,\n RETRY_BACKOFF_MAX = 16 * 60 * 1000\n}\n\nexport class ProactiveRefresh {\n private isRunning = false;\n\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private timerId: any | null = null;\n private errorBackoff = Duration.RETRY_BACKOFF_MIN;\n\n constructor(private readonly user: UserInternal) {}\n\n _start(): void {\n if (this.isRunning) {\n return;\n }\n\n this.isRunning = true;\n this.schedule();\n }\n\n _stop(): void {\n if (!this.isRunning) {\n return;\n }\n\n this.isRunning = false;\n if (this.timerId !== null) {\n clearTimeout(this.timerId);\n }\n }\n\n private getInterval(wasError: boolean): number {\n if (wasError) {\n const interval = this.errorBackoff;\n this.errorBackoff = Math.min(\n this.errorBackoff * 2,\n Duration.RETRY_BACKOFF_MAX\n );\n return interval;\n } else {\n // Reset the error backoff\n this.errorBackoff = Duration.RETRY_BACKOFF_MIN;\n const expTime = this.user.stsTokenManager.expirationTime ?? 0;\n const interval = expTime - Date.now() - Duration.OFFSET;\n\n return Math.max(0, interval);\n }\n }\n\n private schedule(wasError = false): void {\n if (!this.isRunning) {\n // Just in case...\n return;\n }\n\n const interval = this.getInterval(wasError);\n this.timerId = setTimeout(async () => {\n await this.iteration();\n }, interval);\n }\n\n private async iteration(): Promise<void> {\n try {\n await this.user.getIdToken(true);\n } catch (e) {\n // Only retry on network errors\n if (\n (e as FirebaseError)?.code ===\n `auth/${AuthErrorCode.NETWORK_REQUEST_FAILED}`\n ) {\n this.schedule(/* wasError */ true);\n }\n\n return;\n }\n this.schedule();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserMetadata as UserMetadataType } from '../../model/public_types';\n\nimport { utcTimestampToDateString } from '../util/time';\n\nexport class UserMetadata implements UserMetadataType {\n creationTime?: string;\n lastSignInTime?: string;\n\n constructor(\n private createdAt?: string | number,\n private lastLoginAt?: string | number\n ) {\n this._initializeTime();\n }\n\n private _initializeTime(): void {\n this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);\n this.creationTime = utcTimestampToDateString(this.createdAt);\n }\n\n _copy(metadata: UserMetadata): void {\n this.createdAt = metadata.createdAt;\n this.lastLoginAt = metadata.lastLoginAt;\n this._initializeTime();\n }\n\n toJSON(): object {\n return {\n createdAt: this.createdAt,\n lastLoginAt: this.lastLoginAt\n };\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User, UserInfo } from '../../model/public_types';\n\nimport {\n getAccountInfo,\n ProviderUserInfo\n} from '../../api/account_management/account';\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { UserMetadata } from './user_metadata';\nimport { getModularInstance } from '@firebase/util';\n\nexport async function _reloadWithoutSaving(user: UserInternal): Promise<void> {\n const auth = user.auth;\n const idToken = await user.getIdToken();\n const response = await _logoutIfInvalidated(\n user,\n getAccountInfo(auth, { idToken })\n );\n\n _assert(response?.users.length, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const coreAccount = response.users[0];\n\n user._notifyReloadListener(coreAccount);\n\n const newProviderData = coreAccount.providerUserInfo?.length\n ? extractProviderData(coreAccount.providerUserInfo)\n : [];\n\n const providerData = mergeProviderData(user.providerData, newProviderData);\n\n // Preserves the non-nonymous status of the stored user, even if no more\n // credentials (federated or email/password) are linked to the user. If\n // the user was previously anonymous, then use provider data to update.\n // On the other hand, if it was not anonymous before, it should never be\n // considered anonymous now.\n const oldIsAnonymous = user.isAnonymous;\n const newIsAnonymous =\n !(user.email && coreAccount.passwordHash) && !providerData?.length;\n const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;\n\n const updates: Partial<UserInternal> = {\n uid: coreAccount.localId,\n displayName: coreAccount.displayName || null,\n photoURL: coreAccount.photoUrl || null,\n email: coreAccount.email || null,\n emailVerified: coreAccount.emailVerified || false,\n phoneNumber: coreAccount.phoneNumber || null,\n tenantId: coreAccount.tenantId || null,\n providerData,\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\n isAnonymous\n };\n\n Object.assign(user, updates);\n}\n\n/**\n * Reloads user account data, if signed in.\n *\n * @param user - The user.\n *\n * @public\n */\nexport async function reload(user: User): Promise<void> {\n const userInternal: UserInternal = getModularInstance(user) as UserInternal;\n await _reloadWithoutSaving(userInternal);\n\n // Even though the current user hasn't changed, update\n // current user will trigger a persistence update w/ the\n // new info.\n await userInternal.auth._persistUserIfCurrent(userInternal);\n userInternal.auth._notifyListenersIfCurrent(userInternal);\n}\n\nfunction mergeProviderData(\n original: UserInfo[],\n newData: UserInfo[]\n): UserInfo[] {\n const deduped = original.filter(\n o => !newData.some(n => n.providerId === o.providerId)\n );\n return [...deduped, ...newData];\n}\n\nfunction extractProviderData(providers: ProviderUserInfo[]): UserInfo[] {\n return providers.map(({ providerId, ...provider }) => {\n return {\n providerId,\n uid: provider.rawId || '',\n displayName: provider.displayName || null,\n email: provider.email || null,\n phoneNumber: provider.phoneNumber || null,\n photoURL: provider.photoUrl || null\n };\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Endpoint, HttpMethod, _performApiRequest } from '../index';\nimport { MfaEnrollment } from './mfa';\nimport { Auth } from '../../model/public_types';\n\nexport interface DeleteAccountRequest {\n idToken: string;\n}\n\nexport async function deleteAccount(\n auth: Auth,\n request: DeleteAccountRequest\n): Promise<void> {\n return _performApiRequest<DeleteAccountRequest, void>(\n auth,\n HttpMethod.POST,\n Endpoint.DELETE_ACCOUNT,\n request\n );\n}\n\nexport interface ProviderUserInfo {\n providerId: string;\n rawId?: string;\n email?: string;\n displayName?: string;\n photoUrl?: string;\n phoneNumber?: string;\n}\n\nexport interface DeleteLinkedAccountsRequest {\n idToken: string;\n deleteProvider: string[];\n}\n\nexport interface DeleteLinkedAccountsResponse {\n providerUserInfo: ProviderUserInfo[];\n}\n\nexport async function deleteLinkedAccounts(\n auth: Auth,\n request: DeleteLinkedAccountsRequest\n): Promise<DeleteLinkedAccountsResponse> {\n return _performApiRequest<\n DeleteLinkedAccountsRequest,\n DeleteLinkedAccountsResponse\n >(auth, HttpMethod.POST, Endpoint.SET_ACCOUNT_INFO, request);\n}\n\nexport interface APIUserInfo {\n localId?: string;\n displayName?: string;\n photoUrl?: string;\n email?: string;\n emailVerified?: boolean;\n phoneNumber?: string;\n lastLoginAt?: number;\n createdAt?: number;\n tenantId?: string;\n passwordHash?: string;\n providerUserInfo?: ProviderUserInfo[];\n mfaInfo?: MfaEnrollment[];\n}\n\nexport interface GetAccountInfoRequest {\n idToken: string;\n}\n\nexport interface GetAccountInfoResponse {\n users: APIUserInfo[];\n}\n\nexport async function getAccountInfo(\n auth: Auth,\n request: GetAccountInfoRequest\n): Promise<GetAccountInfoResponse> {\n return _performApiRequest<GetAccountInfoRequest, GetAccountInfoResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.GET_ACCOUNT_INFO,\n request\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FinalizeMfaResponse } from '../../api/authentication/mfa';\nimport { requestStsToken } from '../../api/authentication/token';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { PersistedBlob } from '../persistence';\nimport { _assert, debugFail } from '../util/assert';\nimport { _tokenExpiresIn } from './id_token_result';\n\n/**\n * The number of milliseconds before the official expiration time of a token\n * to refresh that token, to provide a buffer for RPCs to complete.\n */\nexport const enum Buffer {\n TOKEN_REFRESH = 30_000\n}\n\n/**\n * We need to mark this class as internal explicitly to exclude it in the public typings, because\n * it references AuthInternal which has a circular dependency with UserInternal.\n *\n * @internal\n */\nexport class StsTokenManager {\n refreshToken: string | null = null;\n accessToken: string | null = null;\n expirationTime: number | null = null;\n\n get isExpired(): boolean {\n return (\n !this.expirationTime ||\n Date.now() > this.expirationTime - Buffer.TOKEN_REFRESH\n );\n }\n\n updateFromServerResponse(\n response: IdTokenResponse | FinalizeMfaResponse\n ): void {\n _assert(response.idToken, AuthErrorCode.INTERNAL_ERROR);\n _assert(\n typeof response.idToken !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n _assert(\n typeof response.refreshToken !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n const expiresIn =\n 'expiresIn' in response && typeof response.expiresIn !== 'undefined'\n ? Number(response.expiresIn)\n : _tokenExpiresIn(response.idToken);\n this.updateTokensAndExpiration(\n response.idToken,\n response.refreshToken,\n expiresIn\n );\n }\n\n async getToken(\n auth: AuthInternal,\n forceRefresh = false\n ): Promise<string | null> {\n _assert(\n !this.accessToken || this.refreshToken,\n auth,\n AuthErrorCode.TOKEN_EXPIRED\n );\n\n if (!forceRefresh && this.accessToken && !this.isExpired) {\n return this.accessToken;\n }\n\n if (this.refreshToken) {\n await this.refresh(auth, this.refreshToken!);\n return this.accessToken;\n }\n\n return null;\n }\n\n clearRefreshToken(): void {\n this.refreshToken = null;\n }\n\n private async refresh(auth: AuthInternal, oldToken: string): Promise<void> {\n const { accessToken, refreshToken, expiresIn } = await requestStsToken(\n auth,\n oldToken\n );\n this.updateTokensAndExpiration(\n accessToken,\n refreshToken,\n Number(expiresIn)\n );\n }\n\n private updateTokensAndExpiration(\n accessToken: string,\n refreshToken: string,\n expiresInSec: number\n ): void {\n this.refreshToken = refreshToken || null;\n this.accessToken = accessToken || null;\n this.expirationTime = Date.now() + expiresInSec * 1000;\n }\n\n static fromJSON(appName: string, object: PersistedBlob): StsTokenManager {\n const { refreshToken, accessToken, expirationTime } = object;\n\n const manager = new StsTokenManager();\n if (refreshToken) {\n _assert(typeof refreshToken === 'string', AuthErrorCode.INTERNAL_ERROR, {\n appName\n });\n manager.refreshToken = refreshToken;\n }\n if (accessToken) {\n _assert(typeof accessToken === 'string', AuthErrorCode.INTERNAL_ERROR, {\n appName\n });\n manager.accessToken = accessToken;\n }\n if (expirationTime) {\n _assert(\n typeof expirationTime === 'number',\n AuthErrorCode.INTERNAL_ERROR,\n {\n appName\n }\n );\n manager.expirationTime = expirationTime;\n }\n return manager;\n }\n\n toJSON(): object {\n return {\n refreshToken: this.refreshToken,\n accessToken: this.accessToken,\n expirationTime: this.expirationTime\n };\n }\n\n _assign(stsTokenManager: StsTokenManager): void {\n this.accessToken = stsTokenManager.accessToken;\n this.refreshToken = stsTokenManager.refreshToken;\n this.expirationTime = stsTokenManager.expirationTime;\n }\n\n _clone(): StsTokenManager {\n return Object.assign(new StsTokenManager(), this.toJSON());\n }\n\n _performRefresh(): never {\n return debugFail('not implemented');\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable camelcase */\n\nimport { querystring } from '@firebase/util';\n\nimport {\n _getFinalTarget,\n _performFetchWithErrorHandling,\n _performApiRequest,\n _addTidIfNecessary,\n HttpMethod,\n HttpHeader,\n Endpoint\n} from '../index';\nimport { FetchProvider } from '../../core/util/fetch_provider';\nimport { Auth } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\n\nexport const enum TokenType {\n REFRESH_TOKEN = 'REFRESH_TOKEN',\n ACCESS_TOKEN = 'ACCESS_TOKEN'\n}\n\n/** The server responses with snake_case; we convert to camelCase */\ninterface RequestStsTokenServerResponse {\n access_token: string;\n expires_in: string;\n refresh_token: string;\n}\n\nexport interface RequestStsTokenResponse {\n accessToken: string;\n expiresIn: string;\n refreshToken: string;\n}\n\nexport interface RevokeTokenRequest {\n providerId: string;\n tokenType: TokenType;\n token: string;\n idToken: string;\n tenantId?: string;\n}\n\nexport interface RevokeTokenResponse {}\n\nexport async function requestStsToken(\n auth: Auth,\n refreshToken: string\n): Promise<RequestStsTokenResponse> {\n const response =\n await _performFetchWithErrorHandling<RequestStsTokenServerResponse>(\n auth,\n {},\n async () => {\n const body = querystring({\n 'grant_type': 'refresh_token',\n 'refresh_token': refreshToken\n }).slice(1);\n const { tokenApiHost, apiKey } = auth.config;\n const url = _getFinalTarget(\n auth,\n tokenApiHost,\n Endpoint.TOKEN,\n `key=${apiKey}`\n );\n\n const headers = await (auth as AuthInternal)._getAdditionalHeaders();\n headers[HttpHeader.CONTENT_TYPE] = 'application/x-www-form-urlencoded';\n\n return FetchProvider.fetch()(url, {\n method: HttpMethod.POST,\n headers,\n body\n });\n }\n );\n\n // The response comes back in snake_case. Convert to camel:\n return {\n accessToken: response.access_token,\n expiresIn: response.expires_in,\n refreshToken: response.refresh_token\n };\n}\n\nexport async function revokeToken(\n auth: Auth,\n request: RevokeTokenRequest\n): Promise<RevokeTokenResponse> {\n return _performApiRequest<RevokeTokenRequest, RevokeTokenResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.REVOKE_TOKEN,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdTokenResult } from '../../model/public_types';\nimport { NextFn } from '@firebase/util';\n\nimport {\n APIUserInfo,\n deleteAccount\n} from '../../api/account_management/account';\nimport { FinalizeMfaResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport {\n MutableUserInfo,\n UserInternal,\n UserParameters\n} from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { PersistedBlob } from '../persistence';\nimport { _assert } from '../util/assert';\nimport { getIdTokenResult } from './id_token_result';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { ProactiveRefresh } from './proactive_refresh';\nimport { _reloadWithoutSaving, reload } from './reload';\nimport { StsTokenManager } from './token_manager';\nimport { UserMetadata } from './user_metadata';\nimport { ProviderId } from '../../model/enums';\n\nfunction assertStringOrUndefined(\n assertion: unknown,\n appName: string\n): asserts assertion is string | undefined {\n _assert(\n typeof assertion === 'string' || typeof assertion === 'undefined',\n AuthErrorCode.INTERNAL_ERROR,\n { appName }\n );\n}\n\nexport class UserImpl implements UserInternal {\n // For the user object, provider is always Firebase.\n readonly providerId = ProviderId.FIREBASE;\n stsTokenManager: StsTokenManager;\n // Last known accessToken so we know when it changes\n private accessToken: string | null;\n\n uid: string;\n auth: AuthInternal;\n emailVerified: boolean;\n isAnonymous: boolean;\n tenantId: string | null;\n readonly metadata: UserMetadata;\n providerData: MutableUserInfo[];\n\n // Optional fields from UserInfo\n displayName: string | null;\n email: string | null;\n phoneNumber: string | null;\n photoURL: string | null;\n\n _redirectEventId?: string;\n private readonly proactiveRefresh = new ProactiveRefresh(this);\n\n constructor({ uid, auth, stsTokenManager, ...opt }: UserParameters) {\n this.uid = uid;\n this.auth = auth;\n this.stsTokenManager = stsTokenManager;\n this.accessToken = stsTokenManager.accessToken;\n this.displayName = opt.displayName || null;\n this.email = opt.email || null;\n this.emailVerified = opt.emailVerified || false;\n this.phoneNumber = opt.phoneNumber || null;\n this.photoURL = opt.photoURL || null;\n this.isAnonymous = opt.isAnonymous || false;\n this.tenantId = opt.tenantId || null;\n this.providerData = opt.providerData ? [...opt.providerData] : [];\n this.metadata = new UserMetadata(\n opt.createdAt || undefined,\n opt.lastLoginAt || undefined\n );\n }\n\n async getIdToken(forceRefresh?: boolean): Promise<string> {\n const accessToken = await _logoutIfInvalidated(\n this,\n this.stsTokenManager.getToken(this.auth, forceRefresh)\n );\n _assert(accessToken, this.auth, AuthErrorCode.INTERNAL_ERROR);\n\n if (this.accessToken !== accessToken) {\n this.accessToken = accessToken;\n await this.auth._persistUserIfCurrent(this);\n this.auth._notifyListenersIfCurrent(this);\n }\n\n return accessToken;\n }\n\n getIdTokenResult(forceRefresh?: boolean): Promise<IdTokenResult> {\n return getIdTokenResult(this, forceRefresh);\n }\n\n reload(): Promise<void> {\n return reload(this);\n }\n\n private reloadUserInfo: APIUserInfo | null = null;\n private reloadListener: NextFn<APIUserInfo> | null = null;\n\n _assign(user: UserInternal): void {\n if (this === user) {\n return;\n }\n _assert(this.uid === user.uid, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.displayName = user.displayName;\n this.photoURL = user.photoURL;\n this.email = user.email;\n this.emailVerified = user.emailVerified;\n this.phoneNumber = user.phoneNumber;\n this.isAnonymous = user.isAnonymous;\n this.tenantId = user.tenantId;\n this.providerData = user.providerData.map(userInfo => ({ ...userInfo }));\n this.metadata._copy(user.metadata);\n this.stsTokenManager._assign(user.stsTokenManager);\n }\n\n _clone(auth: AuthInternal): UserInternal {\n const newUser = new UserImpl({\n ...this,\n auth,\n stsTokenManager: this.stsTokenManager._clone()\n });\n newUser.metadata._copy(this.metadata);\n return newUser;\n }\n\n _onReload(callback: NextFn<APIUserInfo>): void {\n // There should only ever be one listener, and that is a single instance of MultiFactorUser\n _assert(!this.reloadListener, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.reloadListener = callback;\n if (this.reloadUserInfo) {\n this._notifyReloadListener(this.reloadUserInfo);\n this.reloadUserInfo = null;\n }\n }\n\n _notifyReloadListener(userInfo: APIUserInfo): void {\n if (this.reloadListener) {\n this.reloadListener(userInfo);\n } else {\n // If no listener is subscribed yet, save the result so it's available when they do subscribe\n this.reloadUserInfo = userInfo;\n }\n }\n\n _startProactiveRefresh(): void {\n this.proactiveRefresh._start();\n }\n\n _stopProactiveRefresh(): void {\n this.proactiveRefresh._stop();\n }\n\n async _updateTokensIfNecessary(\n response: IdTokenResponse | FinalizeMfaResponse,\n reload = false\n ): Promise<void> {\n let tokensRefreshed = false;\n if (\n response.idToken &&\n response.idToken !== this.stsTokenManager.accessToken\n ) {\n this.stsTokenManager.updateFromServerResponse(response);\n tokensRefreshed = true;\n }\n\n if (reload) {\n await _reloadWithoutSaving(this);\n }\n\n await this.auth._persistUserIfCurrent(this);\n if (tokensRefreshed) {\n this.auth._notifyListenersIfCurrent(this);\n }\n }\n\n async delete(): Promise<void> {\n const idToken = await this.getIdToken();\n await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));\n this.stsTokenManager.clearRefreshToken();\n\n // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()\n // cancels pending actions...\n\n return this.auth.signOut();\n }\n\n toJSON(): PersistedBlob {\n return {\n uid: this.uid,\n email: this.email || undefined,\n emailVerified: this.emailVerified,\n displayName: this.displayName || undefined,\n isAnonymous: this.isAnonymous,\n photoURL: this.photoURL || undefined,\n phoneNumber: this.phoneNumber || undefined,\n tenantId: this.tenantId || undefined,\n providerData: this.providerData.map(userInfo => ({ ...userInfo })),\n stsTokenManager: this.stsTokenManager.toJSON(),\n // Redirect event ID must be maintained in case there is a pending\n // redirect event.\n _redirectEventId: this._redirectEventId,\n ...this.metadata.toJSON(),\n\n // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):\n apiKey: this.auth.config.apiKey,\n appName: this.auth.name\n // Missing authDomain will be tolerated by the legacy SDK.\n // stsTokenManager.apiKey isn't actually required (despite the legacy SDK persisting it).\n };\n }\n\n get refreshToken(): string {\n return this.stsTokenManager.refreshToken || '';\n }\n\n static _fromJSON(auth: AuthInternal, object: PersistedBlob): UserInternal {\n const displayName = object.displayName ?? undefined;\n const email = object.email ?? undefined;\n const phoneNumber = object.phoneNumber ?? undefined;\n const photoURL = object.photoURL ?? undefined;\n const tenantId = object.tenantId ?? undefined;\n const _redirectEventId = object._redirectEventId ?? undefined;\n const createdAt = object.createdAt ?? undefined;\n const lastLoginAt = object.lastLoginAt ?? undefined;\n const {\n uid,\n emailVerified,\n isAnonymous,\n providerData,\n stsTokenManager: plainObjectTokenManager\n } = object;\n\n _assert(uid && plainObjectTokenManager, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const stsTokenManager = StsTokenManager.fromJSON(\n this.name,\n plainObjectTokenManager as PersistedBlob\n );\n\n _assert(typeof uid === 'string', auth, AuthErrorCode.INTERNAL_ERROR);\n assertStringOrUndefined(displayName, auth.name);\n assertStringOrUndefined(email, auth.name);\n _assert(\n typeof emailVerified === 'boolean',\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n _assert(\n typeof isAnonymous === 'boolean',\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n assertStringOrUndefined(phoneNumber, auth.name);\n assertStringOrUndefined(photoURL, auth.name);\n assertStringOrUndefined(tenantId, auth.name);\n assertStringOrUndefined(_redirectEventId, auth.name);\n assertStringOrUndefined(createdAt, auth.name);\n assertStringOrUndefined(lastLoginAt, auth.name);\n const user = new UserImpl({\n uid,\n auth,\n email,\n emailVerified,\n displayName,\n isAnonymous,\n photoURL,\n phoneNumber,\n tenantId,\n stsTokenManager,\n createdAt,\n lastLoginAt\n });\n\n if (providerData && Array.isArray(providerData)) {\n user.providerData = providerData.map(userInfo => ({ ...userInfo }));\n }\n\n if (_redirectEventId) {\n user._redirectEventId = _redirectEventId;\n }\n\n return user;\n }\n\n /**\n * Initialize a User from an idToken server response\n * @param auth\n * @param idTokenResponse\n */\n static async _fromIdTokenResponse(\n auth: AuthInternal,\n idTokenResponse: IdTokenResponse,\n isAnonymous: boolean = false\n ): Promise<UserInternal> {\n const stsTokenManager = new StsTokenManager();\n stsTokenManager.updateFromServerResponse(idTokenResponse);\n\n // Initialize the Firebase Auth user.\n const user = new UserImpl({\n uid: idTokenResponse.localId,\n auth,\n stsTokenManager,\n isAnonymous\n });\n\n // Updates the user info and data and resolves with a user instance.\n await _reloadWithoutSaving(user);\n return user;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\n/**\n * Our API has a lot of one-off constants that are used to do things.\n * Unfortunately we can't export these as classes instantiated directly since\n * the constructor may side effect and therefore can't be proven to be safely\n * culled. Instead, we export these classes themselves as a lowerCamelCase\n * constant, and instantiate them under the hood.\n */\nexport interface SingletonInstantiator<T> {\n new (): T;\n}\n\nconst instanceCache: Map<unknown, unknown> = new Map();\n\nexport function _getInstance<T>(cls: unknown): T {\n debugAssert(cls instanceof Function, 'Expected a class definition');\n let instance = instanceCache.get(cls) as T | undefined;\n\n if (instance) {\n debugAssert(\n instance instanceof cls,\n 'Instance stored in cache mismatched with class'\n );\n return instance;\n }\n\n instance = new (cls as SingletonInstantiator<T>)();\n instanceCache.set(cls, instance);\n return instance;\n}\n\nexport function _clearInstanceMap(): void {\n instanceCache.clear();\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport {\n PersistenceInternal,\n PersistenceType,\n PersistenceValue,\n StorageEventListener\n} from '../persistence';\n\nexport class InMemoryPersistence implements PersistenceInternal {\n static type: 'NONE' = 'NONE';\n readonly type = PersistenceType.NONE;\n storage: Record<string, PersistenceValue> = {};\n\n async _isAvailable(): Promise<boolean> {\n return true;\n }\n\n async _set(key: string, value: PersistenceValue): Promise<void> {\n this.storage[key] = value;\n }\n\n async _get<T extends PersistenceValue>(key: string): Promise<T | null> {\n const value = this.storage[key];\n return value === undefined ? null : (value as T);\n }\n\n async _remove(key: string): Promise<void> {\n delete this.storage[key];\n }\n\n _addListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n\n _removeListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type 'NONE'.\n *\n * @public\n */\nexport const inMemoryPersistence: Persistence = InMemoryPersistence;\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ApiKey, AppName, AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { PersistedBlob, PersistenceInternal } from '../persistence';\nimport { UserImpl } from '../user/user_impl';\nimport { _getInstance } from '../util/instantiator';\nimport { inMemoryPersistence } from './in_memory';\n\nexport const enum KeyName {\n AUTH_USER = 'authUser',\n AUTH_EVENT = 'authEvent',\n REDIRECT_USER = 'redirectUser',\n PERSISTENCE_USER = 'persistence'\n}\nexport const enum Namespace {\n PERSISTENCE = 'firebase'\n}\n\nexport function _persistenceKeyName(\n key: string,\n apiKey: ApiKey,\n appName: AppName\n): string {\n return `${Namespace.PERSISTENCE}:${key}:${apiKey}:${appName}`;\n}\n\nexport class PersistenceUserManager {\n private readonly fullUserKey: string;\n private readonly fullPersistenceKey: string;\n private readonly boundEventHandler: () => void;\n\n private constructor(\n public persistence: PersistenceInternal,\n private readonly auth: AuthInternal,\n private readonly userKey: string\n ) {\n const { config, name } = this.auth;\n this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);\n this.fullPersistenceKey = _persistenceKeyName(\n KeyName.PERSISTENCE_USER,\n config.apiKey,\n name\n );\n this.boundEventHandler = auth._onStorageEvent.bind(auth);\n this.persistence._addListener(this.fullUserKey, this.boundEventHandler);\n }\n\n setCurrentUser(user: UserInternal): Promise<void> {\n return this.persistence._set(this.fullUserKey, user.toJSON());\n }\n\n async getCurrentUser(): Promise<UserInternal | null> {\n const blob = await this.persistence._get<PersistedBlob>(this.fullUserKey);\n return blob ? UserImpl._fromJSON(this.auth, blob) : null;\n }\n\n removeCurrentUser(): Promise<void> {\n return this.persistence._remove(this.fullUserKey);\n }\n\n savePersistenceForRedirect(): Promise<void> {\n return this.persistence._set(\n this.fullPersistenceKey,\n this.persistence.type\n );\n }\n\n async setPersistence(newPersistence: PersistenceInternal): Promise<void> {\n if (this.persistence === newPersistence) {\n return;\n }\n\n const currentUser = await this.getCurrentUser();\n await this.removeCurrentUser();\n\n this.persistence = newPersistence;\n\n if (currentUser) {\n return this.setCurrentUser(currentUser);\n }\n }\n\n delete(): void {\n this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);\n }\n\n static async create(\n auth: AuthInternal,\n persistenceHierarchy: PersistenceInternal[],\n userKey = KeyName.AUTH_USER\n ): Promise<PersistenceUserManager> {\n if (!persistenceHierarchy.length) {\n return new PersistenceUserManager(\n _getInstance(inMemoryPersistence),\n auth,\n userKey\n );\n }\n\n // Eliminate any persistences that are not available\n const availablePersistences = (\n await Promise.all(\n persistenceHierarchy.map(async persistence => {\n if (await persistence._isAvailable()) {\n return persistence;\n }\n return undefined;\n })\n )\n ).filter(persistence => persistence) as PersistenceInternal[];\n\n // Fall back to the first persistence listed, or in memory if none available\n let selectedPersistence =\n availablePersistences[0] ||\n _getInstance<PersistenceInternal>(inMemoryPersistence);\n\n const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);\n\n // Pull out the existing user, setting the chosen persistence to that\n // persistence if the user exists.\n let userToMigrate: UserInternal | null = null;\n // Note, here we check for a user in _all_ persistences, not just the\n // ones deemed available. If we can migrate a user out of a broken\n // persistence, we will (but only if that persistence supports migration).\n for (const persistence of persistenceHierarchy) {\n try {\n const blob = await persistence._get<PersistedBlob>(key);\n if (blob) {\n const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)\n if (persistence !== selectedPersistence) {\n userToMigrate = user;\n }\n selectedPersistence = persistence;\n break;\n }\n } catch {}\n }\n\n // If we find the user in a persistence that does support migration, use\n // that migration path (of only persistences that support migration)\n const migrationHierarchy = availablePersistences.filter(\n p => p._shouldAllowMigration\n );\n\n // If the persistence does _not_ allow migration, just finish off here\n if (\n !selectedPersistence._shouldAllowMigration ||\n !migrationHierarchy.length\n ) {\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\n }\n\n selectedPersistence = migrationHierarchy[0];\n if (userToMigrate) {\n // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does\n // we'll just let it bubble to surface the error.\n await selectedPersistence._set(key, userToMigrate.toJSON());\n }\n\n // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues\n // such as users getting stuck with a previous account after signing out and refreshing the tab.\n await Promise.all(\n persistenceHierarchy.map(async persistence => {\n if (persistence !== selectedPersistence) {\n try {\n await persistence._remove(key);\n } catch {}\n }\n })\n );\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIE, getUA } from '@firebase/util';\n\ninterface NavigatorStandalone extends Navigator {\n standalone?: unknown;\n}\n\ninterface Document {\n documentMode?: number;\n}\n\n/**\n * Enums for Browser name.\n */\nexport const enum BrowserName {\n ANDROID = 'Android',\n BLACKBERRY = 'Blackberry',\n EDGE = 'Edge',\n FIREFOX = 'Firefox',\n IE = 'IE',\n IEMOBILE = 'IEMobile',\n OPERA = 'Opera',\n OTHER = 'Other',\n CHROME = 'Chrome',\n SAFARI = 'Safari',\n SILK = 'Silk',\n WEBOS = 'Webos'\n}\n\n/**\n * Determine the browser for the purposes of reporting usage to the API\n */\nexport function _getBrowserName(userAgent: string): BrowserName | string {\n const ua = userAgent.toLowerCase();\n if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {\n return BrowserName.OPERA;\n } else if (_isIEMobile(ua)) {\n // Windows phone IEMobile browser.\n return BrowserName.IEMOBILE;\n } else if (ua.includes('msie') || ua.includes('trident/')) {\n return BrowserName.IE;\n } else if (ua.includes('edge/')) {\n return BrowserName.EDGE;\n } else if (_isFirefox(ua)) {\n return BrowserName.FIREFOX;\n } else if (ua.includes('silk/')) {\n return BrowserName.SILK;\n } else if (_isBlackBerry(ua)) {\n // Blackberry browser.\n return BrowserName.BLACKBERRY;\n } else if (_isWebOS(ua)) {\n // WebOS default browser.\n return BrowserName.WEBOS;\n } else if (_isSafari(ua)) {\n return BrowserName.SAFARI;\n } else if (\n (ua.includes('chrome/') || _isChromeIOS(ua)) &&\n !ua.includes('edge/')\n ) {\n return BrowserName.CHROME;\n } else if (_isAndroid(ua)) {\n // Android stock browser.\n return BrowserName.ANDROID;\n } else {\n // Most modern browsers have name/version at end of user agent string.\n const re = /([a-zA-Z\\d\\.]+)\\/[a-zA-Z\\d\\.]*$/;\n const matches = userAgent.match(re);\n if (matches?.length === 2) {\n return matches[1];\n }\n }\n return BrowserName.OTHER;\n}\n\nexport function _isFirefox(ua = getUA()): boolean {\n return /firefox\\//i.test(ua);\n}\n\nexport function _isSafari(userAgent = getUA()): boolean {\n const ua = userAgent.toLowerCase();\n return (\n ua.includes('safari/') &&\n !ua.includes('chrome/') &&\n !ua.includes('crios/') &&\n !ua.includes('android')\n );\n}\n\nexport function _isChromeIOS(ua = getUA()): boolean {\n return /crios\\//i.test(ua);\n}\n\nexport function _isIEMobile(ua = getUA()): boolean {\n return /iemobile/i.test(ua);\n}\n\nexport function _isAndroid(ua = getUA()): boolean {\n return /android/i.test(ua);\n}\n\nexport function _isBlackBerry(ua = getUA()): boolean {\n return /blackberry/i.test(ua);\n}\n\nexport function _isWebOS(ua = getUA()): boolean {\n return /webos/i.test(ua);\n}\n\nexport function _isIOS(ua = getUA()): boolean {\n return (\n /iphone|ipad|ipod/i.test(ua) ||\n (/macintosh/i.test(ua) && /mobile/i.test(ua))\n );\n}\n\nexport function _isIOS7Or8(ua = getUA()): boolean {\n return (\n /(iPad|iPhone|iPod).*OS 7_\\d/i.test(ua) ||\n /(iPad|iPhone|iPod).*OS 8_\\d/i.test(ua)\n );\n}\n\nexport function _isIOSStandalone(ua = getUA()): boolean {\n return _isIOS(ua) && !!(window.navigator as NavigatorStandalone)?.standalone;\n}\n\nexport function _isIE10(): boolean {\n return isIE() && (document as Document).documentMode === 10;\n}\n\nexport function _isMobileBrowser(ua: string = getUA()): boolean {\n // TODO: implement getBrowserName equivalent for OS.\n return (\n _isIOS(ua) ||\n _isAndroid(ua) ||\n _isWebOS(ua) ||\n _isBlackBerry(ua) ||\n /windows phone/i.test(ua) ||\n _isIEMobile(ua)\n );\n}\n\nexport function _isIframe(): boolean {\n try {\n // Check that the current window is not the top window.\n // If so, return true.\n return !!(window && window !== window.top);\n } catch (e) {\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { _getBrowserName } from './browser';\nimport { getUA } from '@firebase/util';\n\nexport const enum ClientImplementation {\n CORE = 'JsCore'\n}\n\n/**\n * @internal\n */\nexport const enum ClientPlatform {\n BROWSER = 'Browser',\n NODE = 'Node',\n REACT_NATIVE = 'ReactNative',\n CORDOVA = 'Cordova',\n WORKER = 'Worker'\n}\n\n/*\n * Determine the SDK version string\n */\nexport function _getClientVersion(\n clientPlatform: ClientPlatform,\n frameworks: readonly string[] = []\n): string {\n let reportedPlatform: string;\n switch (clientPlatform) {\n case ClientPlatform.BROWSER:\n // In a browser environment, report the browser name.\n reportedPlatform = _getBrowserName(getUA());\n break;\n case ClientPlatform.WORKER:\n // Technically a worker runs from a browser but we need to differentiate a\n // worker from a browser.\n // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.\n reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;\n break;\n default:\n reportedPlatform = clientPlatform;\n }\n const reportedFrameworks = frameworks.length\n ? frameworks.join(',')\n : 'FirebaseCore-web'; /* default value if no other framework is used */\n return `${reportedPlatform}/${ClientImplementation.CORE}/${SDK_VERSION}/${reportedFrameworks}`;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthInternal } from '../../model/auth';\nimport { Unsubscribe, User } from '../../model/public_types';\nimport { AuthErrorCode } from '../errors';\n\ninterface MiddlewareEntry {\n (user: User | null): Promise<void>;\n onAbort?: () => void;\n}\n\nexport class AuthMiddlewareQueue {\n private readonly queue: MiddlewareEntry[] = [];\n\n constructor(private readonly auth: AuthInternal) {}\n\n pushCallback(\n callback: (user: User | null) => void | Promise<void>,\n onAbort?: () => void\n ): Unsubscribe {\n // The callback could be sync or async. Wrap it into a\n // function that is always async.\n const wrappedCallback: MiddlewareEntry = (\n user: User | null\n ): Promise<void> =>\n new Promise((resolve, reject) => {\n try {\n const result = callback(user);\n // Either resolve with existing promise or wrap a non-promise\n // return value into a promise.\n resolve(result);\n } catch (e) {\n // Sync callback throws.\n reject(e);\n }\n });\n // Attach the onAbort if present\n wrappedCallback.onAbort = onAbort;\n this.queue.push(wrappedCallback);\n\n const index = this.queue.length - 1;\n return () => {\n // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb\n // indexing of other elements.\n this.queue[index] = () => Promise.resolve();\n };\n }\n\n async runMiddleware(nextUser: User | null): Promise<void> {\n if (this.auth.currentUser === nextUser) {\n return;\n }\n\n // While running the middleware, build a temporary stack of onAbort\n // callbacks to call if one middleware callback rejects.\n\n const onAbortStack: Array<() => void> = [];\n try {\n for (const beforeStateCallback of this.queue) {\n await beforeStateCallback(nextUser);\n\n // Only push the onAbort if the callback succeeds\n if (beforeStateCallback.onAbort) {\n onAbortStack.push(beforeStateCallback.onAbort);\n }\n }\n } catch (e) {\n // Run all onAbort, with separate try/catch to ignore any errors and\n // continue\n onAbortStack.reverse();\n for (const onAbort of onAbortStack) {\n try {\n onAbort();\n } catch (_) {\n /* swallow error */\n }\n }\n\n throw this.auth._errorFactory.create(AuthErrorCode.LOGIN_BLOCKED, {\n originalMessage: (e as Error)?.message\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GetPasswordPolicyResponse } from '../../api/password_policy/get_password_policy';\nimport {\n PasswordPolicyCustomStrengthOptions,\n PasswordPolicyInternal,\n PasswordValidationStatusInternal\n} from '../../model/password_policy';\nimport { PasswordValidationStatus } from '../../model/public_types';\n\n// Minimum min password length enforced by the backend, even if no minimum length is set.\nconst MINIMUM_MIN_PASSWORD_LENGTH = 6;\n\n/**\n * Stores password policy requirements and provides password validation against the policy.\n *\n * @internal\n */\nexport class PasswordPolicyImpl implements PasswordPolicyInternal {\n readonly customStrengthOptions: PasswordPolicyCustomStrengthOptions;\n readonly allowedNonAlphanumericCharacters: string;\n readonly enforcementState: string;\n readonly forceUpgradeOnSignin: boolean;\n readonly schemaVersion: number;\n\n constructor(response: GetPasswordPolicyResponse) {\n // Only include custom strength options defined in the response.\n const responseOptions = response.customStrengthOptions;\n this.customStrengthOptions = {};\n // TODO: Remove once the backend is updated to include the minimum min password length instead of undefined when there is no minimum length set.\n this.customStrengthOptions.minPasswordLength =\n responseOptions.minPasswordLength ?? MINIMUM_MIN_PASSWORD_LENGTH;\n if (responseOptions.maxPasswordLength) {\n this.customStrengthOptions.maxPasswordLength =\n responseOptions.maxPasswordLength;\n }\n if (responseOptions.containsLowercaseCharacter !== undefined) {\n this.customStrengthOptions.containsLowercaseLetter =\n responseOptions.containsLowercaseCharacter;\n }\n if (responseOptions.containsUppercaseCharacter !== undefined) {\n this.customStrengthOptions.containsUppercaseLetter =\n responseOptions.containsUppercaseCharacter;\n }\n if (responseOptions.containsNumericCharacter !== undefined) {\n this.customStrengthOptions.containsNumericCharacter =\n responseOptions.containsNumericCharacter;\n }\n if (responseOptions.containsNonAlphanumericCharacter !== undefined) {\n this.customStrengthOptions.containsNonAlphanumericCharacter =\n responseOptions.containsNonAlphanumericCharacter;\n }\n\n this.enforcementState = response.enforcementState;\n if (this.enforcementState === 'ENFORCEMENT_STATE_UNSPECIFIED') {\n this.enforcementState = 'OFF';\n }\n\n // Use an empty string if no non-alphanumeric characters are specified in the response.\n this.allowedNonAlphanumericCharacters =\n response.allowedNonAlphanumericCharacters?.join('') ?? '';\n\n this.forceUpgradeOnSignin = response.forceUpgradeOnSignin ?? false;\n this.schemaVersion = response.schemaVersion;\n }\n\n validatePassword(password: string): PasswordValidationStatus {\n const status: PasswordValidationStatusInternal = {\n isValid: true,\n passwordPolicy: this\n };\n\n // Check the password length and character options.\n this.validatePasswordLengthOptions(password, status);\n this.validatePasswordCharacterOptions(password, status);\n\n // Combine the status into single isValid property.\n status.isValid &&= status.meetsMinPasswordLength ?? true;\n status.isValid &&= status.meetsMaxPasswordLength ?? true;\n status.isValid &&= status.containsLowercaseLetter ?? true;\n status.isValid &&= status.containsUppercaseLetter ?? true;\n status.isValid &&= status.containsNumericCharacter ?? true;\n status.isValid &&= status.containsNonAlphanumericCharacter ?? true;\n\n return status;\n }\n\n /**\n * Validates that the password meets the length options for the policy.\n *\n * @param password Password to validate.\n * @param status Validation status.\n */\n private validatePasswordLengthOptions(\n password: string,\n status: PasswordValidationStatusInternal\n ): void {\n const minPasswordLength = this.customStrengthOptions.minPasswordLength;\n const maxPasswordLength = this.customStrengthOptions.maxPasswordLength;\n if (minPasswordLength) {\n status.meetsMinPasswordLength = password.length >= minPasswordLength;\n }\n if (maxPasswordLength) {\n status.meetsMaxPasswordLength = password.length <= maxPasswordLength;\n }\n }\n\n /**\n * Validates that the password meets the character options for the policy.\n *\n * @param password Password to validate.\n * @param status Validation status.\n */\n private validatePasswordCharacterOptions(\n password: string,\n status: PasswordValidationStatusInternal\n ): void {\n // Assign statuses for requirements even if the password is an empty string.\n this.updatePasswordCharacterOptionsStatuses(\n status,\n /* containsLowercaseCharacter= */ false,\n /* containsUppercaseCharacter= */ false,\n /* containsNumericCharacter= */ false,\n /* containsNonAlphanumericCharacter= */ false\n );\n\n let passwordChar;\n for (let i = 0; i < password.length; i++) {\n passwordChar = password.charAt(i);\n this.updatePasswordCharacterOptionsStatuses(\n status,\n /* containsLowercaseCharacter= */ passwordChar >= 'a' &&\n passwordChar <= 'z',\n /* containsUppercaseCharacter= */ passwordChar >= 'A' &&\n passwordChar <= 'Z',\n /* containsNumericCharacter= */ passwordChar >= '0' &&\n passwordChar <= '9',\n /* containsNonAlphanumericCharacter= */ this.allowedNonAlphanumericCharacters.includes(\n passwordChar\n )\n );\n }\n }\n\n /**\n * Updates the running validation status with the statuses for the character options.\n * Expected to be called each time a character is processed to update each option status\n * based on the current character.\n *\n * @param status Validation status.\n * @param containsLowercaseCharacter Whether the character is a lowercase letter.\n * @param containsUppercaseCharacter Whether the character is an uppercase letter.\n * @param containsNumericCharacter Whether the character is a numeric character.\n * @param containsNonAlphanumericCharacter Whether the character is a non-alphanumeric character.\n */\n private updatePasswordCharacterOptionsStatuses(\n status: PasswordValidationStatusInternal,\n containsLowercaseCharacter: boolean,\n containsUppercaseCharacter: boolean,\n containsNumericCharacter: boolean,\n containsNonAlphanumericCharacter: boolean\n ): void {\n if (this.customStrengthOptions.containsLowercaseLetter) {\n status.containsLowercaseLetter ||= containsLowercaseCharacter;\n }\n if (this.customStrengthOptions.containsUppercaseLetter) {\n status.containsUppercaseLetter ||= containsUppercaseCharacter;\n }\n if (this.customStrengthOptions.containsNumericCharacter) {\n status.containsNumericCharacter ||= containsNumericCharacter;\n }\n if (this.customStrengthOptions.containsNonAlphanumericCharacter) {\n status.containsNonAlphanumericCharacter ||=\n containsNonAlphanumericCharacter;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _FirebaseService, FirebaseApp } from '@firebase/app';\nimport { Provider } from '@firebase/component';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\nimport {\n Auth,\n AuthErrorMap,\n AuthSettings,\n EmulatorConfig,\n NextOrObserver,\n Persistence,\n PopupRedirectResolver,\n User,\n UserCredential,\n CompleteFn,\n ErrorFn,\n NextFn,\n Unsubscribe,\n PasswordValidationStatus\n} from '../../model/public_types';\nimport {\n createSubscribe,\n ErrorFactory,\n FirebaseError,\n getModularInstance,\n Observer,\n Subscribe\n} from '@firebase/util';\n\nimport { AuthInternal, ConfigInternal } from '../../model/auth';\nimport { PopupRedirectResolverInternal } from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport {\n AuthErrorCode,\n AuthErrorParams,\n ErrorMapRetriever,\n _DEFAULT_AUTH_ERROR_FACTORY\n} from '../errors';\nimport { PersistenceInternal } from '../persistence';\nimport {\n KeyName,\n PersistenceUserManager\n} from '../persistence/persistence_user_manager';\nimport { _reloadWithoutSaving } from '../user/reload';\nimport { _assert } from '../util/assert';\nimport { _getInstance } from '../util/instantiator';\nimport { _getUserLanguage } from '../util/navigator';\nimport { _getClientVersion } from '../util/version';\nimport { HttpHeader } from '../../api';\nimport {\n RevokeTokenRequest,\n TokenType,\n revokeToken\n} from '../../api/authentication/token';\nimport { AuthMiddlewareQueue } from './middleware';\nimport { RecaptchaConfig } from '../../platform_browser/recaptcha/recaptcha';\nimport { _logWarn } from '../util/log';\nimport { _getPasswordPolicy } from '../../api/password_policy/get_password_policy';\nimport { PasswordPolicyInternal } from '../../model/password_policy';\nimport { PasswordPolicyImpl } from './password_policy_impl';\n\ninterface AsyncAction {\n (): Promise<void>;\n}\n\nexport const enum DefaultConfig {\n TOKEN_API_HOST = 'securetoken.googleapis.com',\n API_HOST = 'identitytoolkit.googleapis.com',\n API_SCHEME = 'https'\n}\n\nexport class AuthImpl implements AuthInternal, _FirebaseService {\n currentUser: User | null = null;\n emulatorConfig: EmulatorConfig | null = null;\n private operations = Promise.resolve();\n private persistenceManager?: PersistenceUserManager;\n private redirectPersistenceManager?: PersistenceUserManager;\n private authStateSubscription = new Subscription<User>(this);\n private idTokenSubscription = new Subscription<User>(this);\n private readonly beforeStateQueue = new AuthMiddlewareQueue(this);\n private redirectUser: UserInternal | null = null;\n private isProactiveRefreshEnabled = false;\n private readonly EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION: number = 1;\n\n // Any network calls will set this to true and prevent subsequent emulator\n // initialization\n _canInitEmulator = true;\n _isInitialized = false;\n _deleted = false;\n _initializationPromise: Promise<void> | null = null;\n _popupRedirectResolver: PopupRedirectResolverInternal | null = null;\n _errorFactory: ErrorFactory<AuthErrorCode, AuthErrorParams> =\n _DEFAULT_AUTH_ERROR_FACTORY;\n _agentRecaptchaConfig: RecaptchaConfig | null = null;\n _tenantRecaptchaConfigs: Record<string, RecaptchaConfig> = {};\n _projectPasswordPolicy: PasswordPolicyInternal | null = null;\n _tenantPasswordPolicies: Record<string, PasswordPolicyInternal> = {};\n readonly name: string;\n\n // Tracks the last notified UID for state change listeners to prevent\n // repeated calls to the callbacks. Undefined means it's never been\n // called, whereas null means it's been called with a signed out user\n private lastNotifiedUid: string | null | undefined = undefined;\n\n languageCode: string | null = null;\n tenantId: string | null = null;\n settings: AuthSettings = { appVerificationDisabledForTesting: false };\n\n constructor(\n public readonly app: FirebaseApp,\n private readonly heartbeatServiceProvider: Provider<'heartbeat'>,\n private readonly appCheckServiceProvider: Provider<AppCheckInternalComponentName>,\n public readonly config: ConfigInternal\n ) {\n this.name = app.name;\n this.clientVersion = config.sdkClientVersion;\n }\n\n _initializeWithPersistence(\n persistenceHierarchy: PersistenceInternal[],\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise<void> {\n if (popupRedirectResolver) {\n this._popupRedirectResolver = _getInstance(popupRedirectResolver);\n }\n\n // Have to check for app deletion throughout initialization (after each\n // promise resolution)\n this._initializationPromise = this.queue(async () => {\n if (this._deleted) {\n return;\n }\n\n this.persistenceManager = await PersistenceUserManager.create(\n this,\n persistenceHierarchy\n );\n\n if (this._deleted) {\n return;\n }\n\n // Initialize the resolver early if necessary (only applicable to web:\n // this will cause the iframe to load immediately in certain cases)\n if (this._popupRedirectResolver?._shouldInitProactively) {\n // If this fails, don't halt auth loading\n try {\n await this._popupRedirectResolver._initialize(this);\n } catch (e) {\n /* Ignore the error */\n }\n }\n\n await this.initializeCurrentUser(popupRedirectResolver);\n this.lastNotifiedUid = this.currentUser?.uid || null;\n\n if (this._deleted) {\n return;\n }\n\n this._isInitialized = true;\n });\n\n return this._initializationPromise;\n }\n\n /**\n * If the persistence is changed in another window, the user manager will let us know\n */\n async _onStorageEvent(): Promise<void> {\n if (this._deleted) {\n return;\n }\n\n const user = await this.assertedPersistence.getCurrentUser();\n\n if (!this.currentUser && !user) {\n // No change, do nothing (was signed out and remained signed out).\n return;\n }\n\n // If the same user is to be synchronized.\n if (this.currentUser && user && this.currentUser.uid === user.uid) {\n // Data update, simply copy data changes.\n this._currentUser._assign(user);\n // If tokens changed from previous user tokens, this will trigger\n // notifyAuthListeners_.\n await this.currentUser.getIdToken();\n return;\n }\n\n // Update current Auth state. Either a new login or logout.\n // Skip blocking callbacks, they should not apply to a change in another tab.\n await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);\n }\n\n private async initializeCurrentUser(\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise<void> {\n // First check to see if we have a pending redirect event.\n const previouslyStoredUser =\n (await this.assertedPersistence.getCurrentUser()) as UserInternal | null;\n let futureCurrentUser = previouslyStoredUser;\n let needsTocheckMiddleware = false;\n if (popupRedirectResolver && this.config.authDomain) {\n await this.getOrInitRedirectPersistenceManager();\n const redirectUserEventId = this.redirectUser?._redirectEventId;\n const storedUserEventId = futureCurrentUser?._redirectEventId;\n const result = await this.tryRedirectSignIn(popupRedirectResolver);\n\n // If the stored user (i.e. the old \"currentUser\") has a redirectId that\n // matches the redirect user, then we want to initially sign in with the\n // new user object from result.\n // TODO(samgho): More thoroughly test all of this\n if (\n (!redirectUserEventId || redirectUserEventId === storedUserEventId) &&\n result?.user\n ) {\n futureCurrentUser = result.user as UserInternal;\n needsTocheckMiddleware = true;\n }\n }\n\n // If no user in persistence, there is no current user. Set to null.\n if (!futureCurrentUser) {\n return this.directlySetCurrentUser(null);\n }\n\n if (!futureCurrentUser._redirectEventId) {\n // This isn't a redirect link operation, we can reload and bail.\n // First though, ensure that we check the middleware is happy.\n if (needsTocheckMiddleware) {\n try {\n await this.beforeStateQueue.runMiddleware(futureCurrentUser);\n } catch (e) {\n futureCurrentUser = previouslyStoredUser;\n // We know this is available since the bit is only set when the\n // resolver is available\n this._popupRedirectResolver!._overrideRedirectResult(this, () =>\n Promise.reject(e)\n );\n }\n }\n\n if (futureCurrentUser) {\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n } else {\n return this.directlySetCurrentUser(null);\n }\n }\n\n _assert(this._popupRedirectResolver, this, AuthErrorCode.ARGUMENT_ERROR);\n await this.getOrInitRedirectPersistenceManager();\n\n // If the redirect user's event ID matches the current user's event ID,\n // DO NOT reload the current user, otherwise they'll be cleared from storage.\n // This is important for the reauthenticateWithRedirect() flow.\n if (\n this.redirectUser &&\n this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId\n ) {\n return this.directlySetCurrentUser(futureCurrentUser);\n }\n\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n }\n\n private async tryRedirectSignIn(\n redirectResolver: PopupRedirectResolver\n ): Promise<UserCredential | null> {\n // The redirect user needs to be checked (and signed in if available)\n // during auth initialization. All of the normal sign in and link/reauth\n // flows call back into auth and push things onto the promise queue. We\n // need to await the result of the redirect sign in *inside the promise\n // queue*. This presents a problem: we run into deadlock. See:\n // ┌> [Initialization] ─────┐\n // ┌> [<other queue tasks>] │\n // └─ [getRedirectResult] <─┘\n // where [] are tasks on the queue and arrows denote awaits\n // Initialization will never complete because it's waiting on something\n // that's waiting for initialization to complete!\n //\n // Instead, this method calls getRedirectResult() (stored in\n // _completeRedirectFn) with an optional parameter that instructs all of\n // the underlying auth operations to skip anything that mutates auth state.\n\n let result: UserCredential | null = null;\n try {\n // We know this._popupRedirectResolver is set since redirectResolver\n // is passed in. The _completeRedirectFn expects the unwrapped extern.\n result = await this._popupRedirectResolver!._completeRedirectFn(\n this,\n redirectResolver,\n true\n );\n } catch (e) {\n // Swallow any errors here; the code can retrieve them in\n // getRedirectResult().\n await this._setRedirectUser(null);\n }\n\n return result;\n }\n\n private async reloadAndSetCurrentUserOrClear(\n user: UserInternal\n ): Promise<void> {\n try {\n await _reloadWithoutSaving(user);\n } catch (e) {\n if (\n (e as FirebaseError)?.code !==\n `auth/${AuthErrorCode.NETWORK_REQUEST_FAILED}`\n ) {\n // Something's wrong with the user's token. Log them out and remove\n // them from storage\n return this.directlySetCurrentUser(null);\n }\n }\n\n return this.directlySetCurrentUser(user);\n }\n\n useDeviceLanguage(): void {\n this.languageCode = _getUserLanguage();\n }\n\n async _delete(): Promise<void> {\n this._deleted = true;\n }\n\n async updateCurrentUser(userExtern: User | null): Promise<void> {\n // The public updateCurrentUser method needs to make a copy of the user,\n // and also check that the project matches\n const user = userExtern\n ? (getModularInstance(userExtern) as UserInternal)\n : null;\n if (user) {\n _assert(\n user.auth.config.apiKey === this.config.apiKey,\n this,\n AuthErrorCode.INVALID_AUTH\n );\n }\n return this._updateCurrentUser(user && user._clone(this));\n }\n\n async _updateCurrentUser(\n user: User | null,\n skipBeforeStateCallbacks: boolean = false\n ): Promise<void> {\n if (this._deleted) {\n return;\n }\n if (user) {\n _assert(\n this.tenantId === user.tenantId,\n this,\n AuthErrorCode.TENANT_ID_MISMATCH\n );\n }\n\n if (!skipBeforeStateCallbacks) {\n await this.beforeStateQueue.runMiddleware(user);\n }\n\n return this.queue(async () => {\n await this.directlySetCurrentUser(user as UserInternal | null);\n this.notifyAuthListeners();\n });\n }\n\n async signOut(): Promise<void> {\n // Run first, to block _setRedirectUser() if any callbacks fail.\n await this.beforeStateQueue.runMiddleware(null);\n // Clear the redirect user when signOut is called\n if (this.redirectPersistenceManager || this._popupRedirectResolver) {\n await this._setRedirectUser(null);\n }\n\n // Prevent callbacks from being called again in _updateCurrentUser, as\n // they were already called in the first line.\n return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);\n }\n\n setPersistence(persistence: Persistence): Promise<void> {\n return this.queue(async () => {\n await this.assertedPersistence.setPersistence(_getInstance(persistence));\n });\n }\n\n _getRecaptchaConfig(): RecaptchaConfig | null {\n if (this.tenantId == null) {\n return this._agentRecaptchaConfig;\n } else {\n return this._tenantRecaptchaConfigs[this.tenantId];\n }\n }\n\n async validatePassword(password: string): Promise<PasswordValidationStatus> {\n if (!this._getPasswordPolicyInternal()) {\n await this._updatePasswordPolicy();\n }\n\n // Password policy will be defined after fetching.\n const passwordPolicy: PasswordPolicyInternal =\n this._getPasswordPolicyInternal()!;\n\n // Check that the policy schema version is supported by the SDK.\n // TODO: Update this logic to use a max supported policy schema version once we have multiple schema versions.\n if (\n passwordPolicy.schemaVersion !==\n this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION\n ) {\n return Promise.reject(\n this._errorFactory.create(\n AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION,\n {}\n )\n );\n }\n\n return passwordPolicy.validatePassword(password);\n }\n\n _getPasswordPolicyInternal(): PasswordPolicyInternal | null {\n if (this.tenantId === null) {\n return this._projectPasswordPolicy;\n } else {\n return this._tenantPasswordPolicies[this.tenantId];\n }\n }\n\n async _updatePasswordPolicy(): Promise<void> {\n const response = await _getPasswordPolicy(this);\n\n const passwordPolicy: PasswordPolicyInternal = new PasswordPolicyImpl(\n response\n );\n\n if (this.tenantId === null) {\n this._projectPasswordPolicy = passwordPolicy;\n } else {\n this._tenantPasswordPolicies[this.tenantId] = passwordPolicy;\n }\n }\n\n _getPersistence(): string {\n return this.assertedPersistence.persistence.type;\n }\n\n _updateErrorMap(errorMap: AuthErrorMap): void {\n this._errorFactory = new ErrorFactory<AuthErrorCode, AuthErrorParams>(\n 'auth',\n 'Firebase',\n (errorMap as ErrorMapRetriever)()\n );\n }\n\n onAuthStateChanged(\n nextOrObserver: NextOrObserver<User>,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n return this.registerStateListener(\n this.authStateSubscription,\n nextOrObserver,\n error,\n completed\n );\n }\n\n beforeAuthStateChanged(\n callback: (user: User | null) => void | Promise<void>,\n onAbort?: () => void\n ): Unsubscribe {\n return this.beforeStateQueue.pushCallback(callback, onAbort);\n }\n\n onIdTokenChanged(\n nextOrObserver: NextOrObserver<User>,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n return this.registerStateListener(\n this.idTokenSubscription,\n nextOrObserver,\n error,\n completed\n );\n }\n\n authStateReady(): Promise<void> {\n return new Promise((resolve, reject) => {\n if (this.currentUser) {\n resolve();\n } else {\n const unsubscribe = this.onAuthStateChanged(() => {\n unsubscribe();\n resolve();\n }, reject);\n }\n });\n }\n\n /**\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\n */\n async revokeAccessToken(token: string): Promise<void> {\n if (this.currentUser) {\n const idToken = await this.currentUser.getIdToken();\n // Generalize this to accept other providers once supported.\n const request: RevokeTokenRequest = {\n providerId: 'apple.com',\n tokenType: TokenType.ACCESS_TOKEN,\n token,\n idToken\n };\n if (this.tenantId != null) {\n request.tenantId = this.tenantId;\n }\n await revokeToken(this, request);\n }\n }\n\n toJSON(): object {\n return {\n apiKey: this.config.apiKey,\n authDomain: this.config.authDomain,\n appName: this.name,\n currentUser: this._currentUser?.toJSON()\n };\n }\n\n async _setRedirectUser(\n user: UserInternal | null,\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise<void> {\n const redirectManager = await this.getOrInitRedirectPersistenceManager(\n popupRedirectResolver\n );\n return user === null\n ? redirectManager.removeCurrentUser()\n : redirectManager.setCurrentUser(user);\n }\n\n private async getOrInitRedirectPersistenceManager(\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise<PersistenceUserManager> {\n if (!this.redirectPersistenceManager) {\n const resolver: PopupRedirectResolverInternal | null =\n (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||\n this._popupRedirectResolver;\n _assert(resolver, this, AuthErrorCode.ARGUMENT_ERROR);\n this.redirectPersistenceManager = await PersistenceUserManager.create(\n this,\n [_getInstance(resolver._redirectPersistence)],\n KeyName.REDIRECT_USER\n );\n this.redirectUser =\n await this.redirectPersistenceManager.getCurrentUser();\n }\n\n return this.redirectPersistenceManager;\n }\n\n async _redirectUserForId(id: string): Promise<UserInternal | null> {\n // Make sure we've cleared any pending persistence actions if we're not in\n // the initializer\n if (this._isInitialized) {\n await this.queue(async () => {});\n }\n\n if (this._currentUser?._redirectEventId === id) {\n return this._currentUser;\n }\n\n if (this.redirectUser?._redirectEventId === id) {\n return this.redirectUser;\n }\n\n return null;\n }\n\n async _persistUserIfCurrent(user: UserInternal): Promise<void> {\n if (user === this.currentUser) {\n return this.queue(async () => this.directlySetCurrentUser(user));\n }\n }\n\n /** Notifies listeners only if the user is current */\n _notifyListenersIfCurrent(user: UserInternal): void {\n if (user === this.currentUser) {\n this.notifyAuthListeners();\n }\n }\n\n _key(): string {\n return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;\n }\n\n _startProactiveRefresh(): void {\n this.isProactiveRefreshEnabled = true;\n if (this.currentUser) {\n this._currentUser._startProactiveRefresh();\n }\n }\n\n _stopProactiveRefresh(): void {\n this.isProactiveRefreshEnabled = false;\n if (this.currentUser) {\n this._currentUser._stopProactiveRefresh();\n }\n }\n\n /** Returns the current user cast as the internal type */\n get _currentUser(): UserInternal {\n return this.currentUser as UserInternal;\n }\n\n private notifyAuthListeners(): void {\n if (!this._isInitialized) {\n return;\n }\n\n this.idTokenSubscription.next(this.currentUser);\n\n const currentUid = this.currentUser?.uid ?? null;\n if (this.lastNotifiedUid !== currentUid) {\n this.lastNotifiedUid = currentUid;\n this.authStateSubscription.next(this.currentUser);\n }\n }\n\n private registerStateListener(\n subscription: Subscription<User>,\n nextOrObserver: NextOrObserver<User>,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n if (this._deleted) {\n return () => {};\n }\n\n const cb =\n typeof nextOrObserver === 'function'\n ? nextOrObserver\n : nextOrObserver.next.bind(nextOrObserver);\n\n let isUnsubscribed = false;\n\n const promise = this._isInitialized\n ? Promise.resolve()\n : this._initializationPromise;\n _assert(promise, this, AuthErrorCode.INTERNAL_ERROR);\n // The callback needs to be called asynchronously per the spec.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n promise.then(() => {\n if (isUnsubscribed) {\n return;\n }\n cb(this.currentUser);\n });\n\n if (typeof nextOrObserver === 'function') {\n const unsubscribe = subscription.addObserver(\n nextOrObserver,\n error,\n completed\n );\n return () => {\n isUnsubscribed = true;\n unsubscribe();\n };\n } else {\n const unsubscribe = subscription.addObserver(nextOrObserver);\n return () => {\n isUnsubscribed = true;\n unsubscribe();\n };\n }\n }\n\n /**\n * Unprotected (from race conditions) method to set the current user. This\n * should only be called from within a queued callback. This is necessary\n * because the queue shouldn't rely on another queued callback.\n */\n private async directlySetCurrentUser(\n user: UserInternal | null\n ): Promise<void> {\n if (this.currentUser && this.currentUser !== user) {\n this._currentUser._stopProactiveRefresh();\n }\n if (user && this.isProactiveRefreshEnabled) {\n user._startProactiveRefresh();\n }\n\n this.currentUser = user;\n\n if (user) {\n await this.assertedPersistence.setCurrentUser(user);\n } else {\n await this.assertedPersistence.removeCurrentUser();\n }\n }\n\n private queue(action: AsyncAction): Promise<void> {\n // In case something errors, the callback still should be called in order\n // to keep the promise chain alive\n this.operations = this.operations.then(action, action);\n return this.operations;\n }\n\n private get assertedPersistence(): PersistenceUserManager {\n _assert(this.persistenceManager, this, AuthErrorCode.INTERNAL_ERROR);\n return this.persistenceManager;\n }\n\n private frameworks: string[] = [];\n private clientVersion: string;\n _logFramework(framework: string): void {\n if (!framework || this.frameworks.includes(framework)) {\n return;\n }\n this.frameworks.push(framework);\n\n // Sort alphabetically so that \"FirebaseCore-web,FirebaseUI-web\" and\n // \"FirebaseUI-web,FirebaseCore-web\" aren't viewed as different.\n this.frameworks.sort();\n this.clientVersion = _getClientVersion(\n this.config.clientPlatform,\n this._getFrameworks()\n );\n }\n _getFrameworks(): readonly string[] {\n return this.frameworks;\n }\n async _getAdditionalHeaders(): Promise<Record<string, string>> {\n // Additional headers on every request\n const headers: Record<string, string> = {\n [HttpHeader.X_CLIENT_VERSION]: this.clientVersion\n };\n\n if (this.app.options.appId) {\n headers[HttpHeader.X_FIREBASE_GMPID] = this.app.options.appId;\n }\n\n // If the heartbeat service exists, add the heartbeat string\n const heartbeatsHeader = await this.heartbeatServiceProvider\n .getImmediate({\n optional: true\n })\n ?.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers[HttpHeader.X_FIREBASE_CLIENT] = heartbeatsHeader;\n }\n\n // If the App Check service exists, add the App Check token in the headers\n const appCheckToken = await this._getAppCheckToken();\n if (appCheckToken) {\n headers[HttpHeader.X_FIREBASE_APP_CHECK] = appCheckToken;\n }\n\n return headers;\n }\n\n async _getAppCheckToken(): Promise<string | undefined> {\n const appCheckTokenResult = await this.appCheckServiceProvider\n .getImmediate({ optional: true })\n ?.getToken();\n if (appCheckTokenResult?.error) {\n // Context: appCheck.getToken() will never throw even if an error happened.\n // In the error case, a dummy token will be returned along with an error field describing\n // the error. In general, we shouldn't care about the error condition and just use\n // the token (actual or dummy) to send requests.\n _logWarn(\n `Error while retrieving App Check token: ${appCheckTokenResult.error}`\n );\n }\n return appCheckTokenResult?.token;\n }\n}\n\n/**\n * Method to be used to cast down to our private implmentation of Auth.\n * It will also handle unwrapping from the compat type if necessary\n *\n * @param auth Auth object passed in from developer\n */\nexport function _castAuth(auth: Auth): AuthInternal {\n return getModularInstance(auth) as AuthInternal;\n}\n\n/** Helper class to wrap subscriber logic */\nclass Subscription<T> {\n private observer: Observer<T | null> | null = null;\n readonly addObserver: Subscribe<T | null> = createSubscribe(\n observer => (this.observer = observer)\n );\n\n constructor(readonly auth: AuthInternal) {}\n\n get next(): NextFn<T | null> {\n _assert(this.observer, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return this.observer.next.bind(this.observer);\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _performApiRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\n/**\n * Request object for fetching the password policy.\n */\nexport interface GetPasswordPolicyRequest {\n tenantId?: string;\n}\n\n/**\n * Response object for fetching the password policy.\n */\nexport interface GetPasswordPolicyResponse {\n customStrengthOptions: {\n minPasswordLength?: number;\n maxPasswordLength?: number;\n containsLowercaseCharacter?: boolean;\n containsUppercaseCharacter?: boolean;\n containsNumericCharacter?: boolean;\n containsNonAlphanumericCharacter?: boolean;\n };\n allowedNonAlphanumericCharacters?: string[];\n enforcementState: string;\n forceUpgradeOnSignin?: boolean;\n schemaVersion: number;\n}\n\n/**\n * Fetches the password policy for the currently set tenant or the project if no tenant is set.\n *\n * @param auth Auth object.\n * @param request Password policy request.\n * @returns Password policy response.\n */\nexport async function _getPasswordPolicy(\n auth: Auth,\n request: GetPasswordPolicyRequest = {}\n): Promise<GetPasswordPolicyResponse> {\n return _performApiRequest<\n GetPasswordPolicyRequest,\n GetPasswordPolicyResponse\n >(\n auth,\n HttpMethod.GET,\n Endpoint.GET_PASSWORD_POLICY,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../core/errors';\nimport { _createError } from '../core/util/assert';\n\nfunction getScriptParentElement(): HTMLDocument | HTMLHeadElement {\n return document.getElementsByTagName('head')?.[0] ?? document;\n}\n\nexport function _loadJS(url: string): Promise<Event> {\n // TODO: consider adding timeout support & cancellation\n return new Promise((resolve, reject) => {\n const el = document.createElement('script');\n el.setAttribute('src', url);\n el.onload = resolve;\n el.onerror = e => {\n const error = _createError(AuthErrorCode.INTERNAL_ERROR);\n error.customData = e as unknown as Record<string, unknown>;\n reject(error);\n };\n el.type = 'text/javascript';\n el.charset = 'UTF-8';\n getScriptParentElement().appendChild(el);\n });\n}\n\nexport function _generateCallbackName(prefix: string): string {\n return `__${prefix}${Math.floor(Math.random() * 1000000)}`;\n}\n","/* eslint-disable @typescript-eslint/no-require-imports */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isEnterprise, RecaptchaConfig } from './recaptcha';\nimport { getRecaptchaConfig } from '../../api/authentication/recaptcha';\nimport {\n RecaptchaClientType,\n RecaptchaVersion,\n RecaptchaActionName,\n RecaptchaProvider\n} from '../../api';\n\nimport { Auth } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport * as jsHelpers from '../load_js';\nimport { AuthErrorCode } from '../../core/errors';\n\nconst RECAPTCHA_ENTERPRISE_URL =\n 'https://www.google.com/recaptcha/enterprise.js?render=';\n\nexport const RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = 'recaptcha-enterprise';\nexport const FAKE_TOKEN = 'NO_RECAPTCHA';\n\nexport class RecaptchaEnterpriseVerifier {\n /**\n * Identifies the type of application verifier (e.g. \"recaptcha-enterprise\").\n */\n readonly type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;\n\n private readonly auth: AuthInternal;\n\n /**\n *\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\n *\n */\n constructor(authExtern: Auth) {\n this.auth = _castAuth(authExtern);\n }\n\n /**\n * Executes the verification process.\n *\n * @returns A Promise for a token that can be used to assert the validity of a request.\n */\n async verify(\n action: string = 'verify',\n forceRefresh = false\n ): Promise<string> {\n async function retrieveSiteKey(auth: AuthInternal): Promise<string> {\n if (!forceRefresh) {\n if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {\n return auth._agentRecaptchaConfig.siteKey;\n }\n if (\n auth.tenantId != null &&\n auth._tenantRecaptchaConfigs[auth.tenantId] !== undefined\n ) {\n return auth._tenantRecaptchaConfigs[auth.tenantId].siteKey;\n }\n }\n\n return new Promise<string>(async (resolve, reject) => {\n getRecaptchaConfig(auth, {\n clientType: RecaptchaClientType.WEB,\n version: RecaptchaVersion.ENTERPRISE\n })\n .then(response => {\n if (response.recaptchaKey === undefined) {\n reject(new Error('recaptcha Enterprise site key undefined'));\n } else {\n const config = new RecaptchaConfig(response);\n if (auth.tenantId == null) {\n auth._agentRecaptchaConfig = config;\n } else {\n auth._tenantRecaptchaConfigs[auth.tenantId] = config;\n }\n return resolve(config.siteKey);\n }\n })\n .catch(error => {\n reject(error);\n });\n });\n }\n\n function retrieveRecaptchaToken(\n siteKey: string,\n resolve: (value: string | PromiseLike<string>) => void,\n reject: (reason?: unknown) => void\n ): void {\n const grecaptcha = window.grecaptcha;\n if (isEnterprise(grecaptcha)) {\n grecaptcha.enterprise.ready(() => {\n grecaptcha.enterprise\n .execute(siteKey, { action })\n .then(token => {\n resolve(token);\n })\n .catch(() => {\n resolve(FAKE_TOKEN);\n });\n });\n } else {\n reject(Error('No reCAPTCHA enterprise script loaded.'));\n }\n }\n\n return new Promise<string>((resolve, reject) => {\n retrieveSiteKey(this.auth)\n .then(siteKey => {\n if (!forceRefresh && isEnterprise(window.grecaptcha)) {\n retrieveRecaptchaToken(siteKey, resolve, reject);\n } else {\n if (typeof window === 'undefined') {\n reject(\n new Error('RecaptchaVerifier is only supported in browser')\n );\n return;\n }\n jsHelpers\n ._loadJS(RECAPTCHA_ENTERPRISE_URL + siteKey)\n .then(() => {\n retrieveRecaptchaToken(siteKey, resolve, reject);\n })\n .catch(error => {\n reject(error);\n });\n }\n })\n .catch(error => {\n reject(error);\n });\n });\n }\n}\n\nexport async function injectRecaptchaFields<T>(\n auth: AuthInternal,\n request: T,\n action: RecaptchaActionName,\n captchaResp = false\n): Promise<T> {\n const verifier = new RecaptchaEnterpriseVerifier(auth);\n let captchaResponse;\n try {\n captchaResponse = await verifier.verify(action);\n } catch (error) {\n captchaResponse = await verifier.verify(action, true);\n }\n const newRequest = { ...request };\n if (!captchaResp) {\n Object.assign(newRequest, { captchaResponse });\n } else {\n Object.assign(newRequest, { 'captchaResp': captchaResponse });\n }\n Object.assign(newRequest, { 'clientType': RecaptchaClientType.WEB });\n Object.assign(newRequest, {\n 'recaptchaVersion': RecaptchaVersion.ENTERPRISE\n });\n return newRequest;\n}\n\ntype ActionMethod<TRequest, TResponse> = (\n auth: Auth,\n request: TRequest\n) => Promise<TResponse>;\n\nexport async function handleRecaptchaFlow<TRequest, TResponse>(\n authInstance: AuthInternal,\n request: TRequest,\n actionName: RecaptchaActionName,\n actionMethod: ActionMethod<TRequest, TResponse>\n): Promise<TResponse> {\n if (\n authInstance\n ._getRecaptchaConfig()\n ?.isProviderEnabled(RecaptchaProvider.EMAIL_PASSWORD_PROVIDER)\n ) {\n const requestWithRecaptcha = await injectRecaptchaFields(\n authInstance,\n request,\n actionName,\n actionName === RecaptchaActionName.GET_OOB_CODE\n );\n return actionMethod(authInstance, requestWithRecaptcha);\n } else {\n return actionMethod(authInstance, request).catch(async error => {\n if (error.code === `auth/${AuthErrorCode.MISSING_RECAPTCHA_TOKEN}`) {\n console.log(\n `${actionName} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`\n );\n const requestWithRecaptcha = await injectRecaptchaFields(\n authInstance,\n request,\n actionName,\n actionName === RecaptchaActionName.GET_OOB_CODE\n );\n return actionMethod(authInstance, requestWithRecaptcha);\n } else {\n return Promise.reject(error);\n }\n });\n }\n}\n\nexport async function _initializeRecaptchaConfig(auth: Auth): Promise<void> {\n const authInternal = _castAuth(auth);\n\n const response = await getRecaptchaConfig(authInternal, {\n clientType: RecaptchaClientType.WEB,\n version: RecaptchaVersion.ENTERPRISE\n });\n\n const config = new RecaptchaConfig(response);\n if (authInternal.tenantId == null) {\n authInternal._agentRecaptchaConfig = config;\n } else {\n authInternal._tenantRecaptchaConfigs[authInternal.tenantId] = config;\n }\n\n if (config.isProviderEnabled(RecaptchaProvider.EMAIL_PASSWORD_PROVIDER)) {\n const verifier = new RecaptchaEnterpriseVerifier(authInternal);\n void verifier.verify();\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Auth } from '../../model/public_types';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _castAuth } from './auth_impl';\n\n/**\n * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production\n * Firebase Auth services.\n *\n * @remarks\n * This must be called synchronously immediately following the first call to\n * {@link initializeAuth}. Do not use with production credentials as emulator\n * traffic is not encrypted.\n *\n *\n * @example\n * ```javascript\n * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').\n * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to\n * `true` to disable the warning banner attached to the DOM.\n *\n * @public\n */\nexport function connectAuthEmulator(\n auth: Auth,\n url: string,\n options?: { disableWarnings: boolean }\n): void {\n const authInternal = _castAuth(auth);\n _assert(\n authInternal._canInitEmulator,\n authInternal,\n AuthErrorCode.EMULATOR_CONFIG_FAILED\n );\n\n _assert(\n /^https?:\\/\\//.test(url),\n authInternal,\n AuthErrorCode.INVALID_EMULATOR_SCHEME\n );\n\n const disableWarnings = !!options?.disableWarnings;\n\n const protocol = extractProtocol(url);\n const { host, port } = extractHostAndPort(url);\n const portStr = port === null ? '' : `:${port}`;\n\n // Always replace path with \"/\" (even if input url had no path at all, or had a different one).\n authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };\n authInternal.settings.appVerificationDisabledForTesting = true;\n authInternal.emulatorConfig = Object.freeze({\n host,\n port,\n protocol: protocol.replace(':', ''),\n options: Object.freeze({ disableWarnings })\n });\n\n if (!disableWarnings) {\n emitEmulatorWarning();\n }\n}\n\nfunction extractProtocol(url: string): string {\n const protocolEnd = url.indexOf(':');\n return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);\n}\n\nfunction extractHostAndPort(url: string): {\n host: string;\n port: number | null;\n} {\n const protocol = extractProtocol(url);\n const authority = /(\\/\\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.\n if (!authority) {\n return { host: '', port: null };\n }\n const hostAndPort = authority[2].split('@').pop() || ''; // Strip out \"username:password@\".\n const bracketedIPv6 = /^(\\[[^\\]]+\\])(:|$)/.exec(hostAndPort);\n if (bracketedIPv6) {\n const host = bracketedIPv6[1];\n return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };\n } else {\n const [host, port] = hostAndPort.split(':');\n return { host, port: parsePort(port) };\n }\n}\n\nfunction parsePort(portStr: string): number | null {\n if (!portStr) {\n return null;\n }\n const port = Number(portStr);\n if (isNaN(port)) {\n return null;\n }\n return port;\n}\n\nfunction emitEmulatorWarning(): void {\n function attachBanner(): void {\n const el = document.createElement('p');\n const sty = el.style;\n el.innerText =\n 'Running in emulator mode. Do not use with production credentials.';\n sty.position = 'fixed';\n sty.width = '100%';\n sty.backgroundColor = '#ffffff';\n sty.border = '.1em solid #000000';\n sty.color = '#b50000';\n sty.bottom = '0px';\n sty.left = '0px';\n sty.margin = '0px';\n sty.zIndex = '10000';\n sty.textAlign = 'center';\n el.classList.add('firebase-emulator-warning');\n document.body.appendChild(el);\n }\n\n if (typeof console !== 'undefined' && typeof console.info === 'function') {\n console.info(\n 'WARNING: You are using the Auth Emulator,' +\n ' which is intended for local testing only. Do not use with' +\n ' production credentials.'\n );\n }\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n if (document.readyState === 'loading') {\n window.addEventListener('DOMContentLoaded', attachBanner);\n } else {\n attachBanner();\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { debugFail } from '../util/assert';\n\n/**\n * Interface that represents the credentials returned by an {@link AuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nexport class AuthCredential {\n /** @internal */\n protected constructor(\n /**\n * The authentication provider ID for the credential.\n *\n * @remarks\n * For example, 'facebook.com', or 'google.com'.\n */\n readonly providerId: string,\n /**\n * The authentication sign in method for the credential.\n *\n * @remarks\n * For example, {@link SignInMethod}.EMAIL_PASSWORD, or\n * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method\n * identifier as returned in {@link fetchSignInMethodsForEmail}.\n */\n readonly signInMethod: string\n ) {}\n\n /**\n * Returns a JSON-serializable representation of this object.\n *\n * @returns a JSON-serializable representation of this object.\n */\n toJSON(): object {\n return debugFail('not implemented');\n }\n\n /** @internal */\n _getIdTokenResponse(_auth: AuthInternal): Promise<PhoneOrOauthTokenResponse> {\n return debugFail('not implemented');\n }\n /** @internal */\n _linkToIdToken(\n _auth: AuthInternal,\n _idToken: string\n ): Promise<IdTokenResponse> {\n return debugFail('not implemented');\n }\n /** @internal */\n _getReauthenticationResolver(_auth: AuthInternal): Promise<IdTokenResponse> {\n return debugFail('not implemented');\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActionCodeOperation, Auth } from '../../model/public_types';\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { MfaEnrollment } from './mfa';\nimport { SignUpRequest, SignUpResponse } from '../authentication/sign_up';\n\nexport interface ResetPasswordRequest {\n oobCode: string;\n newPassword?: string;\n tenantId?: string;\n}\n\nexport interface ResetPasswordResponse {\n email: string;\n newEmail?: string;\n requestType?: ActionCodeOperation;\n mfaInfo?: MfaEnrollment;\n}\n\nexport async function resetPassword(\n auth: Auth,\n request: ResetPasswordRequest\n): Promise<ResetPasswordResponse> {\n return _performApiRequest<ResetPasswordRequest, ResetPasswordResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.RESET_PASSWORD,\n _addTidIfNecessary(auth, request)\n );\n}\nexport interface UpdateEmailPasswordRequest {\n idToken: string;\n returnSecureToken?: boolean;\n email?: string;\n password?: string;\n}\n\nexport interface UpdateEmailPasswordResponse extends IdTokenResponse {}\n\nexport async function updateEmailPassword(\n auth: Auth,\n request: UpdateEmailPasswordRequest\n): Promise<UpdateEmailPasswordResponse> {\n return _performApiRequest<\n UpdateEmailPasswordRequest,\n UpdateEmailPasswordResponse\n >(auth, HttpMethod.POST, Endpoint.SET_ACCOUNT_INFO, request);\n}\n\n// Used for linking an email/password account to an existing idToken. Uses the same request/response\n// format as updateEmailPassword.\nexport async function linkEmailPassword(\n auth: Auth,\n request: SignUpRequest\n): Promise<SignUpResponse> {\n return _performApiRequest<SignUpRequest, SignUpResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_UP,\n request\n );\n}\n\nexport interface ApplyActionCodeRequest {\n oobCode: string;\n tenantId?: string;\n}\n\nexport interface ApplyActionCodeResponse {}\n\nexport async function applyActionCode(\n auth: Auth,\n request: ApplyActionCodeRequest\n): Promise<ApplyActionCodeResponse> {\n return _performApiRequest<ApplyActionCodeRequest, ApplyActionCodeResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SET_ACCOUNT_INFO,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActionCodeOperation, Auth } from '../../model/public_types';\n\nimport {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _addTidIfNecessary,\n _performApiRequest,\n _performSignInRequest\n} from '../index';\nimport { IdToken, IdTokenResponse } from '../../model/id_token';\n\nexport interface SignInWithPasswordRequest {\n returnSecureToken?: boolean;\n email: string;\n password: string;\n tenantId?: string;\n captchaResponse?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface SignInWithPasswordResponse extends IdTokenResponse {\n email: string;\n displayName: string;\n}\n\nexport async function signInWithPassword(\n auth: Auth,\n request: SignInWithPasswordRequest\n): Promise<SignInWithPasswordResponse> {\n return _performSignInRequest<\n SignInWithPasswordRequest,\n SignInWithPasswordResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PASSWORD,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface GetOobCodeRequest {\n email?: string; // Everything except VERIFY_AND_CHANGE_EMAIL\n continueUrl?: string;\n iOSBundleId?: string;\n iosAppStoreId?: string;\n androidPackageName?: string;\n androidInstallApp?: boolean;\n androidMinimumVersionCode?: string;\n canHandleCodeInApp?: boolean;\n dynamicLinkDomain?: string;\n tenantId?: string;\n targetProjectid?: string;\n}\n\nexport interface VerifyEmailRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.VERIFY_EMAIL;\n idToken: IdToken;\n}\n\nexport interface PasswordResetRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.PASSWORD_RESET;\n email: string;\n captchaResp?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface EmailSignInRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.EMAIL_SIGNIN;\n email: string;\n captchaResp?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface VerifyAndChangeEmailRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL;\n idToken: IdToken;\n newEmail: string;\n}\n\ninterface GetOobCodeResponse {\n email: string;\n}\n\nexport interface VerifyEmailResponse extends GetOobCodeResponse {}\nexport interface PasswordResetResponse extends GetOobCodeResponse {}\nexport interface EmailSignInResponse extends GetOobCodeResponse {}\nexport interface VerifyAndChangeEmailResponse extends GetOobCodeRequest {}\n\nasync function sendOobCode(\n auth: Auth,\n request: GetOobCodeRequest\n): Promise<GetOobCodeResponse> {\n return _performApiRequest<GetOobCodeRequest, GetOobCodeResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SEND_OOB_CODE,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport async function sendEmailVerification(\n auth: Auth,\n request: VerifyEmailRequest\n): Promise<VerifyEmailResponse> {\n return sendOobCode(auth, request);\n}\n\nexport async function sendPasswordResetEmail(\n auth: Auth,\n request: PasswordResetRequest\n): Promise<PasswordResetResponse> {\n return sendOobCode(auth, request);\n}\n\nexport async function sendSignInLinkToEmail(\n auth: Auth,\n request: EmailSignInRequest\n): Promise<EmailSignInResponse> {\n return sendOobCode(auth, request);\n}\n\nexport async function verifyAndChangeEmail(\n auth: Auth,\n request: VerifyAndChangeEmailRequest\n): Promise<VerifyAndChangeEmailResponse> {\n return sendOobCode(auth, request);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\nimport { linkEmailPassword } from '../../api/account_management/email_and_password';\nimport {\n signInWithPassword,\n SignInWithPasswordRequest\n} from '../../api/authentication/email_and_password';\nimport {\n signInWithEmailLink,\n signInWithEmailLinkForLinking\n} from '../../api/authentication/email_link';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from '../util/assert';\nimport { AuthCredential } from './auth_credential';\nimport { handleRecaptchaFlow } from '../../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { RecaptchaActionName, RecaptchaClientType } from '../../api';\nimport { SignUpRequest } from '../../api/authentication/sign_up';\n/**\n * Interface that represents the credentials returned by {@link EmailAuthProvider} for\n * {@link ProviderId}.PASSWORD\n *\n * @remarks\n * Covers both {@link SignInMethod}.EMAIL_PASSWORD and\n * {@link SignInMethod}.EMAIL_LINK.\n *\n * @public\n */\nexport class EmailAuthCredential extends AuthCredential {\n /** @internal */\n private constructor(\n /** @internal */\n readonly _email: string,\n /** @internal */\n readonly _password: string,\n signInMethod: SignInMethod,\n /** @internal */\n readonly _tenantId: string | null = null\n ) {\n super(ProviderId.PASSWORD, signInMethod);\n }\n\n /** @internal */\n static _fromEmailAndPassword(\n email: string,\n password: string\n ): EmailAuthCredential {\n return new EmailAuthCredential(\n email,\n password,\n SignInMethod.EMAIL_PASSWORD\n );\n }\n\n /** @internal */\n static _fromEmailAndCode(\n email: string,\n oobCode: string,\n tenantId: string | null = null\n ): EmailAuthCredential {\n return new EmailAuthCredential(\n email,\n oobCode,\n SignInMethod.EMAIL_LINK,\n tenantId\n );\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n email: this._email,\n password: this._password,\n signInMethod: this.signInMethod,\n tenantId: this._tenantId\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.\n *\n * @param json - Either `object` or the stringified representation of the object. When string is\n * provided, `JSON.parse` would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: object | string): EmailAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n if (obj?.email && obj?.password) {\n if (obj.signInMethod === SignInMethod.EMAIL_PASSWORD) {\n return this._fromEmailAndPassword(obj.email, obj.password);\n } else if (obj.signInMethod === SignInMethod.EMAIL_LINK) {\n return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);\n }\n }\n return null;\n }\n\n /** @internal */\n async _getIdTokenResponse(auth: AuthInternal): Promise<IdTokenResponse> {\n switch (this.signInMethod) {\n case SignInMethod.EMAIL_PASSWORD:\n const request: SignInWithPasswordRequest = {\n returnSecureToken: true,\n email: this._email,\n password: this._password,\n clientType: RecaptchaClientType.WEB\n };\n return handleRecaptchaFlow(\n auth,\n request,\n RecaptchaActionName.SIGN_IN_WITH_PASSWORD,\n signInWithPassword\n );\n case SignInMethod.EMAIL_LINK:\n return signInWithEmailLink(auth, {\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n /** @internal */\n async _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n switch (this.signInMethod) {\n case SignInMethod.EMAIL_PASSWORD:\n const request: SignUpRequest = {\n idToken,\n returnSecureToken: true,\n email: this._email,\n password: this._password,\n clientType: RecaptchaClientType.WEB\n };\n return handleRecaptchaFlow(\n auth,\n request,\n RecaptchaActionName.SIGN_UP_PASSWORD,\n linkEmailPassword\n );\n case SignInMethod.EMAIL_LINK:\n return signInWithEmailLinkForLinking(auth, {\n idToken,\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n return this._getIdTokenResponse(auth);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _performSignInRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithEmailLinkRequest {\n email: string;\n oobCode: string;\n tenantId?: string;\n}\n\nexport interface SignInWithEmailLinkResponse extends IdTokenResponse {\n email: string;\n isNewUser: boolean;\n}\n\nexport async function signInWithEmailLink(\n auth: Auth,\n request: SignInWithEmailLinkRequest\n): Promise<SignInWithEmailLinkResponse> {\n return _performSignInRequest<\n SignInWithEmailLinkRequest,\n SignInWithEmailLinkResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_EMAIL_LINK,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface SignInWithEmailLinkForLinkingRequest\n extends SignInWithEmailLinkRequest {\n idToken: string;\n}\n\nexport async function signInWithEmailLinkForLinking(\n auth: Auth,\n request: SignInWithEmailLinkForLinkingRequest\n): Promise<SignInWithEmailLinkResponse> {\n return _performSignInRequest<\n SignInWithEmailLinkForLinkingRequest,\n SignInWithEmailLinkResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_EMAIL_LINK,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdToken, IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithIdpRequest {\n requestUri: string;\n postBody?: string;\n sessionId?: string;\n tenantId?: string;\n returnSecureToken: boolean;\n returnIdpCredential?: boolean;\n idToken?: IdToken;\n autoCreate?: boolean;\n pendingToken?: string;\n}\n\n/**\n * @internal\n */\nexport interface SignInWithIdpResponse extends IdTokenResponse {\n oauthAccessToken?: string;\n oauthTokenSecret?: string;\n nonce?: string;\n oauthIdToken?: string;\n pendingToken?: string;\n}\n\nexport async function signInWithIdp(\n auth: Auth,\n request: SignInWithIdpRequest\n): Promise<SignInWithIdpResponse> {\n return _performSignInRequest<SignInWithIdpRequest, SignInWithIdpResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_IDP,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { querystring } from '@firebase/util';\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from '../util/assert';\nimport { AuthCredential } from './auth_credential';\n\nconst IDP_REQUEST_URI = 'http://localhost';\n\nexport interface OAuthCredentialParams {\n // OAuth 2 uses either id token or access token\n idToken?: string | null;\n accessToken?: string | null;\n\n // These fields are used with OAuth 1\n oauthToken?: string;\n secret?: string;\n oauthTokenSecret?: string;\n\n // Nonce is only set if pendingToken is not present\n nonce?: string;\n pendingToken?: string;\n\n // Utilities\n providerId: string;\n signInMethod: string;\n}\n\n/**\n * Represents the OAuth credentials returned by an {@link OAuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nexport class OAuthCredential extends AuthCredential {\n /**\n * The OAuth ID token associated with the credential if it belongs to an OIDC provider,\n * such as `google.com`.\n * @readonly\n */\n idToken?: string;\n /**\n * The OAuth access token associated with the credential if it belongs to an\n * {@link OAuthProvider}, such as `facebook.com`, `twitter.com`, etc.\n * @readonly\n */\n accessToken?: string;\n /**\n * The OAuth access token secret associated with the credential if it belongs to an OAuth 1.0\n * provider, such as `twitter.com`.\n * @readonly\n */\n secret?: string;\n\n private nonce?: string;\n private pendingToken: string | null = null;\n\n /** @internal */\n static _fromParams(params: OAuthCredentialParams): OAuthCredential {\n const cred = new OAuthCredential(params.providerId, params.signInMethod);\n\n if (params.idToken || params.accessToken) {\n // OAuth 2 and either ID token or access token.\n if (params.idToken) {\n cred.idToken = params.idToken;\n }\n\n if (params.accessToken) {\n cred.accessToken = params.accessToken;\n }\n\n // Add nonce if available and no pendingToken is present.\n if (params.nonce && !params.pendingToken) {\n cred.nonce = params.nonce;\n }\n\n if (params.pendingToken) {\n cred.pendingToken = params.pendingToken;\n }\n } else if (params.oauthToken && params.oauthTokenSecret) {\n // OAuth 1 and OAuth token with token secret\n cred.accessToken = params.oauthToken;\n cred.secret = params.oauthTokenSecret;\n } else {\n _fail(AuthErrorCode.ARGUMENT_ERROR);\n }\n\n return cred;\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n idToken: this.idToken,\n accessToken: this.accessToken,\n secret: this.secret,\n nonce: this.nonce,\n pendingToken: this.pendingToken,\n providerId: this.providerId,\n signInMethod: this.signInMethod\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an\n * {@link AuthCredential}.\n *\n * @param json - Input can be either Object or the stringified representation of the object.\n * When string is provided, JSON.parse would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: string | object): OAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n const { providerId, signInMethod, ...rest }: OAuthCredentialParams = obj;\n if (!providerId || !signInMethod) {\n return null;\n }\n\n const cred = new OAuthCredential(providerId, signInMethod);\n cred.idToken = rest.idToken || undefined;\n cred.accessToken = rest.accessToken || undefined;\n cred.secret = rest.secret;\n cred.nonce = rest.nonce;\n cred.pendingToken = rest.pendingToken || null;\n return cred;\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n request.idToken = idToken;\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n request.autoCreate = false;\n return signInWithIdp(auth, request);\n }\n\n private buildRequest(): SignInWithIdpRequest {\n const request: SignInWithIdpRequest = {\n requestUri: IDP_REQUEST_URI,\n returnSecureToken: true\n };\n\n if (this.pendingToken) {\n request.pendingToken = this.pendingToken;\n } else {\n const postBody: Record<string, string> = {};\n if (this.idToken) {\n postBody['id_token'] = this.idToken;\n }\n if (this.accessToken) {\n postBody['access_token'] = this.accessToken;\n }\n if (this.secret) {\n postBody['oauth_token_secret'] = this.secret;\n }\n\n postBody['providerId'] = this.providerId;\n if (this.nonce && !this.pendingToken) {\n postBody['nonce'] = this.nonce;\n }\n\n request.postBody = querystring(postBody);\n }\n\n return request;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _makeTaggedError,\n _performApiRequest,\n _performSignInRequest\n} from '../index';\nimport { AuthErrorCode } from '../../core/errors';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { ServerError, ServerErrorMap } from '../errors';\nimport { Auth } from '../../model/public_types';\n\nexport interface SendPhoneVerificationCodeRequest {\n phoneNumber: string;\n recaptchaToken: string;\n tenantId?: string;\n}\n\nexport interface SendPhoneVerificationCodeResponse {\n sessionInfo: string;\n}\n\nexport async function sendPhoneVerificationCode(\n auth: Auth,\n request: SendPhoneVerificationCodeRequest\n): Promise<SendPhoneVerificationCodeResponse> {\n return _performApiRequest<\n SendPhoneVerificationCodeRequest,\n SendPhoneVerificationCodeResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SEND_VERIFICATION_CODE,\n _addTidIfNecessary(auth, request)\n );\n}\n\n/**\n * @internal\n */\nexport interface SignInWithPhoneNumberRequest {\n temporaryProof?: string;\n phoneNumber?: string;\n sessionInfo?: string;\n code?: string;\n tenantId?: string;\n}\n\nexport interface LinkWithPhoneNumberRequest\n extends SignInWithPhoneNumberRequest {\n idToken: string;\n}\n\n/**\n * @internal\n */\nexport interface SignInWithPhoneNumberResponse extends IdTokenResponse {\n temporaryProof?: string;\n phoneNumber?: string;\n}\n\nexport async function signInWithPhoneNumber(\n auth: Auth,\n request: SignInWithPhoneNumberRequest\n): Promise<SignInWithPhoneNumberResponse> {\n return _performSignInRequest<\n SignInWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport async function linkWithPhoneNumber(\n auth: Auth,\n request: LinkWithPhoneNumberRequest\n): Promise<SignInWithPhoneNumberResponse> {\n const response = await _performSignInRequest<\n LinkWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, request)\n );\n if (response.temporaryProof) {\n throw _makeTaggedError(auth, AuthErrorCode.NEED_CONFIRMATION, response);\n }\n return response;\n}\n\ninterface VerifyPhoneNumberForExistingRequest\n extends SignInWithPhoneNumberRequest {\n operation: 'REAUTH';\n}\n\nconst VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_: Partial<\n ServerErrorMap<ServerError>\n> = {\n [ServerError.USER_NOT_FOUND]: AuthErrorCode.USER_DELETED\n};\n\nexport async function verifyPhoneNumberForExisting(\n auth: Auth,\n request: SignInWithPhoneNumberRequest\n): Promise<SignInWithPhoneNumberResponse> {\n const apiRequest: VerifyPhoneNumberForExistingRequest = {\n ...request,\n operation: 'REAUTH'\n };\n return _performSignInRequest<\n VerifyPhoneNumberForExistingRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, apiRequest),\n VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport {\n linkWithPhoneNumber,\n signInWithPhoneNumber,\n SignInWithPhoneNumberRequest,\n verifyPhoneNumberForExisting\n} from '../../api/authentication/sms';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthCredential } from './auth_credential';\n\nexport interface PhoneAuthCredentialParameters {\n verificationId?: string;\n verificationCode?: string;\n phoneNumber?: string;\n temporaryProof?: string;\n}\n\n/**\n * Represents the credentials returned by {@link PhoneAuthProvider}.\n *\n * @public\n */\nexport class PhoneAuthCredential extends AuthCredential {\n private constructor(private readonly params: PhoneAuthCredentialParameters) {\n super(ProviderId.PHONE, SignInMethod.PHONE);\n }\n\n /** @internal */\n static _fromVerification(\n verificationId: string,\n verificationCode: string\n ): PhoneAuthCredential {\n return new PhoneAuthCredential({ verificationId, verificationCode });\n }\n\n /** @internal */\n static _fromTokenResponse(\n phoneNumber: string,\n temporaryProof: string\n ): PhoneAuthCredential {\n return new PhoneAuthCredential({ phoneNumber, temporaryProof });\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise<PhoneOrOauthTokenResponse> {\n return signInWithPhoneNumber(auth, this._makeVerificationRequest());\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n return linkWithPhoneNumber(auth, {\n idToken,\n ...this._makeVerificationRequest()\n });\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());\n }\n\n /** @internal */\n _makeVerificationRequest(): SignInWithPhoneNumberRequest {\n const { temporaryProof, phoneNumber, verificationId, verificationCode } =\n this.params;\n if (temporaryProof && phoneNumber) {\n return { temporaryProof, phoneNumber };\n }\n\n return {\n sessionInfo: verificationId,\n code: verificationCode\n };\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n const obj: Record<string, string> = {\n providerId: this.providerId\n };\n if (this.params.phoneNumber) {\n obj.phoneNumber = this.params.phoneNumber;\n }\n if (this.params.temporaryProof) {\n obj.temporaryProof = this.params.temporaryProof;\n }\n if (this.params.verificationCode) {\n obj.verificationCode = this.params.verificationCode;\n }\n if (this.params.verificationId) {\n obj.verificationId = this.params.verificationId;\n }\n\n return obj;\n }\n\n /** Generates a phone credential based on a plain object or a JSON string. */\n static fromJSON(json: object | string): PhoneAuthCredential | null {\n if (typeof json === 'string') {\n json = JSON.parse(json);\n }\n\n const { verificationId, verificationCode, phoneNumber, temporaryProof } =\n json as { [key: string]: string };\n if (\n !verificationCode &&\n !verificationId &&\n !phoneNumber &&\n !temporaryProof\n ) {\n return null;\n }\n\n return new PhoneAuthCredential({\n verificationId,\n verificationCode,\n phoneNumber,\n temporaryProof\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { extractQuerystring, querystringDecode } from '@firebase/util';\nimport { ActionCodeOperation } from '../model/public_types';\nimport { AuthErrorCode } from './errors';\nimport { _assert } from './util/assert';\n\n/**\n * Enums for fields in URL query string.\n *\n * @enum {string}\n */\nconst enum QueryField {\n API_KEY = 'apiKey',\n CODE = 'oobCode',\n CONTINUE_URL = 'continueUrl',\n LANGUAGE_CODE = 'languageCode',\n MODE = 'mode',\n TENANT_ID = 'tenantId'\n}\n\n/**\n * Maps the mode string in action code URL to Action Code Info operation.\n *\n * @param mode\n */\nfunction parseMode(mode: string | null): ActionCodeOperation | null {\n switch (mode) {\n case 'recoverEmail':\n return ActionCodeOperation.RECOVER_EMAIL;\n case 'resetPassword':\n return ActionCodeOperation.PASSWORD_RESET;\n case 'signIn':\n return ActionCodeOperation.EMAIL_SIGNIN;\n case 'verifyEmail':\n return ActionCodeOperation.VERIFY_EMAIL;\n case 'verifyAndChangeEmail':\n return ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL;\n case 'revertSecondFactorAddition':\n return ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION;\n default:\n return null;\n }\n}\n\n/**\n * Helper to parse FDL links\n *\n * @param url\n */\nfunction parseDeepLink(url: string): string {\n const link = querystringDecode(extractQuerystring(url))['link'];\n\n // Double link case (automatic redirect).\n const doubleDeepLink = link\n ? querystringDecode(extractQuerystring(link))['deep_link_id']\n : null;\n // iOS custom scheme links.\n const iOSDeepLink = querystringDecode(extractQuerystring(url))[\n 'deep_link_id'\n ];\n const iOSDoubleDeepLink = iOSDeepLink\n ? querystringDecode(extractQuerystring(iOSDeepLink))['link']\n : null;\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\n}\n\n/**\n * A utility class to parse email action URLs such as password reset, email verification,\n * email link sign in, etc.\n *\n * @public\n */\nexport class ActionCodeURL {\n /**\n * The API key of the email action link.\n */\n readonly apiKey: string;\n /**\n * The action code of the email action link.\n */\n readonly code: string;\n /**\n * The continue URL of the email action link. Null if not provided.\n */\n readonly continueUrl: string | null;\n /**\n * The language code of the email action link. Null if not provided.\n */\n readonly languageCode: string | null;\n /**\n * The action performed by the email action link. It returns from one of the types from\n * {@link ActionCodeInfo}\n */\n readonly operation: string;\n /**\n * The tenant ID of the email action link. Null if the email action is from the parent project.\n */\n readonly tenantId: string | null;\n\n /**\n * @param actionLink - The link from which to extract the URL.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @internal\n */\n constructor(actionLink: string) {\n const searchParams = querystringDecode(extractQuerystring(actionLink));\n const apiKey = searchParams[QueryField.API_KEY] ?? null;\n const code = searchParams[QueryField.CODE] ?? null;\n const operation = parseMode(searchParams[QueryField.MODE] ?? null);\n // Validate API key, code and mode.\n _assert(apiKey && code && operation, AuthErrorCode.ARGUMENT_ERROR);\n this.apiKey = apiKey;\n this.operation = operation;\n this.code = code;\n this.continueUrl = searchParams[QueryField.CONTINUE_URL] ?? null;\n this.languageCode = searchParams[QueryField.LANGUAGE_CODE] ?? null;\n this.tenantId = searchParams[QueryField.TENANT_ID] ?? null;\n }\n\n /**\n * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,\n * otherwise returns null.\n *\n * @param link - The email action link string.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @public\n */\n static parseLink(link: string): ActionCodeURL | null {\n const actionLink = parseDeepLink(link);\n try {\n return new ActionCodeURL(actionLink);\n } catch {\n return null;\n }\n }\n}\n\n/**\n * Parses the email action link string and returns an {@link ActionCodeURL} if\n * the link is valid, otherwise returns null.\n *\n * @public\n */\nexport function parseActionCodeURL(link: string): ActionCodeURL | null {\n return ActionCodeURL.parseLink(link);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\nimport { AuthProvider } from '../../model/public_types';\n\nimport { ActionCodeURL } from '../action_code_url';\nimport { EmailAuthCredential } from '../credentials/email';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\n\n/**\n * Provider for generating {@link EmailAuthCredential}.\n *\n * @public\n */\nexport class EmailAuthProvider implements AuthProvider {\n /**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\n static readonly PROVIDER_ID: 'password' = ProviderId.PASSWORD;\n /**\n * Always set to {@link SignInMethod}.EMAIL_PASSWORD.\n */\n static readonly EMAIL_PASSWORD_SIGN_IN_METHOD: 'password' =\n SignInMethod.EMAIL_PASSWORD;\n /**\n * Always set to {@link SignInMethod}.EMAIL_LINK.\n */\n static readonly EMAIL_LINK_SIGN_IN_METHOD: 'emailLink' =\n SignInMethod.EMAIL_LINK;\n /**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\n readonly providerId = EmailAuthProvider.PROVIDER_ID;\n\n /**\n * Initialize an {@link AuthCredential} using an email and password.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credential(email, password);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * const userCredential = await signInWithEmailAndPassword(auth, email, password);\n * ```\n *\n * @param email - Email address.\n * @param password - User account password.\n * @returns The auth provider credential.\n */\n static credential(email: string, password: string): EmailAuthCredential {\n return EmailAuthCredential._fromEmailAndPassword(email, password);\n }\n\n /**\n * Initialize an {@link AuthCredential} using an email and an email link after a sign in with\n * email link operation.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * await sendSignInLinkToEmail(auth, email);\n * // Obtain emailLink from user.\n * const userCredential = await signInWithEmailLink(auth, email, emailLink);\n * ```\n *\n * @param auth - The {@link Auth} instance used to verify the link.\n * @param email - Email address.\n * @param emailLink - Sign-in email link.\n * @returns - The auth provider credential.\n */\n static credentialWithLink(\n email: string,\n emailLink: string\n ): EmailAuthCredential {\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\n _assert(actionCodeUrl, AuthErrorCode.ARGUMENT_ERROR);\n\n return EmailAuthCredential._fromEmailAndCode(\n email,\n actionCodeUrl.code,\n actionCodeUrl.tenantId\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider } from '../../model/public_types';\n\n/**\n * Map of OAuth Custom Parameters.\n *\n * @public\n */\nexport type CustomParameters = Record<string, string>;\n\n/**\n * The base class for all Federated providers (OAuth (including OIDC), SAML).\n *\n * This class is not meant to be instantiated directly.\n *\n * @public\n */\nexport abstract class FederatedAuthProvider implements AuthProvider {\n /** @internal */\n defaultLanguageCode: string | null = null;\n /** @internal */\n private customParameters: CustomParameters = {};\n\n /**\n * Constructor for generic OAuth providers.\n *\n * @param providerId - Provider for which credentials should be generated.\n */\n constructor(readonly providerId: string) {}\n\n /**\n * Set the language gode.\n *\n * @param languageCode - language code\n */\n setDefaultLanguage(languageCode: string | null): void {\n this.defaultLanguageCode = languageCode;\n }\n\n /**\n * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in\n * operations.\n *\n * @remarks\n * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,\n * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.\n *\n * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.\n */\n setCustomParameters(customOAuthParameters: CustomParameters): AuthProvider {\n this.customParameters = customOAuthParameters;\n return this;\n }\n\n /**\n * Retrieve the current list of {@link CustomParameters}.\n */\n getCustomParameters(): CustomParameters {\n return this.customParameters;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider, UserCredential } from '../../model/public_types';\n\nimport { _assert } from '../util/assert';\nimport { AuthErrorCode } from '../errors';\n\nimport { OAuthCredential, OAuthCredentialParams } from '../credentials/oauth';\nimport { UserCredentialInternal } from '../../model/user';\nimport { FirebaseError } from '@firebase/util';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { SignInWithIdpResponse } from '../../../internal';\nimport { FederatedAuthProvider } from './federated';\n\n/**\n * Defines the options for initializing an {@link OAuthCredential}.\n *\n * @remarks\n * For ID tokens with nonce claim, the raw nonce has to also be provided.\n *\n * @public\n */\nexport interface OAuthCredentialOptions {\n /**\n * The OAuth ID token used to initialize the {@link OAuthCredential}.\n */\n idToken?: string;\n /**\n * The OAuth access token used to initialize the {@link OAuthCredential}.\n */\n accessToken?: string;\n /**\n * The raw nonce associated with the ID token.\n *\n * @remarks\n * It is required when an ID token with a nonce field is provided. The SHA-256 hash of the\n * raw nonce must match the nonce field in the ID token.\n */\n rawNonce?: string;\n}\n\n/**\n * Common code to all OAuth providers. This is separate from the\n * {@link OAuthProvider} so that child providers (like\n * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.\n * Instead, they rely on a static `credential` method.\n */\nexport abstract class BaseOAuthProvider\n extends FederatedAuthProvider\n implements AuthProvider\n{\n /** @internal */\n private scopes: string[] = [];\n\n /**\n * Add an OAuth scope to the credential.\n *\n * @param scope - Provider OAuth scope to add.\n */\n addScope(scope: string): AuthProvider {\n // If not already added, add scope to list.\n if (!this.scopes.includes(scope)) {\n this.scopes.push(scope);\n }\n return this;\n }\n\n /**\n * Retrieve the current list of OAuth scopes.\n */\n getScopes(): string[] {\n return [...this.scopes];\n }\n}\n\n/**\n * Provider for generating generic {@link OAuthCredential}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new OAuthProvider('google.com');\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new OAuthProvider('google.com');\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nexport class OAuthProvider extends BaseOAuthProvider {\n /**\n * Creates an {@link OAuthCredential} from a JSON string or a plain object.\n * @param json - A plain object or a JSON string\n */\n static credentialFromJSON(json: object | string): OAuthCredential {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n _assert(\n 'providerId' in obj && 'signInMethod' in obj,\n AuthErrorCode.ARGUMENT_ERROR\n );\n return OAuthCredential._fromParams(obj);\n }\n\n /**\n * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.\n *\n * @remarks\n * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of\n * the raw nonce must match the nonce field in the ID token.\n *\n * @example\n * ```javascript\n * // `googleUser` from the onsuccess Google Sign In callback.\n * // Initialize a generate OAuth provider with a `google.com` providerId.\n * const provider = new OAuthProvider('google.com');\n * const credential = provider.credential({\n * idToken: googleUser.getAuthResponse().id_token,\n * });\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param params - Either the options object containing the ID token, access token and raw nonce\n * or the ID token string.\n */\n credential(params: OAuthCredentialOptions): OAuthCredential {\n return this._credential({ ...params, nonce: params.rawNonce });\n }\n\n /** An internal credential method that accepts more permissive options */\n private _credential(\n params: Omit<OAuthCredentialParams, 'signInMethod' | 'providerId'>\n ): OAuthCredential {\n _assert(params.idToken || params.accessToken, AuthErrorCode.ARGUMENT_ERROR);\n // For OAuthCredential, sign in method is same as providerId.\n return OAuthCredential._fromParams({\n ...params,\n providerId: this.providerId,\n signInMethod: this.providerId\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return OAuthProvider.oauthCredentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return OAuthProvider.oauthCredentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static oauthCredentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const {\n oauthIdToken,\n oauthAccessToken,\n oauthTokenSecret,\n pendingToken,\n nonce,\n providerId\n } = tokenResponse as SignInWithIdpResponse;\n if (\n !oauthAccessToken &&\n !oauthTokenSecret &&\n !oauthIdToken &&\n !pendingToken\n ) {\n return null;\n }\n\n if (!providerId) {\n return null;\n }\n\n try {\n return new OAuthProvider(providerId)._credential({\n idToken: oauthIdToken,\n accessToken: oauthAccessToken,\n nonce,\n pendingToken\n });\n } catch (e) {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('user_birthday');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * provider.addScope('user_birthday');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nexport class FacebookAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.FACEBOOK. */\n static readonly FACEBOOK_SIGN_IN_METHOD: 'facebook.com' =\n SignInMethod.FACEBOOK;\n /** Always set to {@link ProviderId}.FACEBOOK. */\n static readonly PROVIDER_ID: 'facebook.com' = ProviderId.FACEBOOK;\n\n constructor() {\n super(ProviderId.FACEBOOK);\n }\n\n /**\n * Creates a credential for Facebook.\n *\n * @example\n * ```javascript\n * // `event` from the Facebook auth.authResponseChange callback.\n * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param accessToken - Facebook access token.\n */\n static credential(accessToken: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: FacebookAuthProvider.PROVIDER_ID,\n signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return FacebookAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return FacebookAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n\n try {\n return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GoogleAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GoogleAuthProvider();\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nexport class GoogleAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.GOOGLE. */\n static readonly GOOGLE_SIGN_IN_METHOD: 'google.com' = SignInMethod.GOOGLE;\n /** Always set to {@link ProviderId}.GOOGLE. */\n static readonly PROVIDER_ID: 'google.com' = ProviderId.GOOGLE;\n\n constructor() {\n super(ProviderId.GOOGLE);\n this.addScope('profile');\n }\n\n /**\n * Creates a credential for Google. At least one of ID token and access token is required.\n *\n * @example\n * ```javascript\n * // \\`googleUser\\` from the onsuccess Google Sign In callback.\n * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param idToken - Google ID token.\n * @param accessToken - Google access token.\n */\n static credential(\n idToken?: string | null,\n accessToken?: string | null\n ): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: GoogleAuthProvider.PROVIDER_ID,\n signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,\n idToken,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return GoogleAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return GoogleAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const { oauthIdToken, oauthAccessToken } =\n tokenResponse as SignInWithIdpResponse;\n if (!oauthIdToken && !oauthAccessToken) {\n // This could be an oauth 1 credential or a phone credential\n return null;\n }\n\n try {\n return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.\n *\n * @remarks\n * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use\n * the {@link signInWithPopup} handler:\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GithubAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('repo');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Github Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GithubAuthProvider();\n * provider.addScope('repo');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Github Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nexport class GithubAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.GITHUB. */\n static readonly GITHUB_SIGN_IN_METHOD: 'github.com' = SignInMethod.GITHUB;\n /** Always set to {@link ProviderId}.GITHUB. */\n static readonly PROVIDER_ID: 'github.com' = ProviderId.GITHUB;\n\n constructor() {\n super(ProviderId.GITHUB);\n }\n\n /**\n * Creates a credential for Github.\n *\n * @param accessToken - Github access token.\n */\n static credential(accessToken: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: GithubAuthProvider.PROVIDER_ID,\n signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return GithubAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return GithubAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n\n try {\n return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @license\n * Copyright 2020 Twitter LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new TwitterAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new TwitterAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * ```\n *\n * @public\n */\nexport class TwitterAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.TWITTER. */\n static readonly TWITTER_SIGN_IN_METHOD: 'twitter.com' = SignInMethod.TWITTER;\n /** Always set to {@link ProviderId}.TWITTER. */\n static readonly PROVIDER_ID: 'twitter.com' = ProviderId.TWITTER;\n\n constructor() {\n super(ProviderId.TWITTER);\n }\n\n /**\n * Creates a credential for Twitter.\n *\n * @param token - Twitter access token.\n * @param secret - Twitter secret.\n */\n static credential(token: string, secret: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: TwitterAuthProvider.PROVIDER_ID,\n signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,\n oauthToken: token,\n oauthTokenSecret: secret\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return TwitterAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return TwitterAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n const { oauthAccessToken, oauthTokenSecret } =\n tokenResponse as SignInWithIdpResponse;\n if (!oauthAccessToken || !oauthTokenSecret) {\n return null;\n }\n\n try {\n return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignUpRequest {\n idToken?: string;\n returnSecureToken?: boolean;\n email?: string;\n password?: string;\n tenantId?: string;\n captchaResponse?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface SignUpResponse extends IdTokenResponse {\n displayName?: string;\n email?: string;\n}\n\nexport async function signUp(\n auth: Auth,\n request: SignUpRequest\n): Promise<SignUpResponse> {\n return _performSignInRequest<SignUpRequest, SignUpResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_UP,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { UserImpl } from './user_impl';\nimport { AuthInternal } from '../../model/auth';\nimport { OperationType, ProviderId } from '../../model/enums';\n\ninterface UserCredentialParams {\n readonly user: UserInternal;\n readonly providerId: ProviderId | string | null;\n readonly _tokenResponse?: PhoneOrOauthTokenResponse;\n readonly operationType: OperationType;\n}\n\nexport class UserCredentialImpl\n implements UserCredentialInternal, UserCredentialParams\n{\n readonly user: UserInternal;\n readonly providerId: ProviderId | string | null;\n readonly _tokenResponse: PhoneOrOauthTokenResponse | undefined;\n readonly operationType: OperationType;\n\n constructor(params: UserCredentialParams) {\n this.user = params.user;\n this.providerId = params.providerId;\n this._tokenResponse = params._tokenResponse;\n this.operationType = params.operationType;\n }\n\n static async _fromIdTokenResponse(\n auth: AuthInternal,\n operationType: OperationType,\n idTokenResponse: IdTokenResponse,\n isAnonymous: boolean = false\n ): Promise<UserCredentialInternal> {\n const user = await UserImpl._fromIdTokenResponse(\n auth,\n idTokenResponse,\n isAnonymous\n );\n const providerId = providerIdForResponse(idTokenResponse);\n const userCred = new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: idTokenResponse,\n operationType\n });\n return userCred;\n }\n\n static async _forOperation(\n user: UserInternal,\n operationType: OperationType,\n response: PhoneOrOauthTokenResponse\n ): Promise<UserCredentialImpl> {\n await user._updateTokensIfNecessary(response, /* reload */ true);\n const providerId = providerIdForResponse(response);\n return new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: response,\n operationType\n });\n }\n}\n\nfunction providerIdForResponse(\n response: IdTokenResponse\n): ProviderId | string | null {\n if (response.providerId) {\n return response.providerId;\n }\n\n if ('phoneNumber' in response) {\n return ProviderId.PHONE;\n }\n\n return null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MultiFactorError as MultiFactorErrorPublic } from '../model/public_types';\nimport { FirebaseError } from '@firebase/util';\nimport { AuthInternal } from '../model/auth';\nimport { IdTokenResponse } from '../model/id_token';\nimport { AuthErrorCode } from '../core/errors';\nimport { UserInternal } from '../model/user';\nimport { AuthCredential } from '../core/credentials';\nimport { IdTokenMfaResponse } from '../api/authentication/mfa';\nimport { OperationType } from '../model/enums';\n\nexport type MultiFactorErrorData = MultiFactorErrorPublic['customData'] & {\n _serverResponse: IdTokenMfaResponse;\n};\n\nexport class MultiFactorError\n extends FirebaseError\n implements MultiFactorErrorPublic\n{\n readonly customData: MultiFactorErrorData;\n\n private constructor(\n auth: AuthInternal,\n error: FirebaseError,\n readonly operationType: OperationType,\n readonly user?: UserInternal\n ) {\n super(error.code, error.message);\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MultiFactorError.prototype);\n this.customData = {\n appName: auth.name,\n tenantId: auth.tenantId ?? undefined,\n _serverResponse: error.customData!._serverResponse as IdTokenMfaResponse,\n operationType\n };\n }\n\n static _fromErrorAndOperation(\n auth: AuthInternal,\n error: FirebaseError,\n operationType: OperationType,\n user?: UserInternal\n ): MultiFactorError {\n return new MultiFactorError(auth, error, operationType, user);\n }\n}\n\nexport function _processCredentialSavingMfaContextIfNecessary(\n auth: AuthInternal,\n operationType: OperationType,\n credential: AuthCredential,\n user?: UserInternal\n): Promise<IdTokenResponse> {\n const idTokenProvider =\n operationType === OperationType.REAUTHENTICATE\n ? credential._getReauthenticationResolver(auth)\n : credential._getIdTokenResponse(auth);\n\n return idTokenProvider.catch(error => {\n if (error.code === `auth/${AuthErrorCode.MFA_REQUIRED}`) {\n throw MultiFactorError._fromErrorAndOperation(\n auth,\n error,\n operationType,\n user\n );\n }\n\n throw error;\n });\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../../model/public_types';\n\nimport { deleteLinkedAccounts } from '../../api/account_management/account';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { providerDataAsNames } from '../util/providers';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { _reloadWithoutSaving } from './reload';\nimport { UserCredentialImpl } from './user_credential_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType, ProviderId } from '../../model/enums';\n\n/**\n * Unlinks a provider from a user account.\n *\n * @param user - The user.\n * @param providerId - The provider to unlink.\n *\n * @public\n */\nexport async function unlink(user: User, providerId: string): Promise<User> {\n const userInternal = getModularInstance(user) as UserInternal;\n await _assertLinkedStatus(true, userInternal, providerId);\n const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {\n idToken: await userInternal.getIdToken(),\n deleteProvider: [providerId]\n });\n\n const providersLeft = providerDataAsNames(providerUserInfo || []);\n\n userInternal.providerData = userInternal.providerData.filter(pd =>\n providersLeft.has(pd.providerId)\n );\n if (!providersLeft.has(ProviderId.PHONE)) {\n userInternal.phoneNumber = null;\n }\n\n await userInternal.auth._persistUserIfCurrent(userInternal);\n return userInternal;\n}\n\nexport async function _link(\n user: UserInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise<UserCredentialInternal> {\n const response = await _logoutIfInvalidated(\n user,\n credential._linkToIdToken(user.auth, await user.getIdToken()),\n bypassAuthState\n );\n return UserCredentialImpl._forOperation(user, OperationType.LINK, response);\n}\n\nexport async function _assertLinkedStatus(\n expected: boolean,\n user: UserInternal,\n provider: string\n): Promise<void> {\n await _reloadWithoutSaving(user);\n const providerIds = providerDataAsNames(user.providerData);\n\n const code =\n expected === false\n ? AuthErrorCode.PROVIDER_ALREADY_LINKED\n : AuthErrorCode.NO_SUCH_PROVIDER;\n _assert(providerIds.has(provider) === expected, user.auth, code);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { _processCredentialSavingMfaContextIfNecessary } from '../../mfa/mfa_error';\nimport { OperationType } from '../../model/enums';\nimport { UserInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { AuthErrorCode } from '../errors';\nimport { _assert, _fail } from '../util/assert';\nimport { _parseToken } from './id_token_result';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { UserCredentialImpl } from './user_credential_impl';\n\nexport async function _reauthenticate(\n user: UserInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise<UserCredentialImpl> {\n const { auth } = user;\n const operationType = OperationType.REAUTHENTICATE;\n\n try {\n const response = await _logoutIfInvalidated(\n user,\n _processCredentialSavingMfaContextIfNecessary(\n auth,\n operationType,\n credential,\n user\n ),\n bypassAuthState\n );\n _assert(response.idToken, auth, AuthErrorCode.INTERNAL_ERROR);\n const parsed = _parseToken(response.idToken);\n _assert(parsed, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const { sub: localId } = parsed;\n _assert(user.uid === localId, auth, AuthErrorCode.USER_MISMATCH);\n\n return UserCredentialImpl._forOperation(user, operationType, response);\n } catch (e) {\n // Convert user deleted error into user mismatch\n if ((e as FirebaseError)?.code === `auth/${AuthErrorCode.USER_DELETED}`) {\n _fail(auth, AuthErrorCode.USER_MISMATCH);\n }\n throw e;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential, Auth, User } from '../../model/public_types';\n\nimport { _processCredentialSavingMfaContextIfNecessary } from '../../mfa/mfa_error';\nimport { AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { _assertLinkedStatus, _link } from '../user/link_unlink';\nimport { _reauthenticate } from '../user/reauthenticate';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../../model/enums';\n\nexport async function _signInWithCredential(\n auth: AuthInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise<UserCredential> {\n const operationType = OperationType.SIGN_IN;\n const response = await _processCredentialSavingMfaContextIfNecessary(\n auth,\n operationType,\n credential\n );\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n auth,\n operationType,\n response\n );\n\n if (!bypassAuthState) {\n await auth._updateCurrentUser(userCredential.user);\n }\n return userCredential;\n}\n\n/**\n * Asynchronously signs in with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * @param auth - The {@link Auth} instance.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function signInWithCredential(\n auth: Auth,\n credential: AuthCredential\n): Promise<UserCredential> {\n return _signInWithCredential(_castAuth(auth), credential);\n}\n\n/**\n * Links the user account with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function linkWithCredential(\n user: User,\n credential: AuthCredential\n): Promise<UserCredential> {\n const userInternal = getModularInstance(user) as UserInternal;\n\n await _assertLinkedStatus(false, userInternal, credential.providerId);\n\n return _link(userInternal, credential);\n}\n\n/**\n * Re-authenticates a user using a fresh credential.\n *\n * @remarks\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in\n * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error\n * or a `TOKEN_EXPIRED` error.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function reauthenticateWithCredential(\n user: User,\n credential: AuthCredential\n): Promise<UserCredential> {\n return _reauthenticate(getModularInstance(user) as UserInternal, credential);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ActionCodeInfo,\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n UserCredential\n} from '../../model/public_types';\n\nimport * as account from '../../api/account_management/email_and_password';\nimport * as authentication from '../../api/authentication/email_and_password';\nimport { signUp, SignUpRequest } from '../../api/authentication/sign_up';\nimport { MultiFactorInfoImpl } from '../../mfa/mfa_info';\nimport { EmailAuthProvider } from '../providers/email';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _assert } from '../util/assert';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { signInWithCredential } from './credential';\nimport { _castAuth } from '../auth/auth_impl';\nimport { AuthErrorCode } from '../errors';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../../model/enums';\nimport { handleRecaptchaFlow } from '../../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { RecaptchaActionName, RecaptchaClientType } from '../../api';\n\n/**\n * Updates the password policy cached in the {@link Auth} instance if a policy is already\n * cached for the project or tenant.\n *\n * @remarks\n * We only fetch the password policy if the password did not meet policy requirements and\n * there is an existing policy cached. A developer must call validatePassword at least\n * once for the cache to be automatically updated.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @private\n */\nasync function recachePasswordPolicy(auth: Auth): Promise<void> {\n const authInternal = _castAuth(auth);\n if (authInternal._getPasswordPolicyInternal()) {\n await authInternal._updatePasswordPolicy();\n }\n}\n\n/**\n * Sends a password reset email to the given email address.\n *\n * @remarks\n * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in\n * the email sent to the user, along with the new password specified by the user.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain code from user.\n * await confirmPasswordReset('user@example.com', code);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendPasswordResetEmail(\n auth: Auth,\n email: string,\n actionCodeSettings?: ActionCodeSettings\n): Promise<void> {\n const authInternal = _castAuth(auth);\n const request: authentication.PasswordResetRequest = {\n requestType: ActionCodeOperation.PASSWORD_RESET,\n email,\n clientType: RecaptchaClientType.WEB\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\n }\n await handleRecaptchaFlow(\n authInternal,\n request,\n RecaptchaActionName.GET_OOB_CODE,\n authentication.sendPasswordResetEmail\n );\n}\n\n/**\n * Completes the password reset process, given a confirmation code and new password.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A confirmation code sent to the user.\n * @param newPassword - The new password.\n *\n * @public\n */\nexport async function confirmPasswordReset(\n auth: Auth,\n oobCode: string,\n newPassword: string\n): Promise<void> {\n await account\n .resetPassword(getModularInstance(auth), {\n oobCode,\n newPassword\n })\n .catch(async error => {\n if (\n error.code ===\n `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\n });\n // Do not return the email.\n}\n\n/**\n * Applies a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nexport async function applyActionCode(\n auth: Auth,\n oobCode: string\n): Promise<void> {\n await account.applyActionCode(getModularInstance(auth), { oobCode });\n}\n\n/**\n * Checks a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @returns metadata about the code.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nexport async function checkActionCode(\n auth: Auth,\n oobCode: string\n): Promise<ActionCodeInfo> {\n const authModular = getModularInstance(auth);\n const response = await account.resetPassword(authModular, { oobCode });\n\n // Email could be empty only if the request type is EMAIL_SIGNIN or\n // VERIFY_AND_CHANGE_EMAIL.\n // New email should not be empty if the request type is\n // VERIFY_AND_CHANGE_EMAIL.\n // Multi-factor info could not be empty if the request type is\n // REVERT_SECOND_FACTOR_ADDITION.\n const operation = response.requestType;\n _assert(operation, authModular, AuthErrorCode.INTERNAL_ERROR);\n switch (operation) {\n case ActionCodeOperation.EMAIL_SIGNIN:\n break;\n case ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL:\n _assert(response.newEmail, authModular, AuthErrorCode.INTERNAL_ERROR);\n break;\n case ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION:\n _assert(response.mfaInfo, authModular, AuthErrorCode.INTERNAL_ERROR);\n // fall through\n default:\n _assert(response.email, authModular, AuthErrorCode.INTERNAL_ERROR);\n }\n\n // The multi-factor info for revert second factor addition\n let multiFactorInfo: MultiFactorInfoImpl | null = null;\n if (response.mfaInfo) {\n multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(\n _castAuth(authModular),\n response.mfaInfo\n );\n }\n\n return {\n data: {\n email:\n (response.requestType === ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL\n ? response.newEmail\n : response.email) || null,\n previousEmail:\n (response.requestType === ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL\n ? response.email\n : response.newEmail) || null,\n multiFactorInfo\n },\n operation\n };\n}\n\n/**\n * Checks a password reset code sent to the user by email or other out-of-band mechanism.\n *\n * @returns the user's email address if valid.\n *\n * @param auth - The {@link Auth} instance.\n * @param code - A verification code sent to the user.\n *\n * @public\n */\nexport async function verifyPasswordResetCode(\n auth: Auth,\n code: string\n): Promise<string> {\n const { data } = await checkActionCode(getModularInstance(auth), code);\n // Email should always be present since a code was sent to it\n return data.email!;\n}\n\n/**\n * Creates a new user account associated with the specified email address and password.\n *\n * @remarks\n * On successful creation of the user account, this user will also be signed in to your application.\n *\n * User account creation can fail if the account already exists or the password is invalid.\n *\n * Note: The email address acts as a unique identifier for the user and enables an email-based\n * password reset. This function will create a new user account and set the initial user password.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param password - The user's chosen password.\n *\n * @public\n */\nexport async function createUserWithEmailAndPassword(\n auth: Auth,\n email: string,\n password: string\n): Promise<UserCredential> {\n const authInternal = _castAuth(auth);\n const request: SignUpRequest = {\n returnSecureToken: true,\n email,\n password,\n clientType: RecaptchaClientType.WEB\n };\n const signUpResponse: Promise<IdTokenResponse> = handleRecaptchaFlow(\n authInternal,\n request,\n RecaptchaActionName.SIGN_UP_PASSWORD,\n signUp\n );\n const response = await signUpResponse.catch(error => {\n if (\n error.code === `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\n });\n\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response\n );\n await authInternal._updateCurrentUser(userCredential.user);\n\n return userCredential;\n}\n\n/**\n * Asynchronously signs in using an email and password.\n *\n * @remarks\n * Fails with an error if the email address and password do not match.\n *\n * Note: The user's password is NOT the password used to access the user's email account. The\n * email address serves as a unique identifier for the user, and the password is used to access\n * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The users email address.\n * @param password - The users password.\n *\n * @public\n */\nexport function signInWithEmailAndPassword(\n auth: Auth,\n email: string,\n password: string\n): Promise<UserCredential> {\n return signInWithCredential(\n getModularInstance(auth),\n EmailAuthProvider.credential(email, password)\n ).catch(async error => {\n if (\n error.code === `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n MultiFactorAssertion,\n MultiFactorInfo,\n MultiFactorSession,\n MultiFactorUser,\n User\n} from '../model/public_types';\n\nimport { withdrawMfa } from '../api/account_management/mfa';\nimport { _logoutIfInvalidated } from '../core/user/invalidation';\nimport { UserInternal } from '../model/user';\nimport { MultiFactorAssertionImpl } from './mfa_assertion';\nimport { MultiFactorInfoImpl } from './mfa_info';\nimport { MultiFactorSessionImpl } from './mfa_session';\nimport { getModularInstance } from '@firebase/util';\n\nexport class MultiFactorUserImpl implements MultiFactorUser {\n enrolledFactors: MultiFactorInfo[] = [];\n\n private constructor(readonly user: UserInternal) {\n user._onReload(userInfo => {\n if (userInfo.mfaInfo) {\n this.enrolledFactors = userInfo.mfaInfo.map(enrollment =>\n MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment)\n );\n }\n });\n }\n\n static _fromUser(user: UserInternal): MultiFactorUserImpl {\n return new MultiFactorUserImpl(user);\n }\n\n async getSession(): Promise<MultiFactorSession> {\n return MultiFactorSessionImpl._fromIdtoken(\n await this.user.getIdToken(),\n this.user\n );\n }\n\n async enroll(\n assertionExtern: MultiFactorAssertion,\n displayName?: string | null\n ): Promise<void> {\n const assertion = assertionExtern as MultiFactorAssertionImpl;\n const session = (await this.getSession()) as MultiFactorSessionImpl;\n const finalizeMfaResponse = await _logoutIfInvalidated(\n this.user,\n assertion._process(this.user.auth, session, displayName)\n );\n // New tokens will be issued after enrollment of the new second factors.\n // They need to be updated on the user.\n await this.user._updateTokensIfNecessary(finalizeMfaResponse);\n // The user needs to be reloaded to get the new multi-factor information\n // from server. USER_RELOADED event will be triggered and `enrolledFactors`\n // will be updated.\n return this.user.reload();\n }\n\n async unenroll(infoOrUid: MultiFactorInfo | string): Promise<void> {\n const mfaEnrollmentId =\n typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;\n const idToken = await this.user.getIdToken();\n try {\n const idTokenResponse = await _logoutIfInvalidated(\n this.user,\n withdrawMfa(this.user.auth, {\n idToken,\n mfaEnrollmentId\n })\n );\n // Remove the second factor from the user's list.\n this.enrolledFactors = this.enrolledFactors.filter(\n ({ uid }) => uid !== mfaEnrollmentId\n );\n // Depending on whether the backend decided to revoke the user's session,\n // the tokenResponse may be empty. If the tokens were not updated (and they\n // are now invalid), reloading the user will discover this and invalidate\n // the user's state accordingly.\n await this.user._updateTokensIfNecessary(idTokenResponse);\n await this.user.reload();\n } catch (e) {\n throw e;\n }\n }\n}\n\nconst multiFactorUserCache = new WeakMap<User, MultiFactorUser>();\n\n/**\n * The {@link MultiFactorUser} corresponding to the user.\n *\n * @remarks\n * This is used to access all multi-factor properties and operations related to the user.\n *\n * @param user - The user.\n *\n * @public\n */\nexport function multiFactor(user: User): MultiFactorUser {\n const userModular = getModularInstance(user);\n if (!multiFactorUserCache.has(userModular)) {\n multiFactorUserCache.set(\n userModular,\n MultiFactorUserImpl._fromUser(userModular as UserInternal)\n );\n }\n return multiFactorUserCache.get(userModular)!;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Persistence } from '../../model/public_types';\n\nexport const enum PersistenceType {\n SESSION = 'SESSION',\n LOCAL = 'LOCAL',\n NONE = 'NONE'\n}\n\nexport type PersistedBlob = Record<string, unknown>;\n\nexport interface Instantiator<T> {\n (blob: PersistedBlob): T;\n}\n\nexport type PersistenceValue = PersistedBlob | string;\n\nexport const STORAGE_AVAILABLE_KEY = '__sak';\n\nexport interface StorageEventListener {\n (value: PersistenceValue | null): void;\n}\n\nexport interface PersistenceInternal extends Persistence {\n type: PersistenceType;\n _isAvailable(): Promise<boolean>;\n _set(key: string, value: PersistenceValue): Promise<void>;\n _get<T extends PersistenceValue>(key: string): Promise<T | null>;\n _remove(key: string): Promise<void>;\n _addListener(key: string, listener: StorageEventListener): void;\n _removeListener(key: string, listener: StorageEventListener): void;\n // Should this persistence allow migration up the chosen hierarchy?\n _shouldAllowMigration?: boolean;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n PersistenceValue,\n STORAGE_AVAILABLE_KEY,\n PersistenceType\n} from '../../core/persistence';\n\n// There are two different browser persistence types: local and session.\n// Both have the same implementation but use a different underlying storage\n// object.\n\nexport abstract class BrowserPersistenceClass {\n protected constructor(\n protected readonly storageRetriever: () => Storage,\n readonly type: PersistenceType\n ) {}\n\n _isAvailable(): Promise<boolean> {\n try {\n if (!this.storage) {\n return Promise.resolve(false);\n }\n this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');\n this.storage.removeItem(STORAGE_AVAILABLE_KEY);\n return Promise.resolve(true);\n } catch {\n return Promise.resolve(false);\n }\n }\n\n _set(key: string, value: PersistenceValue): Promise<void> {\n this.storage.setItem(key, JSON.stringify(value));\n return Promise.resolve();\n }\n\n _get<T extends PersistenceValue>(key: string): Promise<T | null> {\n const json = this.storage.getItem(key);\n return Promise.resolve(json ? JSON.parse(json) : null);\n }\n\n _remove(key: string): Promise<void> {\n this.storage.removeItem(key);\n return Promise.resolve();\n }\n\n protected get storage(): Storage {\n return this.storageRetriever();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport { getUA } from '@firebase/util';\nimport {\n _isSafari,\n _isIOS,\n _isIframe,\n _isMobileBrowser,\n _isIE10\n} from '../../core/util/browser';\nimport {\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n PersistenceValue,\n StorageEventListener\n} from '../../core/persistence';\nimport { BrowserPersistenceClass } from './browser';\n\nfunction _iframeCannotSyncWebStorage(): boolean {\n const ua = getUA();\n return _isSafari(ua) || _isIOS(ua);\n}\n\n// The polling period in case events are not supported\nexport const _POLLING_INTERVAL_MS = 1000;\n\n// The IE 10 localStorage cross tab synchronization delay in milliseconds\nconst IE10_LOCAL_STORAGE_SYNC_DELAY = 10;\n\nclass BrowserLocalPersistence\n extends BrowserPersistenceClass\n implements InternalPersistence\n{\n static type: 'LOCAL' = 'LOCAL';\n\n constructor() {\n super(() => window.localStorage, PersistenceType.LOCAL);\n }\n\n private readonly boundEventHandler = (\n event: StorageEvent,\n poll?: boolean\n ): void => this.onStorageEvent(event, poll);\n private readonly listeners: Record<string, Set<StorageEventListener>> = {};\n private readonly localCache: Record<string, string | null> = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private pollTimer: any | null = null;\n\n // Safari or iOS browser and embedded in an iframe.\n private readonly safariLocalStorageNotSynced =\n _iframeCannotSyncWebStorage() && _isIframe();\n // Whether to use polling instead of depending on window events\n private readonly fallbackToPolling = _isMobileBrowser();\n readonly _shouldAllowMigration = true;\n\n private forAllChangedKeys(\n cb: (key: string, oldValue: string | null, newValue: string | null) => void\n ): void {\n // Check all keys with listeners on them.\n for (const key of Object.keys(this.listeners)) {\n // Get value from localStorage.\n const newValue = this.storage.getItem(key);\n const oldValue = this.localCache[key];\n // If local map value does not match, trigger listener with storage event.\n // Differentiate this simulated event from the real storage event.\n if (newValue !== oldValue) {\n cb(key, oldValue, newValue);\n }\n }\n }\n\n private onStorageEvent(event: StorageEvent, poll = false): void {\n // Key would be null in some situations, like when localStorage is cleared\n if (!event.key) {\n this.forAllChangedKeys(\n (key: string, _oldValue: string | null, newValue: string | null) => {\n this.notifyListeners(key, newValue);\n }\n );\n return;\n }\n\n const key = event.key;\n\n // Check the mechanism how this event was detected.\n // The first event will dictate the mechanism to be used.\n if (poll) {\n // Environment detects storage changes via polling.\n // Remove storage event listener to prevent possible event duplication.\n this.detachListener();\n } else {\n // Environment detects storage changes via storage event listener.\n // Remove polling listener to prevent possible event duplication.\n this.stopPolling();\n }\n\n // Safari embedded iframe. Storage event will trigger with the delta\n // changes but no changes will be applied to the iframe localStorage.\n if (this.safariLocalStorageNotSynced) {\n // Get current iframe page value.\n const storedValue = this.storage.getItem(key);\n // Value not synchronized, synchronize manually.\n if (event.newValue !== storedValue) {\n if (event.newValue !== null) {\n // Value changed from current value.\n this.storage.setItem(key, event.newValue);\n } else {\n // Current value deleted.\n this.storage.removeItem(key);\n }\n } else if (this.localCache[key] === event.newValue && !poll) {\n // Already detected and processed, do not trigger listeners again.\n return;\n }\n }\n\n const triggerListeners = (): void => {\n // Keep local map up to date in case storage event is triggered before\n // poll.\n const storedValue = this.storage.getItem(key);\n if (!poll && this.localCache[key] === storedValue) {\n // Real storage event which has already been detected, do nothing.\n // This seems to trigger in some IE browsers for some reason.\n return;\n }\n this.notifyListeners(key, storedValue);\n };\n\n const storedValue = this.storage.getItem(key);\n if (\n _isIE10() &&\n storedValue !== event.newValue &&\n event.newValue !== event.oldValue\n ) {\n // IE 10 has this weird bug where a storage event would trigger with the\n // correct key, oldValue and newValue but localStorage.getItem(key) does\n // not yield the updated value until a few milliseconds. This ensures\n // this recovers from that situation.\n setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);\n } else {\n triggerListeners();\n }\n }\n\n private notifyListeners(key: string, value: string | null): void {\n this.localCache[key] = value;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(value ? JSON.parse(value) : value);\n }\n }\n }\n\n private startPolling(): void {\n this.stopPolling();\n\n this.pollTimer = setInterval(() => {\n this.forAllChangedKeys(\n (key: string, oldValue: string | null, newValue: string | null) => {\n this.onStorageEvent(\n new StorageEvent('storage', {\n key,\n oldValue,\n newValue\n }),\n /* poll */ true\n );\n }\n );\n }, _POLLING_INTERVAL_MS);\n }\n\n private stopPolling(): void {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n private attachListener(): void {\n window.addEventListener('storage', this.boundEventHandler);\n }\n\n private detachListener(): void {\n window.removeEventListener('storage', this.boundEventHandler);\n }\n\n _addListener(key: string, listener: StorageEventListener): void {\n if (Object.keys(this.listeners).length === 0) {\n // Whether browser can detect storage event when it had already been pushed to the background.\n // This may happen in some mobile browsers. A localStorage change in the foreground window\n // will not be detected in the background window via the storage event.\n // This was detected in iOS 7.x mobile browsers\n if (this.fallbackToPolling) {\n this.startPolling();\n } else {\n this.attachListener();\n }\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n this.localCache[key] = this.storage.getItem(key);\n }\n this.listeners[key].add(listener);\n }\n\n _removeListener(key: string, listener: StorageEventListener): void {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n\n if (Object.keys(this.listeners).length === 0) {\n this.detachListener();\n this.stopPolling();\n }\n }\n\n // Update local cache on base operations:\n\n async _set(key: string, value: PersistenceValue): Promise<void> {\n await super._set(key, value);\n this.localCache[key] = JSON.stringify(value);\n }\n\n async _get<T extends PersistenceValue>(key: string): Promise<T | null> {\n const value = await super._get<T>(key);\n this.localCache[key] = JSON.stringify(value);\n return value;\n }\n\n async _remove(key: string): Promise<void> {\n await super._remove(key);\n delete this.localCache[key];\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`\n * for the underlying storage.\n *\n * @public\n */\nexport const browserLocalPersistence: Persistence = BrowserLocalPersistence;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport {\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n StorageEventListener\n} from '../../core/persistence';\nimport { BrowserPersistenceClass } from './browser';\n\nclass BrowserSessionPersistence\n extends BrowserPersistenceClass\n implements InternalPersistence\n{\n static type: 'SESSION' = 'SESSION';\n\n constructor() {\n super(() => window.sessionStorage, PersistenceType.SESSION);\n }\n\n _addListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n\n _removeListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n}\n\n/**\n * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`\n * for the underlying storage.\n *\n * @public\n */\nexport const browserSessionPersistence: Persistence = BrowserSessionPersistence;\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ReceiverHandler,\n _EventType,\n _ReceiverResponse,\n SenderMessageEvent,\n _Status,\n _SenderRequest\n} from './index';\nimport { _allSettled } from './promise';\n\n/**\n * Interface class for receiving messages.\n *\n */\nexport class Receiver {\n private static readonly receivers: Receiver[] = [];\n private readonly boundEventHandler: EventListener;\n\n private readonly handlersMap: {\n // Typescript doesn't have existential types :(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [eventType: string]: Set<ReceiverHandler<any, any>>;\n } = {};\n\n constructor(private readonly eventTarget: EventTarget) {\n this.boundEventHandler = this.handleEvent.bind(this);\n }\n\n /**\n * Obtain an instance of a Receiver for a given event target, if none exists it will be created.\n *\n * @param eventTarget - An event target (such as window or self) through which the underlying\n * messages will be received.\n */\n static _getInstance(eventTarget: EventTarget): Receiver {\n // The results are stored in an array since objects can't be keys for other\n // objects. In addition, setting a unique property on an event target as a\n // hash map key may not be allowed due to CORS restrictions.\n const existingInstance = this.receivers.find(receiver =>\n receiver.isListeningto(eventTarget)\n );\n if (existingInstance) {\n return existingInstance;\n }\n const newInstance = new Receiver(eventTarget);\n this.receivers.push(newInstance);\n return newInstance;\n }\n\n private isListeningto(eventTarget: EventTarget): boolean {\n return this.eventTarget === eventTarget;\n }\n\n /**\n * Fans out a MessageEvent to the appropriate listeners.\n *\n * @remarks\n * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have\n * finished processing.\n *\n * @param event - The MessageEvent.\n *\n */\n private async handleEvent<\n T extends _ReceiverResponse,\n S extends _SenderRequest\n >(event: Event): Promise<void> {\n const messageEvent = event as MessageEvent<SenderMessageEvent<S>>;\n const { eventId, eventType, data } = messageEvent.data;\n\n const handlers: Set<ReceiverHandler<T, S>> | undefined =\n this.handlersMap[eventType];\n if (!handlers?.size) {\n return;\n }\n\n messageEvent.ports[0].postMessage({\n status: _Status.ACK,\n eventId,\n eventType\n });\n\n const promises = Array.from(handlers).map(async handler =>\n handler(messageEvent.origin, data)\n );\n const response = await _allSettled(promises);\n messageEvent.ports[0].postMessage({\n status: _Status.DONE,\n eventId,\n eventType,\n response\n });\n }\n\n /**\n * Subscribe an event handler for a particular event.\n *\n * @param eventType - Event name to subscribe to.\n * @param eventHandler - The event handler which should receive the events.\n *\n */\n _subscribe<T extends _ReceiverResponse, S extends _SenderRequest>(\n eventType: _EventType,\n eventHandler: ReceiverHandler<T, S>\n ): void {\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.addEventListener('message', this.boundEventHandler);\n }\n\n if (!this.handlersMap[eventType]) {\n this.handlersMap[eventType] = new Set();\n }\n\n this.handlersMap[eventType].add(eventHandler);\n }\n\n /**\n * Unsubscribe an event handler from a particular event.\n *\n * @param eventType - Event name to unsubscribe from.\n * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.\n *\n */\n _unsubscribe<T extends _ReceiverResponse, S extends _SenderRequest>(\n eventType: _EventType,\n eventHandler?: ReceiverHandler<T, S>\n ): void {\n if (this.handlersMap[eventType] && eventHandler) {\n this.handlersMap[eventType].delete(eventHandler);\n }\n if (!eventHandler || this.handlersMap[eventType].size === 0) {\n delete this.handlersMap[eventType];\n }\n\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.removeEventListener('message', this.boundEventHandler);\n }\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** TODO: remove this once tslib has a polyfill for Promise.allSettled */\ninterface PromiseFulfilledResult<T> {\n fulfilled: true;\n value: T;\n}\n\ninterface PromiseRejectedResult {\n fulfilled: false;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n reason: any;\n}\n\nexport type PromiseSettledResult<T> =\n | PromiseFulfilledResult<T>\n | PromiseRejectedResult;\n\n/**\n * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.\n *\n * @param promises - Array of promises to wait on.\n */\nexport function _allSettled<T>(\n promises: Array<Promise<T>>\n): Promise<Array<PromiseSettledResult<T>>> {\n return Promise.all(\n promises.map(async promise => {\n try {\n const value = await promise;\n return {\n fulfilled: true,\n value\n } as PromiseFulfilledResult<T>;\n } catch (reason) {\n return {\n fulfilled: false,\n reason\n } as PromiseRejectedResult;\n }\n })\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function _generateEventId(prefix = '', digits = 10): string {\n let random = '';\n for (let i = 0; i < digits; i++) {\n random += Math.floor(Math.random() * 10);\n }\n return prefix + random;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _generateEventId } from '../../core/util/event_id';\nimport {\n _SenderRequest,\n _EventType,\n ReceiverMessageEvent,\n _MessageError,\n SenderMessageEvent,\n _Status,\n _ReceiverMessageResponse,\n _ReceiverResponse,\n _TimeoutDuration\n} from './index';\n\ninterface MessageHandler {\n messageChannel: MessageChannel;\n onMessage: EventListenerOrEventListenerObject;\n}\n\n/**\n * Interface for sending messages and waiting for a completion response.\n *\n */\nexport class Sender {\n private readonly handlers = new Set<MessageHandler>();\n\n constructor(private readonly target: ServiceWorker) {}\n\n /**\n * Unsubscribe the handler and remove it from our tracking Set.\n *\n * @param handler - The handler to unsubscribe.\n */\n private removeMessageHandler(handler: MessageHandler): void {\n if (handler.messageChannel) {\n handler.messageChannel.port1.removeEventListener(\n 'message',\n handler.onMessage\n );\n handler.messageChannel.port1.close();\n }\n this.handlers.delete(handler);\n }\n\n /**\n * Send a message to the Receiver located at {@link target}.\n *\n * @remarks\n * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the\n * receiver has had a chance to fully process the event.\n *\n * @param eventType - Type of event to send.\n * @param data - The payload of the event.\n * @param timeout - Timeout for waiting on an ACK from the receiver.\n *\n * @returns An array of settled promises from all the handlers that were listening on the receiver.\n */\n async _send<T extends _ReceiverResponse, S extends _SenderRequest>(\n eventType: _EventType,\n data: S,\n timeout = _TimeoutDuration.ACK\n ): Promise<_ReceiverMessageResponse<T>> {\n const messageChannel =\n typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;\n if (!messageChannel) {\n throw new Error(_MessageError.CONNECTION_UNAVAILABLE);\n }\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let completionTimer: any;\n let handler: MessageHandler;\n return new Promise<_ReceiverMessageResponse<T>>((resolve, reject) => {\n const eventId = _generateEventId('', 20);\n messageChannel.port1.start();\n const ackTimer = setTimeout(() => {\n reject(new Error(_MessageError.UNSUPPORTED_EVENT));\n }, timeout);\n handler = {\n messageChannel,\n onMessage(event: Event): void {\n const messageEvent = event as MessageEvent<ReceiverMessageEvent<T>>;\n if (messageEvent.data.eventId !== eventId) {\n return;\n }\n switch (messageEvent.data.status) {\n case _Status.ACK:\n // The receiver should ACK first.\n clearTimeout(ackTimer);\n completionTimer = setTimeout(() => {\n reject(new Error(_MessageError.TIMEOUT));\n }, _TimeoutDuration.COMPLETION);\n break;\n case _Status.DONE:\n // Once the receiver's handlers are finished we will get the results.\n clearTimeout(completionTimer);\n resolve(messageEvent.data.response);\n break;\n default:\n clearTimeout(ackTimer);\n clearTimeout(completionTimer);\n reject(new Error(_MessageError.INVALID_RESPONSE));\n break;\n }\n }\n };\n this.handlers.add(handler);\n messageChannel.port1.addEventListener('message', handler.onMessage);\n this.target.postMessage(\n {\n eventType,\n eventId,\n data\n } as SenderMessageEvent<S>,\n [messageChannel.port2]\n );\n }).finally(() => {\n if (handler) {\n this.removeMessageHandler(handler);\n }\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Recaptcha, GreCAPTCHATopLevel } from './recaptcha/recaptcha';\n\n/**\n * A specialized window type that melds the normal window type plus the\n * various bits we need. The three different blocks that are &'d together\n * cant be defined in the same block together.\n */\nexport type AuthWindow = {\n // Standard window types\n [T in keyof Window]: Window[T];\n} & {\n // Any known / named properties we want to add\n grecaptcha?: Recaptcha | GreCAPTCHATopLevel;\n /* eslint-disable-next-line @typescript-eslint/no-explicit-any */\n ___jsl?: Record<string, any>;\n gapi?: typeof gapi;\n} & {\n // A final catch-all for callbacks (which will have random names) that\n // we will stick on the window.\n [callback: string]: (...args: unknown[]) => void;\n};\n\n/**\n * Lazy accessor for window, since the compat layer won't tree shake this out,\n * we need to make sure not to mess with window unless we have to\n */\nexport function _window(): AuthWindow {\n return window as unknown as AuthWindow;\n}\n\nexport function _setWindowLocation(url: string): void {\n _window().location.href = url;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _window } from '../auth_window';\n\nexport function _isWorker(): boolean {\n return (\n typeof _window()['WorkerGlobalScope'] !== 'undefined' &&\n typeof _window()['importScripts'] === 'function'\n );\n}\n\nexport async function _getActiveServiceWorker(): Promise<ServiceWorker | null> {\n if (!navigator?.serviceWorker) {\n return null;\n }\n try {\n const registration = await navigator.serviceWorker.ready;\n return registration.active;\n } catch {\n return null;\n }\n}\n\nexport function _getServiceWorkerController(): ServiceWorker | null {\n return navigator?.serviceWorker?.controller || null;\n}\n\nexport function _getWorkerGlobalScope(): ServiceWorker | null {\n return _isWorker() ? (self as unknown as ServiceWorker) : null;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\nimport {\n PersistedBlob,\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n PersistenceValue,\n StorageEventListener,\n STORAGE_AVAILABLE_KEY\n} from '../../core/persistence/';\nimport {\n _EventType,\n _PingResponse,\n KeyChangedResponse,\n KeyChangedRequest,\n PingRequest,\n _TimeoutDuration\n} from '../messagechannel/index';\nimport { Receiver } from '../messagechannel/receiver';\nimport { Sender } from '../messagechannel/sender';\nimport {\n _isWorker,\n _getActiveServiceWorker,\n _getServiceWorkerController,\n _getWorkerGlobalScope\n} from '../util/worker';\n\nexport const DB_NAME = 'firebaseLocalStorageDb';\nconst DB_VERSION = 1;\nconst DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';\nconst DB_DATA_KEYPATH = 'fbase_key';\n\ninterface DBObject {\n [DB_DATA_KEYPATH]: string;\n value: PersistedBlob;\n}\n\n/**\n * Promise wrapper for IDBRequest\n *\n * Unfortunately we can't cleanly extend Promise<T> since promises are not callable in ES6\n *\n */\nclass DBPromise<T> {\n constructor(private readonly request: IDBRequest) {}\n\n toPromise(): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n this.request.addEventListener('success', () => {\n resolve(this.request.result);\n });\n this.request.addEventListener('error', () => {\n reject(this.request.error);\n });\n });\n }\n}\n\nfunction getObjectStore(db: IDBDatabase, isReadWrite: boolean): IDBObjectStore {\n return db\n .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')\n .objectStore(DB_OBJECTSTORE_NAME);\n}\n\nexport async function _clearDatabase(db: IDBDatabase): Promise<void> {\n const objectStore = getObjectStore(db, true);\n return new DBPromise<void>(objectStore.clear()).toPromise();\n}\n\nexport function _deleteDatabase(): Promise<void> {\n const request = indexedDB.deleteDatabase(DB_NAME);\n return new DBPromise<void>(request).toPromise();\n}\n\nexport function _openDatabase(): Promise<IDBDatabase> {\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n return new Promise((resolve, reject) => {\n request.addEventListener('error', () => {\n reject(request.error);\n });\n\n request.addEventListener('upgradeneeded', () => {\n const db = request.result;\n\n try {\n db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });\n } catch (e) {\n reject(e);\n }\n });\n\n request.addEventListener('success', async () => {\n const db: IDBDatabase = request.result;\n // Strange bug that occurs in Firefox when multiple tabs are opened at the\n // same time. The only way to recover seems to be deleting the database\n // and re-initializing it.\n // https://github.com/firebase/firebase-js-sdk/issues/634\n\n if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {\n // Need to close the database or else you get a `blocked` event\n db.close();\n await _deleteDatabase();\n resolve(await _openDatabase());\n } else {\n resolve(db);\n }\n });\n });\n}\n\nexport async function _putObject(\n db: IDBDatabase,\n key: string,\n value: PersistenceValue | string\n): Promise<void> {\n const request = getObjectStore(db, true).put({\n [DB_DATA_KEYPATH]: key,\n value\n });\n return new DBPromise<void>(request).toPromise();\n}\n\nasync function getObject(\n db: IDBDatabase,\n key: string\n): Promise<PersistedBlob | null> {\n const request = getObjectStore(db, false).get(key);\n const data = await new DBPromise<DBObject | undefined>(request).toPromise();\n return data === undefined ? null : data.value;\n}\n\nexport function _deleteObject(db: IDBDatabase, key: string): Promise<void> {\n const request = getObjectStore(db, true).delete(key);\n return new DBPromise<void>(request).toPromise();\n}\n\nexport const _POLLING_INTERVAL_MS = 800;\nexport const _TRANSACTION_RETRY_COUNT = 3;\n\nclass IndexedDBLocalPersistence implements InternalPersistence {\n static type: 'LOCAL' = 'LOCAL';\n\n type = PersistenceType.LOCAL;\n db?: IDBDatabase;\n readonly _shouldAllowMigration = true;\n\n private readonly listeners: Record<string, Set<StorageEventListener>> = {};\n private readonly localCache: Record<string, PersistenceValue | null> = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private pollTimer: any | null = null;\n private pendingWrites = 0;\n\n private receiver: Receiver | null = null;\n private sender: Sender | null = null;\n private serviceWorkerReceiverAvailable = false;\n private activeServiceWorker: ServiceWorker | null = null;\n // Visible for testing only\n readonly _workerInitializationPromise: Promise<void>;\n\n constructor() {\n // Fire & forget the service worker registration as it may never resolve\n this._workerInitializationPromise =\n this.initializeServiceWorkerMessaging().then(\n () => {},\n () => {}\n );\n }\n\n async _openDb(): Promise<IDBDatabase> {\n if (this.db) {\n return this.db;\n }\n this.db = await _openDatabase();\n return this.db;\n }\n\n async _withRetries<T>(op: (db: IDBDatabase) => Promise<T>): Promise<T> {\n let numAttempts = 0;\n\n while (true) {\n try {\n const db = await this._openDb();\n return await op(db);\n } catch (e) {\n if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {\n throw e;\n }\n if (this.db) {\n this.db.close();\n this.db = undefined;\n }\n // TODO: consider adding exponential backoff\n }\n }\n }\n\n /**\n * IndexedDB events do not propagate from the main window to the worker context. We rely on a\n * postMessage interface to send these events to the worker ourselves.\n */\n private async initializeServiceWorkerMessaging(): Promise<void> {\n return _isWorker() ? this.initializeReceiver() : this.initializeSender();\n }\n\n /**\n * As the worker we should listen to events from the main window.\n */\n private async initializeReceiver(): Promise<void> {\n this.receiver = Receiver._getInstance(_getWorkerGlobalScope()!);\n // Refresh from persistence if we receive a KeyChanged message.\n this.receiver._subscribe(\n _EventType.KEY_CHANGED,\n async (_origin: string, data: KeyChangedRequest) => {\n const keys = await this._poll();\n return {\n keyProcessed: keys.includes(data.key)\n };\n }\n );\n // Let the sender know that we are listening so they give us more timeout.\n this.receiver._subscribe(\n _EventType.PING,\n async (_origin: string, _data: PingRequest) => {\n return [_EventType.KEY_CHANGED];\n }\n );\n }\n\n /**\n * As the main window, we should let the worker know when keys change (set and remove).\n *\n * @remarks\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}\n * may not resolve.\n */\n private async initializeSender(): Promise<void> {\n // Check to see if there's an active service worker.\n this.activeServiceWorker = await _getActiveServiceWorker();\n if (!this.activeServiceWorker) {\n return;\n }\n this.sender = new Sender(this.activeServiceWorker);\n // Ping the service worker to check what events they can handle.\n const results = await this.sender._send<_PingResponse, PingRequest>(\n _EventType.PING,\n {},\n _TimeoutDuration.LONG_ACK\n );\n if (!results) {\n return;\n }\n if (\n results[0]?.fulfilled &&\n results[0]?.value.includes(_EventType.KEY_CHANGED)\n ) {\n this.serviceWorkerReceiverAvailable = true;\n }\n }\n\n /**\n * Let the worker know about a changed key, the exact key doesn't technically matter since the\n * worker will just trigger a full sync anyway.\n *\n * @remarks\n * For now, we only support one service worker per page.\n *\n * @param key - Storage key which changed.\n */\n private async notifyServiceWorker(key: string): Promise<void> {\n if (\n !this.sender ||\n !this.activeServiceWorker ||\n _getServiceWorkerController() !== this.activeServiceWorker\n ) {\n return;\n }\n try {\n await this.sender._send<KeyChangedResponse, KeyChangedRequest>(\n _EventType.KEY_CHANGED,\n { key },\n // Use long timeout if receiver has previously responded to a ping from us.\n this.serviceWorkerReceiverAvailable\n ? _TimeoutDuration.LONG_ACK\n : _TimeoutDuration.ACK\n );\n } catch {\n // This is a best effort approach. Ignore errors.\n }\n }\n\n async _isAvailable(): Promise<boolean> {\n try {\n if (!indexedDB) {\n return false;\n }\n const db = await _openDatabase();\n await _putObject(db, STORAGE_AVAILABLE_KEY, '1');\n await _deleteObject(db, STORAGE_AVAILABLE_KEY);\n return true;\n } catch {}\n return false;\n }\n\n private async _withPendingWrite(write: () => Promise<void>): Promise<void> {\n this.pendingWrites++;\n try {\n await write();\n } finally {\n this.pendingWrites--;\n }\n }\n\n async _set(key: string, value: PersistenceValue): Promise<void> {\n return this._withPendingWrite(async () => {\n await this._withRetries((db: IDBDatabase) => _putObject(db, key, value));\n this.localCache[key] = value;\n return this.notifyServiceWorker(key);\n });\n }\n\n async _get<T extends PersistenceValue>(key: string): Promise<T | null> {\n const obj = (await this._withRetries((db: IDBDatabase) =>\n getObject(db, key)\n )) as T;\n this.localCache[key] = obj;\n return obj;\n }\n\n async _remove(key: string): Promise<void> {\n return this._withPendingWrite(async () => {\n await this._withRetries((db: IDBDatabase) => _deleteObject(db, key));\n delete this.localCache[key];\n return this.notifyServiceWorker(key);\n });\n }\n\n private async _poll(): Promise<string[]> {\n // TODO: check if we need to fallback if getAll is not supported\n const result = await this._withRetries((db: IDBDatabase) => {\n const getAllRequest = getObjectStore(db, false).getAll();\n return new DBPromise<DBObject[] | null>(getAllRequest).toPromise();\n });\n\n if (!result) {\n return [];\n }\n\n // If we have pending writes in progress abort, we'll get picked up on the next poll\n if (this.pendingWrites !== 0) {\n return [];\n }\n\n const keys = [];\n const keysInResult = new Set();\n for (const { fbase_key: key, value } of result) {\n keysInResult.add(key);\n if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {\n this.notifyListeners(key, value as PersistenceValue);\n keys.push(key);\n }\n }\n for (const localKey of Object.keys(this.localCache)) {\n if (this.localCache[localKey] && !keysInResult.has(localKey)) {\n // Deleted\n this.notifyListeners(localKey, null);\n keys.push(localKey);\n }\n }\n return keys;\n }\n\n private notifyListeners(\n key: string,\n newValue: PersistenceValue | null\n ): void {\n this.localCache[key] = newValue;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(newValue);\n }\n }\n }\n\n private startPolling(): void {\n this.stopPolling();\n\n this.pollTimer = setInterval(\n async () => this._poll(),\n _POLLING_INTERVAL_MS\n );\n }\n\n private stopPolling(): void {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n _addListener(key: string, listener: StorageEventListener): void {\n if (Object.keys(this.listeners).length === 0) {\n this.startPolling();\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n void this._get(key); // This can happen in the background async and we can return immediately.\n }\n this.listeners[key].add(listener);\n }\n\n _removeListener(key: string, listener: StorageEventListener): void {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n\n if (Object.keys(this.listeners).length === 0) {\n this.stopPolling();\n }\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`\n * for the underlying storage.\n *\n * @public\n */\nexport const indexedDBLocalPersistence: Persistence = IndexedDBLocalPersistence;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { querystring } from '@firebase/util';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert, _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as jsHelpers from '../load_js';\nimport { Recaptcha, isV2 } from './recaptcha';\nimport { MockReCaptcha } from './recaptcha_mock';\n\n// ReCaptcha will load using the same callback, so the callback function needs\n// to be kept around\nexport const _JSLOAD_CALLBACK = jsHelpers._generateCallbackName('rcb');\nconst NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);\nconst RECAPTCHA_BASE = 'https://www.google.com/recaptcha/api.js?';\n\n/**\n * We need to mark this interface as internal explicitly to exclude it in the public typings, because\n * it references AuthInternal which has a circular dependency with UserInternal.\n *\n * @internal\n */\nexport interface ReCaptchaLoader {\n load(auth: AuthInternal, hl?: string): Promise<Recaptcha>;\n clearedOneInstance(): void;\n}\n\n/**\n * Loader for the GReCaptcha library. There should only ever be one of this.\n */\nexport class ReCaptchaLoaderImpl implements ReCaptchaLoader {\n private hostLanguage = '';\n private counter = 0;\n /**\n * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise\n * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but\n * `window.grecaptcha.render()` will not. Another load will add it.\n */\n private readonly librarySeparatelyLoaded = !!_window().grecaptcha?.render;\n\n load(auth: AuthInternal, hl = ''): Promise<Recaptcha> {\n _assert(isHostLanguageValid(hl), auth, AuthErrorCode.ARGUMENT_ERROR);\n\n if (this.shouldResolveImmediately(hl) && isV2(_window().grecaptcha)) {\n return Promise.resolve(_window().grecaptcha! as Recaptcha);\n }\n return new Promise<Recaptcha>((resolve, reject) => {\n const networkTimeout = _window().setTimeout(() => {\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n }, NETWORK_TIMEOUT_DELAY.get());\n\n _window()[_JSLOAD_CALLBACK] = () => {\n _window().clearTimeout(networkTimeout);\n delete _window()[_JSLOAD_CALLBACK];\n\n const recaptcha = _window().grecaptcha as Recaptcha;\n\n if (!recaptcha || !isV2(recaptcha)) {\n reject(_createError(auth, AuthErrorCode.INTERNAL_ERROR));\n return;\n }\n\n // Wrap the greptcha render function so that we know if the developer has\n // called it separately\n const render = recaptcha.render;\n recaptcha.render = (container, params) => {\n const widgetId = render(container, params);\n this.counter++;\n return widgetId;\n };\n\n this.hostLanguage = hl;\n resolve(recaptcha);\n };\n\n const url = `${RECAPTCHA_BASE}?${querystring({\n onload: _JSLOAD_CALLBACK,\n render: 'explicit',\n hl\n })}`;\n\n jsHelpers._loadJS(url).catch(() => {\n clearTimeout(networkTimeout);\n reject(_createError(auth, AuthErrorCode.INTERNAL_ERROR));\n });\n });\n }\n\n clearedOneInstance(): void {\n this.counter--;\n }\n\n private shouldResolveImmediately(hl: string): boolean {\n // We can resolve immediately if:\n // • grecaptcha is already defined AND (\n // 1. the requested language codes are the same OR\n // 2. there exists already a ReCaptcha on the page\n // 3. the library was already loaded by the app\n // In cases (2) and (3), we _can't_ reload as it would break the recaptchas\n // that are already in the page\n return (\n !!_window().grecaptcha?.render &&\n (hl === this.hostLanguage ||\n this.counter > 0 ||\n this.librarySeparatelyLoaded)\n );\n }\n}\n\nfunction isHostLanguageValid(hl: string): boolean {\n return hl.length <= 6 && /^\\s*[a-zA-Z0-9\\-]*\\s*$/.test(hl);\n}\n\nexport class MockReCaptchaLoaderImpl implements ReCaptchaLoader {\n async load(auth: AuthInternal): Promise<Recaptcha> {\n return new MockReCaptcha(auth);\n }\n\n clearedOneInstance(): void {}\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth, RecaptchaParameters } from '../../model/public_types';\nimport { getRecaptchaParams } from '../../api/authentication/recaptcha';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport { _isHttpOrHttps } from '../../core/util/location';\nimport { ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport { _isWorker } from '../util/worker';\nimport { Recaptcha } from './recaptcha';\nimport {\n MockReCaptchaLoaderImpl,\n ReCaptchaLoader,\n ReCaptchaLoaderImpl\n} from './recaptcha_loader';\n\nexport const RECAPTCHA_VERIFIER_TYPE = 'recaptcha';\n\nconst DEFAULT_PARAMS: RecaptchaParameters = {\n theme: 'light',\n type: 'image'\n};\n\ntype TokenCallback = (token: string) => void;\n\n/**\n * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.\n *\n * @remarks\n * `RecaptchaVerifier` does not work in a Node.js environment.\n *\n * @public\n */\nexport class RecaptchaVerifier implements ApplicationVerifierInternal {\n /**\n * The application verifier type.\n *\n * @remarks\n * For a reCAPTCHA verifier, this is 'recaptcha'.\n */\n readonly type = RECAPTCHA_VERIFIER_TYPE;\n private destroyed = false;\n private widgetId: number | null = null;\n private readonly container: HTMLElement;\n private readonly isInvisible: boolean;\n private readonly tokenChangeListeners = new Set<TokenCallback>();\n private renderPromise: Promise<number> | null = null;\n private readonly auth: AuthInternal;\n\n /** @internal */\n readonly _recaptchaLoader: ReCaptchaLoader;\n private recaptcha: Recaptcha | null = null;\n\n /**\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\n *\n * @param containerOrId - The reCAPTCHA container parameter.\n *\n * @remarks\n * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a\n * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to\n * an element ID. The corresponding element must also must be in the DOM at the time of\n * initialization.\n *\n * @param parameters - The optional reCAPTCHA parameters.\n *\n * @remarks\n * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for\n * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will\n * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value\n * 'invisible'.\n */\n constructor(\n authExtern: Auth,\n containerOrId: HTMLElement | string,\n private readonly parameters: RecaptchaParameters = {\n ...DEFAULT_PARAMS\n }\n ) {\n this.auth = _castAuth(authExtern);\n this.isInvisible = this.parameters.size === 'invisible';\n _assert(\n typeof document !== 'undefined',\n this.auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n const container =\n typeof containerOrId === 'string'\n ? document.getElementById(containerOrId)\n : containerOrId;\n _assert(container, this.auth, AuthErrorCode.ARGUMENT_ERROR);\n\n this.container = container;\n this.parameters.callback = this.makeTokenCallback(this.parameters.callback);\n\n this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting\n ? new MockReCaptchaLoaderImpl()\n : new ReCaptchaLoaderImpl();\n\n this.validateStartingState();\n // TODO: Figure out if sdk version is needed\n }\n\n /**\n * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.\n *\n * @returns A Promise for the reCAPTCHA token.\n */\n async verify(): Promise<string> {\n this.assertNotDestroyed();\n const id = await this.render();\n const recaptcha = this.getAssertedRecaptcha();\n\n const response = recaptcha.getResponse(id);\n if (response) {\n return response;\n }\n\n return new Promise<string>(resolve => {\n const tokenChange = (token: string): void => {\n if (!token) {\n return; // Ignore token expirations.\n }\n this.tokenChangeListeners.delete(tokenChange);\n resolve(token);\n };\n\n this.tokenChangeListeners.add(tokenChange);\n if (this.isInvisible) {\n recaptcha.execute(id);\n }\n });\n }\n\n /**\n * Renders the reCAPTCHA widget on the page.\n *\n * @returns A Promise that resolves with the reCAPTCHA widget ID.\n */\n render(): Promise<number> {\n try {\n this.assertNotDestroyed();\n } catch (e) {\n // This method returns a promise. Since it's not async (we want to return the\n // _same_ promise if rendering is still occurring), the API surface should\n // reject with the error rather than just throw\n return Promise.reject(e);\n }\n\n if (this.renderPromise) {\n return this.renderPromise;\n }\n\n this.renderPromise = this.makeRenderPromise().catch(e => {\n this.renderPromise = null;\n throw e;\n });\n\n return this.renderPromise;\n }\n\n /** @internal */\n _reset(): void {\n this.assertNotDestroyed();\n if (this.widgetId !== null) {\n this.getAssertedRecaptcha().reset(this.widgetId);\n }\n }\n\n /**\n * Clears the reCAPTCHA widget from the page and destroys the instance.\n */\n clear(): void {\n this.assertNotDestroyed();\n this.destroyed = true;\n this._recaptchaLoader.clearedOneInstance();\n if (!this.isInvisible) {\n this.container.childNodes.forEach(node => {\n this.container.removeChild(node);\n });\n }\n }\n\n private validateStartingState(): void {\n _assert(!this.parameters.sitekey, this.auth, AuthErrorCode.ARGUMENT_ERROR);\n _assert(\n this.isInvisible || !this.container.hasChildNodes(),\n this.auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n typeof document !== 'undefined',\n this.auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n }\n\n private makeTokenCallback(\n existing: TokenCallback | string | undefined\n ): TokenCallback {\n return token => {\n this.tokenChangeListeners.forEach(listener => listener(token));\n if (typeof existing === 'function') {\n existing(token);\n } else if (typeof existing === 'string') {\n const globalFunc = _window()[existing];\n if (typeof globalFunc === 'function') {\n globalFunc(token);\n }\n }\n };\n }\n\n private assertNotDestroyed(): void {\n _assert(!this.destroyed, this.auth, AuthErrorCode.INTERNAL_ERROR);\n }\n\n private async makeRenderPromise(): Promise<number> {\n await this.init();\n if (!this.widgetId) {\n let container = this.container;\n if (!this.isInvisible) {\n const guaranteedEmpty = document.createElement('div');\n container.appendChild(guaranteedEmpty);\n container = guaranteedEmpty;\n }\n\n this.widgetId = this.getAssertedRecaptcha().render(\n container,\n this.parameters\n );\n }\n\n return this.widgetId;\n }\n\n private async init(): Promise<void> {\n _assert(\n _isHttpOrHttps() && !_isWorker(),\n this.auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n\n await domReady();\n this.recaptcha = await this._recaptchaLoader.load(\n this.auth,\n this.auth.languageCode || undefined\n );\n\n const siteKey = await getRecaptchaParams(this.auth);\n _assert(siteKey, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.parameters.sitekey = siteKey;\n }\n\n private getAssertedRecaptcha(): Recaptcha {\n _assert(this.recaptcha, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return this.recaptcha;\n }\n}\n\nfunction domReady(): Promise<void> {\n let resolver: (() => void) | null = null;\n return new Promise<void>(resolve => {\n if (document.readyState === 'complete') {\n resolve();\n return;\n }\n\n // Document not ready, wait for load before resolving.\n // Save resolver, so we can remove listener in case it was externally\n // cancelled.\n resolver = () => resolve();\n window.addEventListener('load', resolver);\n }).catch(e => {\n if (resolver) {\n window.removeEventListener('load', resolver);\n }\n\n throw e;\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ApplicationVerifier,\n Auth,\n ConfirmationResult,\n PhoneInfoOptions,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { startEnrollPhoneMfa } from '../../api/account_management/mfa';\nimport { startSignInPhoneMfa } from '../../api/authentication/mfa';\nimport { sendPhoneVerificationCode } from '../../api/authentication/sms';\nimport { ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { PhoneAuthCredential } from '../../core/credentials/phone';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assertLinkedStatus, _link } from '../../core/user/link_unlink';\nimport { _assert } from '../../core/util/assert';\nimport { AuthInternal } from '../../model/auth';\nimport {\n linkWithCredential,\n reauthenticateWithCredential,\n signInWithCredential\n} from '../../core/strategies/credential';\nimport {\n MultiFactorSessionImpl,\n MultiFactorSessionType\n} from '../../mfa/mfa_session';\nimport { UserInternal } from '../../model/user';\nimport { RECAPTCHA_VERIFIER_TYPE } from '../recaptcha/recaptcha_verifier';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { ProviderId } from '../../model/enums';\n\ninterface OnConfirmationCallback {\n (credential: PhoneAuthCredential): Promise<UserCredential>;\n}\n\nclass ConfirmationResultImpl implements ConfirmationResult {\n constructor(\n readonly verificationId: string,\n private readonly onConfirmation: OnConfirmationCallback\n ) {}\n\n confirm(verificationCode: string): Promise<UserCredential> {\n const authCredential = PhoneAuthCredential._fromVerification(\n this.verificationId,\n verificationCode\n );\n return this.onConfirmation(authCredential);\n }\n}\n\n/**\n * Asynchronously signs in using a phone number.\n *\n * @remarks\n * This method sends a code via SMS to the given\n * phone number, and returns a {@link ConfirmationResult}. After the user\n * provides the code sent to their phone, call {@link ConfirmationResult.confirm}\n * with the code to sign the user in.\n *\n * For abuse prevention, this method also requires a {@link ApplicationVerifier}.\n * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.\n * This function can work on other platforms that do not support the\n * {@link RecaptchaVerifier} (like React Native), but you need to use a\n * third-party {@link ApplicationVerifier} implementation.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain a verificationCode from the user.\n * const credential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function signInWithPhoneNumber(\n auth: Auth,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise<ConfirmationResult> {\n const authInternal = _castAuth(auth);\n const verificationId = await _verifyPhoneNumber(\n authInternal,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n signInWithCredential(authInternal, cred)\n );\n}\n\n/**\n * Links the user account with the given phone number.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function linkWithPhoneNumber(\n user: User,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise<ConfirmationResult> {\n const userInternal = getModularInstance(user) as UserInternal;\n await _assertLinkedStatus(false, userInternal, ProviderId.PHONE);\n const verificationId = await _verifyPhoneNumber(\n userInternal.auth,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n linkWithCredential(userInternal, cred)\n );\n}\n\n/**\n * Re-authenticates a user using a fresh phone credential.\n *\n * @remarks\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.\n *\n * This method does not work in a Node.js environment.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function reauthenticateWithPhoneNumber(\n user: User,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise<ConfirmationResult> {\n const userInternal = getModularInstance(user) as UserInternal;\n const verificationId = await _verifyPhoneNumber(\n userInternal.auth,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n reauthenticateWithCredential(userInternal, cred)\n );\n}\n\n/**\n * Returns a verification ID to be used in conjunction with the SMS code that is sent.\n *\n */\nexport async function _verifyPhoneNumber(\n auth: AuthInternal,\n options: PhoneInfoOptions | string,\n verifier: ApplicationVerifierInternal\n): Promise<string> {\n const recaptchaToken = await verifier.verify();\n\n try {\n _assert(\n typeof recaptchaToken === 'string',\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n verifier.type === RECAPTCHA_VERIFIER_TYPE,\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n\n let phoneInfoOptions: PhoneInfoOptions;\n\n if (typeof options === 'string') {\n phoneInfoOptions = {\n phoneNumber: options\n };\n } else {\n phoneInfoOptions = options;\n }\n\n if ('session' in phoneInfoOptions) {\n const session = phoneInfoOptions.session as MultiFactorSessionImpl;\n\n if ('phoneNumber' in phoneInfoOptions) {\n _assert(\n session.type === MultiFactorSessionType.ENROLL,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const response = await startEnrollPhoneMfa(auth, {\n idToken: session.credential,\n phoneEnrollmentInfo: {\n phoneNumber: phoneInfoOptions.phoneNumber,\n recaptchaToken\n }\n });\n return response.phoneSessionInfo.sessionInfo;\n } else {\n _assert(\n session.type === MultiFactorSessionType.SIGN_IN,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const mfaEnrollmentId =\n phoneInfoOptions.multiFactorHint?.uid ||\n phoneInfoOptions.multiFactorUid;\n _assert(mfaEnrollmentId, auth, AuthErrorCode.MISSING_MFA_INFO);\n const response = await startSignInPhoneMfa(auth, {\n mfaPendingCredential: session.credential,\n mfaEnrollmentId,\n phoneSignInInfo: {\n recaptchaToken\n }\n });\n return response.phoneResponseInfo.sessionInfo;\n }\n } else {\n const { sessionInfo } = await sendPhoneVerificationCode(auth, {\n phoneNumber: phoneInfoOptions.phoneNumber,\n recaptchaToken\n });\n return sessionInfo;\n }\n } finally {\n verifier._reset();\n }\n}\n\n/**\n * Updates the user's phone number.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * await updatePhoneNumber(user, phoneCredential);\n * ```\n *\n * @param user - The user.\n * @param credential - A credential authenticating the new phone number.\n *\n * @public\n */\nexport async function updatePhoneNumber(\n user: User,\n credential: PhoneAuthCredential\n): Promise<void> {\n await _link(getModularInstance(user) as UserInternal, credential);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { SignInWithPhoneNumberRequest } from '../authentication/sms';\nimport { FinalizeMfaResponse } from '../authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\n\n/**\n * MFA Info as returned by the API.\n */\ninterface BaseMfaEnrollment {\n mfaEnrollmentId: string;\n enrolledAt: number;\n displayName?: string;\n}\n\n/**\n * An MFA provided by SMS verification.\n */\nexport interface PhoneMfaEnrollment extends BaseMfaEnrollment {\n phoneInfo: string;\n}\n\n/**\n * An MFA provided by TOTP (Time-based One Time Password).\n */\nexport interface TotpMfaEnrollment extends BaseMfaEnrollment {}\n\n/**\n * MfaEnrollment can be any subtype of BaseMfaEnrollment, currently only PhoneMfaEnrollment and TotpMfaEnrollment are supported.\n */\nexport type MfaEnrollment = PhoneMfaEnrollment | TotpMfaEnrollment;\n\nexport interface StartPhoneMfaEnrollmentRequest {\n idToken: string;\n phoneEnrollmentInfo: {\n phoneNumber: string;\n recaptchaToken: string;\n };\n tenantId?: string;\n}\n\nexport interface StartPhoneMfaEnrollmentResponse {\n phoneSessionInfo: {\n sessionInfo: string;\n };\n}\n\nexport function startEnrollPhoneMfa(\n auth: AuthInternal,\n request: StartPhoneMfaEnrollmentRequest\n): Promise<StartPhoneMfaEnrollmentResponse> {\n return _performApiRequest<\n StartPhoneMfaEnrollmentRequest,\n StartPhoneMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface FinalizePhoneMfaEnrollmentRequest {\n idToken: string;\n phoneVerificationInfo: SignInWithPhoneNumberRequest;\n displayName?: string | null;\n tenantId?: string;\n}\n\nexport interface FinalizePhoneMfaEnrollmentResponse\n extends FinalizeMfaResponse {}\n\nexport function finalizeEnrollPhoneMfa(\n auth: AuthInternal,\n request: FinalizePhoneMfaEnrollmentRequest\n): Promise<FinalizePhoneMfaEnrollmentResponse> {\n return _performApiRequest<\n FinalizePhoneMfaEnrollmentRequest,\n FinalizePhoneMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\nexport interface StartTotpMfaEnrollmentRequest {\n idToken: string;\n totpEnrollmentInfo: {};\n tenantId?: string;\n}\n\nexport interface StartTotpMfaEnrollmentResponse {\n totpSessionInfo: {\n sharedSecretKey: string;\n verificationCodeLength: number;\n hashingAlgorithm: string;\n periodSec: number;\n sessionInfo: string;\n finalizeEnrollmentTime: number;\n };\n}\n\nexport function startEnrollTotpMfa(\n auth: AuthInternal,\n request: StartTotpMfaEnrollmentRequest\n): Promise<StartTotpMfaEnrollmentResponse> {\n return _performApiRequest<\n StartTotpMfaEnrollmentRequest,\n StartTotpMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface TotpVerificationInfo {\n sessionInfo: string;\n verificationCode: string;\n}\nexport interface FinalizeTotpMfaEnrollmentRequest {\n idToken: string;\n totpVerificationInfo: TotpVerificationInfo;\n displayName?: string | null;\n tenantId?: string;\n}\n\nexport interface FinalizeTotpMfaEnrollmentResponse\n extends FinalizeMfaResponse {}\n\nexport function finalizeEnrollTotpMfa(\n auth: AuthInternal,\n request: FinalizeTotpMfaEnrollmentRequest\n): Promise<FinalizeTotpMfaEnrollmentResponse> {\n return _performApiRequest<\n FinalizeTotpMfaEnrollmentRequest,\n FinalizeTotpMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface WithdrawMfaRequest {\n idToken: string;\n mfaEnrollmentId: string;\n tenantId?: string;\n}\n\nexport interface WithdrawMfaResponse extends FinalizeMfaResponse {}\n\nexport function withdrawMfa(\n auth: AuthInternal,\n request: WithdrawMfaRequest\n): Promise<WithdrawMfaResponse> {\n return _performApiRequest<WithdrawMfaRequest, WithdrawMfaResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.WITHDRAW_MFA,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _performApiRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { MfaEnrollment } from '../account_management/mfa';\nimport { SignInWithIdpResponse } from './idp';\nimport {\n SignInWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n} from './sms';\n\nexport interface FinalizeMfaResponse {\n idToken: string;\n refreshToken: string;\n}\n\n/**\n * @internal\n */\nexport interface IdTokenMfaResponse extends IdTokenResponse {\n mfaPendingCredential?: string;\n mfaInfo?: MfaEnrollment[];\n}\n\nexport interface StartPhoneMfaSignInRequest {\n mfaPendingCredential: string;\n mfaEnrollmentId: string;\n phoneSignInInfo: {\n recaptchaToken: string;\n };\n tenantId?: string;\n}\n\nexport interface StartPhoneMfaSignInResponse {\n phoneResponseInfo: {\n sessionInfo: string;\n };\n}\n\nexport function startSignInPhoneMfa(\n auth: Auth,\n request: StartPhoneMfaSignInRequest\n): Promise<StartPhoneMfaSignInResponse> {\n return _performApiRequest<\n StartPhoneMfaSignInRequest,\n StartPhoneMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface FinalizePhoneMfaSignInRequest {\n mfaPendingCredential: string;\n phoneVerificationInfo: SignInWithPhoneNumberRequest;\n tenantId?: string;\n}\n\n// TOTP MFA Sign in only has a finalize phase. Phone MFA has a start phase to initiate sending an\n// SMS and a finalize phase to complete sign in. With TOTP, the user already has the OTP in the\n// TOTP/Authenticator app.\nexport interface FinalizeTotpMfaSignInRequest {\n mfaPendingCredential: string;\n totpVerificationInfo: { verificationCode: string };\n tenantId?: string;\n mfaEnrollmentId: string;\n}\n\nexport interface FinalizePhoneMfaSignInResponse extends FinalizeMfaResponse {}\n\nexport interface FinalizeTotpMfaSignInResponse extends FinalizeMfaResponse {}\n\nexport function finalizeSignInPhoneMfa(\n auth: Auth,\n request: FinalizePhoneMfaSignInRequest\n): Promise<FinalizePhoneMfaSignInResponse> {\n return _performApiRequest<\n FinalizePhoneMfaSignInRequest,\n FinalizePhoneMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport function finalizeSignInTotpMfa(\n auth: Auth,\n request: FinalizeTotpMfaSignInRequest\n): Promise<FinalizeTotpMfaSignInResponse> {\n return _performApiRequest<\n FinalizeTotpMfaSignInRequest,\n FinalizeTotpMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\n/**\n * @internal\n */\nexport type PhoneOrOauthTokenResponse =\n | SignInWithPhoneNumberResponse\n | SignInWithIdpResponse\n | IdTokenResponse;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n PhoneInfoOptions,\n ApplicationVerifier,\n UserCredential\n} from '../../model/public_types';\n\nimport { SignInWithPhoneNumberResponse } from '../../api/authentication/sms';\nimport { ApplicationVerifierInternal as ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { AuthInternal as AuthInternal } from '../../model/auth';\nimport { UserCredentialInternal as UserCredentialInternal } from '../../model/user';\nimport { PhoneAuthCredential } from '../../core/credentials/phone';\nimport { _verifyPhoneNumber } from '../strategies/phone';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthCredential } from '../../core';\nimport { FirebaseError, getModularInstance } from '@firebase/util';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link PhoneAuthCredential}.\n *\n * @remarks\n * `PhoneAuthProvider` does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, phoneCredential);\n * ```\n *\n * @public\n */\nexport class PhoneAuthProvider {\n /** Always set to {@link ProviderId}.PHONE. */\n static readonly PROVIDER_ID: 'phone' = ProviderId.PHONE;\n /** Always set to {@link SignInMethod}.PHONE. */\n static readonly PHONE_SIGN_IN_METHOD: 'phone' = SignInMethod.PHONE;\n\n /** Always set to {@link ProviderId}.PHONE. */\n readonly providerId = PhoneAuthProvider.PROVIDER_ID;\n private readonly auth: AuthInternal;\n\n /**\n * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.\n *\n */\n constructor(auth: Auth) {\n this.auth = _castAuth(auth);\n }\n\n /**\n *\n * Starts a phone number authentication flow by sending a verification code to the given phone\n * number.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in\n * E.164 format (e.g. +16505550101).\n * @param applicationVerifier - For abuse prevention, this method also requires a\n * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,\n * {@link RecaptchaVerifier}.\n *\n * @returns A Promise for a verification ID that can be passed to\n * {@link PhoneAuthProvider.credential} to identify this flow..\n */\n verifyPhoneNumber(\n phoneOptions: PhoneInfoOptions | string,\n applicationVerifier: ApplicationVerifier\n ): Promise<string> {\n return _verifyPhoneNumber(\n this.auth,\n phoneOptions,\n getModularInstance(applicationVerifier as ApplicationVerifierInternal)\n );\n }\n\n /**\n * Creates a phone auth credential, given the verification ID from\n * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's\n * mobile device.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.\n * @param verificationCode - The verification code sent to the user's mobile device.\n *\n * @returns The auth provider credential.\n */\n static credential(\n verificationId: string,\n verificationCode: string\n ): PhoneAuthCredential {\n return PhoneAuthCredential._fromVerification(\n verificationId,\n verificationCode\n );\n }\n\n /**\n * Generates an {@link AuthCredential} from a {@link UserCredential}.\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): AuthCredential | null {\n const credential = userCredential as UserCredentialInternal;\n return PhoneAuthProvider.credentialFromTaggedObject(credential);\n }\n\n /**\n * Returns an {@link AuthCredential} when passed an error.\n *\n * @remarks\n *\n * This method works for errors like\n * `auth/account-exists-with-different-credentials`. This is useful for\n * recovering when attempting to set a user's phone number but the number\n * in question is already tied to another account. For example, the following\n * code tries to update the current user's phone number, and if that\n * fails, links the user with the account associated with that number:\n *\n * ```js\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(number, verifier);\n * try {\n * const code = ''; // Prompt the user for the verification code\n * await updatePhoneNumber(\n * auth.currentUser,\n * PhoneAuthProvider.credential(verificationId, code));\n * } catch (e) {\n * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {\n * const cred = PhoneAuthProvider.credentialFromError(e);\n * await linkWithCredential(auth.currentUser, cred);\n * }\n * }\n *\n * // At this point, auth.currentUser.phoneNumber === number.\n * ```\n *\n * @param error - The error to generate a credential from.\n */\n static credentialFromError(error: FirebaseError): AuthCredential | null {\n return PhoneAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): AuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n const { phoneNumber, temporaryProof } =\n tokenResponse as SignInWithPhoneNumberResponse;\n if (phoneNumber && temporaryProof) {\n return PhoneAuthCredential._fromTokenResponse(\n phoneNumber,\n temporaryProof\n );\n }\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PopupRedirectResolver } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\nimport { PopupRedirectResolverInternal } from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from './assert';\nimport { _getInstance } from './instantiator';\n\n/**\n * Chooses a popup/redirect resolver to use. This prefers the override (which\n * is directly passed in), and falls back to the property set on the auth\n * object. If neither are available, this function errors w/ an argument error.\n */\nexport function _withDefaultResolver(\n auth: AuthInternal,\n resolverOverride: PopupRedirectResolver | undefined\n): PopupRedirectResolverInternal {\n if (resolverOverride) {\n return _getInstance(resolverOverride);\n }\n\n _assert(auth._popupRedirectResolver, auth, AuthErrorCode.ARGUMENT_ERROR);\n\n return auth._popupRedirectResolver;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { _link as _linkUser } from '../user/link_unlink';\nimport { _reauthenticate } from '../user/reauthenticate';\nimport { _assert } from '../util/assert';\nimport { _signInWithCredential } from './credential';\nimport { AuthErrorCode } from '../errors';\nimport { ProviderId } from '../../model/enums';\n\nexport interface IdpTaskParams {\n auth: AuthInternal;\n requestUri: string;\n sessionId?: string;\n tenantId?: string;\n postBody?: string;\n pendingToken?: string;\n user?: UserInternal;\n bypassAuthState?: boolean;\n}\n\nexport type IdpTask = (\n params: IdpTaskParams\n) => Promise<UserCredentialInternal>;\n\nclass IdpCredential extends AuthCredential {\n constructor(readonly params: IdpTaskParams) {\n super(ProviderId.CUSTOM, ProviderId.CUSTOM);\n }\n\n _getIdTokenResponse(auth: AuthInternal): Promise<PhoneOrOauthTokenResponse> {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n return signInWithIdp(auth, this._buildIdpRequest(idToken));\n }\n\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n\n private _buildIdpRequest(idToken?: string): SignInWithIdpRequest {\n const request: SignInWithIdpRequest = {\n requestUri: this.params.requestUri,\n sessionId: this.params.sessionId,\n postBody: this.params.postBody,\n tenantId: this.params.tenantId,\n pendingToken: this.params.pendingToken,\n returnSecureToken: true,\n returnIdpCredential: true\n };\n\n if (idToken) {\n request.idToken = idToken;\n }\n\n return request;\n }\n}\n\nexport function _signIn(\n params: IdpTaskParams\n): Promise<UserCredentialInternal> {\n return _signInWithCredential(\n params.auth,\n new IdpCredential(params),\n params.bypassAuthState\n ) as Promise<UserCredentialInternal>;\n}\n\nexport function _reauth(\n params: IdpTaskParams\n): Promise<UserCredentialInternal> {\n const { auth, user } = params;\n _assert(user, auth, AuthErrorCode.INTERNAL_ERROR);\n return _reauthenticate(\n user,\n new IdpCredential(params),\n params.bypassAuthState\n );\n}\n\nexport async function _link(\n params: IdpTaskParams\n): Promise<UserCredentialInternal> {\n const { auth, user } = params;\n _assert(user, auth, AuthErrorCode.INTERNAL_ERROR);\n return _linkUser(user, new IdpCredential(params), params.bypassAuthState);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\nimport {\n AuthEvent,\n AuthEventConsumer,\n AuthEventType,\n EventManager,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { debugAssert, _fail } from '../util/assert';\nimport {\n _link,\n _reauth,\n _signIn,\n IdpTask,\n IdpTaskParams\n} from '../strategies/idp';\nimport { AuthInternal } from '../../model/auth';\n\ninterface PendingPromise {\n resolve: (cred: UserCredentialInternal | null) => void;\n reject: (error: Error) => void;\n}\n\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n */\nexport abstract class AbstractPopupRedirectOperation\n implements AuthEventConsumer\n{\n private pendingPromise: PendingPromise | null = null;\n private eventManager: EventManager | null = null;\n readonly filter: AuthEventType[];\n\n abstract eventId: string | null;\n\n constructor(\n protected readonly auth: AuthInternal,\n filter: AuthEventType | AuthEventType[],\n protected readonly resolver: PopupRedirectResolverInternal,\n protected user?: UserInternal,\n protected readonly bypassAuthState = false\n ) {\n this.filter = Array.isArray(filter) ? filter : [filter];\n }\n\n abstract onExecution(): Promise<void>;\n\n execute(): Promise<UserCredentialInternal | null> {\n return new Promise<UserCredentialInternal | null>(\n async (resolve, reject) => {\n this.pendingPromise = { resolve, reject };\n\n try {\n this.eventManager = await this.resolver._initialize(this.auth);\n await this.onExecution();\n this.eventManager.registerConsumer(this);\n } catch (e) {\n this.reject(e as Error);\n }\n }\n );\n }\n\n async onAuthEvent(event: AuthEvent): Promise<void> {\n const { urlResponse, sessionId, postBody, tenantId, error, type } = event;\n if (error) {\n this.reject(error);\n return;\n }\n\n const params: IdpTaskParams = {\n auth: this.auth,\n requestUri: urlResponse!,\n sessionId: sessionId!,\n tenantId: tenantId || undefined,\n postBody: postBody || undefined,\n user: this.user,\n bypassAuthState: this.bypassAuthState\n };\n\n try {\n this.resolve(await this.getIdpTask(type)(params));\n } catch (e) {\n this.reject(e as Error);\n }\n }\n\n onError(error: FirebaseError): void {\n this.reject(error);\n }\n\n private getIdpTask(type: AuthEventType): IdpTask {\n switch (type) {\n case AuthEventType.SIGN_IN_VIA_POPUP:\n case AuthEventType.SIGN_IN_VIA_REDIRECT:\n return _signIn;\n case AuthEventType.LINK_VIA_POPUP:\n case AuthEventType.LINK_VIA_REDIRECT:\n return _link;\n case AuthEventType.REAUTH_VIA_POPUP:\n case AuthEventType.REAUTH_VIA_REDIRECT:\n return _reauth;\n default:\n _fail(this.auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n protected resolve(cred: UserCredentialInternal | null): void {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.resolve(cred);\n this.unregisterAndCleanUp();\n }\n\n protected reject(error: Error): void {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.reject(error);\n this.unregisterAndCleanUp();\n }\n\n private unregisterAndCleanUp(): void {\n if (this.eventManager) {\n this.eventManager.unregisterConsumer(this);\n }\n\n this.pendingPromise = null;\n this.cleanUp();\n }\n\n abstract cleanUp(): void;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n AuthProvider,\n PopupRedirectResolver,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthErrorCode } from '../../core/errors';\nimport {\n _assert,\n debugAssert,\n _createError,\n _assertInstanceOf\n} from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { _generateEventId } from '../../core/util/event_id';\nimport { AuthInternal } from '../../model/auth';\nimport {\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport { _withDefaultResolver } from '../../core/util/resolver';\nimport { AuthPopup } from '../util/popup';\nimport { AbstractPopupRedirectOperation } from '../../core/strategies/abstract_popup_redirect_operation';\nimport { FederatedAuthProvider } from '../../core/providers/federated';\nimport { getModularInstance } from '@firebase/util';\n\n/*\n * The event timeout is the same on mobile and desktop, no need for Delay. Set this to 8s since\n * blocking functions can take upto 7s to complete sign in, as documented in:\n * https://cloud.google.com/identity-platform/docs/blocking-functions#understanding_blocking_functions\n * https://firebase.google.com/docs/auth/extend-with-blocking-functions#understanding_blocking_functions\n */\nexport const enum _Timeout {\n AUTH_EVENT = 8000\n}\nexport const _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);\n\n/**\n * Authenticates a Firebase client using a popup-based OAuth authentication flow.\n *\n * @remarks\n * If succeeds, returns the signed in user along with the provider's credential. If sign in was\n * unsuccessful, returns an error object containing additional information about the error.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function signInWithPopup(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<UserCredential> {\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n const action = new PopupOperation(\n authInternal,\n AuthEventType.SIGN_IN_VIA_POPUP,\n provider,\n resolverInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based\n * OAuth flow.\n *\n * @remarks\n * If the reauthentication is successful, the returned result will contain the user and the\n * provider's credential.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n * // Reauthenticate using a popup.\n * await reauthenticateWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function reauthenticateWithPopup(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<UserCredential> {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n const action = new PopupOperation(\n userInternal.auth,\n AuthEventType.REAUTH_VIA_POPUP,\n provider,\n resolverInternal,\n userInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Links the authenticated provider to the user account using a pop-up based OAuth flow.\n *\n * @remarks\n * If the linking is successful, the returned result will contain the user and the provider's credential.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a popup.\n * const provider = new FacebookAuthProvider();\n * await linkWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function linkWithPopup(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<UserCredential> {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n\n const action = new PopupOperation(\n userInternal.auth,\n AuthEventType.LINK_VIA_POPUP,\n provider,\n resolverInternal,\n userInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n *\n */\nclass PopupOperation extends AbstractPopupRedirectOperation {\n // Only one popup is ever shown at once. The lifecycle of the current popup\n // can be managed / cancelled by the constructor.\n private static currentPopupAction: PopupOperation | null = null;\n private authWindow: AuthPopup | null = null;\n private pollId: number | null = null;\n\n constructor(\n auth: AuthInternal,\n filter: AuthEventType,\n private readonly provider: AuthProvider,\n resolver: PopupRedirectResolverInternal,\n user?: UserInternal\n ) {\n super(auth, filter, resolver, user);\n if (PopupOperation.currentPopupAction) {\n PopupOperation.currentPopupAction.cancel();\n }\n\n PopupOperation.currentPopupAction = this;\n }\n\n async executeNotNull(): Promise<UserCredential> {\n const result = await this.execute();\n _assert(result, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return result;\n }\n\n async onExecution(): Promise<void> {\n debugAssert(\n this.filter.length === 1,\n 'Popup operations only handle one event'\n );\n const eventId = _generateEventId();\n this.authWindow = await this.resolver._openPopup(\n this.auth,\n this.provider,\n this.filter[0], // There's always one, see constructor\n eventId\n );\n this.authWindow.associatedEvent = eventId;\n\n // Check for web storage support and origin validation _after_ the popup is\n // loaded. These operations are slow (~1 second or so) Rather than\n // waiting on them before opening the window, optimistically open the popup\n // and check for storage support at the same time. If storage support is\n // not available, this will cause the whole thing to reject properly. It\n // will also close the popup, but since the promise has already rejected,\n // the popup closed by user poll will reject into the void.\n this.resolver._originValidation(this.auth).catch(e => {\n this.reject(e);\n });\n\n this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {\n if (!isSupported) {\n this.reject(\n _createError(this.auth, AuthErrorCode.WEB_STORAGE_UNSUPPORTED)\n );\n }\n });\n\n // Handle user closure. Notice this does *not* use await\n this.pollUserCancellation();\n }\n\n get eventId(): string | null {\n return this.authWindow?.associatedEvent || null;\n }\n\n cancel(): void {\n this.reject(_createError(this.auth, AuthErrorCode.EXPIRED_POPUP_REQUEST));\n }\n\n cleanUp(): void {\n if (this.authWindow) {\n this.authWindow.close();\n }\n\n if (this.pollId) {\n window.clearTimeout(this.pollId);\n }\n\n this.authWindow = null;\n this.pollId = null;\n PopupOperation.currentPopupAction = null;\n }\n\n private pollUserCancellation(): void {\n const poll = (): void => {\n if (this.authWindow?.window?.closed) {\n // Make sure that there is sufficient time for whatever action to\n // complete. The window could have closed but the sign in network\n // call could still be in flight. This is specifically true for\n // Firefox or if the opener is in an iframe, in which case the oauth\n // helper closes the popup.\n this.pollId = window.setTimeout(() => {\n this.pollId = null;\n this.reject(\n _createError(this.auth, AuthErrorCode.POPUP_CLOSED_BY_USER)\n );\n }, _Timeout.AUTH_EVENT);\n return;\n }\n\n this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());\n };\n\n poll();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthInternal } from '../../model/auth';\nimport {\n AuthEvent,\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserCredentialInternal } from '../../model/user';\nimport { PersistenceInternal } from '../persistence';\nimport { _persistenceKeyName } from '../persistence/persistence_user_manager';\nimport { _getInstance } from '../util/instantiator';\nimport { AbstractPopupRedirectOperation } from './abstract_popup_redirect_operation';\n\nconst PENDING_REDIRECT_KEY = 'pendingRedirect';\n\n// We only get one redirect outcome for any one auth, so just store it\n// in here.\nconst redirectOutcomeMap: Map<\n string,\n () => Promise<UserCredentialInternal | null>\n> = new Map();\n\nexport class RedirectAction extends AbstractPopupRedirectOperation {\n eventId = null;\n\n constructor(\n auth: AuthInternal,\n resolver: PopupRedirectResolverInternal,\n bypassAuthState = false\n ) {\n super(\n auth,\n [\n AuthEventType.SIGN_IN_VIA_REDIRECT,\n AuthEventType.LINK_VIA_REDIRECT,\n AuthEventType.REAUTH_VIA_REDIRECT,\n AuthEventType.UNKNOWN\n ],\n resolver,\n undefined,\n bypassAuthState\n );\n }\n\n /**\n * Override the execute function; if we already have a redirect result, then\n * just return it.\n */\n async execute(): Promise<UserCredentialInternal | null> {\n let readyOutcome = redirectOutcomeMap.get(this.auth._key());\n if (!readyOutcome) {\n try {\n const hasPendingRedirect = await _getAndClearPendingRedirectStatus(\n this.resolver,\n this.auth\n );\n const result = hasPendingRedirect ? await super.execute() : null;\n readyOutcome = () => Promise.resolve(result);\n } catch (e) {\n readyOutcome = () => Promise.reject(e);\n }\n\n redirectOutcomeMap.set(this.auth._key(), readyOutcome);\n }\n\n // If we're not bypassing auth state, the ready outcome should be set to\n // null.\n if (!this.bypassAuthState) {\n redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));\n }\n\n return readyOutcome();\n }\n\n async onAuthEvent(event: AuthEvent): Promise<void> {\n if (event.type === AuthEventType.SIGN_IN_VIA_REDIRECT) {\n return super.onAuthEvent(event);\n } else if (event.type === AuthEventType.UNKNOWN) {\n // This is a sentinel value indicating there's no pending redirect\n this.resolve(null);\n return;\n }\n\n if (event.eventId) {\n const user = await this.auth._redirectUserForId(event.eventId);\n if (user) {\n this.user = user;\n return super.onAuthEvent(event);\n } else {\n this.resolve(null);\n }\n }\n }\n\n async onExecution(): Promise<void> {}\n\n cleanUp(): void {}\n}\n\nexport async function _getAndClearPendingRedirectStatus(\n resolver: PopupRedirectResolverInternal,\n auth: AuthInternal\n): Promise<boolean> {\n const key = pendingRedirectKey(auth);\n const persistence = resolverPersistence(resolver);\n if (!(await persistence._isAvailable())) {\n return false;\n }\n const hasPendingRedirect = (await persistence._get(key)) === 'true';\n await persistence._remove(key);\n return hasPendingRedirect;\n}\n\nexport async function _setPendingRedirectStatus(\n resolver: PopupRedirectResolverInternal,\n auth: AuthInternal\n): Promise<void> {\n return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');\n}\n\nexport function _clearRedirectOutcomes(): void {\n redirectOutcomeMap.clear();\n}\n\nexport function _overrideRedirectResult(\n auth: AuthInternal,\n result: () => Promise<UserCredentialInternal | null>\n): void {\n redirectOutcomeMap.set(auth._key(), result);\n}\n\nfunction resolverPersistence(\n resolver: PopupRedirectResolverInternal\n): PersistenceInternal {\n return _getInstance(resolver._redirectPersistence);\n}\n\nfunction pendingRedirectKey(auth: AuthInternal): string {\n return _persistenceKeyName(\n PENDING_REDIRECT_KEY,\n auth.config.apiKey,\n auth.name\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n AuthProvider,\n PopupRedirectResolver,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { _assertLinkedStatus } from '../../core/user/link_unlink';\nimport { _assertInstanceOf } from '../../core/util/assert';\nimport { _generateEventId } from '../../core/util/event_id';\nimport { AuthEventType } from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport { _withDefaultResolver } from '../../core/util/resolver';\nimport {\n RedirectAction,\n _setPendingRedirectStatus\n} from '../../core/strategies/redirect';\nimport { FederatedAuthProvider } from '../../core/providers/federated';\nimport { getModularInstance } from '@firebase/util';\n\n/**\n * Authenticates a Firebase client using a full-page redirect flow.\n *\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link signInWithRedirect}.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function signInWithRedirect(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<never> {\n return _signInWithRedirect(auth, provider, resolver) as Promise<never>;\n}\n\nexport async function _signInWithRedirect(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<void | never> {\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await authInternal._initializationPromise;\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n await _setPendingRedirectStatus(resolverInternal, authInternal);\n\n return resolverInternal._openRedirect(\n authInternal,\n provider,\n AuthEventType.SIGN_IN_VIA_REDIRECT\n );\n}\n\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link reauthenticateWithRedirect}.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * // Reauthenticate using a redirect.\n * await reauthenticateWithRedirect(result.user, provider);\n * // This will again trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function reauthenticateWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<never> {\n return _reauthenticateWithRedirect(\n user,\n provider,\n resolver\n ) as Promise<never>;\n}\nexport async function _reauthenticateWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<void | never> {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await userInternal.auth._initializationPromise;\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(\n userInternal.auth,\n provider,\n AuthEventType.REAUTH_VIA_REDIRECT,\n eventId\n );\n}\n\n/**\n * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link linkWithRedirect}.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a redirect.\n * const provider = new FacebookAuthProvider();\n * await linkWithRedirect(result.user, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function linkWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<never> {\n return _linkWithRedirect(user, provider, resolver) as Promise<never>;\n}\nexport async function _linkWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<void | never> {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await userInternal.auth._initializationPromise;\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _assertLinkedStatus(false, userInternal, provider.providerId);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(\n userInternal.auth,\n provider,\n AuthEventType.LINK_VIA_REDIRECT,\n eventId\n );\n}\n\n/**\n * Returns a {@link UserCredential} from the redirect-based sign-in flow.\n *\n * @remarks\n * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an\n * error. If no redirect operation was called, returns `null`.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function getRedirectResult(\n auth: Auth,\n resolver?: PopupRedirectResolver\n): Promise<UserCredential | null> {\n await _castAuth(auth)._initializationPromise;\n return _getRedirectResult(auth, resolver, false);\n}\n\nexport async function _getRedirectResult(\n auth: Auth,\n resolverExtern?: PopupRedirectResolver,\n bypassAuthState = false\n): Promise<UserCredential | null> {\n const authInternal = _castAuth(auth);\n const resolver = _withDefaultResolver(authInternal, resolverExtern);\n const action = new RedirectAction(authInternal, resolver, bypassAuthState);\n const result = await action.execute();\n\n if (result && !bypassAuthState) {\n delete result.user._redirectEventId;\n await authInternal._persistUserIfCurrent(result.user as UserInternal);\n await authInternal._setRedirectUser(null, resolverExtern);\n }\n\n return result;\n}\n\nasync function prepareUserForRedirect(user: UserInternal): Promise<string> {\n const eventId = _generateEventId(`${user.uid}:::`);\n user._redirectEventId = eventId;\n await user.auth._setRedirectUser(user);\n await user.auth._persistUserIfCurrent(user);\n return eventId;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AuthEvent,\n AuthEventConsumer,\n AuthEventType,\n EventManager\n} from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { AuthInternal } from '../../model/auth';\nimport { _createError } from '../util/assert';\n\n// The amount of time to store the UIDs of seen events; this is\n// set to 10 min by default\nconst EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;\n\nexport class AuthEventManager implements EventManager {\n private readonly cachedEventUids: Set<string> = new Set();\n private readonly consumers: Set<AuthEventConsumer> = new Set();\n protected queuedRedirectEvent: AuthEvent | null = null;\n protected hasHandledPotentialRedirect = false;\n private lastProcessedEventTime = Date.now();\n\n constructor(private readonly auth: AuthInternal) {}\n\n registerConsumer(authEventConsumer: AuthEventConsumer): void {\n this.consumers.add(authEventConsumer);\n\n if (\n this.queuedRedirectEvent &&\n this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)\n ) {\n this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);\n this.saveEventToCache(this.queuedRedirectEvent);\n this.queuedRedirectEvent = null;\n }\n }\n\n unregisterConsumer(authEventConsumer: AuthEventConsumer): void {\n this.consumers.delete(authEventConsumer);\n }\n\n onEvent(event: AuthEvent): boolean {\n // Check if the event has already been handled\n if (this.hasEventBeenHandled(event)) {\n return false;\n }\n\n let handled = false;\n this.consumers.forEach(consumer => {\n if (this.isEventForConsumer(event, consumer)) {\n handled = true;\n this.sendToConsumer(event, consumer);\n this.saveEventToCache(event);\n }\n });\n\n if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {\n // If we've already seen a redirect before, or this is a popup event,\n // bail now\n return handled;\n }\n\n this.hasHandledPotentialRedirect = true;\n\n // If the redirect wasn't handled, hang on to it\n if (!handled) {\n this.queuedRedirectEvent = event;\n handled = true;\n }\n\n return handled;\n }\n\n private sendToConsumer(event: AuthEvent, consumer: AuthEventConsumer): void {\n if (event.error && !isNullRedirectEvent(event)) {\n const code =\n (event.error.code?.split('auth/')[1] as AuthErrorCode) ||\n AuthErrorCode.INTERNAL_ERROR;\n consumer.onError(_createError(this.auth, code));\n } else {\n consumer.onAuthEvent(event);\n }\n }\n\n private isEventForConsumer(\n event: AuthEvent,\n consumer: AuthEventConsumer\n ): boolean {\n const eventIdMatches =\n consumer.eventId === null ||\n (!!event.eventId && event.eventId === consumer.eventId);\n return consumer.filter.includes(event.type) && eventIdMatches;\n }\n\n private hasEventBeenHandled(event: AuthEvent): boolean {\n if (\n Date.now() - this.lastProcessedEventTime >=\n EVENT_DUPLICATION_CACHE_DURATION_MS\n ) {\n this.cachedEventUids.clear();\n }\n\n return this.cachedEventUids.has(eventUid(event));\n }\n\n private saveEventToCache(event: AuthEvent): void {\n this.cachedEventUids.add(eventUid(event));\n this.lastProcessedEventTime = Date.now();\n }\n}\n\nfunction eventUid(e: AuthEvent): string {\n return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');\n}\n\nfunction isNullRedirectEvent({ type, error }: AuthEvent): boolean {\n return (\n type === AuthEventType.UNKNOWN &&\n error?.code === `auth/${AuthErrorCode.NO_AUTH_EVENT}`\n );\n}\n\nfunction isRedirectEvent(event: AuthEvent): boolean {\n switch (event.type) {\n case AuthEventType.SIGN_IN_VIA_REDIRECT:\n case AuthEventType.LINK_VIA_REDIRECT:\n case AuthEventType.REAUTH_VIA_REDIRECT:\n return true;\n case AuthEventType.UNKNOWN:\n return isNullRedirectEvent(event);\n default:\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProjectConfig } from '../../api/project_config/get_project_config';\nimport { AuthInternal } from '../../model/auth';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from './assert';\nimport { _getCurrentUrl } from './location';\n\nconst IP_ADDRESS_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\nconst HTTP_REGEX = /^https?/;\n\nexport async function _validateOrigin(auth: AuthInternal): Promise<void> {\n // Skip origin validation if we are in an emulated environment\n if (auth.config.emulator) {\n return;\n }\n\n const { authorizedDomains } = await _getProjectConfig(auth);\n\n for (const domain of authorizedDomains) {\n try {\n if (matchDomain(domain)) {\n return;\n }\n } catch {\n // Do nothing if there's a URL error; just continue searching\n }\n }\n\n // In the old SDK, this error also provides helpful messages.\n _fail(auth, AuthErrorCode.INVALID_ORIGIN);\n}\n\nfunction matchDomain(expected: string): boolean {\n const currentUrl = _getCurrentUrl();\n const { protocol, hostname } = new URL(currentUrl);\n if (expected.startsWith('chrome-extension://')) {\n const ceUrl = new URL(expected);\n\n if (ceUrl.hostname === '' && hostname === '') {\n // For some reason we're not parsing chrome URLs properly\n return (\n protocol === 'chrome-extension:' &&\n expected.replace('chrome-extension://', '') ===\n currentUrl.replace('chrome-extension://', '')\n );\n }\n\n return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;\n }\n\n if (!HTTP_REGEX.test(protocol)) {\n return false;\n }\n\n if (IP_ADDRESS_REGEX.test(expected)) {\n // The domain has to be exactly equal to the pattern, as an IP domain will\n // only contain the IP, no extra character.\n return hostname === expected;\n }\n\n // Dots in pattern should be escaped.\n const escapedDomainPattern = expected.replace(/\\./g, '\\\\.');\n // Non ip address domains.\n // domain.com = *.domain.com OR domain.com\n const re = new RegExp(\n '^(.+\\\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$',\n 'i'\n );\n return re.test(hostname);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _performApiRequest, Endpoint, HttpMethod } from '../index';\nimport { Auth } from '../../model/public_types';\n\nexport interface GetProjectConfigRequest {\n androidPackageName?: string;\n iosBundleId?: string;\n}\n\nexport interface GetProjectConfigResponse {\n authorizedDomains: string[];\n}\n\nexport async function _getProjectConfig(\n auth: Auth,\n request: GetProjectConfigRequest = {}\n): Promise<GetProjectConfigResponse> {\n return _performApiRequest<GetProjectConfigRequest, GetProjectConfigResponse>(\n auth,\n HttpMethod.GET,\n Endpoint.GET_PROJECT_CONFIG,\n request\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as js from '../load_js';\n\nconst NETWORK_TIMEOUT = new Delay(30000, 60000);\n\n/**\n * Reset unlaoded GApi modules. If gapi.load fails due to a network error,\n * it will stop working after a retrial. This is a hack to fix this issue.\n */\nfunction resetUnloadedGapiModules(): void {\n // Clear last failed gapi.load state to force next gapi.load to first\n // load the failed gapi.iframes module.\n // Get gapix.beacon context.\n const beacon = _window().___jsl;\n // Get current hint.\n if (beacon?.H) {\n // Get gapi hint.\n for (const hint of Object.keys(beacon.H)) {\n // Requested modules.\n beacon.H[hint].r = beacon.H[hint].r || [];\n // Loaded modules.\n beacon.H[hint].L = beacon.H[hint].L || [];\n // Set requested modules to a copy of the loaded modules.\n beacon.H[hint].r = [...beacon.H[hint].L];\n // Clear pending callbacks.\n if (beacon.CP) {\n for (let i = 0; i < beacon.CP.length; i++) {\n // Remove all failed pending callbacks.\n beacon.CP[i] = null;\n }\n }\n }\n }\n}\n\nfunction loadGapi(auth: AuthInternal): Promise<gapi.iframes.Context> {\n return new Promise<gapi.iframes.Context>((resolve, reject) => {\n // Function to run when gapi.load is ready.\n function loadGapiIframe(): void {\n // The developer may have tried to previously run gapi.load and failed.\n // Run this to fix that.\n resetUnloadedGapiModules();\n gapi.load('gapi.iframes', {\n callback: () => {\n resolve(gapi.iframes.getContext());\n },\n ontimeout: () => {\n // The above reset may be sufficient, but having this reset after\n // failure ensures that if the developer calls gapi.load after the\n // connection is re-established and before another attempt to embed\n // the iframe, it would work and would not be broken because of our\n // failed attempt.\n // Timeout when gapi.iframes.Iframe not loaded.\n resetUnloadedGapiModules();\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n },\n timeout: NETWORK_TIMEOUT.get()\n });\n }\n\n if (_window().gapi?.iframes?.Iframe) {\n // If gapi.iframes.Iframe available, resolve.\n resolve(gapi.iframes.getContext());\n } else if (!!_window().gapi?.load) {\n // Gapi loader ready, load gapi.iframes.\n loadGapiIframe();\n } else {\n // Create a new iframe callback when this is called so as not to overwrite\n // any previous defined callback. This happens if this method is called\n // multiple times in parallel and could result in the later callback\n // overwriting the previous one. This would end up with a iframe\n // timeout.\n const cbName = js._generateCallbackName('iframefcb');\n // GApi loader not available, dynamically load platform.js.\n _window()[cbName] = () => {\n // GApi loader should be ready.\n if (!!gapi.load) {\n loadGapiIframe();\n } else {\n // Gapi loader failed, throw error.\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n }\n };\n // Load GApi loader.\n return js\n ._loadJS(`https://apis.google.com/js/api.js?onload=${cbName}`)\n .catch(e => reject(e));\n }\n }).catch(error => {\n // Reset cached promise to allow for retrial.\n cachedGApiLoader = null;\n throw error;\n });\n}\n\nlet cachedGApiLoader: Promise<gapi.iframes.Context> | null = null;\nexport function _loadGapi(auth: AuthInternal): Promise<gapi.iframes.Context> {\n cachedGApiLoader = cachedGApiLoader || loadGapi(auth);\n return cachedGApiLoader;\n}\n\nexport function _resetLoader(): void {\n cachedGApiLoader = null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { querystring } from '@firebase/util';\nimport { DefaultConfig } from '../../../internal';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert, _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { _emulatorUrl } from '../../core/util/emulator';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as gapiLoader from './gapi';\n\nconst PING_TIMEOUT = new Delay(5000, 15000);\nconst IFRAME_PATH = '__/auth/iframe';\nconst EMULATED_IFRAME_PATH = 'emulator/auth/iframe';\n\nconst IFRAME_ATTRIBUTES = {\n style: {\n position: 'absolute',\n top: '-100px',\n width: '1px',\n height: '1px'\n },\n 'aria-hidden': 'true',\n tabindex: '-1'\n};\n\n// Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to\n// anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.\nconst EID_FROM_APIHOST = new Map([\n [DefaultConfig.API_HOST, 'p'], // production\n ['staging-identitytoolkit.sandbox.googleapis.com', 's'], // staging\n ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test\n]);\n\nfunction getIframeUrl(auth: AuthInternal): string {\n const config = auth.config;\n _assert(config.authDomain, auth, AuthErrorCode.MISSING_AUTH_DOMAIN);\n const url = config.emulator\n ? _emulatorUrl(config, EMULATED_IFRAME_PATH)\n : `https://${auth.config.authDomain}/${IFRAME_PATH}`;\n\n const params: Record<string, string> = {\n apiKey: config.apiKey,\n appName: auth.name,\n v: SDK_VERSION\n };\n const eid = EID_FROM_APIHOST.get(auth.config.apiHost);\n if (eid) {\n params.eid = eid;\n }\n const frameworks = auth._getFrameworks();\n if (frameworks.length) {\n params.fw = frameworks.join(',');\n }\n return `${url}?${querystring(params).slice(1)}`;\n}\n\nexport async function _openIframe(\n auth: AuthInternal\n): Promise<gapi.iframes.Iframe> {\n const context = await gapiLoader._loadGapi(auth);\n const gapi = _window().gapi;\n _assert(gapi, auth, AuthErrorCode.INTERNAL_ERROR);\n return context.open(\n {\n where: document.body,\n url: getIframeUrl(auth),\n messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,\n attributes: IFRAME_ATTRIBUTES,\n dontclear: true\n },\n (iframe: gapi.iframes.Iframe) =>\n new Promise(async (resolve, reject) => {\n await iframe.restyle({\n // Prevent iframe from closing on mouse out.\n setHideOnLeave: false\n });\n\n const networkError = _createError(\n auth,\n AuthErrorCode.NETWORK_REQUEST_FAILED\n );\n // Confirm iframe is correctly loaded.\n // To fallback on failure, set a timeout.\n const networkErrorTimer = _window().setTimeout(() => {\n reject(networkError);\n }, PING_TIMEOUT.get());\n // Clear timer and resolve pending iframe ready promise.\n function clearTimerAndResolve(): void {\n _window().clearTimeout(networkErrorTimer);\n resolve(iframe);\n }\n // This returns an IThenable. However the reject part does not call\n // when the iframe is not loaded.\n iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {\n reject(networkError);\n });\n })\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getUA } from '@firebase/util';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport {\n _isChromeIOS,\n _isFirefox,\n _isIOSStandalone\n} from '../../core/util/browser';\nimport { AuthInternal } from '../../model/auth';\n\nconst BASE_POPUP_OPTIONS = {\n location: 'yes',\n resizable: 'yes',\n statusbar: 'yes',\n toolbar: 'no'\n};\n\nconst DEFAULT_WIDTH = 500;\nconst DEFAULT_HEIGHT = 600;\nconst TARGET_BLANK = '_blank';\n\nconst FIREFOX_EMPTY_URL = 'http://localhost';\n\nexport class AuthPopup {\n associatedEvent: string | null = null;\n\n constructor(readonly window: Window | null) {}\n\n close(): void {\n if (this.window) {\n try {\n this.window.close();\n } catch (e) {}\n }\n }\n}\n\nexport function _open(\n auth: AuthInternal,\n url?: string,\n name?: string,\n width = DEFAULT_WIDTH,\n height = DEFAULT_HEIGHT\n): AuthPopup {\n const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();\n const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();\n let target = '';\n\n const options: { [key: string]: string } = {\n ...BASE_POPUP_OPTIONS,\n width: width.toString(),\n height: height.toString(),\n top,\n left\n };\n\n // Chrome iOS 7 and 8 is returning an undefined popup win when target is\n // specified, even though the popup is not necessarily blocked.\n const ua = getUA().toLowerCase();\n\n if (name) {\n target = _isChromeIOS(ua) ? TARGET_BLANK : name;\n }\n\n if (_isFirefox(ua)) {\n // Firefox complains when invalid URLs are popped out. Hacky way to bypass.\n url = url || FIREFOX_EMPTY_URL;\n // Firefox disables by default scrolling on popup windows, which can create\n // issues when the user has many Google accounts, for instance.\n options.scrollbars = 'yes';\n }\n\n const optionsString = Object.entries(options).reduce(\n (accum, [key, value]) => `${accum}${key}=${value},`,\n ''\n );\n\n if (_isIOSStandalone(ua) && target !== '_self') {\n openAsNewWindowIOS(url || '', target);\n return new AuthPopup(null);\n }\n\n // about:blank getting sanitized causing browsers like IE/Edge to display\n // brief error message before redirecting to handler.\n const newWin = window.open(url || '', target, optionsString);\n _assert(newWin, auth, AuthErrorCode.POPUP_BLOCKED);\n\n // Flaky on IE edge, encapsulate with a try and catch.\n try {\n newWin.focus();\n } catch (e) {}\n\n return new AuthPopup(newWin);\n}\n\nfunction openAsNewWindowIOS(url: string, target: string): void {\n const el = document.createElement('a');\n el.href = url;\n el.target = target;\n const click = document.createEvent('MouseEvent');\n click.initMouseEvent(\n 'click',\n true,\n true,\n window,\n 1,\n 0,\n 0,\n 0,\n 0,\n false,\n false,\n false,\n false,\n 1,\n null\n );\n el.dispatchEvent(click);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { AuthProvider } from '../../model/public_types';\nimport { ApiKey, AppName, AuthInternal } from '../../model/auth';\nimport { AuthEventType } from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from './assert';\nimport { isEmpty, querystring } from '@firebase/util';\nimport { _emulatorUrl } from './emulator';\nimport { FederatedAuthProvider } from '../providers/federated';\nimport { BaseOAuthProvider } from '../providers/oauth';\n\n/**\n * URL for Authentication widget which will initiate the OAuth handshake\n *\n * @internal\n */\nconst WIDGET_PATH = '__/auth/handler';\n\n/**\n * URL for emulated environment\n *\n * @internal\n */\nconst EMULATOR_WIDGET_PATH = 'emulator/auth/handler';\n\n/**\n * Fragment name for the App Check token that gets passed to the widget\n *\n * @internal\n */\nconst FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent('fac');\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ntype WidgetParams = {\n apiKey: ApiKey;\n appName: AppName;\n authType: AuthEventType;\n redirectUrl?: string;\n v: string;\n providerId?: string;\n scopes?: string;\n customParameters?: string;\n eventId?: string;\n tid?: string;\n} & { [key: string]: string | undefined };\n\nexport async function _getRedirectUrl(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n redirectUrl?: string,\n eventId?: string,\n additionalParams?: Record<string, string>\n): Promise<string> {\n _assert(auth.config.authDomain, auth, AuthErrorCode.MISSING_AUTH_DOMAIN);\n _assert(auth.config.apiKey, auth, AuthErrorCode.INVALID_API_KEY);\n\n const params: WidgetParams = {\n apiKey: auth.config.apiKey,\n appName: auth.name,\n authType,\n redirectUrl,\n v: SDK_VERSION,\n eventId\n };\n\n if (provider instanceof FederatedAuthProvider) {\n provider.setDefaultLanguage(auth.languageCode);\n params.providerId = provider.providerId || '';\n if (!isEmpty(provider.getCustomParameters())) {\n params.customParameters = JSON.stringify(provider.getCustomParameters());\n }\n\n // TODO set additionalParams from the provider as well?\n for (const [key, value] of Object.entries(additionalParams || {})) {\n params[key] = value;\n }\n }\n\n if (provider instanceof BaseOAuthProvider) {\n const scopes = provider.getScopes().filter(scope => scope !== '');\n if (scopes.length > 0) {\n params.scopes = scopes.join(',');\n }\n }\n\n if (auth.tenantId) {\n params.tid = auth.tenantId;\n }\n\n // TODO: maybe set eid as endipointId\n // TODO: maybe set fw as Frameworks.join(\",\")\n\n const paramsDict = params as Record<string, string | number>;\n for (const key of Object.keys(paramsDict)) {\n if (paramsDict[key] === undefined) {\n delete paramsDict[key];\n }\n }\n\n // Sets the App Check token to pass to the widget\n const appCheckToken = await auth._getAppCheckToken();\n const appCheckTokenFragment = appCheckToken\n ? `#${FIREBASE_APP_CHECK_FRAGMENT_ID}=${encodeURIComponent(appCheckToken)}`\n : '';\n\n // Start at index 1 to skip the leading '&' in the query string\n return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(\n 1\n )}${appCheckTokenFragment}`;\n}\n\nfunction getHandlerBase({ config }: AuthInternal): string {\n if (!config.emulator) {\n return `https://${config.authDomain}/${WIDGET_PATH}`;\n }\n\n return _emulatorUrl(config, EMULATOR_WIDGET_PATH);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider, PopupRedirectResolver } from '../model/public_types';\n\nimport { AuthEventManager } from '../core/auth/auth_event_manager';\nimport { AuthErrorCode } from '../core/errors';\nimport { _assert, debugAssert, _fail } from '../core/util/assert';\nimport { _generateEventId } from '../core/util/event_id';\nimport { _getCurrentUrl } from '../core/util/location';\nimport { _validateOrigin } from '../core/util/validate_origin';\nimport { AuthInternal } from '../model/auth';\nimport {\n AuthEventType,\n EventManager,\n GapiAuthEvent,\n GapiOutcome,\n PopupRedirectResolverInternal\n} from '../model/popup_redirect';\nimport { _setWindowLocation } from './auth_window';\nimport { _openIframe } from './iframe/iframe';\nimport { browserSessionPersistence } from './persistence/session_storage';\nimport { _open, AuthPopup } from './util/popup';\nimport { _getRedirectResult } from './strategies/redirect';\nimport { _getRedirectUrl } from '../core/util/handler';\nimport { _isIOS, _isMobileBrowser, _isSafari } from '../core/util/browser';\nimport { _overrideRedirectResult } from '../core/strategies/redirect';\n\n/**\n * The special web storage event\n *\n */\nconst WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';\n\ninterface WebStorageSupportMessage extends gapi.iframes.Message {\n [index: number]: Record<string, boolean>;\n}\n\ninterface ManagerOrPromise {\n manager?: EventManager;\n promise?: Promise<EventManager>;\n}\n\nclass BrowserPopupRedirectResolver implements PopupRedirectResolverInternal {\n private readonly eventManagers: Record<string, ManagerOrPromise> = {};\n private readonly iframes: Record<string, gapi.iframes.Iframe> = {};\n private readonly originValidationPromises: Record<string, Promise<void>> = {};\n\n readonly _redirectPersistence = browserSessionPersistence;\n\n // Wrapping in async even though we don't await anywhere in order\n // to make sure errors are raised as promise rejections\n async _openPopup(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise<AuthPopup> {\n debugAssert(\n this.eventManagers[auth._key()]?.manager,\n '_initialize() not called before _openPopup()'\n );\n\n const url = await _getRedirectUrl(\n auth,\n provider,\n authType,\n _getCurrentUrl(),\n eventId\n );\n return _open(auth, url, _generateEventId());\n }\n\n async _openRedirect(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise<never> {\n await this._originValidation(auth);\n const url = await _getRedirectUrl(\n auth,\n provider,\n authType,\n _getCurrentUrl(),\n eventId\n );\n _setWindowLocation(url);\n return new Promise(() => {});\n }\n\n _initialize(auth: AuthInternal): Promise<EventManager> {\n const key = auth._key();\n if (this.eventManagers[key]) {\n const { manager, promise } = this.eventManagers[key];\n if (manager) {\n return Promise.resolve(manager);\n } else {\n debugAssert(promise, 'If manager is not set, promise should be');\n return promise;\n }\n }\n\n const promise = this.initAndGetManager(auth);\n this.eventManagers[key] = { promise };\n\n // If the promise is rejected, the key should be removed so that the\n // operation can be retried later.\n promise.catch(() => {\n delete this.eventManagers[key];\n });\n\n return promise;\n }\n\n private async initAndGetManager(auth: AuthInternal): Promise<EventManager> {\n const iframe = await _openIframe(auth);\n const manager = new AuthEventManager(auth);\n iframe.register<GapiAuthEvent>(\n 'authEvent',\n (iframeEvent: GapiAuthEvent | null) => {\n _assert(iframeEvent?.authEvent, auth, AuthErrorCode.INVALID_AUTH_EVENT);\n // TODO: Consider splitting redirect and popup events earlier on\n\n const handled = manager.onEvent(iframeEvent.authEvent);\n return { status: handled ? GapiOutcome.ACK : GapiOutcome.ERROR };\n },\n gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER\n );\n\n this.eventManagers[auth._key()] = { manager };\n this.iframes[auth._key()] = iframe;\n return manager;\n }\n\n _isIframeWebStorageSupported(\n auth: AuthInternal,\n cb: (supported: boolean) => unknown\n ): void {\n const iframe = this.iframes[auth._key()];\n iframe.send<gapi.iframes.Message, WebStorageSupportMessage>(\n WEB_STORAGE_SUPPORT_KEY,\n { type: WEB_STORAGE_SUPPORT_KEY },\n result => {\n const isSupported = result?.[0]?.[WEB_STORAGE_SUPPORT_KEY];\n if (isSupported !== undefined) {\n cb(!!isSupported);\n }\n\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n },\n gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER\n );\n }\n\n _originValidation(auth: AuthInternal): Promise<void> {\n const key = auth._key();\n if (!this.originValidationPromises[key]) {\n this.originValidationPromises[key] = _validateOrigin(auth);\n }\n\n return this.originValidationPromises[key];\n }\n\n get _shouldInitProactively(): boolean {\n // Mobile browsers and Safari need to optimistically initialize\n return _isMobileBrowser() || _isSafari() || _isIOS();\n }\n\n _completeRedirectFn = _getRedirectResult;\n\n _overrideRedirectResult = _overrideRedirectResult;\n}\n\n/**\n * An implementation of {@link PopupRedirectResolver} suitable for browser\n * based applications.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @public\n */\nexport const browserPopupRedirectResolver: PopupRedirectResolver =\n BrowserPopupRedirectResolver;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Unsubscribe } from '@firebase/util';\nimport { FirebaseAuthInternal } from '@firebase/auth-interop-types';\n\nimport { AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { _assert } from '../util/assert';\nimport { AuthErrorCode } from '../errors';\n\ninterface TokenListener {\n (tok: string | null): unknown;\n}\n\nexport class AuthInterop implements FirebaseAuthInternal {\n private readonly internalListeners: Map<TokenListener, Unsubscribe> =\n new Map();\n\n constructor(private readonly auth: AuthInternal) {}\n\n getUid(): string | null {\n this.assertAuthConfigured();\n return this.auth.currentUser?.uid || null;\n }\n\n async getToken(\n forceRefresh?: boolean\n ): Promise<{ accessToken: string } | null> {\n this.assertAuthConfigured();\n await this.auth._initializationPromise;\n if (!this.auth.currentUser) {\n return null;\n }\n\n const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);\n return { accessToken };\n }\n\n addAuthTokenListener(listener: TokenListener): void {\n this.assertAuthConfigured();\n if (this.internalListeners.has(listener)) {\n return;\n }\n\n const unsubscribe = this.auth.onIdTokenChanged(user => {\n listener(\n (user as UserInternal | null)?.stsTokenManager.accessToken || null\n );\n });\n this.internalListeners.set(listener, unsubscribe);\n this.updateProactiveRefresh();\n }\n\n removeAuthTokenListener(listener: TokenListener): void {\n this.assertAuthConfigured();\n const unsubscribe = this.internalListeners.get(listener);\n if (!unsubscribe) {\n return;\n }\n\n this.internalListeners.delete(listener);\n unsubscribe();\n this.updateProactiveRefresh();\n }\n\n private assertAuthConfigured(): void {\n _assert(\n this.auth._initializationPromise,\n AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH\n );\n }\n\n private updateProactiveRefresh(): void {\n if (this.internalListeners.size > 0) {\n this.auth._startProactiveRefresh();\n } else {\n this.auth._stopProactiveRefresh();\n }\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, getApp, _getProvider } from '@firebase/app';\n\nimport {\n initializeAuth,\n beforeAuthStateChanged,\n onIdTokenChanged,\n connectAuthEmulator\n} from '..';\nimport { registerAuth } from '../core/auth/register';\nimport { ClientPlatform } from '../core/util/version';\nimport { browserLocalPersistence } from './persistence/local_storage';\nimport { browserSessionPersistence } from './persistence/session_storage';\nimport { indexedDBLocalPersistence } from './persistence/indexed_db';\nimport { browserPopupRedirectResolver } from './popup_redirect';\nimport { Auth, User } from '../model/public_types';\nimport { getDefaultEmulatorHost, getExperimentalSetting } from '@firebase/util';\n\nconst DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;\nconst authIdTokenMaxAge =\n getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;\n\nlet lastPostedIdToken: string | undefined | null = null;\n\nconst mintCookieFactory = (url: string) => async (user: User | null) => {\n const idTokenResult = user && (await user.getIdTokenResult());\n const idTokenAge =\n idTokenResult &&\n (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1_000;\n if (idTokenAge && idTokenAge > authIdTokenMaxAge) {\n return;\n }\n // Specifically trip null => undefined when logged out, to delete any existing cookie\n const idToken = idTokenResult?.token;\n if (lastPostedIdToken === idToken) {\n return;\n }\n lastPostedIdToken = idToken;\n await fetch(url, {\n method: idToken ? 'POST' : 'DELETE',\n headers: idToken\n ? {\n 'Authorization': `Bearer ${idToken}`\n }\n : {}\n });\n};\n\n/**\n * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.\n * If no instance exists, initializes an Auth instance with platform-specific default dependencies.\n *\n * @param app - The Firebase App.\n *\n * @public\n */\nexport function getAuth(app: FirebaseApp = getApp()): Auth {\n const provider = _getProvider(app, 'auth');\n\n if (provider.isInitialized()) {\n return provider.getImmediate();\n }\n\n const auth = initializeAuth(app, {\n popupRedirectResolver: browserPopupRedirectResolver,\n persistence: [\n indexedDBLocalPersistence,\n browserLocalPersistence,\n browserSessionPersistence\n ]\n });\n\n const authTokenSyncUrl = getExperimentalSetting('authTokenSyncURL');\n if (authTokenSyncUrl) {\n const mintCookie = mintCookieFactory(authTokenSyncUrl);\n beforeAuthStateChanged(auth, mintCookie, () =>\n mintCookie(auth.currentUser)\n );\n onIdTokenChanged(auth, user => mintCookie(user));\n }\n\n const authEmulatorHost = getDefaultEmulatorHost('auth');\n if (authEmulatorHost) {\n connectAuthEmulator(auth, `http://${authEmulatorHost}`);\n }\n\n return auth;\n}\n\nregisterAuth(ClientPlatform.BROWSER);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _registerComponent, registerVersion } from '@firebase/app';\nimport {\n Component,\n ComponentType,\n InstantiationMode\n} from '@firebase/component';\n\nimport { name, version } from '../../../package.json';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _getClientVersion, ClientPlatform } from '../util/version';\nimport { _castAuth, AuthImpl, DefaultConfig } from './auth_impl';\nimport { AuthInterop } from './firebase_internal';\nimport { ConfigInternal } from '../../model/auth';\nimport { Dependencies } from '../../model/public_types';\nimport { _initializeAuthInstance } from './initialize';\n\nexport const enum _ComponentName {\n AUTH = 'auth',\n AUTH_INTERNAL = 'auth-internal'\n}\n\nfunction getVersionForPlatform(\n clientPlatform: ClientPlatform\n): string | undefined {\n switch (clientPlatform) {\n case ClientPlatform.NODE:\n return 'node';\n case ClientPlatform.REACT_NATIVE:\n return 'rn';\n case ClientPlatform.WORKER:\n return 'webworker';\n case ClientPlatform.CORDOVA:\n return 'cordova';\n default:\n return undefined;\n }\n}\n\n/** @internal */\nexport function registerAuth(clientPlatform: ClientPlatform): void {\n _registerComponent(\n new Component(\n _ComponentName.AUTH,\n (container, { options: deps }: { options?: Dependencies }) => {\n const app = container.getProvider('app').getImmediate()!;\n const heartbeatServiceProvider =\n container.getProvider<'heartbeat'>('heartbeat');\n const appCheckServiceProvider =\n container.getProvider<'app-check-internal'>('app-check-internal');\n const { apiKey, authDomain } = app.options;\n\n _assert(\n apiKey && !apiKey.includes(':'),\n AuthErrorCode.INVALID_API_KEY,\n { appName: app.name }\n );\n\n const config: ConfigInternal = {\n apiKey,\n authDomain,\n clientPlatform,\n apiHost: DefaultConfig.API_HOST,\n tokenApiHost: DefaultConfig.TOKEN_API_HOST,\n apiScheme: DefaultConfig.API_SCHEME,\n sdkClientVersion: _getClientVersion(clientPlatform)\n };\n\n const authInstance = new AuthImpl(\n app,\n heartbeatServiceProvider,\n appCheckServiceProvider,\n config\n );\n _initializeAuthInstance(authInstance, deps);\n\n return authInstance;\n },\n ComponentType.PUBLIC\n )\n /**\n * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()\n * For why we do this, See go/firebase-next-auth-init\n */\n .setInstantiationMode(InstantiationMode.EXPLICIT)\n /**\n * Because all firebase products that depend on auth depend on auth-internal directly,\n * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.\n */\n .setInstanceCreatedCallback(\n (container, _instanceIdentifier, _instance) => {\n const authInternalProvider = container.getProvider(\n _ComponentName.AUTH_INTERNAL\n );\n authInternalProvider.initialize();\n }\n )\n );\n\n _registerComponent(\n new Component(\n _ComponentName.AUTH_INTERNAL,\n container => {\n const auth = _castAuth(\n container.getProvider(_ComponentName.AUTH).getImmediate()!\n );\n return (auth => new AuthInterop(auth))(auth);\n },\n ComponentType.PRIVATE\n ).setInstantiationMode(InstantiationMode.EXPLICIT)\n );\n\n registerVersion(name, version, getVersionForPlatform(clientPlatform));\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProvider, FirebaseApp } from '@firebase/app';\nimport { deepEqual } from '@firebase/util';\nimport { Auth, Dependencies } from '../../model/public_types';\n\nimport { AuthErrorCode } from '../errors';\nimport { PersistenceInternal } from '../persistence';\nimport { _fail } from '../util/assert';\nimport { _getInstance } from '../util/instantiator';\nimport { AuthImpl } from './auth_impl';\n\n/**\n * Initializes an {@link Auth} instance with fine-grained control over\n * {@link Dependencies}.\n *\n * @remarks\n *\n * This function allows more control over the {@link Auth} instance than\n * {@link getAuth}. `getAuth` uses platform-specific defaults to supply\n * the {@link Dependencies}. In general, `getAuth` is the easiest way to\n * initialize Auth and works for most use cases. Use `initializeAuth` if you\n * need control over which persistence layer is used, or to minimize bundle\n * size if you're not using either `signInWithPopup` or `signInWithRedirect`.\n *\n * For example, if your app only uses anonymous accounts and you only want\n * accounts saved for the current session, initialize `Auth` with:\n *\n * ```js\n * const auth = initializeAuth(app, {\n * persistence: browserSessionPersistence,\n * popupRedirectResolver: undefined,\n * });\n * ```\n *\n * @public\n */\nexport function initializeAuth(app: FirebaseApp, deps?: Dependencies): Auth {\n const provider = _getProvider(app, 'auth');\n\n if (provider.isInitialized()) {\n const auth = provider.getImmediate() as AuthImpl;\n const initialOptions = provider.getOptions() as Dependencies;\n if (deepEqual(initialOptions, deps ?? {})) {\n return auth;\n } else {\n _fail(auth, AuthErrorCode.ALREADY_INITIALIZED);\n }\n }\n\n const auth = provider.initialize({ options: deps }) as AuthImpl;\n\n return auth;\n}\n\nexport function _initializeAuthInstance(\n auth: AuthImpl,\n deps?: Dependencies\n): void {\n const persistence = deps?.persistence || [];\n const hierarchy = (\n Array.isArray(persistence) ? persistence : [persistence]\n ).map<PersistenceInternal>(_getInstance);\n if (deps?.errorMap) {\n auth._updateErrorMap(deps.errorMap);\n }\n\n // This promise is intended to float; auth initialization happens in the\n // background, meanwhile the auth object may be used by the app.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n auth._initializeWithPersistence(hierarchy, deps?.popupRedirectResolver);\n}\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Bootstrap for the Google JS Library (Closure).\n *\n * In uncompiled mode base.js will attempt to load Closure's deps file, unless\n * the global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects\n * to include their own deps file(s) from different locations.\n *\n * Avoid including base.js more than once. This is strictly discouraged and not\n * supported. goog.require(...) won't work properly in that case.\n *\n * @suppress {deprecated} Users cannot remove deprecated uses here.\n * @provideGoog\n */\n\n\n/**\n * @define {boolean} Overridden to true by the compiler.\n */\nvar COMPILED = false;\n\n\n/**\n * Base namespace for the Closure library. Checks to see goog is already\n * defined in the current scope before assigning to prevent clobbering if\n * base.js is loaded more than once.\n *\n * @const\n */\nvar goog = goog || {};\n\n/**\n * Reference to the global object.\n * https://www.ecma-international.org/ecma-262/9.0/index.html#sec-global-object\n *\n * More info on this implementation here:\n * https://docs.google.com/document/d/1NAeW4Wk7I7FV0Y2tcUFvQdGMc89k2vdgSXInw8_nvCI/edit\n *\n * @const\n * @suppress {undefinedVars} self won't be referenced unless `this` is falsy.\n * @type {!Global}\n */\ngoog.global =\n // Check `this` first for backwards compatibility.\n // Valid unless running as an ES module or in a function wrapper called\n // without setting `this` properly.\n // Note that base.js can't usefully be imported as an ES module, but it may\n // be compiled into bundles that are loadable as ES modules.\n this ||\n // https://developer.mozilla.org/en-US/docs/Web/API/Window/self\n // For in-page browser environments and workers.\n self;\n\n\n/**\n * A hook for overriding the define values in uncompiled mode.\n *\n * In uncompiled mode, `CLOSURE_UNCOMPILED_DEFINES` may be defined before\n * loading base.js. If a key is defined in `CLOSURE_UNCOMPILED_DEFINES`,\n * `goog.define` will use the value instead of the default value. This\n * allows flags to be overwritten without compilation (this is normally\n * accomplished with the compiler's \"define\" flag).\n *\n * Example:\n * <pre>\n * var CLOSURE_UNCOMPILED_DEFINES = {'goog.DEBUG': false};\n * </pre>\n *\n * @type {Object<string, (string|number|boolean)>|undefined}\n */\ngoog.global.CLOSURE_UNCOMPILED_DEFINES;\n\n\n/**\n * A hook for overriding the define values in uncompiled or compiled mode,\n * like CLOSURE_UNCOMPILED_DEFINES but effective in compiled code. In\n * uncompiled code CLOSURE_UNCOMPILED_DEFINES takes precedence.\n *\n * Also unlike CLOSURE_UNCOMPILED_DEFINES the values must be number, boolean or\n * string literals or the compiler will emit an error.\n *\n * While any @define value may be set, only those set with goog.define will be\n * effective for uncompiled code.\n *\n * Example:\n * <pre>\n * var CLOSURE_DEFINES = {'goog.DEBUG': false} ;\n * </pre>\n *\n * Currently the Closure Compiler will only recognize very simple definitions of\n * this value when looking for values to apply to compiled code and ignore all\n * other references. Specifically, it looks the value defined at the variable\n * declaration, as with the example above.\n *\n * TODO(user): Improve the recognized definitions.\n *\n * @type {!Object<string, (string|number|boolean)>|null|undefined}\n */\ngoog.global.CLOSURE_DEFINES;\n\n\n/**\n * Builds an object structure for the provided namespace path, ensuring that\n * names that already exist are not overwritten. For example:\n * \"a.b.c\" -> a = {};a.b={};a.b.c={};\n * Used by goog.provide and goog.exportSymbol.\n * @param {string} name The name of the object that this file defines.\n * @param {*=} object The object to expose at the end of the path.\n * @param {boolean=} overwriteImplicit If object is set and a previous call\n * implicitly constructed the namespace given by name, this parameter\n * controls whether object should overwrite the implicitly constructed\n * namespace or be merged into it. Defaults to false.\n * @param {?Object=} objectToExportTo The object to add the path to; if this\n * field is not specified, its value defaults to `goog.global`.\n * @private\n */\ngoog.exportPath_ = function(name, object, overwriteImplicit, objectToExportTo) {\n var parts = name.split('.');\n var cur = objectToExportTo || goog.global;\n\n // Internet Explorer exhibits strange behavior when throwing errors from\n // methods externed in this manner. See the testExportSymbolExceptions in\n // base_test.html for an example.\n if (!(parts[0] in cur) && typeof cur.execScript != 'undefined') {\n cur.execScript('var ' + parts[0]);\n }\n\n for (var part; parts.length && (part = parts.shift());) {\n if (!parts.length && object !== undefined) {\n if (!overwriteImplicit && goog.isObject(object) &&\n goog.isObject(cur[part])) {\n // Merge properties on object (the input parameter) with the existing\n // implicitly defined namespace, so as to not clobber previously\n // defined child namespaces.\n for (var prop in object) {\n if (object.hasOwnProperty(prop)) {\n cur[part][prop] = object[prop];\n }\n }\n } else {\n // Either there is no existing implicit namespace, or overwriteImplicit\n // is set to true, so directly assign object (the input parameter) to\n // the namespace.\n cur[part] = object;\n }\n } else if (cur[part] && cur[part] !== Object.prototype[part]) {\n cur = cur[part];\n } else {\n cur = cur[part] = {};\n }\n }\n};\n\n\n/**\n * Defines a named value. In uncompiled mode, the value is retrieved from\n * CLOSURE_DEFINES or CLOSURE_UNCOMPILED_DEFINES if the object is defined and\n * has the property specified, and otherwise used the defined defaultValue.\n * When compiled the default can be overridden using the compiler options or the\n * value set in the CLOSURE_DEFINES object. Returns the defined value so that it\n * can be used safely in modules. Note that the value type MUST be either\n * boolean, number, or string.\n *\n * @param {string} name The distinguished name to provide.\n * @param {T} defaultValue\n * @return {T} The defined value.\n * @template T\n */\ngoog.define = function(name, defaultValue) {\n var value = defaultValue;\n if (!COMPILED) {\n var uncompiledDefines = goog.global.CLOSURE_UNCOMPILED_DEFINES;\n var defines = goog.global.CLOSURE_DEFINES;\n if (uncompiledDefines &&\n // Anti DOM-clobbering runtime check (b/37736576).\n /** @type {?} */ (uncompiledDefines).nodeType === undefined &&\n Object.prototype.hasOwnProperty.call(uncompiledDefines, name)) {\n value = uncompiledDefines[name];\n } else if (\n defines &&\n // Anti DOM-clobbering runtime check (b/37736576).\n /** @type {?} */ (defines).nodeType === undefined &&\n Object.prototype.hasOwnProperty.call(defines, name)) {\n value = defines[name];\n }\n }\n return value;\n};\n\n\n/**\n * @define {number} Integer year indicating the set of browser features that are\n * guaranteed to be present. This is defined to include exactly features that\n * work correctly on all \"modern\" browsers that are stable on January 1 of the\n * specified year. For example,\n * ```js\n * if (goog.FEATURESET_YEAR >= 2019) {\n * // use APIs known to be available on all major stable browsers Jan 1, 2019\n * } else {\n * // polyfill for older browsers\n * }\n * ```\n * This is intended to be the primary define for removing\n * unnecessary browser compatibility code (such as ponyfills and workarounds),\n * and should inform the default value for most other defines:\n * ```js\n * const ASSUME_NATIVE_PROMISE =\n * goog.define('ASSUME_NATIVE_PROMISE', goog.FEATURESET_YEAR >= 2016);\n * ```\n *\n * The default assumption is that IE9 is the lowest supported browser, which was\n * first available Jan 1, 2012.\n *\n * TODO(user): Reference more thorough documentation when it's available.\n */\ngoog.FEATURESET_YEAR = goog.define('goog.FEATURESET_YEAR', 2012);\n\n\n/**\n * @define {boolean} DEBUG is provided as a convenience so that debugging code\n * that should not be included in a production. It can be easily stripped\n * by specifying --define goog.DEBUG=false to the Closure Compiler aka\n * JSCompiler. For example, most toString() methods should be declared inside an\n * \"if (goog.DEBUG)\" conditional because they are generally used for debugging\n * purposes and it is difficult for the JSCompiler to statically determine\n * whether they are used.\n */\ngoog.DEBUG = goog.define('goog.DEBUG', true);\n\n\n/**\n * @define {string} LOCALE defines the locale being used for compilation. It is\n * used to select locale specific data to be compiled in js binary. BUILD rule\n * can specify this value by \"--define goog.LOCALE=<locale_name>\" as a compiler\n * option.\n *\n * Take into account that the locale code format is important. You should use\n * the canonical Unicode format with hyphen as a delimiter. Language must be\n * lowercase, Language Script - Capitalized, Region - UPPERCASE.\n * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN.\n *\n * See more info about locale codes here:\n * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers\n *\n * For language codes you should use values defined by ISO 693-1. See it here\n * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from\n * this rule: the Hebrew language. For legacy reasons the old code (iw) should\n * be used instead of the new code (he).\n *\n */\ngoog.LOCALE = goog.define('goog.LOCALE', 'en'); // default to en\n\n\n/**\n * @define {boolean} Whether this code is running on trusted sites.\n *\n * On untrusted sites, several native functions can be defined or overridden by\n * external libraries like Prototype, Datejs, and JQuery and setting this flag\n * to false forces closure to use its own implementations when possible.\n *\n * If your JavaScript can be loaded by a third party site and you are wary about\n * relying on non-standard implementations, specify\n * \"--define goog.TRUSTED_SITE=false\" to the compiler.\n */\ngoog.TRUSTED_SITE = goog.define('goog.TRUSTED_SITE', true);\n\n\n/**\n * @define {boolean} Whether code that calls {@link goog.setTestOnly} should\n * be disallowed in the compilation unit.\n */\ngoog.DISALLOW_TEST_ONLY_CODE =\n goog.define('goog.DISALLOW_TEST_ONLY_CODE', COMPILED && !goog.DEBUG);\n\n\n/**\n * @define {boolean} Whether to use a Chrome app CSP-compliant method for\n * loading scripts via goog.require. @see appendScriptSrcNode_.\n */\ngoog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING =\n goog.define('goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING', false);\n\n\n/**\n * Defines a namespace in Closure.\n *\n * A namespace may only be defined once in a codebase. It may be defined using\n * goog.provide() or goog.module().\n *\n * The presence of one or more goog.provide() calls in a file indicates\n * that the file defines the given objects/namespaces.\n * Provided symbols must not be null or undefined.\n *\n * In addition, goog.provide() creates the object stubs for a namespace\n * (for example, goog.provide(\"goog.foo.bar\") will create the object\n * goog.foo.bar if it does not already exist).\n *\n * Build tools also scan for provide/require/module statements\n * to discern dependencies, build dependency files (see deps.js), etc.\n *\n * @see goog.require\n * @see goog.module\n * @param {string} name Namespace provided by this file in the form\n * \"goog.package.part\".\n * deprecated Use goog.module (see b/159289405)\n */\ngoog.provide = function(name) {\n if (goog.isInModuleLoader_()) {\n throw new Error('goog.provide cannot be used within a module.');\n }\n if (!COMPILED) {\n // Ensure that the same namespace isn't provided twice.\n // A goog.module/goog.provide maps a goog.require to a specific file\n if (goog.isProvided_(name)) {\n throw new Error('Namespace \"' + name + '\" already declared.');\n }\n }\n\n goog.constructNamespace_(name);\n};\n\n\n/**\n * @param {string} name Namespace provided by this file in the form\n * \"goog.package.part\".\n * @param {?Object=} object The object to embed in the namespace.\n * @param {boolean=} overwriteImplicit If object is set and a previous call\n * implicitly constructed the namespace given by name, this parameter\n * controls whether opt_obj should overwrite the implicitly constructed\n * namespace or be merged into it. Defaults to false.\n * @private\n */\ngoog.constructNamespace_ = function(name, object, overwriteImplicit) {\n if (!COMPILED) {\n delete goog.implicitNamespaces_[name];\n\n var namespace = name;\n while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) {\n if (goog.getObjectByName(namespace)) {\n break;\n }\n goog.implicitNamespaces_[namespace] = true;\n }\n }\n\n goog.exportPath_(name, object, overwriteImplicit);\n};\n\n\n/**\n * According to the CSP3 spec a nonce must be a valid base64 string.\n * @see https://www.w3.org/TR/CSP3/#grammardef-base64-value\n * @private @const\n */\ngoog.NONCE_PATTERN_ = /^[\\w+/_-]+[=]{0,2}$/;\n\n\n/**\n * Returns CSP nonce, if set for any script tag.\n * @param {?Window=} opt_window The window context used to retrieve the nonce.\n * Defaults to global context.\n * @return {string} CSP nonce or empty string if no nonce is present.\n * @private\n */\ngoog.getScriptNonce_ = function(opt_window) {\n var doc = (opt_window || goog.global).document;\n var script = doc.querySelector && doc.querySelector('script[nonce]');\n if (script) {\n // Try to get the nonce from the IDL property first, because browsers that\n // implement additional nonce protection features (currently only Chrome) to\n // prevent nonce stealing via CSS do not expose the nonce via attributes.\n // See https://github.com/whatwg/html/issues/2369\n var nonce = script['nonce'] || script.getAttribute('nonce');\n if (nonce && goog.NONCE_PATTERN_.test(nonce)) {\n return nonce;\n }\n }\n return '';\n};\n\n\n/**\n * Module identifier validation regexp.\n * Note: This is a conservative check, it is very possible to be more lenient,\n * the primary exclusion here is \"/\" and \"\\\" and a leading \".\", these\n * restrictions are intended to leave the door open for using goog.require\n * with relative file paths rather than module identifiers.\n * @private\n */\ngoog.VALID_MODULE_RE_ = /^[a-zA-Z_$][a-zA-Z0-9._$]*$/;\n\n\n/**\n * Defines a module in Closure.\n *\n * Marks that this file must be loaded as a module and claims the namespace.\n *\n * A namespace may only be defined once in a codebase. It may be defined using\n * goog.provide() or goog.module().\n *\n * goog.module() has three requirements:\n * - goog.module may not be used in the same file as goog.provide.\n * - goog.module must be the first statement in the file.\n * - only one goog.module is allowed per file.\n *\n * When a goog.module annotated file is loaded, it is enclosed in\n * a strict function closure. This means that:\n * - any variables declared in a goog.module file are private to the file\n * (not global), though the compiler is expected to inline the module.\n * - The code must obey all the rules of \"strict\" JavaScript.\n * - the file will be marked as \"use strict\"\n *\n * NOTE: unlike goog.provide, goog.module does not declare any symbols by\n * itself. If declared symbols are desired, use\n * goog.module.declareLegacyNamespace().\n *\n *\n * See the public goog.module proposal: http://goo.gl/Va1hin\n *\n * @param {string} name Namespace provided by this file in the form\n * \"goog.package.part\", is expected but not required.\n * @return {void}\n */\ngoog.module = function(name) {\n if (typeof name !== 'string' || !name ||\n name.search(goog.VALID_MODULE_RE_) == -1) {\n throw new Error('Invalid module identifier');\n }\n if (!goog.isInGoogModuleLoader_()) {\n throw new Error(\n 'Module ' + name + ' has been loaded incorrectly. Note, ' +\n 'modules cannot be loaded as normal scripts. They require some kind of ' +\n 'pre-processing step. You\\'re likely trying to load a module via a ' +\n 'script tag or as a part of a concatenated bundle without rewriting the ' +\n 'module. For more info see: ' +\n 'https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.');\n }\n if (goog.moduleLoaderState_.moduleName) {\n throw new Error('goog.module may only be called once per module.');\n }\n\n // Store the module name for the loader.\n goog.moduleLoaderState_.moduleName = name;\n if (!COMPILED) {\n // Ensure that the same namespace isn't provided twice.\n // A goog.module/goog.provide maps a goog.require to a specific file\n if (goog.isProvided_(name)) {\n throw new Error('Namespace \"' + name + '\" already declared.');\n }\n delete goog.implicitNamespaces_[name];\n }\n};\n\n\n/**\n * @param {string} name The module identifier.\n * @return {?} The module exports for an already loaded module or null.\n *\n * Note: This is not an alternative to goog.require, it does not\n * indicate a hard dependency, instead it is used to indicate\n * an optional dependency or to access the exports of a module\n * that has already been loaded.\n * @suppress {missingProvide}\n */\ngoog.module.get = function(name) {\n return goog.module.getInternal_(name);\n};\n\n\n/**\n * @param {string} name The module identifier.\n * @return {?} The module exports for an already loaded module or null.\n * @private\n */\ngoog.module.getInternal_ = function(name) {\n if (!COMPILED) {\n if (name in goog.loadedModules_) {\n return goog.loadedModules_[name].exports;\n } else if (!goog.implicitNamespaces_[name]) {\n var ns = goog.getObjectByName(name);\n return ns != null ? ns : null;\n }\n }\n return null;\n};\n\n/**\n * Types of modules the debug loader can load.\n * @enum {string}\n */\ngoog.ModuleType = {\n ES6: 'es6',\n GOOG: 'goog'\n};\n\n\n/**\n * @private {?{\n * moduleName: (string|undefined),\n * declareLegacyNamespace:boolean,\n * type: ?goog.ModuleType\n * }}\n */\ngoog.moduleLoaderState_ = null;\n\n\n/**\n * @private\n * @return {boolean} Whether a goog.module or an es6 module is currently being\n * initialized.\n */\ngoog.isInModuleLoader_ = function() {\n return goog.isInGoogModuleLoader_() || goog.isInEs6ModuleLoader_();\n};\n\n\n/**\n * @private\n * @return {boolean} Whether a goog.module is currently being initialized.\n */\ngoog.isInGoogModuleLoader_ = function() {\n return !!goog.moduleLoaderState_ &&\n goog.moduleLoaderState_.type == goog.ModuleType.GOOG;\n};\n\n\n/**\n * @private\n * @return {boolean} Whether an es6 module is currently being initialized.\n */\ngoog.isInEs6ModuleLoader_ = function() {\n var inLoader = !!goog.moduleLoaderState_ &&\n goog.moduleLoaderState_.type == goog.ModuleType.ES6;\n\n if (inLoader) {\n return true;\n }\n\n var jscomp = goog.global['$jscomp'];\n\n if (jscomp) {\n // jscomp may not have getCurrentModulePath if this is a compiled bundle\n // that has some of the runtime, but not all of it. This can happen if\n // optimizations are turned on so the unused runtime is removed but renaming\n // and Closure pass are off (so $jscomp is still named $jscomp and the\n // goog.provide/require calls still exist).\n if (typeof jscomp.getCurrentModulePath != 'function') {\n return false;\n }\n\n // Bundled ES6 module.\n return !!jscomp.getCurrentModulePath();\n }\n\n return false;\n};\n\n\n/**\n * Provide the module's exports as a globally accessible object under the\n * module's declared name. This is intended to ease migration to goog.module\n * for files that have existing usages.\n * @suppress {missingProvide}\n */\ngoog.module.declareLegacyNamespace = function() {\n if (!COMPILED && !goog.isInGoogModuleLoader_()) {\n throw new Error(\n 'goog.module.declareLegacyNamespace must be called from ' +\n 'within a goog.module');\n }\n if (!COMPILED && !goog.moduleLoaderState_.moduleName) {\n throw new Error(\n 'goog.module must be called prior to ' +\n 'goog.module.declareLegacyNamespace.');\n }\n goog.moduleLoaderState_.declareLegacyNamespace = true;\n};\n\n\n/**\n * Associates an ES6 module with a Closure module ID so that is available via\n * goog.require. The associated ID acts like a goog.module ID - it does not\n * create any global names, it is merely available via goog.require /\n * goog.module.get / goog.forwardDeclare / goog.requireType. goog.require and\n * goog.module.get will return the entire module as if it was import *'d. This\n * allows Closure files to reference ES6 modules for the sake of migration.\n *\n * @param {string} namespace\n * @suppress {missingProvide}\n */\ngoog.declareModuleId = function(namespace) {\n if (!COMPILED) {\n if (!goog.isInEs6ModuleLoader_()) {\n throw new Error(\n 'goog.declareModuleId may only be called from ' +\n 'within an ES6 module');\n }\n if (goog.moduleLoaderState_ && goog.moduleLoaderState_.moduleName) {\n throw new Error(\n 'goog.declareModuleId may only be called once per module.');\n }\n if (namespace in goog.loadedModules_) {\n throw new Error(\n 'Module with namespace \"' + namespace + '\" already exists.');\n }\n }\n if (goog.moduleLoaderState_) {\n // Not bundled - debug loading.\n goog.moduleLoaderState_.moduleName = namespace;\n } else {\n // Bundled - not debug loading, no module loader state.\n var jscomp = goog.global['$jscomp'];\n if (!jscomp || typeof jscomp.getCurrentModulePath != 'function') {\n throw new Error(\n 'Module with namespace \"' + namespace +\n '\" has been loaded incorrectly.');\n }\n var exports = jscomp.require(jscomp.getCurrentModulePath());\n goog.loadedModules_[namespace] = {\n exports: exports,\n type: goog.ModuleType.ES6,\n moduleId: namespace\n };\n }\n};\n\n\n/**\n * Marks that the current file should only be used for testing, and never for\n * live code in production.\n *\n * In the case of unit tests, the message may optionally be an exact namespace\n * for the test (e.g. 'goog.stringTest'). The linter will then ignore the extra\n * provide (if not explicitly defined in the code).\n *\n * @param {string=} opt_message Optional message to add to the error that's\n * raised when used in production code.\n */\ngoog.setTestOnly = function(opt_message) {\n if (goog.DISALLOW_TEST_ONLY_CODE) {\n opt_message = opt_message || '';\n throw new Error(\n 'Importing test-only code into non-debug environment' +\n (opt_message ? ': ' + opt_message : '.'));\n }\n};\n\n\n/**\n * Forward declares a symbol. This is an indication to the compiler that the\n * symbol may be used in the source yet is not required and may not be provided\n * in compilation.\n *\n * The most common usage of forward declaration is code that takes a type as a\n * function parameter but does not need to require it. By forward declaring\n * instead of requiring, no hard dependency is made, and (if not required\n * elsewhere) the namespace may never be required and thus, not be pulled\n * into the JavaScript binary. If it is required elsewhere, it will be type\n * checked as normal.\n *\n * Before using goog.forwardDeclare, please read the documentation at\n * https://github.com/google/closure-compiler/wiki/Bad-Type-Annotation to\n * understand the options and tradeoffs when working with forward declarations.\n *\n * @param {string} name The namespace to forward declare in the form of\n * \"goog.package.part\".\n * @deprecated See go/noforwarddeclaration, Use `goog.requireType` instead.\n */\ngoog.forwardDeclare = function(name) {};\n\n\n/**\n * Forward declare type information. Used to assign types to goog.global\n * referenced object that would otherwise result in unknown type references\n * and thus block property disambiguation.\n */\ngoog.forwardDeclare('Document');\ngoog.forwardDeclare('HTMLScriptElement');\ngoog.forwardDeclare('XMLHttpRequest');\n\n\nif (!COMPILED) {\n /**\n * Check if the given name has been goog.provided. This will return false for\n * names that are available only as implicit namespaces.\n * @param {string} name name of the object to look for.\n * @return {boolean} Whether the name has been provided.\n * @private\n */\n goog.isProvided_ = function(name) {\n return (name in goog.loadedModules_) ||\n (!goog.implicitNamespaces_[name] && goog.getObjectByName(name) != null);\n };\n\n /**\n * Namespaces implicitly defined by goog.provide. For example,\n * goog.provide('goog.events.Event') implicitly declares that 'goog' and\n * 'goog.events' must be namespaces.\n *\n * @type {!Object<string, (boolean|undefined)>}\n * @private\n */\n goog.implicitNamespaces_ = {'goog.module': true};\n\n // NOTE: We add goog.module as an implicit namespace as goog.module is defined\n // here and because the existing module package has not been moved yet out of\n // the goog.module namespace. This satisifies both the debug loader and\n // ahead-of-time dependency management.\n}\n\n\n/**\n * Returns an object based on its fully qualified external name. The object\n * is not found if null or undefined. If you are using a compilation pass that\n * renames property names beware that using this function will not find renamed\n * properties.\n *\n * @param {string} name The fully qualified name.\n * @param {Object=} opt_obj The object within which to look; default is\n * |goog.global|.\n * @return {?} The value (object or primitive) or, if not found, null.\n */\ngoog.getObjectByName = function(name, opt_obj) {\n var parts = name.split('.');\n var cur = opt_obj || goog.global;\n for (var i = 0; i < parts.length; i++) {\n cur = cur[parts[i]];\n if (cur == null) {\n return null;\n }\n }\n return cur;\n};\n\n\n/**\n * Adds a dependency from a file to the files it requires.\n * @param {string} relPath The path to the js file.\n * @param {!Array<string>} provides An array of strings with\n * the names of the objects this file provides.\n * @param {!Array<string>} requires An array of strings with\n * the names of the objects this file requires.\n * @param {boolean|!Object<string>=} opt_loadFlags Parameters indicating\n * how the file must be loaded. The boolean 'true' is equivalent\n * to {'module': 'goog'} for backwards-compatibility. Valid properties\n * and values include {'module': 'goog'} and {'lang': 'es6'}.\n */\ngoog.addDependency = function(relPath, provides, requires, opt_loadFlags) {\n if (!COMPILED && goog.DEPENDENCIES_ENABLED) {\n goog.debugLoader_.addDependency(relPath, provides, requires, opt_loadFlags);\n }\n};\n\n\n// NOTE(nnaze): The debug DOM loader was included in base.js as an original way\n// to do \"debug-mode\" development. The dependency system can sometimes be\n// confusing, as can the debug DOM loader's asynchronous nature.\n//\n// With the DOM loader, a call to goog.require() is not blocking -- the script\n// will not load until some point after the current script. If a namespace is\n// needed at runtime, it needs to be defined in a previous script, or loaded via\n// require() with its registered dependencies.\n//\n// User-defined namespaces may need their own deps file. For a reference on\n// creating a deps file, see:\n// Externally: https://developers.google.com/closure/library/docs/depswriter\n//\n// Because of legacy clients, the DOM loader can't be easily removed from\n// base.js. Work was done to make it disableable or replaceable for\n// different environments (DOM-less JavaScript interpreters like Rhino or V8,\n// for example). See bootstrap/ for more information.\n\n\n/**\n * @define {boolean} Whether to enable the debug loader.\n *\n * If enabled, a call to goog.require() will attempt to load the namespace by\n * appending a script tag to the DOM (if the namespace has been registered).\n *\n * If disabled, goog.require() will simply assert that the namespace has been\n * provided (and depend on the fact that some outside tool correctly ordered\n * the script).\n */\ngoog.ENABLE_DEBUG_LOADER = goog.define('goog.ENABLE_DEBUG_LOADER', false);\n\n\n/**\n * @param {string} msg\n * @private\n */\ngoog.logToConsole_ = function(msg) {\n if (goog.global.console) {\n goog.global.console['error'](msg);\n }\n};\n\n\n/**\n * Implements a system for the dynamic resolution of dependencies that works in\n * parallel with the BUILD system.\n *\n * Note that all calls to goog.require will be stripped by the compiler.\n *\n * @see goog.provide\n * @param {string} namespace Namespace (as was given in goog.provide,\n * goog.module, or goog.declareModuleId) in the form\n * \"goog.package.part\".\n * @return {?} If called within a goog.module or ES6 module file, the associated\n * namespace or module otherwise null.\n */\ngoog.require = function(namespace) {\n if (!COMPILED) {\n // Might need to lazy load on old IE.\n if (goog.ENABLE_DEBUG_LOADER) {\n goog.debugLoader_.requested(namespace);\n }\n\n // If the object already exists we do not need to do anything.\n if (goog.isProvided_(namespace)) {\n if (goog.isInModuleLoader_()) {\n return goog.module.getInternal_(namespace);\n }\n } else if (goog.ENABLE_DEBUG_LOADER) {\n var moduleLoaderState = goog.moduleLoaderState_;\n goog.moduleLoaderState_ = null;\n try {\n goog.debugLoader_.load_(namespace);\n } finally {\n goog.moduleLoaderState_ = moduleLoaderState;\n }\n }\n\n return null;\n }\n};\n\n\n/**\n * Requires a symbol for its type information. This is an indication to the\n * compiler that the symbol may appear in type annotations, yet it is not\n * referenced at runtime.\n *\n * When called within a goog.module or ES6 module file, the return value may be\n * assigned to or destructured into a variable, but it may not be otherwise used\n * in code outside of a type annotation.\n *\n * Note that all calls to goog.requireType will be stripped by the compiler.\n *\n * @param {string} namespace Namespace (as was given in goog.provide,\n * goog.module, or goog.declareModuleId) in the form\n * \"goog.package.part\".\n * @return {?}\n */\ngoog.requireType = function(namespace) {\n // Return an empty object so that single-level destructuring of the return\n // value doesn't crash at runtime when using the debug loader. Multi-level\n // destructuring isn't supported.\n return {};\n};\n\n\n/**\n * Path for included scripts.\n * @type {string}\n */\ngoog.basePath = '';\n\n\n/**\n * A hook for overriding the base path.\n * @type {string|undefined}\n */\ngoog.global.CLOSURE_BASE_PATH;\n\n\n/**\n * Whether to attempt to load Closure's deps file. By default, when uncompiled,\n * deps files will attempt to be loaded.\n * @type {boolean|undefined}\n */\ngoog.global.CLOSURE_NO_DEPS;\n\n\n/**\n * A function to import a single script. This is meant to be overridden when\n * Closure is being run in non-HTML contexts, such as web workers. It's defined\n * in the global scope so that it can be set before base.js is loaded, which\n * allows deps.js to be imported properly.\n *\n * The first parameter the script source, which is a relative URI. The second,\n * optional parameter is the script contents, in the event the script needed\n * transformation. It should return true if the script was imported, false\n * otherwise.\n * @type {(function(string, string=): boolean)|undefined}\n */\ngoog.global.CLOSURE_IMPORT_SCRIPT;\n\n\n/**\n * When defining a class Foo with an abstract method bar(), you can do:\n * Foo.prototype.bar = goog.abstractMethod\n *\n * Now if a subclass of Foo fails to override bar(), an error will be thrown\n * when bar() is invoked.\n *\n * @type {!Function}\n * @throws {Error} when invoked to indicate the method should be overridden.\n * @deprecated Use \"@abstract\" annotation instead of goog.abstractMethod in new\n * code. See\n * https://github.com/google/closure-compiler/wiki/@abstract-classes-and-methods\n */\ngoog.abstractMethod = function() {\n throw new Error('unimplemented abstract method');\n};\n\n\n/**\n * Adds a `getInstance` static method that always returns the same\n * instance object.\n * @param {!Function} ctor The constructor for the class to add the static\n * method to.\n * @suppress {missingProperties} 'instance_' isn't a property on 'Function'\n * but we don't have a better type to use here.\n */\ngoog.addSingletonGetter = function(ctor) {\n // instance_ is immediately set to prevent issues with sealed constructors\n // such as are encountered when a constructor is returned as the export object\n // of a goog.module in unoptimized code.\n // Delcare type to avoid conformance violations that ctor.instance_ is unknown\n /** @type {undefined|!Object} @suppress {underscore} */\n ctor.instance_ = undefined;\n ctor.getInstance = function() {\n if (ctor.instance_) {\n return ctor.instance_;\n }\n if (goog.DEBUG) {\n // NOTE: JSCompiler can't optimize away Array#push.\n goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor;\n }\n // Cast to avoid conformance violations that ctor.instance_ is unknown\n return /** @type {!Object|undefined} */ (ctor.instance_) = new ctor;\n };\n};\n\n\n/**\n * All singleton classes that have been instantiated, for testing. Don't read\n * it directly, use the `goog.testing.singleton` module. The compiler\n * removes this variable if unused.\n * @type {!Array<!Function>}\n * @private\n */\ngoog.instantiatedSingletons_ = [];\n\n\n/**\n * @define {boolean} Whether to load goog.modules using `eval` when using\n * the debug loader. This provides a better debugging experience as the\n * source is unmodified and can be edited using Chrome Workspaces or similar.\n * However in some environments the use of `eval` is banned\n * so we provide an alternative.\n */\ngoog.LOAD_MODULE_USING_EVAL = goog.define('goog.LOAD_MODULE_USING_EVAL', true);\n\n\n/**\n * @define {boolean} Whether the exports of goog.modules should be sealed when\n * possible.\n */\ngoog.SEAL_MODULE_EXPORTS = goog.define('goog.SEAL_MODULE_EXPORTS', goog.DEBUG);\n\n\n/**\n * The registry of initialized modules:\n * The module identifier or path to module exports map.\n * @private @const {!Object<string, {exports:?,type:string,moduleId:string}>}\n */\ngoog.loadedModules_ = {};\n\n\n/**\n * True if the debug loader enabled and used.\n * @const {boolean}\n */\ngoog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER;\n\n\n/**\n * @define {string} How to decide whether to transpile. Valid values\n * are 'always', 'never', and 'detect'. The default ('detect') is to\n * use feature detection to determine which language levels need\n * transpilation.\n */\n// NOTE(sdh): we could expand this to accept a language level to bypass\n// detection: e.g. goog.TRANSPILE == 'es5' would transpile ES6 files but\n// would leave ES3 and ES5 files alone.\ngoog.TRANSPILE = goog.define('goog.TRANSPILE', 'detect');\n\n/**\n * @define {boolean} If true assume that ES modules have already been\n * transpiled by the jscompiler (in the same way that transpile.js would\n * transpile them - to jscomp modules). Useful only for servers that wish to use\n * the debug loader and transpile server side. Thus this is only respected if\n * goog.TRANSPILE is \"never\".\n */\ngoog.ASSUME_ES_MODULES_TRANSPILED =\n goog.define('goog.ASSUME_ES_MODULES_TRANSPILED', false);\n\n\n/**\n * @define {string} Trusted Types policy name. If non-empty then Closure will\n * use Trusted Types.\n */\ngoog.TRUSTED_TYPES_POLICY_NAME =\n goog.define('goog.TRUSTED_TYPES_POLICY_NAME', 'goog');\n\n\n/**\n * @package {?boolean}\n * Visible for testing.\n */\ngoog.hasBadLetScoping = null;\n\n\n/**\n * @param {function(?):?|string} moduleDef The module definition.\n */\ngoog.loadModule = function(moduleDef) {\n // NOTE: we allow function definitions to be either in the from\n // of a string to eval (which keeps the original source intact) or\n // in a eval forbidden environment (CSP) we allow a function definition\n // which in its body must call `goog.module`, and return the exports\n // of the module.\n var previousState = goog.moduleLoaderState_;\n try {\n goog.moduleLoaderState_ = {\n moduleName: '',\n declareLegacyNamespace: false,\n type: goog.ModuleType.GOOG\n };\n var origExports = {};\n var exports = origExports;\n if (typeof moduleDef === 'function') {\n exports = moduleDef.call(undefined, exports);\n } else if (typeof moduleDef === 'string') {\n exports = goog.loadModuleFromSource_.call(undefined, exports, moduleDef);\n } else {\n throw new Error('Invalid module definition');\n }\n\n var moduleName = goog.moduleLoaderState_.moduleName;\n if (typeof moduleName === 'string' && moduleName) {\n // Don't seal legacy namespaces as they may be used as a parent of\n // another namespace\n if (goog.moduleLoaderState_.declareLegacyNamespace) {\n // Whether exports was overwritten via default export assignment.\n // This is important for legacy namespaces as it dictates whether\n // previously a previously loaded implicit namespace should be clobbered\n // or not.\n var isDefaultExport = origExports !== exports;\n goog.constructNamespace_(moduleName, exports, isDefaultExport);\n } else if (\n goog.SEAL_MODULE_EXPORTS && Object.seal &&\n typeof exports == 'object' && exports != null) {\n Object.seal(exports);\n }\n\n var data = {\n exports: exports,\n type: goog.ModuleType.GOOG,\n moduleId: goog.moduleLoaderState_.moduleName\n };\n goog.loadedModules_[moduleName] = data;\n } else {\n throw new Error('Invalid module name \\\"' + moduleName + '\\\"');\n }\n } finally {\n goog.moduleLoaderState_ = previousState;\n }\n};\n\n\n/**\n * @private @const\n */\ngoog.loadModuleFromSource_ =\n /** @type {function(!Object, string):?} */ (function(exports) {\n // NOTE: we avoid declaring parameters or local variables here to avoid\n // masking globals or leaking values into the module definition.\n 'use strict';\n eval(goog.CLOSURE_EVAL_PREFILTER_.createScript(arguments[1]));\n return exports;\n });\n\n\n/**\n * Normalize a file path by removing redundant \"..\" and extraneous \".\" file\n * path components.\n * @param {string} path\n * @return {string}\n * @private\n */\ngoog.normalizePath_ = function(path) {\n var components = path.split('/');\n var i = 0;\n while (i < components.length) {\n if (components[i] == '.') {\n components.splice(i, 1);\n } else if (\n i && components[i] == '..' && components[i - 1] &&\n components[i - 1] != '..') {\n components.splice(--i, 2);\n } else {\n i++;\n }\n }\n return components.join('/');\n};\n\n\n/**\n * Provides a hook for loading a file when using Closure's goog.require() API\n * with goog.modules. In particular this hook is provided to support Node.js.\n *\n * @type {(function(string):string)|undefined}\n */\ngoog.global.CLOSURE_LOAD_FILE_SYNC;\n\n\n/**\n * Loads file by synchronous XHR. Should not be used in production environments.\n * @param {string} src Source URL.\n * @return {?string} File contents, or null if load failed.\n * @private\n */\ngoog.loadFileSync_ = function(src) {\n if (goog.global.CLOSURE_LOAD_FILE_SYNC) {\n return goog.global.CLOSURE_LOAD_FILE_SYNC(src);\n } else {\n try {\n /** @type {XMLHttpRequest} */\n var xhr = new goog.global['XMLHttpRequest']();\n xhr.open('get', src, false);\n xhr.send();\n // NOTE: Successful http: requests have a status of 200, but successful\n // file: requests may have a status of zero. Any other status, or a\n // thrown exception (particularly in case of file: requests) indicates\n // some sort of error, which we treat as a missing or unavailable file.\n return xhr.status == 0 || xhr.status == 200 ? xhr.responseText : null;\n } catch (err) {\n // No need to rethrow or log, since errors should show up on their own.\n return null;\n }\n }\n};\n\n//==============================================================================\n// Language Enhancements\n//==============================================================================\n\n\n/**\n * This is a \"fixed\" version of the typeof operator. It differs from the typeof\n * operator in such a way that null returns 'null' and arrays return 'array'.\n * @param {?} value The value to get the type of.\n * @return {string} The name of the type.\n */\ngoog.typeOf = function(value) {\n var s = typeof value;\n\n if (s != 'object') {\n return s;\n }\n\n if (!value) {\n return 'null';\n }\n\n if (Array.isArray(value)) {\n return 'array';\n }\n return s;\n};\n\n\n/**\n * Returns true if the object looks like an array. To qualify as array like\n * the value needs to be either a NodeList or an object with a Number length\n * property. Note that for this function neither strings nor functions are\n * considered \"array-like\".\n *\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is an array.\n */\ngoog.isArrayLike = function(val) {\n var type = goog.typeOf(val);\n // We do not use goog.isObject here in order to exclude function values.\n return type == 'array' || type == 'object' && typeof val.length == 'number';\n};\n\n\n/**\n * Returns true if the object looks like a Date. To qualify as Date-like the\n * value needs to be an object and have a getFullYear() function.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is a like a Date.\n */\ngoog.isDateLike = function(val) {\n return goog.isObject(val) && typeof val.getFullYear == 'function';\n};\n\n\n/**\n * Returns true if the specified value is an object. This includes arrays and\n * functions.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is an object.\n */\ngoog.isObject = function(val) {\n var type = typeof val;\n return type == 'object' && val != null || type == 'function';\n // return Object(val) === val also works, but is slower, especially if val is\n // not an object.\n};\n\n\n/**\n * Gets a unique ID for an object. This mutates the object so that further calls\n * with the same object as a parameter returns the same value. The unique ID is\n * guaranteed to be unique across the current session amongst objects that are\n * passed into `getUid`. There is no guarantee that the ID is unique or\n * consistent across sessions. It is unsafe to generate unique ID for function\n * prototypes.\n *\n * @param {Object} obj The object to get the unique ID for.\n * @return {number} The unique ID for the object.\n */\ngoog.getUid = function(obj) {\n // TODO(arv): Make the type stricter, do not accept null.\n return Object.prototype.hasOwnProperty.call(obj, goog.UID_PROPERTY_) &&\n obj[goog.UID_PROPERTY_] ||\n (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);\n};\n\n\n/**\n * Whether the given object is already assigned a unique ID.\n *\n * This does not modify the object.\n *\n * @param {!Object} obj The object to check.\n * @return {boolean} Whether there is an assigned unique id for the object.\n */\ngoog.hasUid = function(obj) {\n return !!obj[goog.UID_PROPERTY_];\n};\n\n\n/**\n * Removes the unique ID from an object. This is useful if the object was\n * previously mutated using `goog.getUid` in which case the mutation is\n * undone.\n * @param {Object} obj The object to remove the unique ID field from.\n */\ngoog.removeUid = function(obj) {\n // TODO(arv): Make the type stricter, do not accept null.\n\n // In IE, DOM nodes are not instances of Object and throw an exception if we\n // try to delete. Instead we try to use removeAttribute.\n if (obj !== null && 'removeAttribute' in obj) {\n obj.removeAttribute(goog.UID_PROPERTY_);\n }\n\n try {\n delete obj[goog.UID_PROPERTY_];\n } catch (ex) {\n }\n};\n\n\n/**\n * Name for unique ID property. Initialized in a way to help avoid collisions\n * with other closure JavaScript on the same page.\n * @type {string}\n * @private\n */\ngoog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0);\n\n\n/**\n * Counter for UID.\n * @type {number}\n * @private\n */\ngoog.uidCounter_ = 0;\n\n\n/**\n * Clones a value. The input may be an Object, Array, or basic type. Objects and\n * arrays will be cloned recursively.\n *\n * WARNINGS:\n * <code>goog.cloneObject</code> does not detect reference loops. Objects that\n * refer to themselves will cause infinite recursion.\n *\n * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies\n * UIDs created by <code>getUid</code> into cloned results.\n *\n * @param {*} obj The value to clone.\n * @return {*} A clone of the input value.\n * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods.\n */\ngoog.cloneObject = function(obj) {\n var type = goog.typeOf(obj);\n if (type == 'object' || type == 'array') {\n if (typeof obj.clone === 'function') {\n return obj.clone();\n }\n if (typeof Map !== 'undefined' && obj instanceof Map) {\n return new Map(obj);\n } else if (typeof Set !== 'undefined' && obj instanceof Set) {\n return new Set(obj);\n }\n var clone = type == 'array' ? [] : {};\n for (var key in obj) {\n clone[key] = goog.cloneObject(obj[key]);\n }\n return clone;\n }\n\n return obj;\n};\n\n\n/**\n * A native implementation of goog.bind.\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n * function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n * function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n * invoked as a method of.\n * @template T\n * @private\n */\ngoog.bindNative_ = function(fn, selfObj, var_args) {\n return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));\n};\n\n\n/**\n * A pure-JS implementation of goog.bind.\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n * function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n * function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n * invoked as a method of.\n * @template T\n * @private\n */\ngoog.bindJs_ = function(fn, selfObj, var_args) {\n if (!fn) {\n throw new Error();\n }\n\n if (arguments.length > 2) {\n var boundArgs = Array.prototype.slice.call(arguments, 2);\n return function() {\n // Prepend the bound arguments to the current arguments.\n var newArgs = Array.prototype.slice.call(arguments);\n Array.prototype.unshift.apply(newArgs, boundArgs);\n return fn.apply(selfObj, newArgs);\n };\n\n } else {\n return function() {\n return fn.apply(selfObj, arguments);\n };\n }\n};\n\n\n/**\n * Partially applies this function to a particular 'this object' and zero or\n * more arguments. The result is a new function with some arguments of the first\n * function pre-filled and the value of this 'pre-specified'.\n *\n * Remaining arguments specified at call-time are appended to the pre-specified\n * ones.\n *\n * Also see: {@link #partial}.\n *\n * Usage:\n * <pre>var barMethBound = goog.bind(myFunction, myObj, 'arg1', 'arg2');\n * barMethBound('arg3', 'arg4');</pre>\n *\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n * function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n * function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n * invoked as a method of.\n * @template T\n * @suppress {deprecated} See above.\n * @deprecated use `=> {}` or Function.prototype.bind instead.\n */\ngoog.bind = function(fn, selfObj, var_args) {\n // TODO(nicksantos): narrow the type signature.\n if (Function.prototype.bind &&\n // NOTE(nicksantos): Somebody pulled base.js into the default Chrome\n // extension environment. This means that for Chrome extensions, they get\n // the implementation of Function.prototype.bind that calls goog.bind\n // instead of the native one. Even worse, we don't want to introduce a\n // circular dependency between goog.bind and Function.prototype.bind, so\n // we have to hack this to make sure it works correctly.\n Function.prototype.bind.toString().indexOf('native code') != -1) {\n goog.bind = goog.bindNative_;\n } else {\n goog.bind = goog.bindJs_;\n }\n return goog.bind.apply(null, arguments);\n};\n\n\n/**\n * Like goog.bind(), except that a 'this object' is not required. Useful when\n * the target function is already bound.\n *\n * Usage:\n * var g = goog.partial(f, arg1, arg2);\n * g(arg3, arg4);\n *\n * @param {Function} fn A function to partially apply.\n * @param {...*} var_args Additional arguments that are partially applied to fn.\n * @return {!Function} A partially-applied form of the function goog.partial()\n * was invoked as a method of.\n */\ngoog.partial = function(fn, var_args) {\n var args = Array.prototype.slice.call(arguments, 1);\n return function() {\n // Clone the array (with slice()) and append additional arguments\n // to the existing arguments.\n var newArgs = args.slice();\n newArgs.push.apply(newArgs, arguments);\n return fn.apply(/** @type {?} */ (this), newArgs);\n };\n};\n\n\n/**\n * @return {number} An integer value representing the number of milliseconds\n * between midnight, January 1, 1970 and the current time.\n * @deprecated Use Date.now\n */\ngoog.now = function() {\n return Date.now();\n};\n\n\n/**\n * Evals JavaScript in the global scope.\n *\n * Throws an exception if neither execScript or eval is defined.\n * @param {string|!TrustedScript} script JavaScript string.\n */\ngoog.globalEval = function(script) {\n (0, eval)(script);\n};\n\n\n/**\n * Optional map of CSS class names to obfuscated names used with\n * goog.getCssName().\n * @private {!Object<string, string>|undefined}\n * @see goog.setCssNameMapping\n */\ngoog.cssNameMapping_;\n\n\n/**\n * Optional obfuscation style for CSS class names. Should be set to either\n * 'BY_WHOLE' or 'BY_PART' if defined.\n * @type {string|undefined}\n * @private\n * @see goog.setCssNameMapping\n */\ngoog.cssNameMappingStyle_;\n\n\n\n/**\n * A hook for modifying the default behavior goog.getCssName. The function\n * if present, will receive the standard output of the goog.getCssName as\n * its input.\n *\n * @type {(function(string):string)|undefined}\n */\ngoog.global.CLOSURE_CSS_NAME_MAP_FN;\n\n\n/**\n * Handles strings that are intended to be used as CSS class names.\n *\n * This function works in tandem with @see goog.setCssNameMapping.\n *\n * Without any mapping set, the arguments are simple joined with a hyphen and\n * passed through unaltered.\n *\n * When there is a mapping, there are two possible styles in which these\n * mappings are used. In the BY_PART style, each part (i.e. in between hyphens)\n * of the passed in css name is rewritten according to the map. In the BY_WHOLE\n * style, the full css name is looked up in the map directly. If a rewrite is\n * not specified by the map, the compiler will output a warning.\n *\n * When the mapping is passed to the compiler, it will replace calls to\n * goog.getCssName with the strings from the mapping, e.g.\n * var x = goog.getCssName('foo');\n * var y = goog.getCssName(this.baseClass, 'active');\n * becomes:\n * var x = 'foo';\n * var y = this.baseClass + '-active';\n *\n * If one argument is passed it will be processed, if two are passed only the\n * modifier will be processed, as it is assumed the first argument was generated\n * as a result of calling goog.getCssName.\n *\n * @param {string} className The class name.\n * @param {string=} opt_modifier A modifier to be appended to the class name.\n * @return {string} The class name or the concatenation of the class name and\n * the modifier.\n */\ngoog.getCssName = function(className, opt_modifier) {\n // String() is used for compatibility with compiled soy where the passed\n // className can be non-string objects.\n if (String(className).charAt(0) == '.') {\n throw new Error(\n 'className passed in goog.getCssName must not start with \".\".' +\n ' You passed: ' + className);\n }\n\n var getMapping = function(cssName) {\n return goog.cssNameMapping_[cssName] || cssName;\n };\n\n var renameByParts = function(cssName) {\n // Remap all the parts individually.\n var parts = cssName.split('-');\n var mapped = [];\n for (var i = 0; i < parts.length; i++) {\n mapped.push(getMapping(parts[i]));\n }\n return mapped.join('-');\n };\n\n var rename;\n if (goog.cssNameMapping_) {\n rename =\n goog.cssNameMappingStyle_ == 'BY_WHOLE' ? getMapping : renameByParts;\n } else {\n rename = function(a) {\n return a;\n };\n }\n\n var result =\n opt_modifier ? className + '-' + rename(opt_modifier) : rename(className);\n\n // The special CLOSURE_CSS_NAME_MAP_FN allows users to specify further\n // processing of the class name.\n if (goog.global.CLOSURE_CSS_NAME_MAP_FN) {\n return goog.global.CLOSURE_CSS_NAME_MAP_FN(result);\n }\n\n return result;\n};\n\n\n/**\n * Sets the map to check when returning a value from goog.getCssName(). Example:\n * <pre>\n * goog.setCssNameMapping({\n * \"goog\": \"a\",\n * \"disabled\": \"b\",\n * });\n *\n * var x = goog.getCssName('goog');\n * // The following evaluates to: \"a a-b\".\n * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled')\n * </pre>\n * When declared as a map of string literals to string literals, the JSCompiler\n * will replace all calls to goog.getCssName() using the supplied map if the\n * --process_closure_primitives flag is set.\n *\n * @param {!Object} mapping A map of strings to strings where keys are possible\n * arguments to goog.getCssName() and values are the corresponding values\n * that should be returned.\n * @param {string=} opt_style The style of css name mapping. There are two valid\n * options: 'BY_PART', and 'BY_WHOLE'.\n * @see goog.getCssName for a description.\n */\ngoog.setCssNameMapping = function(mapping, opt_style) {\n goog.cssNameMapping_ = mapping;\n goog.cssNameMappingStyle_ = opt_style;\n};\n\n\n/**\n * To use CSS renaming in compiled mode, one of the input files should have a\n * call to goog.setCssNameMapping() with an object literal that the JSCompiler\n * can extract and use to replace all calls to goog.getCssName(). In uncompiled\n * mode, JavaScript code should be loaded before this base.js file that declares\n * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is\n * to ensure that the mapping is loaded before any calls to goog.getCssName()\n * are made in uncompiled mode.\n *\n * A hook for overriding the CSS name mapping.\n * @type {!Object<string, string>|undefined}\n */\ngoog.global.CLOSURE_CSS_NAME_MAPPING;\n\n\nif (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) {\n // This does not call goog.setCssNameMapping() because the JSCompiler\n // requires that goog.setCssNameMapping() be called with an object literal.\n goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING;\n}\n\n/**\n * Options bag type for `goog.getMsg()` third argument.\n *\n * It is important to note that these options need to be known at compile time,\n * so they must always be provided to `goog.getMsg()` as an actual object\n * literal in the function call. Otherwise, closure-compiler will report an\n * error.\n * @record\n */\ngoog.GetMsgOptions = function() {};\n\n/**\n * If `true`, escape '<' in the message string to '<'.\n *\n * Used by Closure Templates where the generated code size and performance is\n * critical which is why {@link goog.html.SafeHtmlFormatter} is not used.\n * The value must be literal `true` or `false`.\n * @type {boolean|undefined}\n */\ngoog.GetMsgOptions.prototype.html;\n\n/**\n * If `true`, unescape common html entities: >, <, ', " and\n * &.\n *\n * Used for messages not in HTML context, such as with the `textContent`\n * property.\n * The value must be literal `true` or `false`.\n * @type {boolean|undefined}\n */\ngoog.GetMsgOptions.prototype.unescapeHtmlEntities;\n\n/**\n * Associates placeholder names with strings showing how their values are\n * obtained.\n *\n * This field is intended for use in automatically generated JS code.\n * Human-written code should use meaningful placeholder names instead.\n *\n * closure-compiler uses this as the contents of the `<ph>` tag in the\n * XMB file it generates or defaults to `-` for historical reasons.\n *\n * Must be an object literal.\n * Ignored at runtime.\n * Keys are placeholder names.\n * Values are string literals indicating how the value is obtained.\n * Typically this is a snippet of source code.\n * @type {!Object<string, string>|undefined}\n */\ngoog.GetMsgOptions.prototype.original_code;\n\n/**\n * Associates placeholder names with example values.\n *\n * closure-compiler uses this as the contents of the `<ex>` tag in the\n * XMB file it generates or defaults to `-` for historical reasons.\n *\n * Must be an object literal.\n * Ignored at runtime.\n * Keys are placeholder names.\n * Values are string literals containing example placeholder values.\n * (e.g. \"George McFly\" for a name placeholder)\n * @type {!Object<string, string>|undefined}\n */\ngoog.GetMsgOptions.prototype.example;\n\n/**\n * Gets a localized message.\n *\n * This function is a compiler primitive. If you give the compiler a localized\n * message bundle, it will replace the string at compile-time with a localized\n * version, and expand goog.getMsg call to a concatenated string.\n *\n * Messages must be initialized in the form:\n * <code>\n * var MSG_NAME = goog.getMsg('Hello {$placeholder}', {'placeholder': 'world'});\n * </code>\n *\n * This function produces a string which should be treated as plain text. Use\n * {@link goog.html.SafeHtmlFormatter} in conjunction with goog.getMsg to\n * produce SafeHtml.\n *\n * @param {string} str Translatable string, places holders in the form {$foo}.\n * @param {!Object<string, string>=} opt_values Maps place holder name to value.\n * @param {!goog.GetMsgOptions=} opt_options see `goog.GetMsgOptions`\n * @return {string} message with placeholders filled.\n */\ngoog.getMsg = function(str, opt_values, opt_options) {\n if (opt_options && opt_options.html) {\n // Note that '&' is not replaced because the translation can contain HTML\n // entities.\n str = str.replace(/</g, '<');\n }\n if (opt_options && opt_options.unescapeHtmlEntities) {\n // Note that \"&\" must be the last to avoid \"creating\" new entities.\n str = str.replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/'/g, '\\'')\n .replace(/"/g, '\"')\n .replace(/&/g, '&');\n }\n if (opt_values) {\n str = str.replace(/\\{\\$([^}]+)}/g, function(match, key) {\n return (opt_values != null && key in opt_values) ? opt_values[key] :\n match;\n });\n }\n return str;\n};\n\n\n/**\n * Gets a localized message. If the message does not have a translation, gives a\n * fallback message.\n *\n * This is useful when introducing a new message that has not yet been\n * translated into all languages.\n *\n * This function is a compiler primitive. Must be used in the form:\n * <code>var x = goog.getMsgWithFallback(MSG_A, MSG_B);</code>\n * where MSG_A and MSG_B were initialized with goog.getMsg.\n *\n * @param {string} a The preferred message.\n * @param {string} b The fallback message.\n * @return {string} The best translated message.\n */\ngoog.getMsgWithFallback = function(a, b) {\n return a;\n};\n\n\n/**\n * Exposes an unobfuscated global namespace path for the given object.\n * Note that fields of the exported object *will* be obfuscated, unless they are\n * exported in turn via this function or goog.exportProperty.\n *\n * Also handy for making public items that are defined in anonymous closures.\n *\n * ex. goog.exportSymbol('public.path.Foo', Foo);\n *\n * ex. goog.exportSymbol('public.path.Foo.staticFunction', Foo.staticFunction);\n * public.path.Foo.staticFunction();\n *\n * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod',\n * Foo.prototype.myMethod);\n * new public.path.Foo().myMethod();\n *\n * @param {string} publicPath Unobfuscated name to export.\n * @param {*} object Object the name should point to.\n * @param {?Object=} objectToExportTo The object to add the path to; default\n * is goog.global.\n */\ngoog.exportSymbol = function(publicPath, object, objectToExportTo) {\n goog.exportPath_(\n publicPath, object, /* overwriteImplicit= */ true, objectToExportTo);\n};\n\n\n/**\n * Exports a property unobfuscated into the object's namespace.\n * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction);\n * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod);\n * @param {Object} object Object whose static property is being exported.\n * @param {string} publicName Unobfuscated name to export.\n * @param {*} symbol Object the name should point to.\n */\ngoog.exportProperty = function(object, publicName, symbol) {\n object[publicName] = symbol;\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * Usage:\n * <pre>\n * function ParentClass(a, b) { }\n * ParentClass.prototype.foo = function(a) { };\n *\n * function ChildClass(a, b, c) {\n * ChildClass.base(this, 'constructor', a, b);\n * }\n * goog.inherits(ChildClass, ParentClass);\n *\n * var child = new ChildClass('a', 'b', 'see');\n * child.foo(); // This works.\n * </pre>\n *\n * @param {!Function} childCtor Child class.\n * @param {!Function} parentCtor Parent class.\n * @suppress {strictMissingProperties} superClass_ and base is not defined on\n * Function.\n * @deprecated Use ECMAScript class syntax instead.\n */\ngoog.inherits = function(childCtor, parentCtor) {\n /** @constructor */\n function tempCtor() {}\n tempCtor.prototype = parentCtor.prototype;\n childCtor.superClass_ = parentCtor.prototype;\n childCtor.prototype = new tempCtor();\n /** @override */\n childCtor.prototype.constructor = childCtor;\n\n /**\n * Calls superclass constructor/method.\n *\n * This function is only available if you use goog.inherits to\n * express inheritance relationships between classes.\n *\n * NOTE: This is a replacement for goog.base and for superClass_\n * property defined in childCtor.\n *\n * @param {!Object} me Should always be \"this\".\n * @param {string} methodName The method name to call. Calling\n * superclass constructor can be done with the special string\n * 'constructor'.\n * @param {...*} var_args The arguments to pass to superclass\n * method/constructor.\n * @return {*} The return value of the superclass method/constructor.\n */\n childCtor.base = function(me, methodName, var_args) {\n // Copying using loop to avoid deop due to passing arguments object to\n // function. This is faster in many JS engines as of late 2014.\n var args = new Array(arguments.length - 2);\n for (var i = 2; i < arguments.length; i++) {\n args[i - 2] = arguments[i];\n }\n return parentCtor.prototype[methodName].apply(me, args);\n };\n};\n\n\n/**\n * Allow for aliasing within scope functions. This function exists for\n * uncompiled code - in compiled code the calls will be inlined and the aliases\n * applied. In uncompiled code the function is simply run since the aliases as\n * written are valid JavaScript.\n *\n *\n * @param {function()} fn Function to call. This function can contain aliases\n * to namespaces (e.g. \"var dom = goog.dom\") or classes\n * (e.g. \"var Timer = goog.Timer\").\n * @deprecated Use goog.module instead.\n */\ngoog.scope = function(fn) {\n if (goog.isInModuleLoader_()) {\n throw new Error('goog.scope is not supported within a module.');\n }\n fn.call(goog.global);\n};\n\n\n/*\n * To support uncompiled, strict mode bundles that use eval to divide source\n * like so:\n * eval('someSource;//# sourceUrl sourcefile.js');\n * We need to export the globally defined symbols \"goog\" and \"COMPILED\".\n * Exporting \"goog\" breaks the compiler optimizations, so we required that\n * be defined externally.\n * NOTE: We don't use goog.exportSymbol here because we don't want to trigger\n * extern generation when that compiler option is enabled.\n */\nif (!COMPILED) {\n goog.global['COMPILED'] = COMPILED;\n}\n\n\n//==============================================================================\n// goog.defineClass implementation\n//==============================================================================\n\n\n/**\n * Creates a restricted form of a Closure \"class\":\n * - from the compiler's perspective, the instance returned from the\n * constructor is sealed (no new properties may be added). This enables\n * better checks.\n * - the compiler will rewrite this definition to a form that is optimal\n * for type checking and optimization (initially this will be a more\n * traditional form).\n *\n * @param {Function} superClass The superclass, Object or null.\n * @param {goog.defineClass.ClassDescriptor} def\n * An object literal describing\n * the class. It may have the following properties:\n * \"constructor\": the constructor function\n * \"statics\": an object literal containing methods to add to the constructor\n * as \"static\" methods or a function that will receive the constructor\n * function as its only parameter to which static properties can\n * be added.\n * all other properties are added to the prototype.\n * @return {!Function} The class constructor.\n * @deprecated Use ECMAScript class syntax instead.\n */\ngoog.defineClass = function(superClass, def) {\n // TODO(johnlenz): consider making the superClass an optional parameter.\n var constructor = def.constructor;\n var statics = def.statics;\n // Wrap the constructor prior to setting up the prototype and static methods.\n if (!constructor || constructor == Object.prototype.constructor) {\n constructor = function() {\n throw new Error(\n 'cannot instantiate an interface (no constructor defined).');\n };\n }\n\n var cls = goog.defineClass.createSealingConstructor_(constructor, superClass);\n if (superClass) {\n goog.inherits(cls, superClass);\n }\n\n // Remove all the properties that should not be copied to the prototype.\n delete def.constructor;\n delete def.statics;\n\n goog.defineClass.applyProperties_(cls.prototype, def);\n if (statics != null) {\n if (statics instanceof Function) {\n statics(cls);\n } else {\n goog.defineClass.applyProperties_(cls, statics);\n }\n }\n\n return cls;\n};\n\n\n/**\n * @typedef {{\n * constructor: (!Function|undefined),\n * statics: (Object|undefined|function(Function):void)\n * }}\n */\ngoog.defineClass.ClassDescriptor;\n\n\n/**\n * @define {boolean} Whether the instances returned by goog.defineClass should\n * be sealed when possible.\n *\n * When sealing is disabled the constructor function will not be wrapped by\n * goog.defineClass, making it incompatible with ES6 class methods.\n */\ngoog.defineClass.SEAL_CLASS_INSTANCES =\n goog.define('goog.defineClass.SEAL_CLASS_INSTANCES', goog.DEBUG);\n\n\n/**\n * If goog.defineClass.SEAL_CLASS_INSTANCES is enabled and Object.seal is\n * defined, this function will wrap the constructor in a function that seals the\n * results of the provided constructor function.\n *\n * @param {!Function} ctr The constructor whose results maybe be sealed.\n * @param {Function} superClass The superclass constructor.\n * @return {!Function} The replacement constructor.\n * @private\n */\ngoog.defineClass.createSealingConstructor_ = function(ctr, superClass) {\n if (!goog.defineClass.SEAL_CLASS_INSTANCES) {\n // Do now wrap the constructor when sealing is disabled. Angular code\n // depends on this for injection to work properly.\n return ctr;\n }\n\n // NOTE: The sealing behavior has been removed\n\n /**\n * @this {Object}\n * @return {?}\n */\n var wrappedCtr = function() {\n // Don't seal an instance of a subclass when it calls the constructor of\n // its super class as there is most likely still setup to do.\n var instance = ctr.apply(this, arguments) || this;\n instance[goog.UID_PROPERTY_] = instance[goog.UID_PROPERTY_];\n\n return instance;\n };\n\n return wrappedCtr;\n};\n\n\n\n// TODO(johnlenz): share these values with the goog.object\n/**\n * The names of the fields that are defined on Object.prototype.\n * @type {!Array<string>}\n * @private\n * @const\n */\ngoog.defineClass.OBJECT_PROTOTYPE_FIELDS_ = [\n 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',\n 'toLocaleString', 'toString', 'valueOf'\n];\n\n\n// TODO(johnlenz): share this function with the goog.object\n/**\n * @param {!Object} target The object to add properties to.\n * @param {!Object} source The object to copy properties from.\n * @private\n */\ngoog.defineClass.applyProperties_ = function(target, source) {\n // TODO(johnlenz): update this to support ES5 getters/setters\n\n var key;\n for (key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n\n // For IE the for-in-loop does not contain any properties that are not\n // enumerable on the prototype object (for example isPrototypeOf from\n // Object.prototype) and it will also not include 'replace' on objects that\n // extend String and change 'replace' (not that it is common for anyone to\n // extend anything except Object).\n for (var i = 0; i < goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length; i++) {\n key = goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[i];\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n};\n\n/**\n * Returns the parameter.\n * @param {string} s\n * @return {string}\n * @private\n */\ngoog.identity_ = function(s) {\n return s;\n};\n\n\n/**\n * Creates Trusted Types policy if Trusted Types are supported by the browser.\n * The policy just blesses any string as a Trusted Type. It is not visibility\n * restricted because anyone can also call trustedTypes.createPolicy directly.\n * However, the allowed names should be restricted by a HTTP header and the\n * reference to the created policy should be visibility restricted.\n * @param {string} name\n * @return {?TrustedTypePolicy}\n */\ngoog.createTrustedTypesPolicy = function(name) {\n var policy = null;\n var policyFactory = goog.global.trustedTypes;\n if (!policyFactory || !policyFactory.createPolicy) {\n return policy;\n }\n // trustedTypes.createPolicy throws if called with a name that is already\n // registered, even in report-only mode. Until the API changes, catch the\n // error not to break the applications functionally. In such case, the code\n // will fall back to using regular Safe Types.\n // TODO(koto): Remove catching once createPolicy API stops throwing.\n try {\n policy = policyFactory.createPolicy(name, {\n createHTML: goog.identity_,\n createScript: goog.identity_,\n createScriptURL: goog.identity_\n });\n } catch (e) {\n goog.logToConsole_(e.message);\n }\n return policy;\n};\n\n// There's a bug in the compiler where without collapse properties the\n// Closure namespace defines do not guard code correctly. To help reduce code\n// size also check for !COMPILED even though it redundant until this is fixed.\nif (!COMPILED && goog.DEPENDENCIES_ENABLED) {\n\n\n /**\n * Tries to detect whether the current browser is Edge, based on the user\n * agent. This matches only pre-Chromium Edge.\n * @see https://docs.microsoft.com/en-us/microsoft-edge/web-platform/user-agent-string\n * @return {boolean} True if the current browser is Edge.\n * @private\n */\n goog.isEdge_ = function() {\n var userAgent = goog.global.navigator && goog.global.navigator.userAgent ?\n goog.global.navigator.userAgent :\n '';\n var edgeRe = /Edge\\/(\\d+)(\\.\\d)*/i;\n return !!userAgent.match(edgeRe);\n };\n\n\n /**\n * Tries to detect whether is in the context of an HTML document.\n * @return {boolean} True if it looks like HTML document.\n * @private\n */\n goog.inHtmlDocument_ = function() {\n /** @type {!Document} */\n var doc = goog.global.document;\n return doc != null && 'write' in doc; // XULDocument misses write.\n };\n\n\n /**\n * We'd like to check for if the document readyState is 'loading'; however\n * there are bugs on IE 10 and below where the readyState being anything other\n * than 'complete' is not reliable.\n * @return {boolean}\n * @private\n */\n goog.isDocumentLoading_ = function() {\n // attachEvent is available on IE 6 thru 10 only, and thus can be used to\n // detect those browsers.\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n return doc.attachEvent ? doc.readyState != 'complete' :\n doc.readyState == 'loading';\n };\n\n\n /**\n * Tries to detect the base path of base.js script that bootstraps Closure.\n * @private\n */\n goog.findBasePath_ = function() {\n if (goog.global.CLOSURE_BASE_PATH != undefined &&\n // Anti DOM-clobbering runtime check (b/37736576).\n typeof goog.global.CLOSURE_BASE_PATH === 'string') {\n goog.basePath = goog.global.CLOSURE_BASE_PATH;\n return;\n } else if (!goog.inHtmlDocument_()) {\n return;\n }\n /** @type {!Document} */\n var doc = goog.global.document;\n // If we have a currentScript available, use it exclusively.\n var currentScript = doc.currentScript;\n if (currentScript) {\n var scripts = [currentScript];\n } else {\n var scripts = doc.getElementsByTagName('SCRIPT');\n }\n // Search backwards since the current script is in almost all cases the one\n // that has base.js.\n for (var i = scripts.length - 1; i >= 0; --i) {\n var script = /** @type {!HTMLScriptElement} */ (scripts[i]);\n var src = script.src;\n var qmark = src.lastIndexOf('?');\n var l = qmark == -1 ? src.length : qmark;\n if (src.slice(l - 7, l) == 'base.js') {\n goog.basePath = src.slice(0, l - 7);\n return;\n }\n }\n };\n\n goog.findBasePath_();\n\n /**\n * Rewrites closing script tags in input to avoid ending an enclosing script\n * tag.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n goog.protectScriptTag_ = function(str) {\n return str.replace(/<\\/(SCRIPT)/ig, '\\\\x3c/$1');\n };\n\n\n /**\n * A debug loader is responsible for downloading and executing javascript\n * files in an unbundled, uncompiled environment.\n *\n * This can be custimized via the setDependencyFactory method, or by\n * CLOSURE_IMPORT_SCRIPT/CLOSURE_LOAD_FILE_SYNC.\n *\n * @struct @constructor @final @private\n */\n goog.DebugLoader_ = function() {\n /** @private @const {!Object<string, !goog.Dependency>} */\n this.dependencies_ = {};\n /** @private @const {!Object<string, string>} */\n this.idToPath_ = {};\n /** @private @const {!Object<string, boolean>} */\n this.written_ = {};\n /** @private @const {!Array<!goog.Dependency>} */\n this.loadingDeps_ = [];\n /** @private {!Array<!goog.Dependency>} */\n this.depsToLoad_ = [];\n /** @private {boolean} */\n this.paused_ = false;\n /** @private {!goog.DependencyFactory} */\n this.factory_ = new goog.DependencyFactory();\n /** @private @const {!Object<string, !Function>} */\n this.deferredCallbacks_ = {};\n /** @private @const {!Array<string>} */\n this.deferredQueue_ = [];\n };\n\n /**\n * @param {!Array<string>} namespaces\n * @param {function(): undefined} callback Function to call once all the\n * namespaces have loaded.\n */\n goog.DebugLoader_.prototype.bootstrap = function(namespaces, callback) {\n var cb = callback;\n function resolve() {\n if (cb) {\n goog.global.setTimeout(cb, 0);\n cb = null;\n }\n }\n\n if (!namespaces.length) {\n resolve();\n return;\n }\n\n var deps = [];\n for (var i = 0; i < namespaces.length; i++) {\n var path = this.getPathFromDeps_(namespaces[i]);\n if (!path) {\n throw new Error('Unregonized namespace: ' + namespaces[i]);\n }\n deps.push(this.dependencies_[path]);\n }\n\n var require = goog.require;\n var loaded = 0;\n for (var i = 0; i < namespaces.length; i++) {\n require(namespaces[i]);\n deps[i].onLoad(function() {\n if (++loaded == namespaces.length) {\n resolve();\n }\n });\n }\n };\n\n\n /**\n * Loads the Closure Dependency file.\n *\n * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base\n * loaded, setDependencyFactory called, and then this called. i.e. allows\n * custom loading of the deps file.\n */\n goog.DebugLoader_.prototype.loadClosureDeps = function() {\n // Circumvent addDependency, which would try to transpile deps.js if\n // transpile is set to always.\n var relPath = 'deps.js';\n this.depsToLoad_.push(this.factory_.createDependency(\n goog.normalizePath_(goog.basePath + relPath), relPath, [], [], {}));\n this.loadDeps_();\n };\n\n\n /**\n * Notifies the debug loader when a dependency has been requested.\n *\n * @param {string} absPathOrId Path of the dependency or goog id.\n * @param {boolean=} opt_force\n */\n goog.DebugLoader_.prototype.requested = function(absPathOrId, opt_force) {\n var path = this.getPathFromDeps_(absPathOrId);\n if (path &&\n (opt_force || this.areDepsLoaded_(this.dependencies_[path].requires))) {\n var callback = this.deferredCallbacks_[path];\n if (callback) {\n delete this.deferredCallbacks_[path];\n callback();\n }\n }\n };\n\n\n /**\n * Sets the dependency factory, which can be used to create custom\n * goog.Dependency implementations to control how dependencies are loaded.\n *\n * @param {!goog.DependencyFactory} factory\n */\n goog.DebugLoader_.prototype.setDependencyFactory = function(factory) {\n this.factory_ = factory;\n };\n\n\n /**\n * Travserses the dependency graph and queues the given dependency, and all of\n * its transitive dependencies, for loading and then starts loading if not\n * paused.\n *\n * @param {string} namespace\n * @private\n */\n goog.DebugLoader_.prototype.load_ = function(namespace) {\n if (!this.getPathFromDeps_(namespace)) {\n var errorMessage = 'goog.require could not find: ' + namespace;\n goog.logToConsole_(errorMessage);\n } else {\n var loader = this;\n\n var deps = [];\n\n /** @param {string} namespace */\n var visit = function(namespace) {\n var path = loader.getPathFromDeps_(namespace);\n\n if (!path) {\n throw new Error('Bad dependency path or symbol: ' + namespace);\n }\n\n if (loader.written_[path]) {\n return;\n }\n\n loader.written_[path] = true;\n\n var dep = loader.dependencies_[path];\n for (var i = 0; i < dep.requires.length; i++) {\n if (!goog.isProvided_(dep.requires[i])) {\n visit(dep.requires[i]);\n }\n }\n\n deps.push(dep);\n };\n\n visit(namespace);\n\n var wasLoading = !!this.depsToLoad_.length;\n this.depsToLoad_ = this.depsToLoad_.concat(deps);\n\n if (!this.paused_ && !wasLoading) {\n this.loadDeps_();\n }\n }\n };\n\n\n /**\n * Loads any queued dependencies until they are all loaded or paused.\n *\n * @private\n */\n goog.DebugLoader_.prototype.loadDeps_ = function() {\n var loader = this;\n var paused = this.paused_;\n\n while (this.depsToLoad_.length && !paused) {\n (function() {\n var loadCallDone = false;\n var dep = loader.depsToLoad_.shift();\n\n var loaded = false;\n loader.loading_(dep);\n\n var controller = {\n pause: function() {\n if (loadCallDone) {\n throw new Error('Cannot call pause after the call to load.');\n } else {\n paused = true;\n }\n },\n resume: function() {\n if (loadCallDone) {\n loader.resume_();\n } else {\n // Some dep called pause and then resume in the same load call.\n // Just keep running this same loop.\n paused = false;\n }\n },\n loaded: function() {\n if (loaded) {\n throw new Error('Double call to loaded.');\n }\n\n loaded = true;\n loader.loaded_(dep);\n },\n pending: function() {\n // Defensive copy.\n var pending = [];\n for (var i = 0; i < loader.loadingDeps_.length; i++) {\n pending.push(loader.loadingDeps_[i]);\n }\n return pending;\n },\n /**\n * @param {goog.ModuleType} type\n */\n setModuleState: function(type) {\n goog.moduleLoaderState_ = {\n type: type,\n moduleName: '',\n declareLegacyNamespace: false\n };\n },\n /** @type {function(string, string, string=)} */\n registerEs6ModuleExports: function(\n path, exports, opt_closureNamespace) {\n if (opt_closureNamespace) {\n goog.loadedModules_[opt_closureNamespace] = {\n exports: exports,\n type: goog.ModuleType.ES6,\n moduleId: opt_closureNamespace || ''\n };\n }\n },\n /** @type {function(string, ?)} */\n registerGoogModuleExports: function(moduleId, exports) {\n goog.loadedModules_[moduleId] = {\n exports: exports,\n type: goog.ModuleType.GOOG,\n moduleId: moduleId\n };\n },\n clearModuleState: function() {\n goog.moduleLoaderState_ = null;\n },\n defer: function(callback) {\n if (loadCallDone) {\n throw new Error(\n 'Cannot register with defer after the call to load.');\n }\n loader.defer_(dep, callback);\n },\n areDepsLoaded: function() {\n return loader.areDepsLoaded_(dep.requires);\n }\n };\n\n try {\n dep.load(controller);\n } finally {\n loadCallDone = true;\n }\n })();\n }\n\n if (paused) {\n this.pause_();\n }\n };\n\n\n /** @private */\n goog.DebugLoader_.prototype.pause_ = function() {\n this.paused_ = true;\n };\n\n\n /** @private */\n goog.DebugLoader_.prototype.resume_ = function() {\n if (this.paused_) {\n this.paused_ = false;\n this.loadDeps_();\n }\n };\n\n\n /**\n * Marks the given dependency as loading (load has been called but it has not\n * yet marked itself as finished). Useful for dependencies that want to know\n * what else is loading. Example: goog.modules cannot eval if there are\n * loading dependencies.\n *\n * @param {!goog.Dependency} dep\n * @private\n */\n goog.DebugLoader_.prototype.loading_ = function(dep) {\n this.loadingDeps_.push(dep);\n };\n\n\n /**\n * Marks the given dependency as having finished loading and being available\n * for require.\n *\n * @param {!goog.Dependency} dep\n * @private\n */\n goog.DebugLoader_.prototype.loaded_ = function(dep) {\n for (var i = 0; i < this.loadingDeps_.length; i++) {\n if (this.loadingDeps_[i] == dep) {\n this.loadingDeps_.splice(i, 1);\n break;\n }\n }\n\n for (var i = 0; i < this.deferredQueue_.length; i++) {\n if (this.deferredQueue_[i] == dep.path) {\n this.deferredQueue_.splice(i, 1);\n break;\n }\n }\n\n if (this.loadingDeps_.length == this.deferredQueue_.length &&\n !this.depsToLoad_.length) {\n // Something has asked to load these, but they may not be directly\n // required again later, so load them now that we know we're done loading\n // everything else. e.g. a goog module entry point.\n while (this.deferredQueue_.length) {\n this.requested(this.deferredQueue_.shift(), true);\n }\n }\n\n dep.loaded();\n };\n\n\n /**\n * @param {!Array<string>} pathsOrIds\n * @return {boolean}\n * @private\n */\n goog.DebugLoader_.prototype.areDepsLoaded_ = function(pathsOrIds) {\n for (var i = 0; i < pathsOrIds.length; i++) {\n var path = this.getPathFromDeps_(pathsOrIds[i]);\n if (!path ||\n (!(path in this.deferredCallbacks_) &&\n !goog.isProvided_(pathsOrIds[i]))) {\n return false;\n }\n }\n\n return true;\n };\n\n\n /**\n * @param {string} absPathOrId\n * @return {?string}\n * @private\n */\n goog.DebugLoader_.prototype.getPathFromDeps_ = function(absPathOrId) {\n if (absPathOrId in this.idToPath_) {\n return this.idToPath_[absPathOrId];\n } else if (absPathOrId in this.dependencies_) {\n return absPathOrId;\n } else {\n return null;\n }\n };\n\n\n /**\n * @param {!goog.Dependency} dependency\n * @param {!Function} callback\n * @private\n */\n goog.DebugLoader_.prototype.defer_ = function(dependency, callback) {\n this.deferredCallbacks_[dependency.path] = callback;\n this.deferredQueue_.push(dependency.path);\n };\n\n\n /**\n * Interface for goog.Dependency implementations to have some control over\n * loading of dependencies.\n *\n * @record\n */\n goog.LoadController = function() {};\n\n\n /**\n * Tells the controller to halt loading of more dependencies.\n */\n goog.LoadController.prototype.pause = function() {};\n\n\n /**\n * Tells the controller to resume loading of more dependencies if paused.\n */\n goog.LoadController.prototype.resume = function() {};\n\n\n /**\n * Tells the controller that this dependency has finished loading.\n *\n * This causes this to be removed from pending() and any load callbacks to\n * fire.\n */\n goog.LoadController.prototype.loaded = function() {};\n\n\n /**\n * List of dependencies on which load has been called but which have not\n * called loaded on their controller. This includes the current dependency.\n *\n * @return {!Array<!goog.Dependency>}\n */\n goog.LoadController.prototype.pending = function() {};\n\n\n /**\n * Registers an object as an ES6 module's exports so that goog.modules may\n * require it by path.\n *\n * @param {string} path Full path of the module.\n * @param {?} exports\n * @param {string=} opt_closureNamespace Closure namespace to associate with\n * this module.\n */\n goog.LoadController.prototype.registerEs6ModuleExports = function(\n path, exports, opt_closureNamespace) {};\n\n\n /**\n * Sets the current module state.\n *\n * @param {goog.ModuleType} type Type of module.\n */\n goog.LoadController.prototype.setModuleState = function(type) {};\n\n\n /**\n * Clears the current module state.\n */\n goog.LoadController.prototype.clearModuleState = function() {};\n\n\n /**\n * Registers a callback to call once the dependency is actually requested\n * via goog.require + all of the immediate dependencies have been loaded or\n * all other files have been loaded. Allows for lazy loading until\n * require'd without pausing dependency loading, which is needed on old IE.\n *\n * @param {!Function} callback\n */\n goog.LoadController.prototype.defer = function(callback) {};\n\n\n /**\n * @return {boolean}\n */\n goog.LoadController.prototype.areDepsLoaded = function() {};\n\n\n /**\n * Basic super class for all dependencies Closure Library can load.\n *\n * This default implementation is designed to load untranspiled, non-module\n * scripts in a web broswer.\n *\n * For goog.modules see {@see goog.GoogModuleDependency}.\n * For untranspiled ES6 modules {@see goog.Es6ModuleDependency}.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor\n */\n goog.Dependency = function(\n path, relativePath, provides, requires, loadFlags) {\n /** @const */\n this.path = path;\n /** @const */\n this.relativePath = relativePath;\n /** @const */\n this.provides = provides;\n /** @const */\n this.requires = requires;\n /** @const */\n this.loadFlags = loadFlags;\n /** @private {boolean} */\n this.loaded_ = false;\n /** @private {!Array<function()>} */\n this.loadCallbacks_ = [];\n };\n\n\n /**\n * @return {string} The pathname part of this dependency's path if it is a\n * URI.\n */\n goog.Dependency.prototype.getPathName = function() {\n var pathName = this.path;\n var protocolIndex = pathName.indexOf('://');\n if (protocolIndex >= 0) {\n pathName = pathName.substring(protocolIndex + 3);\n var slashIndex = pathName.indexOf('/');\n if (slashIndex >= 0) {\n pathName = pathName.substring(slashIndex + 1);\n }\n }\n return pathName;\n };\n\n\n /**\n * @param {function()} callback Callback to fire as soon as this has loaded.\n * @final\n */\n goog.Dependency.prototype.onLoad = function(callback) {\n if (this.loaded_) {\n callback();\n } else {\n this.loadCallbacks_.push(callback);\n }\n };\n\n\n /**\n * Marks this dependency as loaded and fires any callbacks registered with\n * onLoad.\n * @final\n */\n goog.Dependency.prototype.loaded = function() {\n this.loaded_ = true;\n var callbacks = this.loadCallbacks_;\n this.loadCallbacks_ = [];\n for (var i = 0; i < callbacks.length; i++) {\n callbacks[i]();\n }\n };\n\n\n /**\n * Whether or not document.written / appended script tags should be deferred.\n *\n * @private {boolean}\n */\n goog.Dependency.defer_ = false;\n\n\n /**\n * Map of script ready / state change callbacks. Old IE cannot handle putting\n * these properties on goog.global.\n *\n * @private @const {!Object<string, function(?):undefined>}\n */\n goog.Dependency.callbackMap_ = {};\n\n\n /**\n * @param {function(...?):?} callback\n * @return {string}\n * @private\n */\n goog.Dependency.registerCallback_ = function(callback) {\n var key = Math.random().toString(32);\n goog.Dependency.callbackMap_[key] = callback;\n return key;\n };\n\n\n /**\n * @param {string} key\n * @private\n */\n goog.Dependency.unregisterCallback_ = function(key) {\n delete goog.Dependency.callbackMap_[key];\n };\n\n\n /**\n * @param {string} key\n * @param {...?} var_args\n * @private\n * @suppress {unusedPrivateMembers}\n */\n goog.Dependency.callback_ = function(key, var_args) {\n if (key in goog.Dependency.callbackMap_) {\n var callback = goog.Dependency.callbackMap_[key];\n var args = [];\n for (var i = 1; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n callback.apply(undefined, args);\n } else {\n var errorMessage = 'Callback key ' + key +\n ' does not exist (was base.js loaded more than once?).';\n throw Error(errorMessage);\n }\n };\n\n\n /**\n * Starts loading this dependency. This dependency can pause loading if it\n * needs to and resume it later via the controller interface.\n *\n * When this is loaded it should call controller.loaded(). Note that this will\n * end up calling the loaded method of this dependency; there is no need to\n * call it explicitly.\n *\n * @param {!goog.LoadController} controller\n */\n goog.Dependency.prototype.load = function(controller) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n if (!goog.inHtmlDocument_()) {\n goog.logToConsole_(\n 'Cannot use default debug loader outside of HTML documents.');\n if (this.relativePath == 'deps.js') {\n // Some old code is relying on base.js auto loading deps.js failing with\n // no error before later setting CLOSURE_IMPORT_SCRIPT.\n // CLOSURE_IMPORT_SCRIPT should be set *before* base.js is loaded, or\n // CLOSURE_NO_DEPS set to true.\n goog.logToConsole_(\n 'Consider setting CLOSURE_IMPORT_SCRIPT before loading base.js, ' +\n 'or setting CLOSURE_NO_DEPS to true.');\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n\n // If the user tries to require a new symbol after document load,\n // something has gone terribly wrong. Doing a document.write would\n // wipe out the page. This does not apply to the CSP-compliant method\n // of writing script tags.\n if (doc.readyState == 'complete' &&\n !goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING) {\n // Certain test frameworks load base.js multiple times, which tries\n // to write deps.js each time. If that happens, just fail silently.\n // These frameworks wipe the page between each load of base.js, so this\n // is OK.\n var isDeps = /\\bdeps.js$/.test(this.path);\n if (isDeps) {\n controller.loaded();\n return;\n } else {\n throw Error('Cannot write \"' + this.path + '\" after document load');\n }\n }\n\n var nonce = goog.getScriptNonce_();\n if (!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING &&\n goog.isDocumentLoading_()) {\n var key;\n var callback = function(script) {\n if (script.readyState && script.readyState != 'complete') {\n script.onload = callback;\n return;\n }\n goog.Dependency.unregisterCallback_(key);\n controller.loaded();\n };\n key = goog.Dependency.registerCallback_(callback);\n\n var defer = goog.Dependency.defer_ ? ' defer' : '';\n var nonceAttr = nonce ? ' nonce=\"' + nonce + '\"' : '';\n var script = '<script src=\"' + this.path + '\"' + nonceAttr + defer +\n ' id=\"script-' + key + '\"><\\/script>';\n\n script += '<script' + nonceAttr + '>';\n\n if (goog.Dependency.defer_) {\n script += 'document.getElementById(\\'script-' + key +\n '\\').onload = function() {\\n' +\n ' goog.Dependency.callback_(\\'' + key + '\\', this);\\n' +\n '};\\n';\n } else {\n script += 'goog.Dependency.callback_(\\'' + key +\n '\\', document.getElementById(\\'script-' + key + '\\'));';\n }\n\n script += '<\\/script>';\n\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n } else {\n var scriptEl =\n /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\n scriptEl.defer = goog.Dependency.defer_;\n scriptEl.async = false;\n\n // If CSP nonces are used, propagate them to dynamically created scripts.\n // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\n if (nonce) {\n scriptEl.nonce = nonce;\n }\n\n scriptEl.onload = function() {\n scriptEl.onload = null;\n controller.loaded();\n };\n\n scriptEl.src = goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createScriptURL(this.path) :\n this.path;\n doc.head.appendChild(scriptEl);\n }\n };\n\n\n /**\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides Should be an empty array.\n * TODO(johnplaisted) add support for adding closure namespaces to ES6\n * modules for interop purposes.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor\n * @extends {goog.Dependency}\n */\n goog.Es6ModuleDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.Es6ModuleDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n };\n goog.inherits(goog.Es6ModuleDependency, goog.Dependency);\n\n\n /**\n * @override\n * @param {!goog.LoadController} controller\n */\n goog.Es6ModuleDependency.prototype.load = function(controller) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n if (!goog.inHtmlDocument_()) {\n goog.logToConsole_(\n 'Cannot use default debug loader outside of HTML documents.');\n controller.pause();\n return;\n }\n\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n\n var dep = this;\n\n // TODO(johnplaisted): Does document.writing really speed up anything? Any\n // difference between this and just waiting for interactive mode and then\n // appending?\n function write(src, contents) {\n var nonceAttr = '';\n var nonce = goog.getScriptNonce_();\n if (nonce) {\n nonceAttr = ' nonce=\"' + nonce + '\"';\n }\n\n if (contents) {\n var script = '<script type=\"module\" crossorigin' + nonceAttr + '>' +\n contents + '</' +\n 'script>';\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n } else {\n var script = '<script type=\"module\" crossorigin src=\"' + src + '\"' +\n nonceAttr + '></' +\n 'script>';\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n }\n }\n\n function append(src, contents) {\n var scriptEl =\n /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\n scriptEl.defer = true;\n scriptEl.async = false;\n scriptEl.type = 'module';\n scriptEl.setAttribute('crossorigin', true);\n\n // If CSP nonces are used, propagate them to dynamically created scripts.\n // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\n var nonce = goog.getScriptNonce_();\n if (nonce) {\n scriptEl.nonce = nonce;\n }\n\n if (contents) {\n scriptEl.text = goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createScript(contents) :\n contents;\n } else {\n scriptEl.src = goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createScriptURL(src) :\n src;\n }\n\n doc.head.appendChild(scriptEl);\n }\n\n var create;\n\n if (goog.isDocumentLoading_()) {\n create = write;\n // We can ONLY call document.write if we are guaranteed that any\n // non-module script tags document.written after this are deferred.\n // Small optimization, in theory document.writing is faster.\n goog.Dependency.defer_ = true;\n } else {\n create = append;\n }\n\n // Write 4 separate tags here:\n // 1) Sets the module state at the correct time (just before execution).\n // 2) A src node for this, which just hopefully lets the browser load it a\n // little early (no need to parse #3).\n // 3) Import the module and register it.\n // 4) Clear the module state at the correct time. Guaranteed to run even\n // if there is an error in the module (#3 will not run if there is an\n // error in the module).\n var beforeKey = goog.Dependency.registerCallback_(function() {\n goog.Dependency.unregisterCallback_(beforeKey);\n controller.setModuleState(goog.ModuleType.ES6);\n });\n create(undefined, 'goog.Dependency.callback_(\"' + beforeKey + '\")');\n\n // TODO(johnplaisted): Does this really speed up anything?\n create(this.path, undefined);\n\n var registerKey = goog.Dependency.registerCallback_(function(exports) {\n goog.Dependency.unregisterCallback_(registerKey);\n controller.registerEs6ModuleExports(\n dep.path, exports, goog.moduleLoaderState_.moduleName);\n });\n create(\n undefined,\n 'import * as m from \"' + this.path + '\"; goog.Dependency.callback_(\"' +\n registerKey + '\", m)');\n\n var afterKey = goog.Dependency.registerCallback_(function() {\n goog.Dependency.unregisterCallback_(afterKey);\n controller.clearModuleState();\n controller.loaded();\n });\n create(undefined, 'goog.Dependency.callback_(\"' + afterKey + '\")');\n };\n\n\n /**\n * Superclass of any dependency that needs to be loaded into memory,\n * transformed, and then eval'd (goog.modules and transpiled files).\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor @abstract\n * @extends {goog.Dependency}\n */\n goog.TransformedDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.TransformedDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n /** @private {?string} */\n this.contents_ = null;\n\n /**\n * Whether to lazily make the synchronous XHR (when goog.require'd) or make\n * the synchronous XHR when initially loading. On FireFox 61 there is a bug\n * where an ES6 module cannot make a synchronous XHR (rather, it can, but if\n * it does then no other ES6 modules will load after).\n *\n * tl;dr we lazy load due to bugs on older browsers and eager load due to\n * bugs on newer ones.\n *\n * https://bugzilla.mozilla.org/show_bug.cgi?id=1477090\n *\n * @private @const {boolean}\n */\n this.lazyFetch_ = !goog.inHtmlDocument_() ||\n !('noModule' in goog.global.document.createElement('script'));\n };\n goog.inherits(goog.TransformedDependency, goog.Dependency);\n\n\n /**\n * @override\n * @param {!goog.LoadController} controller\n */\n goog.TransformedDependency.prototype.load = function(controller) {\n var dep = this;\n\n function fetch() {\n dep.contents_ = goog.loadFileSync_(dep.path);\n\n if (dep.contents_) {\n dep.contents_ = dep.transform(dep.contents_);\n if (dep.contents_) {\n dep.contents_ += '\\n//# sourceURL=' + dep.path;\n }\n }\n }\n\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n fetch();\n if (this.contents_ &&\n goog.global.CLOSURE_IMPORT_SCRIPT('', this.contents_)) {\n this.contents_ = null;\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n\n var isEs6 = this.loadFlags['module'] == goog.ModuleType.ES6;\n\n if (!this.lazyFetch_) {\n fetch();\n }\n\n function load() {\n if (dep.lazyFetch_) {\n fetch();\n }\n\n if (!dep.contents_) {\n // loadFileSync_ or transform are responsible. Assume they logged an\n // error.\n return;\n }\n\n if (isEs6) {\n controller.setModuleState(goog.ModuleType.ES6);\n }\n\n var namespace;\n\n try {\n var contents = dep.contents_;\n dep.contents_ = null;\n goog.globalEval(goog.CLOSURE_EVAL_PREFILTER_.createScript(contents));\n if (isEs6) {\n namespace = goog.moduleLoaderState_.moduleName;\n }\n } finally {\n if (isEs6) {\n controller.clearModuleState();\n }\n }\n\n if (isEs6) {\n // Due to circular dependencies this may not be available for require\n // right now.\n goog.global['$jscomp']['require']['ensure'](\n [dep.getPathName()], function() {\n controller.registerEs6ModuleExports(\n dep.path,\n goog.global['$jscomp']['require'](dep.getPathName()),\n namespace);\n });\n }\n\n controller.loaded();\n }\n\n // Do not fetch now; in FireFox 47 the synchronous XHR doesn't block all\n // events. If we fetched now and then document.write'd the contents the\n // document.write would be an eval and would execute too soon! Instead write\n // a script tag to fetch and eval synchronously at the correct time.\n function fetchInOwnScriptThenLoad() {\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n\n var key = goog.Dependency.registerCallback_(function() {\n goog.Dependency.unregisterCallback_(key);\n load();\n });\n\n var nonce = goog.getScriptNonce_();\n var nonceAttr = nonce ? ' nonce=\"' + nonce + '\"' : '';\n var script = '<script' + nonceAttr + '>' +\n goog.protectScriptTag_('goog.Dependency.callback_(\"' + key + '\");') +\n '</' +\n 'script>';\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n }\n\n // If one thing is pending it is this.\n var anythingElsePending = controller.pending().length > 1;\n\n // Additionally if we are meant to defer scripts but the page is still\n // loading (e.g. an ES6 module is loading) then also defer. Or if we are\n // meant to defer and anything else is pending then defer (those may be\n // scripts that did not need transformation and are just script tags with\n // defer set to true, and we need to evaluate after that deferred script).\n var needsAsyncLoading = goog.Dependency.defer_ &&\n (anythingElsePending || goog.isDocumentLoading_());\n\n if (needsAsyncLoading) {\n // Note that we only defer when we have to rather than 100% of the time.\n // Always defering would work, but then in theory the order of\n // goog.require calls would then matter. We want to enforce that most of\n // the time the order of the require calls does not matter.\n controller.defer(function() {\n load();\n });\n return;\n }\n // TODO(johnplaisted): Externs are missing onreadystatechange for\n // HTMLDocument.\n /** @type {?} */\n var doc = goog.global.document;\n\n var isInternetExplorerOrEdge = goog.inHtmlDocument_() &&\n ('ActiveXObject' in goog.global || goog.isEdge_());\n\n // Don't delay in any version of IE or pre-Chromium Edge. There's a bug\n // around this that will cause out of order script execution. This means\n // that on older IE ES6 modules will load too early (while the document is\n // still loading + the dom is not available). The other option is to load\n // too late (when the document is complete and the onload even will never\n // fire). This seems to be the lesser of two evils as scripts already act\n // like the former.\n if (isEs6 && goog.inHtmlDocument_() && goog.isDocumentLoading_() &&\n !isInternetExplorerOrEdge) {\n goog.Dependency.defer_ = true;\n // Transpiled ES6 modules still need to load like regular ES6 modules,\n // aka only after the document is interactive.\n controller.pause();\n var oldCallback = doc.onreadystatechange;\n doc.onreadystatechange = function() {\n if (doc.readyState == 'interactive') {\n doc.onreadystatechange = oldCallback;\n load();\n controller.resume();\n }\n if (typeof oldCallback === 'function') {\n oldCallback.apply(undefined, arguments);\n }\n };\n } else {\n // Always eval on old IE.\n if (!goog.inHtmlDocument_() || !goog.isDocumentLoading_()) {\n load();\n } else {\n fetchInOwnScriptThenLoad();\n }\n }\n };\n\n\n /**\n * @param {string} contents\n * @return {string}\n * @abstract\n */\n goog.TransformedDependency.prototype.transform = function(contents) {};\n\n\n /**\n * An ES6 module dependency that was transpiled to a jscomp module outside\n * of the debug loader, e.g. server side.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor\n * @extends {goog.TransformedDependency}\n */\n goog.PreTranspiledEs6ModuleDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.PreTranspiledEs6ModuleDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n };\n goog.inherits(\n goog.PreTranspiledEs6ModuleDependency, goog.TransformedDependency);\n\n\n /**\n * @override\n * @param {string} contents\n * @return {string}\n */\n goog.PreTranspiledEs6ModuleDependency.prototype.transform = function(\n contents) {\n return contents;\n };\n\n\n /**\n * A goog.module, transpiled or not. Will always perform some minimal\n * transformation even when not transpiled to wrap in a goog.loadModule\n * statement.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor\n * @extends {goog.TransformedDependency}\n */\n goog.GoogModuleDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.GoogModuleDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n };\n goog.inherits(goog.GoogModuleDependency, goog.TransformedDependency);\n\n\n /**\n * @override\n * @param {string} contents\n * @return {string}\n */\n goog.GoogModuleDependency.prototype.transform = function(contents) {\n if (!goog.LOAD_MODULE_USING_EVAL || goog.global.JSON === undefined) {\n return '' +\n 'goog.loadModule(function(exports) {' +\n '\"use strict\";' + contents +\n '\\n' + // terminate any trailing single line comment.\n ';return exports' +\n '});' +\n '\\n//# sourceURL=' + this.path + '\\n';\n } else {\n return '' +\n 'goog.loadModule(' +\n goog.global.JSON.stringify(\n contents + '\\n//# sourceURL=' + this.path + '\\n') +\n ');';\n }\n };\n\n\n /**\n * @param {string} relPath\n * @param {!Array<string>|undefined} provides\n * @param {!Array<string>} requires\n * @param {boolean|!Object<string>=} opt_loadFlags\n * @see goog.addDependency\n */\n goog.DebugLoader_.prototype.addDependency = function(\n relPath, provides, requires, opt_loadFlags) {\n provides = provides || [];\n relPath = relPath.replace(/\\\\/g, '/');\n var path = goog.normalizePath_(goog.basePath + relPath);\n if (!opt_loadFlags || typeof opt_loadFlags === 'boolean') {\n opt_loadFlags = opt_loadFlags ? {'module': goog.ModuleType.GOOG} : {};\n }\n var dep = this.factory_.createDependency(\n path, relPath, provides, requires, opt_loadFlags);\n this.dependencies_[path] = dep;\n for (var i = 0; i < provides.length; i++) {\n this.idToPath_[provides[i]] = path;\n }\n this.idToPath_[relPath] = path;\n };\n\n\n /**\n * Creates goog.Dependency instances for the debug loader to load.\n *\n * Should be overridden to have the debug loader use custom subclasses of\n * goog.Dependency.\n *\n * @struct @constructor\n */\n goog.DependencyFactory = function() {};\n\n\n /**\n * @param {string} path Absolute path of the file.\n * @param {string} relativePath Path relative to closure’s base.js.\n * @param {!Array<string>} provides Array of provided goog.provide/module ids.\n * @param {!Array<string>} requires Array of required goog.provide/module /\n * relative ES6 module paths.\n * @param {!Object<string, string>} loadFlags\n * @return {!goog.Dependency}\n */\n goog.DependencyFactory.prototype.createDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n\n if (loadFlags['module'] == goog.ModuleType.GOOG) {\n return new goog.GoogModuleDependency(\n path, relativePath, provides, requires, loadFlags);\n } else {\n if (loadFlags['module'] == goog.ModuleType.ES6) {\n if (goog.ASSUME_ES_MODULES_TRANSPILED) {\n return new goog.PreTranspiledEs6ModuleDependency(\n path, relativePath, provides, requires, loadFlags);\n } else {\n return new goog.Es6ModuleDependency(\n path, relativePath, provides, requires, loadFlags);\n }\n } else {\n return new goog.Dependency(\n path, relativePath, provides, requires, loadFlags);\n }\n }\n };\n\n\n /** @private @const */\n goog.debugLoader_ = new goog.DebugLoader_();\n\n\n /**\n * Loads the Closure Dependency file.\n *\n * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base\n * loaded, setDependencyFactory called, and then this called. i.e. allows\n * custom loading of the deps file.\n */\n goog.loadClosureDeps = function() {\n goog.debugLoader_.loadClosureDeps();\n };\n\n\n /**\n * Sets the dependency factory, which can be used to create custom\n * goog.Dependency implementations to control how dependencies are loaded.\n *\n * Note: if you wish to call this function and provide your own implemnetation\n * it is a wise idea to set CLOSURE_NO_DEPS to true, otherwise the dependency\n * file and all of its goog.addDependency calls will use the default factory.\n * You can call goog.loadClosureDeps to load the Closure dependency file\n * later, after your factory is injected.\n *\n * @param {!goog.DependencyFactory} factory\n */\n goog.setDependencyFactory = function(factory) {\n goog.debugLoader_.setDependencyFactory(factory);\n };\n\n\n /**\n * Trusted Types policy for the debug loader.\n * @private @const {?TrustedTypePolicy}\n */\n goog.TRUSTED_TYPES_POLICY_ = goog.TRUSTED_TYPES_POLICY_NAME ?\n goog.createTrustedTypesPolicy(goog.TRUSTED_TYPES_POLICY_NAME + '#base') :\n null;\n\n if (!goog.global.CLOSURE_NO_DEPS) {\n goog.debugLoader_.loadClosureDeps();\n }\n\n\n /**\n * Bootstraps the given namespaces and calls the callback once they are\n * available either via goog.require. This is a replacement for using\n * `goog.require` to bootstrap Closure JavaScript. Previously a `goog.require`\n * in an HTML file would guarantee that the require'd namespace was available\n * in the next immediate script tag. With ES6 modules this no longer a\n * guarantee.\n *\n * @param {!Array<string>} namespaces\n * @param {function(): ?} callback Function to call once all the namespaces\n * have loaded. Always called asynchronously.\n */\n goog.bootstrap = function(namespaces, callback) {\n goog.debugLoader_.bootstrap(namespaces, callback);\n };\n}\n\n\nif (!COMPILED) {\n var isChrome87 = false;\n // Cannot run check for Chrome <87 bug in case of strict CSP environments.\n // TODO(user): Remove once Chrome <87 bug is no longer a problem.\n try {\n isChrome87 = eval(goog.global.trustedTypes.emptyScript) !==\n goog.global.trustedTypes.emptyScript;\n } catch (err) {\n }\n\n /**\n * Trusted Types for running dev servers.\n *\n * @private @const\n */\n goog.CLOSURE_EVAL_PREFILTER_ =\n // Detect Chrome <87 bug with TT and eval.\n goog.global.trustedTypes && isChrome87 &&\n goog.createTrustedTypesPolicy('goog#base#devonly#eval') ||\n {createScript: goog.identity_};\n}\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Implements the disposable interface.\n */\n\ngoog.provide('goog.Disposable');\n\ngoog.require('goog.disposable.IDisposable');\ngoog.require('goog.dispose');\n/**\n * TODO(user): Remove this require.\n * @suppress {extraRequire}\n */\ngoog.require('goog.disposeAll');\n\n/**\n * Class that provides the basic implementation for disposable objects. If your\n * class holds references or resources that can't be collected by standard GC,\n * it should extend this class or implement the disposable interface (defined\n * in goog.disposable.IDisposable). See description of\n * goog.disposable.IDisposable for examples of cleanup.\n * @constructor\n * @implements {goog.disposable.IDisposable}\n */\ngoog.Disposable = function() {\n 'use strict';\n /**\n * If monitoring the goog.Disposable instances is enabled, stores the creation\n * stack trace of the Disposable instance.\n * @type {string|undefined}\n */\n this.creationStack;\n\n if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {\n if (goog.Disposable.INCLUDE_STACK_ON_CREATION) {\n this.creationStack = new Error().stack;\n }\n goog.Disposable.instances_[goog.getUid(this)] = this;\n }\n // Support sealing\n this.disposed_ = this.disposed_;\n this.onDisposeCallbacks_ = this.onDisposeCallbacks_;\n};\n\n\n/**\n * @enum {number} Different monitoring modes for Disposable.\n */\ngoog.Disposable.MonitoringMode = {\n /**\n * No monitoring.\n */\n OFF: 0,\n /**\n * Creating and disposing the goog.Disposable instances is monitored. All\n * disposable objects need to call the `goog.Disposable` base\n * constructor. The PERMANENT mode must be switched on before creating any\n * goog.Disposable instances.\n */\n PERMANENT: 1,\n /**\n * INTERACTIVE mode can be switched on and off on the fly without producing\n * errors. It also doesn't warn if the disposable objects don't call the\n * `goog.Disposable` base constructor.\n */\n INTERACTIVE: 2\n};\n\n\n/**\n * @define {number} The monitoring mode of the goog.Disposable\n * instances. Default is OFF. Switching on the monitoring is only\n * recommended for debugging because it has a significant impact on\n * performance and memory usage. If switched off, the monitoring code\n * compiles down to 0 bytes.\n */\ngoog.Disposable.MONITORING_MODE =\n goog.define('goog.Disposable.MONITORING_MODE', 0);\n\n\n/**\n * @define {boolean} Whether to attach creation stack to each created disposable\n * instance; This is only relevant for when MonitoringMode != OFF.\n */\ngoog.Disposable.INCLUDE_STACK_ON_CREATION =\n goog.define('goog.Disposable.INCLUDE_STACK_ON_CREATION', true);\n\n\n/**\n * Maps the unique ID of every undisposed `goog.Disposable` object to\n * the object itself.\n * @type {!Object<number, !goog.Disposable>}\n * @private\n */\ngoog.Disposable.instances_ = {};\n\n\n/**\n * @return {!Array<!goog.Disposable>} All `goog.Disposable` objects that\n * haven't been disposed of.\n */\ngoog.Disposable.getUndisposedObjects = function() {\n 'use strict';\n var ret = [];\n for (var id in goog.Disposable.instances_) {\n if (goog.Disposable.instances_.hasOwnProperty(id)) {\n ret.push(goog.Disposable.instances_[Number(id)]);\n }\n }\n return ret;\n};\n\n\n/**\n * Clears the registry of undisposed objects but doesn't dispose of them.\n */\ngoog.Disposable.clearUndisposedObjects = function() {\n 'use strict';\n goog.Disposable.instances_ = {};\n};\n\n\n/**\n * Whether the object has been disposed of.\n * @type {boolean}\n * @private\n */\ngoog.Disposable.prototype.disposed_ = false;\n\n\n/**\n * Callbacks to invoke when this object is disposed.\n * @type {Array<!Function>}\n * @private\n */\ngoog.Disposable.prototype.onDisposeCallbacks_;\n\n\n/**\n * @return {boolean} Whether the object has been disposed of.\n * @override\n */\ngoog.Disposable.prototype.isDisposed = function() {\n 'use strict';\n return this.disposed_;\n};\n\n\n/**\n * @return {boolean} Whether the object has been disposed of.\n * @deprecated Use {@link #isDisposed} instead.\n */\ngoog.Disposable.prototype.getDisposed = goog.Disposable.prototype.isDisposed;\n\n\n/**\n * Disposes of the object. If the object hasn't already been disposed of, calls\n * {@link #disposeInternal}. Classes that extend `goog.Disposable` should\n * override {@link #disposeInternal} in order to cleanup references, resources\n * and other disposable objects. Reentrant.\n *\n * @return {void} Nothing.\n * @override\n */\ngoog.Disposable.prototype.dispose = function() {\n 'use strict';\n if (!this.disposed_) {\n // Set disposed_ to true first, in case during the chain of disposal this\n // gets disposed recursively.\n this.disposed_ = true;\n this.disposeInternal();\n if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {\n var uid = goog.getUid(this);\n if (goog.Disposable.MONITORING_MODE ==\n goog.Disposable.MonitoringMode.PERMANENT &&\n !goog.Disposable.instances_.hasOwnProperty(uid)) {\n throw new Error(\n this + ' did not call the goog.Disposable base ' +\n 'constructor or was disposed of after a clearUndisposedObjects ' +\n 'call');\n }\n if (goog.Disposable.MONITORING_MODE !=\n goog.Disposable.MonitoringMode.OFF &&\n this.onDisposeCallbacks_ && this.onDisposeCallbacks_.length > 0) {\n throw new Error(\n this + ' did not empty its onDisposeCallbacks queue. This ' +\n 'probably means it overrode dispose() or disposeInternal() ' +\n 'without calling the superclass\\' method.');\n }\n delete goog.Disposable.instances_[uid];\n }\n }\n};\n\n\n/**\n * Associates a disposable object with this object so that they will be disposed\n * together.\n * @param {goog.disposable.IDisposable} disposable that will be disposed when\n * this object is disposed.\n */\ngoog.Disposable.prototype.registerDisposable = function(disposable) {\n 'use strict';\n this.addOnDisposeCallback(goog.partial(goog.dispose, disposable));\n};\n\n\n/**\n * Invokes a callback function when this object is disposed. Callbacks are\n * invoked in the order in which they were added. If a callback is added to\n * an already disposed Disposable, it will be called immediately.\n * @param {function(this:T):?} callback The callback function.\n * @param {T=} opt_scope An optional scope to call the callback in.\n * @template T\n */\ngoog.Disposable.prototype.addOnDisposeCallback = function(callback, opt_scope) {\n 'use strict';\n if (this.disposed_) {\n opt_scope !== undefined ? callback.call(opt_scope) : callback();\n return;\n }\n if (!this.onDisposeCallbacks_) {\n this.onDisposeCallbacks_ = [];\n }\n\n this.onDisposeCallbacks_.push(\n opt_scope !== undefined ? goog.bind(callback, opt_scope) : callback);\n};\n\n\n/**\n * Performs appropriate cleanup. See description of goog.disposable.IDisposable\n * for examples. Classes that extend `goog.Disposable` should override this\n * method. Not reentrant. To avoid calling it twice, it must only be called from\n * the subclass' `disposeInternal` method. Everywhere else the public `dispose`\n * method must be used. For example:\n *\n * <pre>\n * mypackage.MyClass = function() {\n * mypackage.MyClass.base(this, 'constructor');\n * // Constructor logic specific to MyClass.\n * ...\n * };\n * goog.inherits(mypackage.MyClass, goog.Disposable);\n *\n * mypackage.MyClass.prototype.disposeInternal = function() {\n * // Dispose logic specific to MyClass.\n * ...\n * // Call superclass's disposeInternal at the end of the subclass's, like\n * // in C++, to avoid hard-to-catch issues.\n * mypackage.MyClass.base(this, 'disposeInternal');\n * };\n * </pre>\n *\n * @protected\n */\ngoog.Disposable.prototype.disposeInternal = function() {\n 'use strict';\n if (this.onDisposeCallbacks_) {\n while (this.onDisposeCallbacks_.length) {\n this.onDisposeCallbacks_.shift()();\n }\n }\n};\n\n\n/**\n * Returns True if we can verify the object is disposed.\n * Calls `isDisposed` on the argument if it supports it. If obj\n * is not an object with an isDisposed() method, return false.\n * @param {*} obj The object to investigate.\n * @return {boolean} True if we can verify the object is disposed.\n */\ngoog.Disposable.isDisposed = function(obj) {\n 'use strict';\n if (obj && typeof obj.isDisposed == 'function') {\n return obj.isDisposed();\n }\n return false;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for manipulating arrays.\n */\n\n\ngoog.module('goog.array');\ngoog.module.declareLegacyNamespace();\n\nconst asserts = goog.require('goog.asserts');\n\n\n/**\n * @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should\n * rely on Array.prototype functions, if available.\n *\n * The Array.prototype functions can be defined by external libraries like\n * Prototype and setting this flag to false forces closure to use its own\n * goog.array implementation.\n *\n * If your javascript can be loaded by a third party site and you are wary about\n * relying on the prototype functions, specify\n * \"--define goog.NATIVE_ARRAY_PROTOTYPES=false\" to the JSCompiler.\n *\n * Setting goog.TRUSTED_SITE to false will automatically set\n * NATIVE_ARRAY_PROTOTYPES to false.\n */\ngoog.NATIVE_ARRAY_PROTOTYPES =\n goog.define('goog.NATIVE_ARRAY_PROTOTYPES', goog.TRUSTED_SITE);\n\n\n/**\n * @define {boolean} If true, JSCompiler will use the native implementation of\n * array functions where appropriate (e.g., `Array#filter`) and remove the\n * unused pure JS implementation.\n */\nconst ASSUME_NATIVE_FUNCTIONS = goog.define(\n 'goog.array.ASSUME_NATIVE_FUNCTIONS', goog.FEATURESET_YEAR > 2012);\nexports.ASSUME_NATIVE_FUNCTIONS = ASSUME_NATIVE_FUNCTIONS;\n\n\n/**\n * Returns the last element in an array without removing it.\n * Same as {@link goog.array.last}.\n * @param {IArrayLike<T>|string} array The array.\n * @return {T} Last item in array.\n * @template T\n */\nfunction peek(array) {\n return array[array.length - 1];\n}\nexports.peek = peek;\n\n\n/**\n * Returns the last element in an array without removing it.\n * Same as {@link goog.array.peek}.\n * @param {IArrayLike<T>|string} array The array.\n * @return {T} Last item in array.\n * @template T\n */\nexports.last = peek;\n\n// NOTE(arv): Since most of the array functions are generic it allows you to\n// pass an array-like object. Strings have a length and are considered array-\n// like. However, the 'in' operator does not work on strings so we cannot just\n// use the array path even if the browser supports indexing into strings. We\n// therefore end up splitting the string.\n\n\n/**\n * Returns the index of the first element of an array with a specified value, or\n * -1 if the element is not present in the array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-indexof}\n *\n * @param {IArrayLike<T>|string} arr The array to be searched.\n * @param {T} obj The object for which we are searching.\n * @param {number=} opt_fromIndex The index at which to start the search. If\n * omitted the search starts at index 0.\n * @return {number} The index of the first matching array element.\n * @template T\n */\nconst indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.indexOf) ?\n function(arr, obj, opt_fromIndex) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.indexOf.call(arr, obj, opt_fromIndex);\n } :\n function(arr, obj, opt_fromIndex) {\n const fromIndex = opt_fromIndex == null ?\n 0 :\n (opt_fromIndex < 0 ? Math.max(0, arr.length + opt_fromIndex) :\n opt_fromIndex);\n\n if (typeof arr === 'string') {\n // Array.prototype.indexOf uses === so only strings should be found.\n if (typeof obj !== 'string' || obj.length != 1) {\n return -1;\n }\n return arr.indexOf(obj, fromIndex);\n }\n\n for (let i = fromIndex; i < arr.length; i++) {\n if (i in arr && arr[i] === obj) return i;\n }\n return -1;\n };\nexports.indexOf = indexOf;\n\n\n/**\n * Returns the index of the last element of an array with a specified value, or\n * -1 if the element is not present in the array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof}\n *\n * @param {!IArrayLike<T>|string} arr The array to be searched.\n * @param {T} obj The object for which we are searching.\n * @param {?number=} opt_fromIndex The index at which to start the search. If\n * omitted the search starts at the end of the array.\n * @return {number} The index of the last matching array element.\n * @template T\n */\nconst lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.lastIndexOf) ?\n function(arr, obj, opt_fromIndex) {\n asserts.assert(arr.length != null);\n\n // Firefox treats undefined and null as 0 in the fromIndex argument which\n // leads it to always return -1\n const fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;\n return Array.prototype.lastIndexOf.call(arr, obj, fromIndex);\n } :\n function(arr, obj, opt_fromIndex) {\n let fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;\n\n if (fromIndex < 0) {\n fromIndex = Math.max(0, arr.length + fromIndex);\n }\n\n if (typeof arr === 'string') {\n // Array.prototype.lastIndexOf uses === so only strings should be found.\n if (typeof obj !== 'string' || obj.length != 1) {\n return -1;\n }\n return arr.lastIndexOf(obj, fromIndex);\n }\n\n for (let i = fromIndex; i >= 0; i--) {\n if (i in arr && arr[i] === obj) return i;\n }\n return -1;\n };\nexports.lastIndexOf = lastIndexOf;\n\n\n/**\n * Calls a function for each element in an array. Skips holes in the array.\n * See {@link http://tinyurl.com/developer-mozilla-org-array-foreach}\n *\n * @param {IArrayLike<T>|string} arr Array or array like object over\n * which to iterate.\n * @param {?function(this: S, T, number, ?): ?} f The function to call for every\n * element. This function takes 3 arguments (the element, the index and the\n * array). The return value is ignored.\n * @param {S=} opt_obj The object to be used as the value of 'this' within f.\n * @template T,S\n */\nconst forEach = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.forEach) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n Array.prototype.forEach.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2) {\n f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\n }\n }\n };\nexports.forEach = forEach;\n\n\n/**\n * Calls a function for each element in an array, starting from the last\n * element rather than the first.\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this: S, T, number, ?): ?} f The function to call for every\n * element. This function\n * takes 3 arguments (the element, the index and the array). The return\n * value is ignored.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @template T,S\n */\nfunction forEachRight(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = l - 1; i >= 0; --i) {\n if (i in arr2) {\n f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\n }\n }\n}\nexports.forEachRight = forEachRight;\n\n\n/**\n * Calls a function for each element in an array, and if the function returns\n * true adds the element to a new array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-filter}\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?):boolean} f The function to call for\n * every element. This function\n * takes 3 arguments (the element, the index and the array) and must\n * return a Boolean. If the return value is true the element is added to the\n * result array. If it is false the element is not included.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {!Array<T>} a new array in which only elements that passed the test\n * are present.\n * @template T,S\n */\nconst filter = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.filter) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.filter.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const res = [];\n let resLength = 0;\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2) {\n const val = arr2[i]; // in case f mutates arr2\n if (f.call(/** @type {?} */ (opt_obj), val, i, arr)) {\n res[resLength++] = val;\n }\n }\n }\n return res;\n };\nexports.filter = filter;\n\n\n/**\n * Calls a function for each element in an array and inserts the result into a\n * new array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-map}\n *\n * @param {IArrayLike<VALUE>|string} arr Array or array like object\n * over which to iterate.\n * @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call\n * for every element. This function takes 3 arguments (the element,\n * the index and the array) and should return something. The result will be\n * inserted into a new array.\n * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.\n * @return {!Array<RESULT>} a new array with the results from f.\n * @template THIS, VALUE, RESULT\n */\nconst map = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.map) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.map.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const res = new Array(l);\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2) {\n res[i] = f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\n }\n }\n return res;\n };\nexports.map = map;\n\n\n/**\n * Passes every element of an array into a function and accumulates the result.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-reduce}\n * Note that this implementation differs from the native Array.prototype.reduce\n * in that the initial value is assumed to be defined (the MDN docs linked above\n * recommend not omitting this parameter, although it is technically optional).\n *\n * For example:\n * var a = [1, 2, 3, 4];\n * reduce(a, function(r, v, i, arr) {return r + v;}, 0);\n * returns 10\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {function(this:S, R, T, number, ?) : R} f The function to call for\n * every element. This function\n * takes 4 arguments (the function's previous result or the initial value,\n * the value of the current array element, the current array index, and the\n * array itself)\n * function(previousValue, currentValue, index, array).\n * @param {?} val The initial value to pass into the function on the first call.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {R} Result of evaluating f repeatedly across the values of the array.\n * @template T,S,R\n */\nconst reduce = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduce) ?\n function(arr, f, val, opt_obj) {\n asserts.assert(arr.length != null);\n if (opt_obj) {\n f = goog.bind(f, opt_obj);\n }\n return Array.prototype.reduce.call(arr, f, val);\n } :\n function(arr, f, val, opt_obj) {\n let rval = val;\n forEach(arr, function(val, index) {\n rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);\n });\n return rval;\n };\nexports.reduce = reduce;\n\n\n/**\n * Passes every element of an array into a function and accumulates the result,\n * starting from the last element and working towards the first.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright}\n *\n * For example:\n * var a = ['a', 'b', 'c'];\n * reduceRight(a, function(r, v, i, arr) {return r + v;}, '');\n * returns 'cba'\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, R, T, number, ?) : R} f The function to call for\n * every element. This function\n * takes 4 arguments (the function's previous result or the initial value,\n * the value of the current array element, the current array index, and the\n * array itself)\n * function(previousValue, currentValue, index, array).\n * @param {?} val The initial value to pass into the function on the first call.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {R} Object returned as a result of evaluating f repeatedly across the\n * values of the array.\n * @template T,S,R\n */\nconst reduceRight = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduceRight) ?\n function(arr, f, val, opt_obj) {\n asserts.assert(arr.length != null);\n asserts.assert(f != null);\n if (opt_obj) {\n f = goog.bind(f, opt_obj);\n }\n return Array.prototype.reduceRight.call(arr, f, val);\n } :\n function(arr, f, val, opt_obj) {\n let rval = val;\n forEachRight(arr, function(val, index) {\n rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);\n });\n return rval;\n };\nexports.reduceRight = reduceRight;\n\n\n/**\n * Calls f for each element of an array. If any call returns true, some()\n * returns true (without checking the remaining elements). If all calls\n * return false, some() returns false.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-some}\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\n * for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a boolean.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {boolean} true if any element passes the test.\n * @template T,S\n */\nconst some = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.some) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.some.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return true;\n }\n }\n return false;\n };\nexports.some = some;\n\n\n/**\n * Call f for each element of an array. If all calls return true, every()\n * returns true. If any call returns false, every() returns false and\n * does not continue to check the remaining elements.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-every}\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\n * for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a boolean.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {boolean} false if any element fails the test.\n * @template T,S\n */\nconst every = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.every) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.every.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2 && !f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return false;\n }\n }\n return true;\n };\nexports.every = every;\n\n\n/**\n * Counts the array elements that fulfill the predicate, i.e. for which the\n * callback function returns true. Skips holes in the array.\n *\n * @param {!IArrayLike<T>|string} arr Array or array like object\n * over which to iterate.\n * @param {function(this: S, T, number, ?): boolean} f The function to call for\n * every element. Takes 3 arguments (the element, the index and the array).\n * @param {S=} opt_obj The object to be used as the value of 'this' within f.\n * @return {number} The number of the matching elements.\n * @template T,S\n */\nfunction count(arr, f, opt_obj) {\n let count = 0;\n forEach(arr, function(element, index, arr) {\n if (f.call(/** @type {?} */ (opt_obj), element, index, arr)) {\n ++count;\n }\n }, opt_obj);\n return count;\n}\nexports.count = count;\n\n\n/**\n * Search an array for the first element that satisfies a given condition and\n * return that element.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {T|null} The first array element that passes the test, or null if no\n * element is found.\n * @template T,S\n */\nfunction find(arr, f, opt_obj) {\n const i = findIndex(arr, f, opt_obj);\n return i < 0 ? null : typeof arr === 'string' ? arr.charAt(i) : arr[i];\n}\nexports.find = find;\n\n\n/**\n * Search an array for the first element that satisfies a given condition and\n * return its index.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\n * every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {number} The index of the first array element that passes the test,\n * or -1 if no element is found.\n * @template T,S\n */\nfunction findIndex(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return i;\n }\n }\n return -1;\n}\nexports.findIndex = findIndex;\n\n\n/**\n * Search an array (in reverse order) for the last element that satisfies a\n * given condition and return that element.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {T|null} The last array element that passes the test, or null if no\n * element is found.\n * @template T,S\n */\nfunction findRight(arr, f, opt_obj) {\n const i = findIndexRight(arr, f, opt_obj);\n return i < 0 ? null : typeof arr === 'string' ? arr.charAt(i) : arr[i];\n}\nexports.findRight = findRight;\n\n\n/**\n * Search an array (in reverse order) for the last element that satisfies a\n * given condition and return its index.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {number} The index of the last array element that passes the test,\n * or -1 if no element is found.\n * @template T,S\n */\nfunction findIndexRight(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = l - 1; i >= 0; i--) {\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return i;\n }\n }\n return -1;\n}\nexports.findIndexRight = findIndexRight;\n\n\n/**\n * Whether the array contains the given object.\n * @param {IArrayLike<?>|string} arr The array to test for the presence of the\n * element.\n * @param {*} obj The object for which to test.\n * @return {boolean} true if obj is present.\n */\nfunction contains(arr, obj) {\n return indexOf(arr, obj) >= 0;\n}\nexports.contains = contains;\n\n\n/**\n * Whether the array is empty.\n * @param {IArrayLike<?>|string} arr The array to test.\n * @return {boolean} true if empty.\n */\nfunction isEmpty(arr) {\n return arr.length == 0;\n}\nexports.isEmpty = isEmpty;\n\n\n/**\n * Clears the array.\n * @param {IArrayLike<?>} arr Array or array like object to clear.\n */\nfunction clear(arr) {\n // For non real arrays we don't have the magic length so we delete the\n // indices.\n if (!Array.isArray(arr)) {\n for (let i = arr.length - 1; i >= 0; i--) {\n delete arr[i];\n }\n }\n arr.length = 0;\n}\nexports.clear = clear;\n\n\n/**\n * Pushes an item into an array, if it's not already in the array.\n * @param {Array<T>} arr Array into which to insert the item.\n * @param {T} obj Value to add.\n * @template T\n */\nfunction insert(arr, obj) {\n if (!contains(arr, obj)) {\n arr.push(obj);\n }\n}\nexports.insert = insert;\n\n\n/**\n * Inserts an object at the given index of the array.\n * @param {IArrayLike<?>} arr The array to modify.\n * @param {*} obj The object to insert.\n * @param {number=} opt_i The index at which to insert the object. If omitted,\n * treated as 0. A negative index is counted from the end of the array.\n */\nfunction insertAt(arr, obj, opt_i) {\n splice(arr, opt_i, 0, obj);\n}\nexports.insertAt = insertAt;\n\n\n/**\n * Inserts at the given index of the array, all elements of another array.\n * @param {IArrayLike<?>} arr The array to modify.\n * @param {IArrayLike<?>} elementsToAdd The array of elements to add.\n * @param {number=} opt_i The index at which to insert the object. If omitted,\n * treated as 0. A negative index is counted from the end of the array.\n */\nfunction insertArrayAt(arr, elementsToAdd, opt_i) {\n goog.partial(splice, arr, opt_i, 0).apply(null, elementsToAdd);\n}\nexports.insertArrayAt = insertArrayAt;\n\n\n/**\n * Inserts an object into an array before a specified object.\n * @param {Array<T>} arr The array to modify.\n * @param {T} obj The object to insert.\n * @param {T=} opt_obj2 The object before which obj should be inserted. If obj2\n * is omitted or not found, obj is inserted at the end of the array.\n * @template T\n */\nfunction insertBefore(arr, obj, opt_obj2) {\n let i;\n if (arguments.length == 2 || (i = indexOf(arr, opt_obj2)) < 0) {\n arr.push(obj);\n } else {\n insertAt(arr, obj, i);\n }\n}\nexports.insertBefore = insertBefore;\n\n\n/**\n * Removes the first occurrence of a particular value from an array.\n * @param {IArrayLike<T>} arr Array from which to remove\n * value.\n * @param {T} obj Object to remove.\n * @return {boolean} True if an element was removed.\n * @template T\n */\nfunction remove(arr, obj) {\n const i = indexOf(arr, obj);\n let rv;\n if ((rv = i >= 0)) {\n removeAt(arr, i);\n }\n return rv;\n}\nexports.remove = remove;\n\n\n/**\n * Removes the last occurrence of a particular value from an array.\n * @param {!IArrayLike<T>} arr Array from which to remove value.\n * @param {T} obj Object to remove.\n * @return {boolean} True if an element was removed.\n * @template T\n */\nfunction removeLast(arr, obj) {\n const i = lastIndexOf(arr, obj);\n if (i >= 0) {\n removeAt(arr, i);\n return true;\n }\n return false;\n}\nexports.removeLast = removeLast;\n\n\n/**\n * Removes from an array the element at index i\n * @param {IArrayLike<?>} arr Array or array like object from which to\n * remove value.\n * @param {number} i The index to remove.\n * @return {boolean} True if an element was removed.\n */\nfunction removeAt(arr, i) {\n asserts.assert(arr.length != null);\n\n // use generic form of splice\n // splice returns the removed items and if successful the length of that\n // will be 1\n return Array.prototype.splice.call(arr, i, 1).length == 1;\n}\nexports.removeAt = removeAt;\n\n\n/**\n * Removes the first value that satisfies the given condition.\n * @param {IArrayLike<T>} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {boolean} True if an element was removed.\n * @template T,S\n */\nfunction removeIf(arr, f, opt_obj) {\n const i = findIndex(arr, f, opt_obj);\n if (i >= 0) {\n removeAt(arr, i);\n return true;\n }\n return false;\n}\nexports.removeIf = removeIf;\n\n\n/**\n * Removes all values that satisfy the given condition.\n * @param {IArrayLike<T>} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {number} The number of items removed\n * @template T,S\n */\nfunction removeAllIf(arr, f, opt_obj) {\n let removedCount = 0;\n forEachRight(arr, function(val, index) {\n if (f.call(/** @type {?} */ (opt_obj), val, index, arr)) {\n if (removeAt(arr, index)) {\n removedCount++;\n }\n }\n });\n return removedCount;\n}\nexports.removeAllIf = removeAllIf;\n\n\n/**\n * Returns a new array that is the result of joining the arguments. If arrays\n * are passed then their items are added, however, if non-arrays are passed they\n * will be added to the return array as is.\n *\n * Note that ArrayLike objects will be added as is, rather than having their\n * items added.\n *\n * concat([1, 2], [3, 4]) -> [1, 2, 3, 4]\n * concat(0, [1, 2]) -> [0, 1, 2]\n * concat([1, 2], null) -> [1, 2, null]\n *\n * @param {...*} var_args Items to concatenate. Arrays will have each item\n * added, while primitives and objects will be added as is.\n * @return {!Array<?>} The new resultant array.\n */\nfunction concat(var_args) {\n return Array.prototype.concat.apply([], arguments);\n}\nexports.concat = concat;\n\n\n/**\n * Returns a new array that contains the contents of all the arrays passed.\n * @param {...!Array<T>} var_args\n * @return {!Array<T>}\n * @template T\n */\nfunction join(var_args) {\n return Array.prototype.concat.apply([], arguments);\n}\nexports.join = join;\n\n\n/**\n * Converts an object to an array.\n * @param {IArrayLike<T>|string} object The object to convert to an\n * array.\n * @return {!Array<T>} The object converted into an array. If object has a\n * length property, every property indexed with a non-negative number\n * less than length will be included in the result. If object does not\n * have a length property, an empty array will be returned.\n * @template T\n */\nfunction toArray(object) {\n const length = object.length;\n\n // If length is not a number the following is false. This case is kept for\n // backwards compatibility since there are callers that pass objects that are\n // not array like.\n if (length > 0) {\n const rv = new Array(length);\n for (let i = 0; i < length; i++) {\n rv[i] = object[i];\n }\n return rv;\n }\n return [];\n}\nexports.toArray = toArray;\n\n\n/**\n * Does a shallow copy of an array.\n * @param {IArrayLike<T>|string} arr Array or array-like object to\n * clone.\n * @return {!Array<T>} Clone of the input array.\n * @template T\n */\nconst clone = toArray;\nexports.clone = clone;\n\n\n/**\n * Extends an array with another array, element, or \"array like\" object.\n * This function operates 'in-place', it does not create a new Array.\n *\n * Example:\n * var a = [];\n * extend(a, [0, 1]);\n * a; // [0, 1]\n * extend(a, 2);\n * a; // [0, 1, 2]\n *\n * @param {Array<VALUE>} arr1 The array to modify.\n * @param {...(IArrayLike<VALUE>|VALUE)} var_args The elements or arrays of\n * elements to add to arr1.\n * @template VALUE\n */\nfunction extend(arr1, var_args) {\n for (let i = 1; i < arguments.length; i++) {\n const arr2 = arguments[i];\n if (goog.isArrayLike(arr2)) {\n const len1 = arr1.length || 0;\n const len2 = arr2.length || 0;\n arr1.length = len1 + len2;\n for (let j = 0; j < len2; j++) {\n arr1[len1 + j] = arr2[j];\n }\n } else {\n arr1.push(arr2);\n }\n }\n}\nexports.extend = extend;\n\n\n/**\n * Adds or removes elements from an array. This is a generic version of Array\n * splice. This means that it might work on other objects similar to arrays,\n * such as the arguments object.\n *\n * @param {IArrayLike<T>} arr The array to modify.\n * @param {number|undefined} index The index at which to start changing the\n * array. If not defined, treated as 0.\n * @param {number} howMany How many elements to remove (0 means no removal. A\n * value below 0 is treated as zero and so is any other non number. Numbers\n * are floored).\n * @param {...T} var_args Optional, additional elements to insert into the\n * array.\n * @return {!Array<T>} the removed elements.\n * @template T\n */\nfunction splice(arr, index, howMany, var_args) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.splice.apply(arr, slice(arguments, 1));\n}\nexports.splice = splice;\n\n\n/**\n * Returns a new array from a segment of an array. This is a generic version of\n * Array slice. This means that it might work on other objects similar to\n * arrays, such as the arguments object.\n *\n * @param {IArrayLike<T>|string} arr The array from\n * which to copy a segment.\n * @param {number} start The index of the first element to copy.\n * @param {number=} opt_end The index after the last element to copy.\n * @return {!Array<T>} A new array containing the specified segment of the\n * original array.\n * @template T\n */\nfunction slice(arr, start, opt_end) {\n asserts.assert(arr.length != null);\n\n // passing 1 arg to slice is not the same as passing 2 where the second is\n // null or undefined (in that case the second argument is treated as 0).\n // we could use slice on the arguments object and then use apply instead of\n // testing the length\n if (arguments.length <= 2) {\n return Array.prototype.slice.call(arr, start);\n } else {\n return Array.prototype.slice.call(arr, start, opt_end);\n }\n}\nexports.slice = slice;\n\n\n/**\n * Removes all duplicates from an array (retaining only the first\n * occurrence of each array element). This function modifies the\n * array in place and doesn't change the order of the non-duplicate items.\n *\n * For objects, duplicates are identified as having the same unique ID as\n * defined by {@link goog.getUid}.\n *\n * Alternatively you can specify a custom hash function that returns a unique\n * value for each item in the array it should consider unique.\n *\n * Runtime: N,\n * Worstcase space: 2N (no dupes)\n *\n * @param {IArrayLike<T>} arr The array from which to remove\n * duplicates.\n * @param {Array=} opt_rv An optional array in which to return the results,\n * instead of performing the removal inplace. If specified, the original\n * array will remain unchanged.\n * @param {function(T):string=} opt_hashFn An optional function to use to\n * apply to every item in the array. This function should return a unique\n * value for each item in the array it should consider unique.\n * @template T\n */\nfunction removeDuplicates(arr, opt_rv, opt_hashFn) {\n const returnArray = opt_rv || arr;\n const defaultHashFn = function(item) {\n // Prefix each type with a single character representing the type to\n // prevent conflicting keys (e.g. true and 'true').\n return goog.isObject(item) ? 'o' + goog.getUid(item) :\n (typeof item).charAt(0) + item;\n };\n const hashFn = opt_hashFn || defaultHashFn;\n\n let cursorInsert = 0;\n let cursorRead = 0;\n const seen = {};\n\n while (cursorRead < arr.length) {\n const current = arr[cursorRead++];\n const key = hashFn(current);\n if (!Object.prototype.hasOwnProperty.call(seen, key)) {\n seen[key] = true;\n returnArray[cursorInsert++] = current;\n }\n }\n returnArray.length = cursorInsert;\n}\nexports.removeDuplicates = removeDuplicates;\n\n\n/**\n * Searches the specified array for the specified target using the binary\n * search algorithm. If no opt_compareFn is specified, elements are compared\n * using <code>defaultCompare</code>, which compares the elements\n * using the built in < and > operators. This will produce the expected\n * behavior for homogeneous arrays of String(s) and Number(s). The array\n * specified <b>must</b> be sorted in ascending order (as defined by the\n * comparison function). If the array is not sorted, results are undefined.\n * If the array contains multiple instances of the specified target value, the\n * left-most instance will be found.\n *\n * Runtime: O(log n)\n *\n * @param {IArrayLike<VALUE>} arr The array to be searched.\n * @param {TARGET} target The sought value.\n * @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is ordered. Should take 2 arguments to\n * compare, the target value and an element from your array, and return a\n * negative number, zero, or a positive number depending on whether the\n * first argument is less than, equal to, or greater than the second.\n * @return {number} Lowest index of the target value if found, otherwise\n * (-(insertion point) - 1). The insertion point is where the value should\n * be inserted into arr to preserve the sorted property. Return value >= 0\n * iff target is found.\n * @template TARGET, VALUE\n */\nfunction binarySearch(arr, target, opt_compareFn) {\n return binarySearch_(\n arr, opt_compareFn || defaultCompare, false /* isEvaluator */, target);\n}\nexports.binarySearch = binarySearch;\n\n\n/**\n * Selects an index in the specified array using the binary search algorithm.\n * The evaluator receives an element and determines whether the desired index\n * is before, at, or after it. The evaluator must be consistent (formally,\n * map(map(arr, evaluator, opt_obj), goog.math.sign)\n * must be monotonically non-increasing).\n *\n * Runtime: O(log n)\n *\n * @param {IArrayLike<VALUE>} arr The array to be searched.\n * @param {function(this:THIS, VALUE, number, ?): number} evaluator\n * Evaluator function that receives 3 arguments (the element, the index and\n * the array). Should return a negative number, zero, or a positive number\n * depending on whether the desired index is before, at, or after the\n * element passed to it.\n * @param {THIS=} opt_obj The object to be used as the value of 'this'\n * within evaluator.\n * @return {number} Index of the leftmost element matched by the evaluator, if\n * such exists; otherwise (-(insertion point) - 1). The insertion point is\n * the index of the first element for which the evaluator returns negative,\n * or arr.length if no such element exists. The return value is non-negative\n * iff a match is found.\n * @template THIS, VALUE\n */\nfunction binarySelect(arr, evaluator, opt_obj) {\n return binarySearch_(\n arr, evaluator, true /* isEvaluator */, undefined /* opt_target */,\n opt_obj);\n}\nexports.binarySelect = binarySelect;\n\n\n/**\n * Implementation of a binary search algorithm which knows how to use both\n * comparison functions and evaluators. If an evaluator is provided, will call\n * the evaluator with the given optional data object, conforming to the\n * interface defined in binarySelect. Otherwise, if a comparison function is\n * provided, will call the comparison function against the given data object.\n *\n * This implementation purposefully does not use goog.bind or goog.partial for\n * performance reasons.\n *\n * Runtime: O(log n)\n *\n * @param {IArrayLike<?>} arr The array to be searched.\n * @param {function(?, ?, ?): number | function(?, ?): number} compareFn\n * Either an evaluator or a comparison function, as defined by binarySearch\n * and binarySelect above.\n * @param {boolean} isEvaluator Whether the function is an evaluator or a\n * comparison function.\n * @param {?=} opt_target If the function is a comparison function, then\n * this is the target to binary search for.\n * @param {Object=} opt_selfObj If the function is an evaluator, this is an\n * optional this object for the evaluator.\n * @return {number} Lowest index of the target value if found, otherwise\n * (-(insertion point) - 1). The insertion point is where the value should\n * be inserted into arr to preserve the sorted property. Return value >= 0\n * iff target is found.\n * @private\n */\nfunction binarySearch_(arr, compareFn, isEvaluator, opt_target, opt_selfObj) {\n let left = 0; // inclusive\n let right = arr.length; // exclusive\n let found;\n while (left < right) {\n const middle = left + ((right - left) >>> 1);\n let compareResult;\n if (isEvaluator) {\n compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);\n } else {\n // NOTE(dimvar): To avoid this cast, we'd have to use function overloading\n // for the type of binarySearch_, which the type system can't express yet.\n compareResult = /** @type {function(?, ?): number} */ (compareFn)(\n opt_target, arr[middle]);\n }\n if (compareResult > 0) {\n left = middle + 1;\n } else {\n right = middle;\n // We are looking for the lowest index so we can't return immediately.\n found = !compareResult;\n }\n }\n // left is the index if found, or the insertion point otherwise.\n // Avoiding bitwise not operator, as that causes a loss in precision for array\n // indexes outside the bounds of a 32-bit signed integer. Array indexes have\n // a maximum value of 2^32-2 https://tc39.es/ecma262/#array-index\n return found ? left : -left - 1;\n}\n\n\n/**\n * Sorts the specified array into ascending order. If no opt_compareFn is\n * specified, elements are compared using\n * <code>defaultCompare</code>, which compares the elements using\n * the built in < and > operators. This will produce the expected behavior\n * for homogeneous arrays of String(s) and Number(s), unlike the native sort,\n * but will give unpredictable results for heterogeneous lists of strings and\n * numbers with different numbers of digits.\n *\n * This sort is not guaranteed to be stable.\n *\n * Runtime: Same as `Array.prototype.sort`\n *\n * @param {Array<T>} arr The array to be sorted.\n * @param {?function(T,T):number=} opt_compareFn Optional comparison\n * function by which the\n * array is to be ordered. Should take 2 arguments to compare, and return a\n * negative number, zero, or a positive number depending on whether the\n * first argument is less than, equal to, or greater than the second.\n * @template T\n */\nfunction sort(arr, opt_compareFn) {\n // TODO(arv): Update type annotation since null is not accepted.\n arr.sort(opt_compareFn || defaultCompare);\n}\nexports.sort = sort;\n\n\n/**\n * Sorts the specified array into ascending order in a stable way. If no\n * opt_compareFn is specified, elements are compared using\n * <code>defaultCompare</code>, which compares the elements using\n * the built in < and > operators. This will produce the expected behavior\n * for homogeneous arrays of String(s) and Number(s).\n *\n * Runtime: Same as `Array.prototype.sort`, plus an additional\n * O(n) overhead of copying the array twice.\n *\n * @param {Array<T>} arr The array to be sorted.\n * @param {?function(T, T): number=} opt_compareFn Optional comparison function\n * by which the array is to be ordered. Should take 2 arguments to compare,\n * and return a negative number, zero, or a positive number depending on\n * whether the first argument is less than, equal to, or greater than the\n * second.\n * @template T\n */\nfunction stableSort(arr, opt_compareFn) {\n const compArr = new Array(arr.length);\n for (let i = 0; i < arr.length; i++) {\n compArr[i] = {index: i, value: arr[i]};\n }\n const valueCompareFn = opt_compareFn || defaultCompare;\n function stableCompareFn(obj1, obj2) {\n return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;\n }\n sort(compArr, stableCompareFn);\n for (let i = 0; i < arr.length; i++) {\n arr[i] = compArr[i].value;\n }\n}\nexports.stableSort = stableSort;\n\n\n/**\n * Sort the specified array into ascending order based on item keys\n * returned by the specified key function.\n * If no opt_compareFn is specified, the keys are compared in ascending order\n * using <code>defaultCompare</code>.\n *\n * Runtime: O(S(f(n)), where S is runtime of <code>sort</code>\n * and f(n) is runtime of the key function.\n *\n * @param {Array<T>} arr The array to be sorted.\n * @param {function(T): K} keyFn Function taking array element and returning\n * a key used for sorting this element.\n * @param {?function(K, K): number=} opt_compareFn Optional comparison function\n * by which the keys are to be ordered. Should take 2 arguments to compare,\n * and return a negative number, zero, or a positive number depending on\n * whether the first argument is less than, equal to, or greater than the\n * second.\n * @template T,K\n */\nfunction sortByKey(arr, keyFn, opt_compareFn) {\n const keyCompareFn = opt_compareFn || defaultCompare;\n sort(arr, function(a, b) {\n return keyCompareFn(keyFn(a), keyFn(b));\n });\n}\nexports.sortByKey = sortByKey;\n\n\n/**\n * Sorts an array of objects by the specified object key and compare\n * function. If no compare function is provided, the key values are\n * compared in ascending order using <code>defaultCompare</code>.\n * This won't work for keys that get renamed by the compiler. So use\n * {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}.\n * @param {Array<Object>} arr An array of objects to sort.\n * @param {string} key The object key to sort by.\n * @param {Function=} opt_compareFn The function to use to compare key\n * values.\n */\nfunction sortObjectsByKey(arr, key, opt_compareFn) {\n sortByKey(arr, function(obj) {\n return obj[key];\n }, opt_compareFn);\n}\nexports.sortObjectsByKey = sortObjectsByKey;\n\n\n/**\n * Tells if the array is sorted.\n * @param {!IArrayLike<T>} arr The array.\n * @param {?function(T,T):number=} opt_compareFn Function to compare the\n * array elements.\n * Should take 2 arguments to compare, and return a negative number, zero,\n * or a positive number depending on whether the first argument is less\n * than, equal to, or greater than the second.\n * @param {boolean=} opt_strict If true no equal elements are allowed.\n * @return {boolean} Whether the array is sorted.\n * @template T\n */\nfunction isSorted(arr, opt_compareFn, opt_strict) {\n const compare = opt_compareFn || defaultCompare;\n for (let i = 1; i < arr.length; i++) {\n const compareResult = compare(arr[i - 1], arr[i]);\n if (compareResult > 0 || compareResult == 0 && opt_strict) {\n return false;\n }\n }\n return true;\n}\nexports.isSorted = isSorted;\n\n\n/**\n * Compares two arrays for equality. Two arrays are considered equal if they\n * have the same length and their corresponding elements are equal according to\n * the comparison function.\n *\n * @param {IArrayLike<A>} arr1 The first array to compare.\n * @param {IArrayLike<B>} arr2 The second array to compare.\n * @param {?function(A,B):boolean=} opt_equalsFn Optional comparison function.\n * Should take 2 arguments to compare, and return true if the arguments\n * are equal. Defaults to {@link goog.array.defaultCompareEquality} which\n * compares the elements using the built-in '===' operator.\n * @return {boolean} Whether the two arrays are equal.\n * @template A\n * @template B\n */\nfunction equals(arr1, arr2, opt_equalsFn) {\n if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||\n arr1.length != arr2.length) {\n return false;\n }\n const l = arr1.length;\n const equalsFn = opt_equalsFn || defaultCompareEquality;\n for (let i = 0; i < l; i++) {\n if (!equalsFn(arr1[i], arr2[i])) {\n return false;\n }\n }\n return true;\n}\nexports.equals = equals;\n\n\n/**\n * 3-way array compare function.\n * @param {!IArrayLike<VALUE>} arr1 The first array to\n * compare.\n * @param {!IArrayLike<VALUE>} arr2 The second array to\n * compare.\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is to be ordered. Should take 2 arguments to\n * compare, and return a negative number, zero, or a positive number\n * depending on whether the first argument is less than, equal to, or\n * greater than the second.\n * @return {number} Negative number, zero, or a positive number depending on\n * whether the first argument is less than, equal to, or greater than the\n * second.\n * @template VALUE\n */\nfunction compare3(arr1, arr2, opt_compareFn) {\n const compare = opt_compareFn || defaultCompare;\n const l = Math.min(arr1.length, arr2.length);\n for (let i = 0; i < l; i++) {\n const result = compare(arr1[i], arr2[i]);\n if (result != 0) {\n return result;\n }\n }\n return defaultCompare(arr1.length, arr2.length);\n}\nexports.compare3 = compare3;\n\n\n/**\n * Compares its two arguments for order, using the built in < and >\n * operators.\n * @param {VALUE} a The first object to be compared.\n * @param {VALUE} b The second object to be compared.\n * @return {number} A negative number, zero, or a positive number as the first\n * argument is less than, equal to, or greater than the second,\n * respectively.\n * @template VALUE\n */\nfunction defaultCompare(a, b) {\n return a > b ? 1 : a < b ? -1 : 0;\n}\nexports.defaultCompare = defaultCompare;\n\n\n/**\n * Compares its two arguments for inverse order, using the built in < and >\n * operators.\n * @param {VALUE} a The first object to be compared.\n * @param {VALUE} b The second object to be compared.\n * @return {number} A negative number, zero, or a positive number as the first\n * argument is greater than, equal to, or less than the second,\n * respectively.\n * @template VALUE\n */\nfunction inverseDefaultCompare(a, b) {\n return -defaultCompare(a, b);\n}\nexports.inverseDefaultCompare = inverseDefaultCompare;\n\n\n/**\n * Compares its two arguments for equality, using the built in === operator.\n * @param {*} a The first object to compare.\n * @param {*} b The second object to compare.\n * @return {boolean} True if the two arguments are equal, false otherwise.\n */\nfunction defaultCompareEquality(a, b) {\n return a === b;\n}\nexports.defaultCompareEquality = defaultCompareEquality;\n\n\n/**\n * Inserts a value into a sorted array. The array is not modified if the\n * value is already present.\n * @param {IArrayLike<VALUE>} array The array to modify.\n * @param {VALUE} value The object to insert.\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is ordered. Should take 2 arguments to\n * compare, and return a negative number, zero, or a positive number\n * depending on whether the first argument is less than, equal to, or\n * greater than the second.\n * @return {boolean} True if an element was inserted.\n * @template VALUE\n */\nfunction binaryInsert(array, value, opt_compareFn) {\n const index = binarySearch(array, value, opt_compareFn);\n if (index < 0) {\n insertAt(array, value, -(index + 1));\n return true;\n }\n return false;\n}\nexports.binaryInsert = binaryInsert;\n\n\n/**\n * Removes a value from a sorted array.\n * @param {!IArrayLike<VALUE>} array The array to modify.\n * @param {VALUE} value The object to remove.\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is ordered. Should take 2 arguments to\n * compare, and return a negative number, zero, or a positive number\n * depending on whether the first argument is less than, equal to, or\n * greater than the second.\n * @return {boolean} True if an element was removed.\n * @template VALUE\n */\nfunction binaryRemove(array, value, opt_compareFn) {\n const index = binarySearch(array, value, opt_compareFn);\n return (index >= 0) ? removeAt(array, index) : false;\n}\nexports.binaryRemove = binaryRemove;\n\n\n/**\n * Splits an array into disjoint buckets according to a splitting function.\n * @param {IArrayLike<T>} array The array.\n * @param {function(this:S, T, number, !IArrayLike<T>):?} sorter Function to\n * call for every element. This takes 3 arguments (the element, the index\n * and the array) and must return a valid object key (a string, number,\n * etc), or undefined, if that object should not be placed in a bucket.\n * @param {S=} opt_obj The object to be used as the value of 'this' within\n * sorter.\n * @return {!Object<!Array<T>>} An object, with keys being all of the unique\n * return values of sorter, and values being arrays containing the items for\n * which the splitter returned that key.\n * @template T,S\n */\nfunction bucket(array, sorter, opt_obj) {\n const buckets = {};\n\n for (let i = 0; i < array.length; i++) {\n const value = array[i];\n const key = sorter.call(/** @type {?} */ (opt_obj), value, i, array);\n if (key !== undefined) {\n // Push the value to the right bucket, creating it if necessary.\n const bucket = buckets[key] || (buckets[key] = []);\n bucket.push(value);\n }\n }\n\n return buckets;\n}\nexports.bucket = bucket;\n\n\n/**\n * Splits an array into disjoint buckets according to a splitting function.\n * @param {!IArrayLike<V>} array The array.\n * @param {function(V, number, !IArrayLike<V>):(K|undefined)} sorter Function to\n * call for every element. This takes 3 arguments (the element, the index,\n * and the array) and must return a value to use as a key, or undefined, if\n * that object should not be placed in a bucket.\n * @return {!Map<K, !Array<V>>} A map, with keys being all of the unique\n * return values of sorter, and values being arrays containing the items for\n * which the splitter returned that key.\n * @template K,V\n */\nfunction bucketToMap(array, sorter) {\n const /** !Map<K, !Array<V>> */ buckets = new Map();\n\n for (let i = 0; i < array.length; i++) {\n const value = array[i];\n const key = sorter(value, i, array);\n if (key !== undefined) {\n // Push the value to the right bucket, creating it if necessary.\n let bucket = buckets.get(key);\n if (!bucket) {\n bucket = [];\n buckets.set(key, bucket);\n }\n bucket.push(value);\n }\n }\n\n return buckets;\n}\nexports.bucketToMap = bucketToMap;\n\n\n/**\n * Creates a new object built from the provided array and the key-generation\n * function.\n * @param {IArrayLike<T>} arr Array or array like object over\n * which to iterate whose elements will be the values in the new object.\n * @param {?function(this:S, T, number, ?) : string} keyFunc The function to\n * call for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a string that will be used as the\n * key for the element in the new object. If the function returns the same\n * key for more than one element, the value for that key is\n * implementation-defined.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within keyFunc.\n * @return {!Object<T>} The new object.\n * @template T,S\n */\nfunction toObject(arr, keyFunc, opt_obj) {\n const ret = {};\n forEach(arr, function(element, index) {\n ret[keyFunc.call(/** @type {?} */ (opt_obj), element, index, arr)] =\n element;\n });\n return ret;\n}\nexports.toObject = toObject;\n\n\n/**\n * Creates a new ES6 Map built from the provided array and the key-generation\n * function.\n * @param {!IArrayLike<V>} arr Array or array like object over which to iterate\n * whose elements will be the values in the new object.\n * @param {?function(V, number, ?) : K} keyFunc The function to call for every\n * element. This function takes 3 arguments (the element, the index, and the\n * array) and should return a value that will be used as the key for the\n * element in the new object. If the function returns the same key for more\n * than one element, the value for that key is implementation-defined.\n * @return {!Map<K, V>} The new map.\n * @template K,V\n */\nfunction toMap(arr, keyFunc) {\n const /** !Map<K, V> */ map = new Map();\n\n for (let i = 0; i < arr.length; i++) {\n const element = arr[i];\n map.set(keyFunc(element, i, arr), element);\n }\n\n return map;\n}\nexports.toMap = toMap;\n\n\n/**\n * Creates a range of numbers in an arithmetic progression.\n *\n * Range takes 1, 2, or 3 arguments:\n * <pre>\n * range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4]\n * range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4]\n * range(-2, -5, -1) produces [-2, -3, -4]\n * range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5.\n * </pre>\n *\n * @param {number} startOrEnd The starting value of the range if an end argument\n * is provided. Otherwise, the start value is 0, and this is the end value.\n * @param {number=} opt_end The optional end value of the range.\n * @param {number=} opt_step The step size between range values. Defaults to 1\n * if opt_step is undefined or 0.\n * @return {!Array<number>} An array of numbers for the requested range. May be\n * an empty array if adding the step would not converge toward the end\n * value.\n */\nfunction range(startOrEnd, opt_end, opt_step) {\n const array = [];\n let start = 0;\n let end = startOrEnd;\n const step = opt_step || 1;\n if (opt_end !== undefined) {\n start = startOrEnd;\n end = opt_end;\n }\n\n if (step * (end - start) < 0) {\n // Sign mismatch: start + step will never reach the end value.\n return [];\n }\n\n if (step > 0) {\n for (let i = start; i < end; i += step) {\n array.push(i);\n }\n } else {\n for (let i = start; i > end; i += step) {\n array.push(i);\n }\n }\n return array;\n}\nexports.range = range;\n\n\n/**\n * Returns an array consisting of the given value repeated N times.\n *\n * @param {VALUE} value The value to repeat.\n * @param {number} n The repeat count.\n * @return {!Array<VALUE>} An array with the repeated value.\n * @template VALUE\n */\nfunction repeat(value, n) {\n const array = [];\n for (let i = 0; i < n; i++) {\n array[i] = value;\n }\n return array;\n}\nexports.repeat = repeat;\n\n\n/**\n * Returns an array consisting of every argument with all arrays\n * expanded in-place recursively.\n *\n * @param {...*} var_args The values to flatten.\n * @return {!Array<?>} An array containing the flattened values.\n */\nfunction flatten(var_args) {\n const CHUNK_SIZE = 8192;\n\n const result = [];\n for (let i = 0; i < arguments.length; i++) {\n const element = arguments[i];\n if (Array.isArray(element)) {\n for (let c = 0; c < element.length; c += CHUNK_SIZE) {\n const chunk = slice(element, c, c + CHUNK_SIZE);\n const recurseResult = flatten.apply(null, chunk);\n for (let r = 0; r < recurseResult.length; r++) {\n result.push(recurseResult[r]);\n }\n }\n } else {\n result.push(element);\n }\n }\n return result;\n}\nexports.flatten = flatten;\n\n\n/**\n * Rotates an array in-place. After calling this method, the element at\n * index i will be the element previously at index (i - n) %\n * array.length, for all values of i between 0 and array.length - 1,\n * inclusive.\n *\n * For example, suppose list comprises [t, a, n, k, s]. After invoking\n * rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k].\n *\n * @param {!Array<T>} array The array to rotate.\n * @param {number} n The amount to rotate.\n * @return {!Array<T>} The array.\n * @template T\n */\nfunction rotate(array, n) {\n asserts.assert(array.length != null);\n\n if (array.length) {\n n %= array.length;\n if (n > 0) {\n Array.prototype.unshift.apply(array, array.splice(-n, n));\n } else if (n < 0) {\n Array.prototype.push.apply(array, array.splice(0, -n));\n }\n }\n return array;\n}\nexports.rotate = rotate;\n\n\n/**\n * Moves one item of an array to a new position keeping the order of the rest\n * of the items. Example use case: keeping a list of JavaScript objects\n * synchronized with the corresponding list of DOM elements after one of the\n * elements has been dragged to a new position.\n * @param {!IArrayLike<?>} arr The array to modify.\n * @param {number} fromIndex Index of the item to move between 0 and\n * `arr.length - 1`.\n * @param {number} toIndex Target index between 0 and `arr.length - 1`.\n */\nfunction moveItem(arr, fromIndex, toIndex) {\n asserts.assert(fromIndex >= 0 && fromIndex < arr.length);\n asserts.assert(toIndex >= 0 && toIndex < arr.length);\n // Remove 1 item at fromIndex.\n const removedItems = Array.prototype.splice.call(arr, fromIndex, 1);\n // Insert the removed item at toIndex.\n Array.prototype.splice.call(arr, toIndex, 0, removedItems[0]);\n // We don't use goog.array.insertAt and goog.array.removeAt, because they're\n // significantly slower than splice.\n}\nexports.moveItem = moveItem;\n\n\n/**\n * Creates a new array for which the element at position i is an array of the\n * ith element of the provided arrays. The returned array will only be as long\n * as the shortest array provided; additional values are ignored. For example,\n * the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]].\n *\n * This is similar to the zip() function in Python. See {@link\n * http://docs.python.org/library/functions.html#zip}\n *\n * @param {...!IArrayLike<?>} var_args Arrays to be combined.\n * @return {!Array<!Array<?>>} A new array of arrays created from\n * provided arrays.\n */\nfunction zip(var_args) {\n if (!arguments.length) {\n return [];\n }\n const result = [];\n let minLen = arguments[0].length;\n for (let i = 1; i < arguments.length; i++) {\n if (arguments[i].length < minLen) {\n minLen = arguments[i].length;\n }\n }\n for (let i = 0; i < minLen; i++) {\n const value = [];\n for (let j = 0; j < arguments.length; j++) {\n value.push(arguments[j][i]);\n }\n result.push(value);\n }\n return result;\n}\nexports.zip = zip;\n\n\n/**\n * Shuffles the values in the specified array using the Fisher-Yates in-place\n * shuffle (also known as the Knuth Shuffle). By default, calls Math.random()\n * and so resets the state of that random number generator. Similarly, may reset\n * the state of any other specified random number generator.\n *\n * Runtime: O(n)\n *\n * @param {!Array<?>} arr The array to be shuffled.\n * @param {function():number=} opt_randFn Optional random function to use for\n * shuffling.\n * Takes no arguments, and returns a random number on the interval [0, 1).\n * Defaults to Math.random() using JavaScript's built-in Math library.\n */\nfunction shuffle(arr, opt_randFn) {\n const randFn = opt_randFn || Math.random;\n\n for (let i = arr.length - 1; i > 0; i--) {\n // Choose a random array index in [0, i] (inclusive with i).\n const j = Math.floor(randFn() * (i + 1));\n\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n }\n}\nexports.shuffle = shuffle;\n\n\n/**\n * Returns a new array of elements from arr, based on the indexes of elements\n * provided by index_arr. For example, the result of index copying\n * ['a', 'b', 'c'] with index_arr [1,0,0,2] is ['b', 'a', 'a', 'c'].\n *\n * @param {!IArrayLike<T>} arr The array to get a indexed copy from.\n * @param {!IArrayLike<number>} index_arr An array of indexes to get from arr.\n * @return {!Array<T>} A new array of elements from arr in index_arr order.\n * @template T\n */\nfunction copyByIndex(arr, index_arr) {\n const result = [];\n forEach(index_arr, function(index) {\n result.push(arr[index]);\n });\n return result;\n}\nexports.copyByIndex = copyByIndex;\n\n\n/**\n * Maps each element of the input array into zero or more elements of the output\n * array.\n *\n * @param {!IArrayLike<VALUE>|string} arr Array or array like object\n * over which to iterate.\n * @param {function(this:THIS, VALUE, number, ?): !Array<RESULT>} f The function\n * to call for every element. This function takes 3 arguments (the element,\n * the index and the array) and should return an array. The result will be\n * used to extend a new array.\n * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.\n * @return {!Array<RESULT>} a new array with the concatenation of all arrays\n * returned from f.\n * @template THIS, VALUE, RESULT\n */\nfunction concatMap(arr, f, opt_obj) {\n return concat.apply([], map(arr, f, opt_obj));\n}\nexports.concatMap = concatMap;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A base class for event objects.\n */\n\n\ngoog.provide('goog.events.Event');\n\n/**\n * goog.events.Event no longer depends on goog.Disposable. Keep requiring\n * goog.Disposable here to not break projects which assume this dependency.\n * @suppress {extraRequire}\n */\ngoog.require('goog.Disposable');\ngoog.require('goog.events.EventId');\n\n\n/**\n * A base class for event objects, so that they can support preventDefault and\n * stopPropagation.\n *\n * @param {string|!goog.events.EventId} type Event Type.\n * @param {Object=} opt_target Reference to the object that is the target of\n * this event. It has to implement the `EventTarget` interface\n * declared at {@link http://developer.mozilla.org/en/DOM/EventTarget}.\n * @constructor\n */\ngoog.events.Event = function(type, opt_target) {\n 'use strict';\n /**\n * Event type.\n * @type {string}\n */\n this.type = type instanceof goog.events.EventId ? String(type) : type;\n\n /**\n * TODO(tbreisacher): The type should probably be\n * EventTarget|goog.events.EventTarget.\n *\n * Target of the event.\n * @type {Object|undefined}\n */\n this.target = opt_target;\n\n /**\n * Object that had the listener attached.\n * @type {Object|undefined}\n */\n this.currentTarget = this.target;\n\n /**\n * Whether to cancel the event in internal capture/bubble processing for IE.\n * @type {boolean}\n * @private\n */\n this.propagationStopped_ = false;\n\n /**\n * Whether the default action has been prevented.\n * This is a property to match the W3C specification at\n * {@link http://www.w3.org/TR/DOM-Level-3-Events/\n * #events-event-type-defaultPrevented}.\n * Must be treated as read-only outside the class.\n * @type {boolean}\n */\n this.defaultPrevented = false;\n};\n\n/**\n * @return {boolean} true iff internal propagation has been stopped.\n */\ngoog.events.Event.prototype.hasPropagationStopped = function() {\n 'use strict';\n return this.propagationStopped_;\n};\n\n/**\n * Stops event propagation.\n * @return {void}\n */\ngoog.events.Event.prototype.stopPropagation = function() {\n 'use strict';\n this.propagationStopped_ = true;\n};\n\n\n/**\n * Prevents the default action, for example a link redirecting to a url.\n * @return {void}\n */\ngoog.events.Event.prototype.preventDefault = function() {\n 'use strict';\n this.defaultPrevented = true;\n};\n\n\n/**\n * Stops the propagation of the event. It is equivalent to\n * `e.stopPropagation()`, but can be used as the callback argument of\n * {@link goog.events.listen} without declaring another function.\n * @param {!goog.events.Event} e An event.\n * @return {void}\n */\ngoog.events.Event.stopPropagation = function(e) {\n 'use strict';\n e.stopPropagation();\n};\n\n\n/**\n * Prevents the default action. It is equivalent to\n * `e.preventDefault()`, but can be used as the callback argument of\n * {@link goog.events.listen} without declaring another function.\n * @param {!goog.events.Event} e An event.\n * @return {void}\n */\ngoog.events.Event.preventDefault = function(e) {\n 'use strict';\n e.preventDefault();\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Browser capability checks for the events package.\n */\n\ngoog.module('goog.events.BrowserFeature');\ngoog.module.declareLegacyNamespace();\n\n\n/**\n * Tricks Closure Compiler into believing that a function is pure. The compiler\n * assumes that any `valueOf` function is pure, without analyzing its contents.\n *\n * @param {function(): T} fn\n * @return {T}\n * @template T\n */\nconst purify = (fn) => {\n return ({valueOf: fn}).valueOf();\n};\n\n\n/**\n * Enum of browser capabilities.\n * @enum {boolean}\n */\nexports = {\n /**\n * Whether touch is enabled in the browser.\n */\n TOUCH_ENABLED:\n ('ontouchstart' in goog.global ||\n !!(goog.global['document'] && document.documentElement &&\n 'ontouchstart' in document.documentElement) ||\n // IE10 uses non-standard touch events, so it has a different check.\n !!(goog.global['navigator'] &&\n (goog.global['navigator']['maxTouchPoints'] ||\n goog.global['navigator']['msMaxTouchPoints']))),\n\n /**\n * Whether addEventListener supports W3C standard pointer events.\n * http://www.w3.org/TR/pointerevents/\n */\n POINTER_EVENTS: ('PointerEvent' in goog.global),\n\n /**\n * Whether addEventListener supports MSPointer events (only used in IE10).\n * http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx\n * http://msdn.microsoft.com/library/hh673557(v=vs.85).aspx\n */\n MSPOINTER_EVENTS: false,\n\n /**\n * Whether addEventListener supports {passive: true}.\n * https://developers.google.com/web/updates/2016/06/passive-event-listeners\n */\n PASSIVE_EVENTS: purify(function() {\n // If we're in a web worker or other custom environment, we can't tell.\n if (!goog.global.addEventListener || !Object.defineProperty) { // IE 8\n return false;\n }\n\n var passive = false;\n var options = Object.defineProperty({}, 'passive', {\n get: function() {\n passive = true;\n }\n });\n try {\n goog.global.addEventListener('test', () => {}, options);\n goog.global.removeEventListener('test', () => {}, options);\n } catch (e) {\n }\n\n return passive;\n })\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview String functions called from Closure packages that couldn't\n * depend on each other. Outside Closure, use goog.string function which\n * delegate to these.\n */\n\n\ngoog.provide('goog.string.internal');\n\n\n/**\n * Fast prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the start of `str`.\n * @return {boolean} True if `str` begins with `prefix`.\n * @see goog.string.startsWith\n */\ngoog.string.internal.startsWith = function(str, prefix) {\n 'use strict';\n return str.lastIndexOf(prefix, 0) == 0;\n};\n\n\n/**\n * Fast suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix`.\n * @see goog.string.endsWith\n */\ngoog.string.internal.endsWith = function(str, suffix) {\n 'use strict';\n const l = str.length - suffix.length;\n return l >= 0 && str.indexOf(suffix, l) == l;\n};\n\n\n/**\n * Case-insensitive prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the end of `str`.\n * @return {boolean} True if `str` begins with `prefix` (ignoring\n * case).\n * @see goog.string.caseInsensitiveStartsWith\n */\ngoog.string.internal.caseInsensitiveStartsWith = function(str, prefix) {\n 'use strict';\n return (\n goog.string.internal.caseInsensitiveCompare(\n prefix, str.slice(0, prefix.length)) == 0);\n};\n\n\n/**\n * Case-insensitive suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix` (ignoring\n * case).\n * @see goog.string.caseInsensitiveEndsWith\n */\ngoog.string.internal.caseInsensitiveEndsWith = function(str, suffix) {\n 'use strict';\n return (\n goog.string.internal.caseInsensitiveCompare(\n suffix, str.slice(str.length - suffix.length)) == 0);\n};\n\n\n/**\n * Case-insensitive equality checker.\n * @param {string} str1 First string to check.\n * @param {string} str2 Second string to check.\n * @return {boolean} True if `str1` and `str2` are the same string,\n * ignoring case.\n * @see goog.string.caseInsensitiveEquals\n */\ngoog.string.internal.caseInsensitiveEquals = function(str1, str2) {\n 'use strict';\n return str1.toLowerCase() == str2.toLowerCase();\n};\n\n\n/**\n * Checks if a string is empty or contains only whitespaces.\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty or whitespace only.\n * @see goog.string.isEmptyOrWhitespace\n */\ngoog.string.internal.isEmptyOrWhitespace = function(str) {\n 'use strict';\n // testing length == 0 first is actually slower in all browsers (about the\n // same in Opera).\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return /^[\\s\\xa0]*$/.test(str);\n};\n\n\n/**\n * Trims white spaces to the left and right of a string.\n * @param {string} str The string to trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.internal.trim =\n (goog.TRUSTED_SITE && String.prototype.trim) ? function(str) {\n 'use strict';\n return str.trim();\n } : function(str) {\n 'use strict';\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s\n // character class (as required by section 7.2 of the ECMAScript spec),\n // we explicitly include it in the regexp to enforce consistent\n // cross-browser behavior.\n // NOTE: We don't use String#replace because it might have side effects\n // causing this function to not compile to 0 bytes.\n return /^[\\s\\xa0]*([\\s\\S]*?)[\\s\\xa0]*$/.exec(str)[1];\n };\n\n\n/**\n * A string comparator that ignores case.\n * -1 = str1 less than str2\n * 0 = str1 equals str2\n * 1 = str1 greater than str2\n *\n * @param {string} str1 The string to compare.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} The comparator result, as described above.\n * @see goog.string.caseInsensitiveCompare\n */\ngoog.string.internal.caseInsensitiveCompare = function(str1, str2) {\n 'use strict';\n const test1 = String(str1).toLowerCase();\n const test2 = String(str2).toLowerCase();\n\n if (test1 < test2) {\n return -1;\n } else if (test1 == test2) {\n return 0;\n } else {\n return 1;\n }\n};\n\n\n/**\n * Converts \\n to <br>s or <br />s.\n * @param {string} str The string in which to convert newlines.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} A copy of `str` with converted newlines.\n * @see goog.string.newLineToBr\n */\ngoog.string.internal.newLineToBr = function(str, opt_xml) {\n 'use strict';\n return str.replace(/(\\r\\n|\\r|\\n)/g, opt_xml ? '<br />' : '<br>');\n};\n\n\n/**\n * Escapes double quote '\"' and single quote '\\'' characters in addition to\n * '&', '<', and '>' so that a string can be included in an HTML tag attribute\n * value within double or single quotes.\n * @param {string} str string to be escaped.\n * @param {boolean=} opt_isLikelyToContainHtmlChars\n * @return {string} An escaped copy of `str`.\n * @see goog.string.htmlEscape\n */\ngoog.string.internal.htmlEscape = function(\n str, opt_isLikelyToContainHtmlChars) {\n 'use strict';\n if (opt_isLikelyToContainHtmlChars) {\n str = str.replace(goog.string.internal.AMP_RE_, '&')\n .replace(goog.string.internal.LT_RE_, '<')\n .replace(goog.string.internal.GT_RE_, '>')\n .replace(goog.string.internal.QUOT_RE_, '"')\n .replace(goog.string.internal.SINGLE_QUOTE_RE_, ''')\n .replace(goog.string.internal.NULL_RE_, '�');\n return str;\n\n } else {\n // quick test helps in the case when there are no chars to replace, in\n // worst case this makes barely a difference to the time taken\n if (!goog.string.internal.ALL_RE_.test(str)) return str;\n\n // str.indexOf is faster than regex.test in this case\n if (str.indexOf('&') != -1) {\n str = str.replace(goog.string.internal.AMP_RE_, '&');\n }\n if (str.indexOf('<') != -1) {\n str = str.replace(goog.string.internal.LT_RE_, '<');\n }\n if (str.indexOf('>') != -1) {\n str = str.replace(goog.string.internal.GT_RE_, '>');\n }\n if (str.indexOf('\"') != -1) {\n str = str.replace(goog.string.internal.QUOT_RE_, '"');\n }\n if (str.indexOf('\\'') != -1) {\n str = str.replace(goog.string.internal.SINGLE_QUOTE_RE_, ''');\n }\n if (str.indexOf('\\x00') != -1) {\n str = str.replace(goog.string.internal.NULL_RE_, '�');\n }\n return str;\n }\n};\n\n\n/**\n * Regular expression that matches an ampersand, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.AMP_RE_ = /&/g;\n\n\n/**\n * Regular expression that matches a less than sign, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.LT_RE_ = /</g;\n\n\n/**\n * Regular expression that matches a greater than sign, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.GT_RE_ = />/g;\n\n\n/**\n * Regular expression that matches a double quote, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.QUOT_RE_ = /\"/g;\n\n\n/**\n * Regular expression that matches a single quote, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.SINGLE_QUOTE_RE_ = /'/g;\n\n\n/**\n * Regular expression that matches null character, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.NULL_RE_ = /\\x00/g;\n\n\n/**\n * Regular expression that matches any character that needs to be escaped.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.ALL_RE_ = /[\\x00&<>\"']/;\n\n\n/**\n * Do escaping of whitespace to preserve spatial formatting. We use character\n * entity #160 to make it safer for xml.\n * @param {string} str The string in which to escape whitespace.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} An escaped copy of `str`.\n * @see goog.string.whitespaceEscape\n */\ngoog.string.internal.whitespaceEscape = function(str, opt_xml) {\n 'use strict';\n // This doesn't use goog.string.preserveSpaces for backwards compatibility.\n return goog.string.internal.newLineToBr(\n str.replace(/ /g, '  '), opt_xml);\n};\n\n\n/**\n * Determines whether a string contains a substring.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n * @see goog.string.contains\n */\ngoog.string.internal.contains = function(str, subString) {\n 'use strict';\n return str.indexOf(subString) != -1;\n};\n\n\n/**\n * Determines whether a string contains a substring, ignoring case.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n * @see goog.string.caseInsensitiveContains\n */\ngoog.string.internal.caseInsensitiveContains = function(str, subString) {\n 'use strict';\n return goog.string.internal.contains(\n str.toLowerCase(), subString.toLowerCase());\n};\n\n\n/**\n * Compares two version numbers.\n *\n * @param {string|number} version1 Version of first item.\n * @param {string|number} version2 Version of second item.\n *\n * @return {number} 1 if `version1` is higher.\n * 0 if arguments are equal.\n * -1 if `version2` is higher.\n * @see goog.string.compareVersions\n */\ngoog.string.internal.compareVersions = function(version1, version2) {\n 'use strict';\n let order = 0;\n // Trim leading and trailing whitespace and split the versions into\n // subversions.\n const v1Subs = goog.string.internal.trim(String(version1)).split('.');\n const v2Subs = goog.string.internal.trim(String(version2)).split('.');\n const subCount = Math.max(v1Subs.length, v2Subs.length);\n\n // Iterate over the subversions, as long as they appear to be equivalent.\n for (let subIdx = 0; order == 0 && subIdx < subCount; subIdx++) {\n let v1Sub = v1Subs[subIdx] || '';\n let v2Sub = v2Subs[subIdx] || '';\n\n do {\n // Split the subversions into pairs of numbers and qualifiers (like 'b').\n // Two different RegExp objects are use to make it clear the code\n // is side-effect free\n const v1Comp = /(\\d*)(\\D*)(.*)/.exec(v1Sub) || ['', '', '', ''];\n const v2Comp = /(\\d*)(\\D*)(.*)/.exec(v2Sub) || ['', '', '', ''];\n // Break if there are no more matches.\n if (v1Comp[0].length == 0 && v2Comp[0].length == 0) {\n break;\n }\n\n // Parse the numeric part of the subversion. A missing number is\n // equivalent to 0.\n const v1CompNum = v1Comp[1].length == 0 ? 0 : parseInt(v1Comp[1], 10);\n const v2CompNum = v2Comp[1].length == 0 ? 0 : parseInt(v2Comp[1], 10);\n\n // Compare the subversion components. The number has the highest\n // precedence. Next, if the numbers are equal, a subversion without any\n // qualifier is always higher than a subversion with any qualifier. Next,\n // the qualifiers are compared as strings.\n order = goog.string.internal.compareElements_(v1CompNum, v2CompNum) ||\n goog.string.internal.compareElements_(\n v1Comp[2].length == 0, v2Comp[2].length == 0) ||\n goog.string.internal.compareElements_(v1Comp[2], v2Comp[2]);\n // Stop as soon as an inequality is discovered.\n\n v1Sub = v1Comp[3];\n v2Sub = v2Comp[3];\n } while (order == 0);\n }\n\n return order;\n};\n\n\n/**\n * Compares elements of a version number.\n *\n * @param {string|number|boolean} left An element from a version number.\n * @param {string|number|boolean} right An element from a version number.\n *\n * @return {number} 1 if `left` is higher.\n * 0 if arguments are equal.\n * -1 if `right` is higher.\n * @private\n */\ngoog.string.internal.compareElements_ = function(left, right) {\n 'use strict';\n if (left < right) {\n return -1;\n } else if (left > right) {\n return 1;\n }\n return 0;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities used by goog.labs.userAgent tools. These functions\n * should not be used outside of goog.labs.userAgent.*.\n *\n */\n\ngoog.module('goog.labs.userAgent.util');\ngoog.module.declareLegacyNamespace();\n\nconst {caseInsensitiveContains, contains} = goog.require('goog.string.internal');\nconst {useClientHints} = goog.require('goog.labs.userAgent');\n\n/**\n * @const {boolean} If true, use navigator.userAgentData without check.\n * TODO(user): FEATURESET_YEAR >= 2024 if it supports mobile and all the\n * brands we need. See https://caniuse.com/mdn-api_navigator_useragentdata.\n */\nconst ASSUME_CLIENT_HINTS_SUPPORT = false;\n\n/**\n * Gets the native userAgent string from navigator if it exists.\n * If navigator or navigator.userAgent string is missing, returns an empty\n * string.\n * @return {string}\n */\nfunction getNativeUserAgentString() {\n const navigator = getNavigator();\n if (navigator) {\n const userAgent = navigator.userAgent;\n if (userAgent) {\n return userAgent;\n }\n }\n return '';\n}\n\n/**\n * Gets the native userAgentData object from navigator if it exists.\n * If navigator.userAgentData object is missing returns null.\n * @return {?NavigatorUAData}\n */\nfunction getNativeUserAgentData() {\n const navigator = getNavigator();\n // TODO(user): Use navigator?.userAgent ?? null once it's supported.\n if (navigator) {\n return navigator.userAgentData || null;\n }\n return null;\n}\n\n/**\n * Getter for the native navigator.\n * @return {!Navigator}\n */\nfunction getNavigator() {\n return goog.global.navigator;\n}\n\n/**\n * A possible override for applications which wish to not check\n * navigator.userAgent but use a specified value for detection instead.\n * @type {?string}\n */\nlet userAgentInternal = null;\n\n/**\n * A possible override for applications which wish to not check\n * navigator.userAgentData but use a specified value for detection instead.\n * @type {?NavigatorUAData}\n */\nlet userAgentDataInternal = getNativeUserAgentData();\n\n/**\n * Override the user agent string with the given value.\n * This should only be used for testing within the goog.labs.userAgent\n * namespace.\n * Pass `null` to use the native browser object instead.\n * @param {?string=} userAgent The userAgent override.\n * @return {void}\n */\nfunction setUserAgent(userAgent = undefined) {\n userAgentInternal =\n typeof userAgent === 'string' ? userAgent : getNativeUserAgentString();\n}\n\n/** @return {string} The user agent string. */\nfunction getUserAgent() {\n return userAgentInternal == null ? getNativeUserAgentString() :\n userAgentInternal;\n}\n\n/**\n * Override the user agent data object with the given value.\n * This should only be used for testing within the goog.labs.userAgent\n * namespace.\n * Pass `null` to specify the absence of userAgentData. Note that this behavior\n * is different from setUserAgent.\n * @param {?NavigatorUAData} userAgentData The userAgentData override.\n */\nfunction setUserAgentData(userAgentData) {\n userAgentDataInternal = userAgentData;\n}\n\n/**\n * If the user agent data object was overridden using setUserAgentData,\n * reset it so that it uses the native browser object instead, if it exists.\n */\nfunction resetUserAgentData() {\n userAgentDataInternal = getNativeUserAgentData();\n}\n\n/** @return {?NavigatorUAData} Navigator.userAgentData if exist */\nfunction getUserAgentData() {\n return userAgentDataInternal;\n}\n\n/**\n * Checks if any string in userAgentData.brands matches str.\n * Returns false if userAgentData is not supported.\n * @param {string} str\n * @return {boolean} Whether any brand string from userAgentData contains the\n * given string.\n */\nfunction matchUserAgentDataBrand(str) {\n if (!useClientHints()) return false;\n const data = getUserAgentData();\n if (!data) return false;\n return data.brands.some(({brand}) => brand && contains(brand, str));\n}\n\n/**\n * @param {string} str\n * @return {boolean} Whether the user agent contains the given string.\n */\nfunction matchUserAgent(str) {\n const userAgent = getUserAgent();\n return contains(userAgent, str);\n}\n\n/**\n * @param {string} str\n * @return {boolean} Whether the user agent contains the given string, ignoring\n * case.\n */\nfunction matchUserAgentIgnoreCase(str) {\n const userAgent = getUserAgent();\n return caseInsensitiveContains(userAgent, str);\n}\n\n/**\n * Parses the user agent into tuples for each section.\n * @param {string} userAgent\n * @return {!Array<!Array<string>>} Tuples of key, version, and the contents of\n * the parenthetical.\n */\nfunction extractVersionTuples(userAgent) {\n // Matches each section of a user agent string.\n // Example UA:\n // Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us)\n // AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405\n // This has three version tuples: Mozilla, AppleWebKit, and Mobile.\n\n const versionRegExp = new RegExp(\n // Key. Note that a key may have a space.\n // (i.e. 'Mobile Safari' in 'Mobile Safari/5.0')\n '([A-Z][\\\\w ]+)' +\n\n '/' + // slash\n '([^\\\\s]+)' + // version (i.e. '5.0b')\n '\\\\s*' + // whitespace\n '(?:\\\\((.*?)\\\\))?', // parenthetical info. parentheses not matched.\n 'g');\n\n const data = [];\n let match;\n\n // Iterate and collect the version tuples. Each iteration will be the\n // next regex match.\n while (match = versionRegExp.exec(userAgent)) {\n data.push([\n match[1], // key\n match[2], // value\n // || undefined as this is not undefined in IE7 and IE8\n match[3] || undefined // info\n ]);\n }\n\n return data;\n}\n\nexports = {\n ASSUME_CLIENT_HINTS_SUPPORT,\n extractVersionTuples,\n getNativeUserAgentString,\n getUserAgent,\n getUserAgentData,\n matchUserAgent,\n matchUserAgentDataBrand,\n matchUserAgentIgnoreCase,\n resetUserAgentData,\n setUserAgent,\n setUserAgentData,\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Useful compiler idioms.\n */\n\ngoog.provide('goog.reflect');\n\n\n/**\n * Syntax for object literal casts.\n * @see http://go/jscompiler-renaming\n * @see https://goo.gl/CRs09P\n *\n * Use this if you have an object literal whose keys need to have the same names\n * as the properties of some class even after they are renamed by the compiler.\n *\n * @param {!Function} type Type to cast to.\n * @param {Object} object Object literal to cast.\n * @return {Object} The object literal.\n */\ngoog.reflect.object = function(type, object) {\n 'use strict';\n return object;\n};\n\n/**\n * Syntax for renaming property strings.\n * @see http://go/jscompiler-renaming\n * @see https://goo.gl/CRs09P\n *\n * Use this if you have an need to access a property as a string, but want\n * to also have the property renamed by the compiler. In contrast to\n * goog.reflect.object, this method takes an instance of an object.\n *\n * Properties must be simple names (not qualified names).\n *\n * @param {string} prop Name of the property\n * @param {!Object} object Instance of the object whose type will be used\n * for renaming\n * @return {string} The renamed property.\n */\ngoog.reflect.objectProperty = function(prop, object) {\n 'use strict';\n return prop;\n};\n\n/**\n * To assert to the compiler that an operation is needed when it would\n * otherwise be stripped. For example:\n * <code>\n * // Force a layout\n * goog.reflect.sinkValue(dialog.offsetHeight);\n * </code>\n * @param {T} x\n * @return {T}\n * @template T\n */\ngoog.reflect.sinkValue = function(x) {\n 'use strict';\n goog.reflect.sinkValue[' '](x);\n return x;\n};\n\n\n/**\n * The compiler should optimize this function away iff no one ever uses\n * goog.reflect.sinkValue.\n */\ngoog.reflect.sinkValue[' '] = function() {};\n\n\n/**\n * Check if a property can be accessed without throwing an exception.\n * @param {Object} obj The owner of the property.\n * @param {string} prop The property name.\n * @return {boolean} Whether the property is accessible. Will also return true\n * if obj is null.\n */\ngoog.reflect.canAccessProperty = function(obj, prop) {\n 'use strict';\n try {\n goog.reflect.sinkValue(obj[prop]);\n return true;\n } catch (e) {\n }\n return false;\n};\n\n\n/**\n * Retrieves a value from a cache given a key. The compiler provides special\n * consideration for this call such that it is generally considered side-effect\n * free. However, if the `opt_keyFn` or `valueFn` have side-effects\n * then the entire call is considered to have side-effects.\n *\n * Conventionally storing the value on the cache would be considered a\n * side-effect and preclude unused calls from being pruned, ie. even if\n * the value was never used, it would still always be stored in the cache.\n *\n * Providing a side-effect free `valueFn` and `opt_keyFn`\n * allows unused calls to `goog.reflect.cache` to be pruned.\n *\n * @param {!Object<K, V>} cacheObj The object that contains the cached values.\n * @param {?} key The key to lookup in the cache. If it is not string or number\n * then a `opt_keyFn` should be provided. The key is also used as the\n * parameter to the `valueFn`.\n * @param {function(?):V} valueFn The value provider to use to calculate the\n * value to store in the cache. This function should be side-effect free\n * to take advantage of the optimization.\n * @param {function(?):K=} opt_keyFn The key provider to determine the cache\n * map key. This should be used if the given key is not a string or number.\n * If not provided then the given key is used. This function should be\n * side-effect free to take advantage of the optimization.\n * @return {V} The cached or calculated value.\n * @template K\n * @template V\n */\ngoog.reflect.cache = function(cacheObj, key, valueFn, opt_keyFn) {\n 'use strict';\n const storedKey = opt_keyFn ? opt_keyFn(key) : key;\n\n if (Object.prototype.hasOwnProperty.call(cacheObj, storedKey)) {\n return cacheObj[storedKey];\n }\n\n return (cacheObj[storedKey] = valueFn(key));\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Rendering engine detection.\n * @see <a href=\"http://www.useragentstring.com/\">User agent strings</a>\n * For information on the browser brand (such as Safari versus Chrome), see\n * goog.userAgent.product.\n * @see ../demos/useragent.html\n */\n\ngoog.provide('goog.userAgent');\n\ngoog.require('goog.labs.userAgent.browser');\ngoog.require('goog.labs.userAgent.engine');\ngoog.require('goog.labs.userAgent.platform');\ngoog.require('goog.labs.userAgent.util');\ngoog.require('goog.reflect');\ngoog.require('goog.string.internal');\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is IE.\n */\ngoog.userAgent.ASSUME_IE = goog.define('goog.userAgent.ASSUME_IE', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is EDGE,\n * referring to EdgeHTML based Edge.\n */\ngoog.userAgent.ASSUME_EDGE = goog.define('goog.userAgent.ASSUME_EDGE', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is GECKO.\n */\ngoog.userAgent.ASSUME_GECKO = goog.define('goog.userAgent.ASSUME_GECKO', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is WEBKIT.\n */\ngoog.userAgent.ASSUME_WEBKIT =\n goog.define('goog.userAgent.ASSUME_WEBKIT', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is a\n * mobile device running WebKit e.g. iPhone or Android.\n */\ngoog.userAgent.ASSUME_MOBILE_WEBKIT =\n goog.define('goog.userAgent.ASSUME_MOBILE_WEBKIT', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is OPERA,\n * referring to Presto-based Opera.\n */\ngoog.userAgent.ASSUME_OPERA = goog.define('goog.userAgent.ASSUME_OPERA', false);\n\n\n/**\n * @define {boolean} Whether the\n * `goog.userAgent.isVersionOrHigher`\n * function will return true for any version.\n */\ngoog.userAgent.ASSUME_ANY_VERSION =\n goog.define('goog.userAgent.ASSUME_ANY_VERSION', false);\n\n\n/**\n * Whether we know the browser engine at compile-time.\n * @type {boolean}\n * @private\n */\ngoog.userAgent.BROWSER_KNOWN_ = goog.userAgent.ASSUME_IE ||\n goog.userAgent.ASSUME_EDGE || goog.userAgent.ASSUME_GECKO ||\n goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.ASSUME_WEBKIT ||\n goog.userAgent.ASSUME_OPERA;\n\n\n/**\n * Returns the userAgent string for the current browser.\n *\n * @return {string} The userAgent string.\n */\ngoog.userAgent.getUserAgentString = function() {\n 'use strict';\n return goog.labs.userAgent.util.getUserAgent();\n};\n\n\n/**\n * @return {?Navigator} The native navigator object.\n */\ngoog.userAgent.getNavigatorTyped = function() {\n 'use strict';\n // Need a local navigator reference instead of using the global one,\n // to avoid the rare case where they reference different objects.\n // (in a WorkerPool, for example).\n return goog.global['navigator'] || null;\n};\n\n\n/**\n * TODO(nnaze): Change type to \"Navigator\" and update compilation targets.\n * @return {?Object} The native navigator object.\n */\ngoog.userAgent.getNavigator = function() {\n 'use strict';\n return goog.userAgent.getNavigatorTyped();\n};\n\n\n/**\n * Whether the user agent is Presto-based Opera.\n * @type {boolean}\n */\ngoog.userAgent.OPERA = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_OPERA :\n goog.labs.userAgent.browser.isOpera();\n\n\n/**\n * Whether the user agent is Internet Explorer.\n * @type {boolean}\n */\ngoog.userAgent.IE = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_IE :\n goog.labs.userAgent.browser.isIE();\n\n\n/**\n * Whether the user agent is Microsoft Edge (EdgeHTML based).\n * @type {boolean}\n */\ngoog.userAgent.EDGE = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_EDGE :\n goog.labs.userAgent.engine.isEdge();\n\n\n/**\n * Whether the user agent is MS Internet Explorer or MS Edge (EdgeHTML based).\n * @type {boolean}\n */\ngoog.userAgent.EDGE_OR_IE = goog.userAgent.EDGE || goog.userAgent.IE;\n\n\n/**\n * Whether the user agent is Gecko. Gecko is the rendering engine used by\n * Mozilla, Firefox, and others.\n * @type {boolean}\n */\ngoog.userAgent.GECKO = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_GECKO :\n goog.labs.userAgent.engine.isGecko();\n\n\n/**\n * Whether the user agent is WebKit. WebKit is the rendering engine that\n * Safari, Edge Chromium, Opera Chromium, Android and others use.\n * @type {boolean}\n */\ngoog.userAgent.WEBKIT = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_MOBILE_WEBKIT :\n goog.labs.userAgent.engine.isWebKit();\n\n\n/**\n * Whether the user agent is running on a mobile device.\n *\n * This is a separate function so that the logic can be tested.\n *\n * TODO(nnaze): Investigate swapping in goog.labs.userAgent.device.isMobile().\n *\n * @return {boolean} Whether the user agent is running on a mobile device.\n * @private\n */\ngoog.userAgent.isMobile_ = function() {\n 'use strict';\n return goog.userAgent.WEBKIT &&\n goog.labs.userAgent.util.matchUserAgent('Mobile');\n};\n\n\n/**\n * Whether the user agent is running on a mobile device.\n *\n * TODO(nnaze): Consider deprecating MOBILE when labs.userAgent\n * is promoted as the gecko/webkit logic is likely inaccurate.\n *\n * @type {boolean}\n */\ngoog.userAgent.MOBILE =\n goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.isMobile_();\n\n\n/**\n * Used while transitioning code to use WEBKIT instead.\n * @type {boolean}\n * @deprecated Use {@link goog.userAgent.product.SAFARI} instead.\n * TODO(nicksantos): Delete this from goog.userAgent.\n */\ngoog.userAgent.SAFARI = goog.userAgent.WEBKIT;\n\n\n/**\n * @return {string} the platform (operating system) the user agent is running\n * on. Default to empty string because navigator.platform may not be defined\n * (on Rhino, for example).\n * @private\n */\ngoog.userAgent.determinePlatform_ = function() {\n 'use strict';\n var navigator = goog.userAgent.getNavigatorTyped();\n return navigator && navigator.platform || '';\n};\n\n\n/**\n * The platform (operating system) the user agent is running on. Default to\n * empty string because navigator.platform may not be defined (on Rhino, for\n * example).\n * @type {string}\n */\ngoog.userAgent.PLATFORM = goog.userAgent.determinePlatform_();\n\n\n/**\n * @define {boolean} Whether the user agent is running on a Macintosh operating\n * system.\n */\ngoog.userAgent.ASSUME_MAC = goog.define('goog.userAgent.ASSUME_MAC', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on a Windows operating\n * system.\n */\ngoog.userAgent.ASSUME_WINDOWS =\n goog.define('goog.userAgent.ASSUME_WINDOWS', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on a Linux operating\n * system.\n */\ngoog.userAgent.ASSUME_LINUX = goog.define('goog.userAgent.ASSUME_LINUX', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on a X11 windowing\n * system.\n */\ngoog.userAgent.ASSUME_X11 = goog.define('goog.userAgent.ASSUME_X11', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on Android.\n */\ngoog.userAgent.ASSUME_ANDROID =\n goog.define('goog.userAgent.ASSUME_ANDROID', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPhone.\n */\ngoog.userAgent.ASSUME_IPHONE =\n goog.define('goog.userAgent.ASSUME_IPHONE', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPad.\n */\ngoog.userAgent.ASSUME_IPAD = goog.define('goog.userAgent.ASSUME_IPAD', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPod.\n */\ngoog.userAgent.ASSUME_IPOD = goog.define('goog.userAgent.ASSUME_IPOD', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on KaiOS.\n */\ngoog.userAgent.ASSUME_KAIOS = goog.define('goog.userAgent.ASSUME_KAIOS', false);\n\n\n/**\n * @type {boolean}\n * @private\n */\ngoog.userAgent.PLATFORM_KNOWN_ = goog.userAgent.ASSUME_MAC ||\n goog.userAgent.ASSUME_WINDOWS || goog.userAgent.ASSUME_LINUX ||\n goog.userAgent.ASSUME_X11 || goog.userAgent.ASSUME_ANDROID ||\n goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD ||\n goog.userAgent.ASSUME_IPOD;\n\n\n/**\n * Whether the user agent is running on a Macintosh operating system.\n * @type {boolean}\n */\ngoog.userAgent.MAC = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_MAC :\n goog.labs.userAgent.platform.isMacintosh();\n\n\n/**\n * Whether the user agent is running on a Windows operating system.\n * @type {boolean}\n */\ngoog.userAgent.WINDOWS = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_WINDOWS :\n goog.labs.userAgent.platform.isWindows();\n\n\n/**\n * Whether the user agent is Linux per the legacy behavior of\n * goog.userAgent.LINUX, which considered ChromeOS to also be\n * Linux.\n * @return {boolean}\n * @private\n */\ngoog.userAgent.isLegacyLinux_ = function() {\n 'use strict';\n return goog.labs.userAgent.platform.isLinux() ||\n goog.labs.userAgent.platform.isChromeOS();\n};\n\n\n/**\n * Whether the user agent is running on a Linux operating system.\n *\n * Note that goog.userAgent.LINUX considers ChromeOS to be Linux,\n * while goog.labs.userAgent.platform considers ChromeOS and\n * Linux to be different OSes.\n *\n * @type {boolean}\n */\ngoog.userAgent.LINUX = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_LINUX :\n goog.userAgent.isLegacyLinux_();\n\n\n/**\n * @return {boolean} Whether the user agent is an X11 windowing system.\n * @private\n */\ngoog.userAgent.isX11_ = function() {\n 'use strict';\n var navigator = goog.userAgent.getNavigatorTyped();\n return !!navigator &&\n goog.string.internal.contains(navigator['appVersion'] || '', 'X11');\n};\n\n\n/**\n * Whether the user agent is running on a X11 windowing system.\n * @type {boolean}\n */\ngoog.userAgent.X11 = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_X11 :\n goog.userAgent.isX11_();\n\n\n/**\n * Whether the user agent is running on Android.\n * @type {boolean}\n */\ngoog.userAgent.ANDROID = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_ANDROID :\n goog.labs.userAgent.platform.isAndroid();\n\n\n/**\n * Whether the user agent is running on an iPhone.\n * @type {boolean}\n */\ngoog.userAgent.IPHONE = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPHONE :\n goog.labs.userAgent.platform.isIphone();\n\n\n/**\n * Whether the user agent is running on an iPad.\n * @type {boolean}\n */\ngoog.userAgent.IPAD = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPAD :\n goog.labs.userAgent.platform.isIpad();\n\n\n/**\n * Whether the user agent is running on an iPod.\n * @type {boolean}\n */\ngoog.userAgent.IPOD = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPOD :\n goog.labs.userAgent.platform.isIpod();\n\n\n/**\n * Whether the user agent is running on iOS.\n * @type {boolean}\n */\ngoog.userAgent.IOS = goog.userAgent.PLATFORM_KNOWN_ ?\n (goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD ||\n goog.userAgent.ASSUME_IPOD) :\n goog.labs.userAgent.platform.isIos();\n\n/**\n * Whether the user agent is running on KaiOS.\n * @type {boolean}\n */\ngoog.userAgent.KAIOS = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_KAIOS :\n goog.labs.userAgent.platform.isKaiOS();\n\n\n/**\n * @return {string} The string that describes the version number of the user\n * agent.\n * @private\n */\ngoog.userAgent.determineVersion_ = function() {\n 'use strict';\n // All browsers have different ways to detect the version and they all have\n // different naming schemes.\n // version is a string rather than a number because it may contain 'b', 'a',\n // and so on.\n var version = '';\n var arr = goog.userAgent.getVersionRegexResult_();\n if (arr) {\n version = arr ? arr[1] : '';\n }\n\n if (goog.userAgent.IE) {\n // IE9 can be in document mode 9 but be reporting an inconsistent user agent\n // version. If it is identifying as a version lower than 9 we take the\n // documentMode as the version instead. IE8 has similar behavior.\n // It is recommended to set the X-UA-Compatible header to ensure that IE9\n // uses documentMode 9.\n var docMode = goog.userAgent.getDocumentMode_();\n if (docMode != null && docMode > parseFloat(version)) {\n return String(docMode);\n }\n }\n\n return version;\n};\n\n\n/**\n * @return {?IArrayLike<string>|undefined} The version regex matches from\n * parsing the user\n * agent string. These regex statements must be executed inline so they can\n * be compiled out by the closure compiler with the rest of the useragent\n * detection logic when ASSUME_* is specified.\n * @private\n */\ngoog.userAgent.getVersionRegexResult_ = function() {\n 'use strict';\n var userAgent = goog.userAgent.getUserAgentString();\n if (goog.userAgent.GECKO) {\n return /rv\\:([^\\);]+)(\\)|;)/.exec(userAgent);\n }\n if (goog.userAgent.EDGE) {\n return /Edge\\/([\\d\\.]+)/.exec(userAgent);\n }\n if (goog.userAgent.IE) {\n return /\\b(?:MSIE|rv)[: ]([^\\);]+)(\\)|;)/.exec(userAgent);\n }\n if (goog.userAgent.WEBKIT) {\n // WebKit/125.4\n return /WebKit\\/(\\S+)/.exec(userAgent);\n }\n if (goog.userAgent.OPERA) {\n // If none of the above browsers were detected but the browser is Opera, the\n // only string that is of interest is 'Version/<number>'.\n return /(?:Version)[ \\/]?(\\S+)/.exec(userAgent);\n }\n return undefined;\n};\n\n\n/**\n * @return {number|undefined} Returns the document mode (for testing).\n * @private\n */\ngoog.userAgent.getDocumentMode_ = function() {\n 'use strict';\n // NOTE(user): goog.userAgent may be used in context where there is no DOM.\n var doc = goog.global['document'];\n return doc ? doc['documentMode'] : undefined;\n};\n\n\n/**\n * The version of the user agent. This is a string because it might contain\n * 'b' (as in beta) as well as multiple dots.\n * @type {string}\n */\ngoog.userAgent.VERSION = goog.userAgent.determineVersion_();\n\n\n/**\n * Compares two version numbers.\n *\n * @param {string} v1 Version of first item.\n * @param {string} v2 Version of second item.\n *\n * @return {number} 1 if first argument is higher\n * 0 if arguments are equal\n * -1 if second argument is higher.\n * @deprecated Use goog.string.compareVersions.\n */\ngoog.userAgent.compare = function(v1, v2) {\n 'use strict';\n return goog.string.internal.compareVersions(v1, v2);\n};\n\n\n/**\n * Cache for {@link goog.userAgent.isVersionOrHigher}.\n * Calls to compareVersions are surprisingly expensive and, as a browser's\n * version number is unlikely to change during a session, we cache the results.\n * @const\n * @private\n */\ngoog.userAgent.isVersionOrHigherCache_ = {};\n\n\n/**\n * Whether the user agent version is higher or the same as the given version.\n * NOTE: When checking the version numbers for Firefox and Safari, be sure to\n * use the engine's version, not the browser's version number. For example,\n * Firefox 3.0 corresponds to Gecko 1.9 and Safari 3.0 to Webkit 522.11.\n * Opera and Internet Explorer versions match the product release number.<br>\n * @see <a href=\"http://en.wikipedia.org/wiki/Safari_version_history\">\n * Webkit</a>\n * @see <a href=\"http://en.wikipedia.org/wiki/Gecko_engine\">Gecko</a>\n *\n * @param {string|number} version The version to check.\n * @return {boolean} Whether the user agent version is higher or the same as\n * the given version.\n */\ngoog.userAgent.isVersionOrHigher = function(version) {\n 'use strict';\n return goog.userAgent.ASSUME_ANY_VERSION ||\n goog.reflect.cache(\n goog.userAgent.isVersionOrHigherCache_, version, function() {\n 'use strict';\n return goog.string.internal.compareVersions(\n goog.userAgent.VERSION, version) >= 0;\n });\n};\n\n\n/**\n * Whether the IE effective document mode is higher or the same as the given\n * document mode version.\n * NOTE: Only for IE, return false for another browser.\n *\n * @param {number} documentMode The document mode version to check.\n * @return {boolean} Whether the IE effective document mode is higher or the\n * same as the given version.\n */\ngoog.userAgent.isDocumentModeOrHigher = function(documentMode) {\n 'use strict';\n return Number(goog.userAgent.DOCUMENT_MODE) >= documentMode;\n};\n\n\n/**\n * Deprecated alias to `goog.userAgent.isDocumentModeOrHigher`.\n * @param {number} version The version to check.\n * @return {boolean} Whether the IE effective document mode is higher or the\n * same as the given version.\n * @deprecated Use goog.userAgent.isDocumentModeOrHigher().\n */\ngoog.userAgent.isDocumentMode = goog.userAgent.isDocumentModeOrHigher;\n\n\n/**\n * For IE version < 7, documentMode is undefined, so attempt to use the\n * CSS1Compat property to see if we are in standards mode. If we are in\n * standards mode, treat the browser version as the document mode. Otherwise,\n * IE is emulating version 5.\n *\n * NOTE(user): Support for IE < 7 is long gone, so this is now simplified.\n * It returns document.documentMode for IE and undefined for everything else.\n *\n * @type {number|undefined}\n * @const\n */\ngoog.userAgent.DOCUMENT_MODE = (function() {\n 'use strict';\n var doc = goog.global['document'];\n if (!doc || !goog.userAgent.IE) return undefined;\n // This must be an IE user agent.\n var documentMode = goog.userAgent.getDocumentMode_();\n if (documentMode) return documentMode;\n // The user agent version string begins with the major version.\n // Parse the major version and truncate anything following.\n var ieVersion = parseInt(goog.userAgent.VERSION, 10);\n return ieVersion || undefined;\n})();\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Closure user agent detection (Browser).\n * @see <a href=\"http://www.useragentstring.com/\">User agent strings</a>\n * For more information on rendering engine, platform, or device see the other\n * sub-namespaces in goog.labs.userAgent, goog.labs.userAgent.platform,\n * goog.labs.userAgent.device respectively.)\n */\n\ngoog.module('goog.labs.userAgent.browser');\ngoog.module.declareLegacyNamespace();\n\nconst util = goog.require('goog.labs.userAgent.util');\nconst {AsyncValue, Version} = goog.require('goog.labs.userAgent.highEntropy.highEntropyValue');\nconst {assert, assertExists} = goog.require('goog.asserts');\nconst {compareVersions} = goog.require('goog.string.internal');\nconst {fullVersionList} = goog.require('goog.labs.userAgent.highEntropy.highEntropyData');\nconst {useClientHints} = goog.require('goog.labs.userAgent');\n\n// TODO(nnaze): Refactor to remove excessive exclusion logic in matching\n// functions.\n\n/**\n * A browser brand represents an opaque string that is used for making\n * brand-specific version checks in userAgentData.\n * @enum {string}\n */\nconst Brand = {\n /**\n * The browser brand for Android Browser.\n * Do not depend on the value of this string. Because Android Browser has not\n * implemented userAgentData yet, the value of this string is not guaranteed\n * to stay the same in future revisions.\n */\n ANDROID_BROWSER: 'Android Browser',\n /**\n * The browser brand for Chromium, including Chromium-based Edge and Opera.\n */\n CHROMIUM: 'Chromium',\n /**\n * The browser brand for Edge.\n * This brand can be used to get the version of both EdgeHTML and\n * Chromium-based Edge.\n */\n EDGE: 'Microsoft Edge',\n /**\n * The browser brand for Firefox.\n * Do not depend on the value of this string. Because Firefox has not\n * implemented userAgentData yet, the value of this string is not guaranteed\n * to stay the same in future revisions.\n */\n FIREFOX: 'Firefox',\n /**\n * The browser brand for Internet Explorer.\n * Do not depend on the value of this string. Because IE will never support\n * userAgentData, the value of this string should be treated as opaque (it's\n * used internally for legacy-userAgent fallback).\n */\n IE: 'Internet Explorer',\n /**\n * The browser brand for Opera.\n * This brand can be used to get the version of both Presto- and\n * Chromium-based Opera.\n */\n OPERA: 'Opera',\n /**\n * The browser brand for Safari.\n * Do not depend on the value of this string. Because Safari has not\n * implemented userAgentData yet, the value of this string is not guaranteed\n * to stay the same in future revisions.\n */\n SAFARI: 'Safari',\n /**\n * The browser brand for Silk.\n * See\n * https://docs.aws.amazon.com/silk/latest/developerguide/what-is-silk.html\n * Do not depend on the value of this string. Because Silk does not\n * identify itself in userAgentData yet, the value of this string is not\n * guaranteed to stay the same in future revisions.\n */\n SILK: 'Silk',\n};\nexports.Brand = Brand;\n\n/**\n * @param {boolean=} ignoreClientHintsFlag Iff truthy, the `useClientHints`\n * function will not be called when evaluating if User-Agent Client Hints\n * Brand data can be used. For existing labs.userAgent API surfaces with\n * widespread use, this should be a falsy value so that usage of the Client\n * Hints APIs can be gated behind flags / experiment rollouts.\n * @return {boolean} Whether to use navigator.userAgentData to determine\n * browser's brand.\n */\nfunction useUserAgentDataBrand(ignoreClientHintsFlag = false) {\n if (util.ASSUME_CLIENT_HINTS_SUPPORT) return true;\n // High-entropy API surfaces should not be gated behind the useClientHints\n // check (as in production it is gated behind a define).\n if (!ignoreClientHintsFlag && !useClientHints()) return false;\n const userAgentData = util.getUserAgentData();\n return !!userAgentData && userAgentData.brands.length > 0;\n}\n\n/**\n * @return {boolean} Whether this browser is likely to have the fullVersionList\n * high-entropy Client Hint.\n */\nfunction hasFullVersionList() {\n // https://chromiumdash.appspot.com/commits?commit=1eb643c3057e64ff4d22468432ad16c4cab12879&platform=Linux\n // indicates that for all platforms Chromium 98 shipped this feature.\n // See also\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-CH-UA-Full-Version-List#browser_compatibility\n return isAtLeast(Brand.CHROMIUM, 98);\n}\n\n/**\n * @return {boolean} Whether the user's browser is Opera. Note: Chromium based\n * Opera (Opera 15+) is detected as Chrome to avoid unnecessary special\n * casing.\n */\nfunction matchOpera() {\n if (useUserAgentDataBrand()) {\n // Pre-Chromium Edge doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Opera');\n}\n\n/** @return {boolean} Whether the user's browser is IE. */\nfunction matchIE() {\n if (useUserAgentDataBrand()) {\n // IE doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Trident') || util.matchUserAgent('MSIE');\n}\n\n/**\n * @return {boolean} Whether the user's browser is Edge. This refers to\n * EdgeHTML based Edge.\n */\nfunction matchEdgeHtml() {\n if (useUserAgentDataBrand()) {\n // Pre-Chromium Edge doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Edge');\n}\n\n/** @return {boolean} Whether the user's browser is Chromium based Edge. */\nfunction matchEdgeChromium() {\n if (useUserAgentDataBrand()) {\n return util.matchUserAgentDataBrand(Brand.EDGE);\n }\n return util.matchUserAgent('Edg/');\n}\n\n/** @return {boolean} Whether the user's browser is Chromium based Opera. */\nfunction matchOperaChromium() {\n if (useUserAgentDataBrand()) {\n return util.matchUserAgentDataBrand(Brand.OPERA);\n }\n return util.matchUserAgent('OPR');\n}\n\n/** @return {boolean} Whether the user's browser is Firefox. */\nfunction matchFirefox() {\n // Firefox doesn't support navigator.userAgentData yet, so use\n // navigator.userAgent.\n return util.matchUserAgent('Firefox') || util.matchUserAgent('FxiOS');\n}\n\n/** @return {boolean} Whether the user's browser is Safari. */\nfunction matchSafari() {\n // Apple-based browsers don't support navigator.userAgentData yet, so use\n // navigator.userAgent.\n return util.matchUserAgent('Safari') &&\n !(matchChrome() || matchCoast() || matchOpera() || matchEdgeHtml() ||\n matchEdgeChromium() || matchOperaChromium() || matchFirefox() ||\n isSilk() || util.matchUserAgent('Android'));\n}\n\n/**\n * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based\n * iOS browser).\n */\nfunction matchCoast() {\n if (useUserAgentDataBrand()) {\n // Coast doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Coast');\n}\n\n/** @return {boolean} Whether the user's browser is iOS Webview. */\nfunction matchIosWebview() {\n // Apple-based browsers don't support navigator.userAgentData yet, so use\n // navigator.userAgent.\n // iOS Webview does not show up as Chrome or Safari.\n return (util.matchUserAgent('iPad') || util.matchUserAgent('iPhone')) &&\n !matchSafari() && !matchChrome() && !matchCoast() && !matchFirefox() &&\n util.matchUserAgent('AppleWebKit');\n}\n\n/**\n * @return {boolean} Whether the user's browser is any Chromium browser. This\n * returns true for Chrome, Opera 15+, and Edge Chromium.\n */\nfunction matchChrome() {\n if (useUserAgentDataBrand()) {\n return util.matchUserAgentDataBrand(Brand.CHROMIUM);\n }\n return ((util.matchUserAgent('Chrome') || util.matchUserAgent('CriOS')) &&\n !matchEdgeHtml()) ||\n isSilk();\n}\n\n/** @return {boolean} Whether the user's browser is the Android browser. */\nfunction matchAndroidBrowser() {\n // Android can appear in the user agent string for Chrome on Android.\n // This is not the Android standalone browser if it does.\n return util.matchUserAgent('Android') &&\n !(isChrome() || isFirefox() || isOpera() || isSilk());\n}\n\n/** @return {boolean} Whether the user's browser is Opera. */\nconst isOpera = matchOpera;\nexports.isOpera = isOpera;\n\n/** @return {boolean} Whether the user's browser is IE. */\nconst isIE = matchIE;\nexports.isIE = isIE;\n\n/** @return {boolean} Whether the user's browser is EdgeHTML based Edge. */\nconst isEdge = matchEdgeHtml;\nexports.isEdge = isEdge;\n\n/** @return {boolean} Whether the user's browser is Chromium based Edge. */\nconst isEdgeChromium = matchEdgeChromium;\nexports.isEdgeChromium = isEdgeChromium;\n\n/** @return {boolean} Whether the user's browser is Chromium based Opera. */\nconst isOperaChromium = matchOperaChromium;\nexports.isOperaChromium = isOperaChromium;\n\n/** @return {boolean} Whether the user's browser is Firefox. */\nconst isFirefox = matchFirefox;\nexports.isFirefox = isFirefox;\n\n/** @return {boolean} Whether the user's browser is Safari. */\nconst isSafari = matchSafari;\nexports.isSafari = isSafari;\n\n/**\n * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based\n * iOS browser).\n */\nconst isCoast = matchCoast;\nexports.isCoast = isCoast;\n\n/** @return {boolean} Whether the user's browser is iOS Webview. */\nconst isIosWebview = matchIosWebview;\nexports.isIosWebview = isIosWebview;\n\n/**\n * @return {boolean} Whether the user's browser is any Chromium based browser (\n * Chrome, Blink-based Opera (15+) and Edge Chromium).\n */\nconst isChrome = matchChrome;\nexports.isChrome = isChrome;\n\n/** @return {boolean} Whether the user's browser is the Android browser. */\nconst isAndroidBrowser = matchAndroidBrowser;\nexports.isAndroidBrowser = isAndroidBrowser;\n\n/**\n * For more information, see:\n * http://docs.aws.amazon.com/silk/latest/developerguide/user-agent.html\n * @return {boolean} Whether the user's browser is Silk.\n */\nfunction isSilk() {\n // As of Silk 93, Silk does not identify itself in userAgentData.brands.\n // When Silk changes this behavior, update this method to call\n // matchUserAgentDataBrand (akin to isChrome, etc.)\n return util.matchUserAgent('Silk');\n}\nexports.isSilk = isSilk;\n\n/**\n * A helper function that returns a function mapping a list of candidate\n * version tuple keys to the first version string present under a key.\n * Ex:\n * <code>\n * // Arg extracted from \"Foo/1.2.3 Bar/0.2021\"\n * const mapVersion = createVersionMap([[\"Foo\", \"1.2.3\"], [\"Bar\", \"0.2021\"]]);\n * mapVersion([\"Bar\", \"Foo\"]); // returns \"0.2021\"\n * mapVersion([\"Baz\", \"Foo\"]); // returns \"1.2.3\"\n * mapVersion([\"Baz\", \"???\"]); // returns \"\"\n * </code>\n * @param {!Array<!Array<string>>} versionTuples Version tuples pre-extracted\n * from a user agent string.\n * @return {function(!Array<string>): string} The version string, or empty\n * string if it doesn't exist under the given key.\n */\nfunction createVersionMap(versionTuples) {\n // Construct a map for easy lookup.\n const versionMap = {};\n versionTuples.forEach((tuple) => {\n // Note that the tuple is of length three, but we only care about the\n // first two.\n const key = tuple[0];\n const value = tuple[1];\n versionMap[key] = value;\n });\n\n // Gives the value with the first key it finds, otherwise empty string.\n return (keys) => versionMap[keys.find((key) => key in versionMap)] || '';\n}\n\n/**\n * Returns the browser version.\n *\n * Note that for browsers with multiple brands, this function assumes a primary\n * brand and returns the version for that brand.\n *\n * Additionally, this function is not userAgentData-aware and will return\n * incorrect values when the User Agent string is frozen. The current status of\n * User Agent string freezing is available here:\n * https://www.chromestatus.com/feature/5704553745874944\n *\n * To mitigate both of these potential issues, use\n * getVersionStringForLogging() or fullVersionOf() instead.\n *\n * @return {string} The browser version or empty string if version cannot be\n * determined. Note that for Internet Explorer, this returns the version of\n * the browser, not the version of the rendering engine. (IE 8 in\n * compatibility mode will return 8.0 rather than 7.0. To determine the\n * rendering engine version, look at document.documentMode instead. See\n * http://msdn.microsoft.com/en-us/library/cc196988(v=vs.85).aspx for more\n * details.)\n */\nfunction getVersion() {\n const userAgentString = util.getUserAgent();\n\n // Special case IE since IE's version is inside the parenthesis and\n // without the '/'.\n if (isIE()) {\n return getIEVersion(userAgentString);\n }\n\n const versionTuples = util.extractVersionTuples(userAgentString);\n const lookUpValueWithKeys = createVersionMap(versionTuples);\n\n // Check Opera before Chrome since Opera 15+ has \"Chrome\" in the string.\n // See\n // http://my.opera.com/ODIN/blog/2013/07/15/opera-user-agent-strings-opera-15-and-beyond\n if (isOpera()) {\n // Opera 10 has Version/10.0 but Opera/9.8, so look for \"Version\" first.\n // Opera uses 'OPR' for more recent UAs.\n return lookUpValueWithKeys(['Version', 'Opera']);\n }\n\n // Check Edge before Chrome since it has Chrome in the string.\n if (isEdge()) {\n return lookUpValueWithKeys(['Edge']);\n }\n\n // Check Chromium Edge before Chrome since it has Chrome in the string.\n if (isEdgeChromium()) {\n return lookUpValueWithKeys(['Edg']);\n }\n\n // Check Silk before Chrome since it may have Chrome in its string and be\n // treated as Chrome.\n if (isSilk()) {\n return lookUpValueWithKeys(['Silk']);\n }\n\n if (isChrome()) {\n return lookUpValueWithKeys(['Chrome', 'CriOS', 'HeadlessChrome']);\n }\n\n // Usually products browser versions are in the third tuple after \"Mozilla\"\n // and the engine.\n const tuple = versionTuples[2];\n return tuple && tuple[1] || '';\n}\nexports.getVersion = getVersion;\n\n/**\n * Returns whether the current browser's version is at least as high as the\n * given one.\n *\n * Note that for browsers with multiple brands, this function assumes a primary\n * brand and checks the version for that brand.\n *\n * Additionally, this function is not userAgentData-aware and will return\n * incorrect values when the User Agent string is frozen. The current status of\n * User Agent string freezing is available here:\n * https://www.chromestatus.com/feature/5704553745874944\n *\n * To mitigate both of these potential issues, use isAtLeast()/isAtMost() or\n * fullVersionOf() instead.\n *\n * @param {string|number} version The version to check.\n * @return {boolean} Whether the browser version is higher or the same as the\n * given version.\n * @deprecated Use isAtLeast()/isAtMost() instead.\n */\nfunction isVersionOrHigher(version) {\n return compareVersions(getVersion(), version) >= 0;\n}\nexports.isVersionOrHigher = isVersionOrHigher;\n\n/**\n * A helper function to determine IE version. More information:\n * http://msdn.microsoft.com/en-us/library/ie/bg182625(v=vs.85).aspx#uaString\n * http://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx\n * http://blogs.msdn.com/b/ie/archive/2010/03/23/introducing-ie9-s-user-agent-string.aspx\n * http://blogs.msdn.com/b/ie/archive/2009/01/09/the-internet-explorer-8-user-agent-string-updated-edition.aspx\n * @param {string} userAgent the User-Agent.\n * @return {string}\n */\nfunction getIEVersion(userAgent) {\n // IE11 may identify itself as MSIE 9.0 or MSIE 10.0 due to an IE 11 upgrade\n // bug. Example UA:\n // Mozilla/5.0 (MSIE 9.0; Windows NT 6.1; WOW64; Trident/7.0; rv:11.0)\n // like Gecko.\n // See http://www.whatismybrowser.com/developers/unknown-user-agent-fragments.\n const rv = /rv: *([\\d\\.]*)/.exec(userAgent);\n if (rv && rv[1]) {\n return rv[1];\n }\n\n let version = '';\n const msie = /MSIE +([\\d\\.]+)/.exec(userAgent);\n if (msie && msie[1]) {\n // IE in compatibility mode usually identifies itself as MSIE 7.0; in this\n // case, use the Trident version to determine the version of IE. For more\n // details, see the links above.\n const tridentVersion = /Trident\\/(\\d.\\d)/.exec(userAgent);\n if (msie[1] == '7.0') {\n if (tridentVersion && tridentVersion[1]) {\n switch (tridentVersion[1]) {\n case '4.0':\n version = '8.0';\n break;\n case '5.0':\n version = '9.0';\n break;\n case '6.0':\n version = '10.0';\n break;\n case '7.0':\n version = '11.0';\n break;\n }\n } else {\n version = '7.0';\n }\n } else {\n version = msie[1];\n }\n }\n return version;\n}\n\n/**\n * A helper function to return the navigator.userAgent-supplied full version\n * number of the current browser or an empty string, based on whether the\n * current browser is the one specified.\n * @param {string} browser The brand whose version should be returned.\n * @return {string}\n */\nfunction getFullVersionFromUserAgentString(browser) {\n const userAgentString = util.getUserAgent();\n // Special case IE since IE's version is inside the parenthesis and\n // without the '/'.\n if (browser === Brand.IE) {\n return isIE() ? getIEVersion(userAgentString) : '';\n }\n\n const versionTuples = util.extractVersionTuples(userAgentString);\n const lookUpValueWithKeys = createVersionMap(versionTuples);\n switch (browser) {\n case Brand.OPERA:\n // Opera 10 has Version/10.0 but Opera/9.8, so look for \"Version\"\n // first. Opera uses 'OPR' for more recent UAs.\n if (isOpera()) {\n return lookUpValueWithKeys(['Version', 'Opera']);\n } else if (isOperaChromium()) {\n return lookUpValueWithKeys(['OPR']);\n }\n break;\n case Brand.EDGE:\n if (isEdge()) {\n return lookUpValueWithKeys(['Edge']);\n } else if (isEdgeChromium()) {\n return lookUpValueWithKeys(['Edg']);\n }\n break;\n case Brand.CHROMIUM:\n if (isChrome()) {\n return lookUpValueWithKeys(['Chrome', 'CriOS', 'HeadlessChrome']);\n }\n break;\n }\n\n // For the following browsers, the browser version is in the third tuple after\n // \"Mozilla\" and the engine.\n if ((browser === Brand.FIREFOX && isFirefox()) ||\n (browser === Brand.SAFARI && isSafari()) ||\n (browser === Brand.ANDROID_BROWSER && isAndroidBrowser()) ||\n (browser === Brand.SILK && isSilk())) {\n const tuple = versionTuples[2];\n return tuple && tuple[1] || '';\n }\n\n return '';\n}\n\n/**\n * Returns the major version of the given browser brand, or NaN if the current\n * browser is not the given brand.\n * Note that the major version number may be different depending on which\n * browser is specified. The returned value can be used to make browser version\n * comparisons using comparison operators.\n * @private\n * @param {!Brand} browser The brand whose version should be returned.\n * @return {number} The major version number associated with the current\n * browser under the given brand, or NaN if the current browser doesn't match\n * the given brand.\n */\nfunction versionOf_(browser) {\n let versionParts;\n // Silk currently does not identify itself in its userAgentData.brands array,\n // so if checking its version, always fall back to the user agent string.\n if (useUserAgentDataBrand() && browser !== Brand.SILK) {\n const data = util.getUserAgentData();\n const matchingBrand = data.brands.find(({brand}) => brand === browser);\n if (!matchingBrand || !matchingBrand.version) {\n return NaN;\n }\n versionParts = matchingBrand.version.split('.');\n } else {\n const fullVersion = getFullVersionFromUserAgentString(browser);\n if (fullVersion === '') {\n return NaN;\n }\n versionParts = fullVersion.split('.');\n }\n if (versionParts.length === 0) {\n return NaN;\n }\n const majorVersion = versionParts[0];\n return Number(majorVersion); // Returns NaN if it is not parseable.\n}\n\n/**\n * Returns true if the current browser matches the given brand and is at least\n * the given major version. The major version must be a whole number (i.e.\n * decimals should not be used to represent a minor version).\n * @param {!Brand} brand The brand whose version should be returned.\n * @param {number} majorVersion The major version number to compare against.\n * This must be a whole number.\n * @return {boolean} Whether the current browser both matches the given brand\n * and is at least the given version.\n */\nfunction isAtLeast(brand, majorVersion) {\n assert(\n Math.floor(majorVersion) === majorVersion,\n 'Major version must be an integer');\n return versionOf_(brand) >= majorVersion;\n}\nexports.isAtLeast = isAtLeast;\n\n/**\n * Returns true if the current browser matches the given brand and is at most\n * the given version. The major version must be a whole number (i.e. decimals\n * should not be used to represent a minor version).\n * @param {!Brand} brand The brand whose version should be returned.\n * @param {number} majorVersion The major version number to compare against.\n * This must be a whole number.\n * @return {boolean} Whether the current browser both matches the given brand\n * and is at most the given version.\n */\nfunction isAtMost(brand, majorVersion) {\n assert(\n Math.floor(majorVersion) === majorVersion,\n 'Major version must be an integer');\n return versionOf_(brand) <= majorVersion;\n}\nexports.isAtMost = isAtMost;\n\n/**\n * Loads the high-entropy browser brand/version data and wraps the correct\n * version string in a Version object.\n * @implements {AsyncValue<!Version>}\n */\nclass HighEntropyBrandVersion {\n /**\n * @param {string} brand The brand whose version is retrieved in this\n * container.\n * @param {boolean} useUach Whether to attempt to use the User-Agent Client\n * Hints (UACH) API surface.\n * @param {string} fallbackVersion The fallback version derived from the\n * userAgent string.\n */\n constructor(brand, useUach, fallbackVersion) {\n /** @private @const {string} */\n this.brand_ = brand;\n\n /** @private @const {!Version} */\n this.version_ = new Version(fallbackVersion);\n\n /** @private @const {boolean} */\n this.useUach_ = useUach;\n }\n\n /**\n * @return {!Version|undefined}\n * @override\n */\n getIfLoaded() {\n if (this.useUach_) {\n const loadedVersionList = fullVersionList.getIfLoaded();\n if (loadedVersionList !== undefined) {\n const matchingBrand =\n loadedVersionList.find(({brand}) => this.brand_ === brand);\n // We assumed in fullVersionOf that if the fullVersionList is defined\n // the brands must match. Double-check this here.\n assertExists(matchingBrand);\n return new Version(matchingBrand.version);\n }\n // Fallthrough to fallback on Pre-UACH implementation\n }\n // We want to make sure the loading semantics of the Pre-UACH implementation\n // match those of the UACH implementation. Loading must happen before any\n // data can be retrieved from getIfLoaded.\n // For HighEntropyBrandVersion, loading can either be done by calling #load\n // or by calling the module-local loadFullVersions function.\n if (preUachHasLoaded) {\n return this.version_;\n }\n return;\n }\n\n /**\n * @return {!Promise<!Version>}\n * @override\n */\n async load() {\n if (this.useUach_) {\n const loadedVersionList = await fullVersionList.load();\n if (loadedVersionList !== undefined) {\n const matchingBrand =\n loadedVersionList.find(({brand}) => this.brand_ === brand);\n assertExists(matchingBrand);\n return new Version(matchingBrand.version);\n }\n // Fallthrough to fallback on Pre-UACH implementation\n } else {\n // Await something so that calling load with or without UACH API\n // availability results in waiting at least one macrotask before allowing\n // access to the cached version information.\n await 0;\n }\n // Regardless of whether we are using UACH APIs, we can now allow access to\n // the fallback case\n preUachHasLoaded = true;\n return this.version_;\n }\n}\n\n/**\n * Whether full version data should be considered available when using UACH\n * fallback implementations. This is flipped to true when either\n * loadFullVersions or HighEntropyBrandVersion.prototype.load are called,\n * matching the global singleton semantics of the UACH codepaths.\n */\nlet preUachHasLoaded = false;\n\n/**\n * Requests all full browser versions to be cached. When the returned promise\n * resolves, subsequent calls to `fullVersionOf(...).getIfLoaded()` will return\n * a value.\n *\n * This method should be avoided in favor of directly awaiting\n * `fullVersionOf(...).load()` where it is used.\n *\n * @return {!Promise<void>}\n */\nasync function loadFullVersions() {\n if (useUserAgentDataBrand(true)) {\n await fullVersionList.load();\n }\n preUachHasLoaded = true;\n}\nexports.loadFullVersions = loadFullVersions;\n\n/**\n * Resets module-local caches used by functionality in this module.\n * This is only for use by goog.labs.userAgent.testUtil.resetUserAgent (and\n * labs.userAgent tests).\n * @package\n */\nexports.resetForTesting = () => {\n preUachHasLoaded = false;\n fullVersionList.resetForTesting();\n};\n\n\n/**\n * Returns an object that provides access to the full version string of the\n * current browser -- or undefined, based on whether the current browser matches\n * the requested browser brand. Note that the full version string is a\n * high-entropy value, and must be asynchronously loaded before it can be\n * accessed synchronously.\n * @param {!Brand} browser The brand whose version should be returned.\n * @return {!AsyncValue<!Version>|undefined} An object that can be used\n * to get or load the full version string as a high-entropy value, or\n * undefined if the current browser doesn't match the given brand.\n */\nfunction fullVersionOf(browser) {\n let fallbackVersionString = '';\n // If we are reasonably certain now that the browser we are on has the\n // fullVersionList high-entropy hint, then we can skip computing the fallback\n // value as we won't end up using it.\n if (!hasFullVersionList()) {\n fallbackVersionString = getFullVersionFromUserAgentString(browser);\n }\n // Silk has the UACH API surface, but currently does not identify itself in\n // the userAgentData.brands array. Fallback to using userAgent string version\n // for Silk.\n const useUach = browser !== Brand.SILK && useUserAgentDataBrand(true);\n if (useUach) {\n const data = util.getUserAgentData();\n // Operate under the assumption that the low-entropy and high-entropy lists\n // of brand/version pairs contain an identical set of brands. Therefore, if\n // the low-entropy list doesn't contain the given brand, return undefined.\n if (!data.brands.find(({brand}) => brand === browser)) {\n return undefined;\n }\n } else if (fallbackVersionString === '') {\n return undefined;\n }\n return new HighEntropyBrandVersion(browser, useUach, fallbackVersionString);\n}\nexports.fullVersionOf = fullVersionOf;\n\n\n/**\n * Returns a version string for the current browser or undefined, based on\n * whether the current browser is the one specified.\n * This value should ONLY be used for logging/debugging purposes. Do not use it\n * to branch code paths. For comparing versions, use isAtLeast()/isAtMost() or\n * fullVersionOf() instead.\n * @param {!Brand} browser The brand whose version should be returned.\n * @return {string} The version as a string.\n */\nfunction getVersionStringForLogging(browser) {\n if (useUserAgentDataBrand(true)) {\n const fullVersionObj = fullVersionOf(browser);\n if (fullVersionObj) {\n const fullVersion = fullVersionObj.getIfLoaded();\n if (fullVersion) {\n return fullVersion.toVersionStringForLogging();\n }\n // No full version, return the major version instead.\n const data = util.getUserAgentData();\n const matchingBrand = data.brands.find(({brand}) => brand === browser);\n // Checking for the existence of matchingBrand is not necessary because\n // the existence of fullVersionObj implies that there is already a\n // matching brand.\n assertExists(matchingBrand);\n return matchingBrand.version;\n }\n // If fullVersionObj is undefined, this doesn't mean that the full version\n // is unavailable, but rather that the current browser doesn't match the\n // input `browser` argument.\n return '';\n } else {\n return getFullVersionFromUserAgentString(browser);\n }\n}\nexports.getVersionStringForLogging = getVersionStringForLogging;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Closure user agent detection.\n * @see http://en.wikipedia.org/wiki/User_agent\n * For more information on browser brand, platform, or device see the other\n * sub-namespaces in goog.labs.userAgent (browser, platform, and device).\n */\n\ngoog.module('goog.labs.userAgent.engine');\ngoog.module.declareLegacyNamespace();\n\nconst googArray = goog.require('goog.array');\nconst googString = goog.require('goog.string.internal');\nconst util = goog.require('goog.labs.userAgent.util');\n\n/**\n * @return {boolean} Whether the rendering engine is Presto.\n */\nfunction isPresto() {\n return util.matchUserAgent('Presto');\n}\n\n/**\n * @return {boolean} Whether the rendering engine is Trident.\n */\nfunction isTrident() {\n // IE only started including the Trident token in IE8.\n return util.matchUserAgent('Trident') || util.matchUserAgent('MSIE');\n}\n\n/**\n * @return {boolean} Whether the rendering engine is EdgeHTML.\n */\nfunction isEdge() {\n return util.matchUserAgent('Edge');\n}\n\n/**\n * @return {boolean} Whether the rendering engine is WebKit. This will return\n * true for Chrome, Blink-based Opera (15+), Edge Chromium and Safari.\n */\nfunction isWebKit() {\n return util.matchUserAgentIgnoreCase('WebKit') && !isEdge();\n}\n\n/**\n * @return {boolean} Whether the rendering engine is Gecko.\n */\nfunction isGecko() {\n return util.matchUserAgent('Gecko') && !isWebKit() && !isTrident() &&\n !isEdge();\n}\n\n/**\n * @return {string} The rendering engine's version or empty string if version\n * can't be determined.\n */\nfunction getVersion() {\n const userAgentString = util.getUserAgent();\n if (userAgentString) {\n const tuples = util.extractVersionTuples(userAgentString);\n\n const engineTuple = getEngineTuple(tuples);\n if (engineTuple) {\n // In Gecko, the version string is either in the browser info or the\n // Firefox version. See Gecko user agent string reference:\n // http://goo.gl/mULqa\n if (engineTuple[0] == 'Gecko') {\n return getVersionForKey(tuples, 'Firefox');\n }\n\n return engineTuple[1];\n }\n\n // MSIE has only one version identifier, and the Trident version is\n // specified in the parenthetical. IE Edge is covered in the engine tuple\n // detection.\n const browserTuple = tuples[0];\n let info;\n if (browserTuple && (info = browserTuple[2])) {\n const match = /Trident\\/([^\\s;]+)/.exec(info);\n if (match) {\n return match[1];\n }\n }\n }\n return '';\n}\n\n/**\n * @param {!Array<!Array<string>>} tuples Extracted version tuples.\n * @return {!Array<string>|undefined} The engine tuple or undefined if not\n * found.\n */\nfunction getEngineTuple(tuples) {\n if (!isEdge()) {\n return tuples[1];\n }\n for (let i = 0; i < tuples.length; i++) {\n const tuple = tuples[i];\n if (tuple[0] == 'Edge') {\n return tuple;\n }\n }\n}\n\n/**\n * @param {string|number} version The version to check.\n * @return {boolean} Whether the rendering engine version is higher or the same\n * as the given version.\n */\nfunction isVersionOrHigher(version) {\n return googString.compareVersions(getVersion(), version) >= 0;\n}\n\n/**\n * @param {!Array<!Array<string>>} tuples Version tuples.\n * @param {string} key The key to look for.\n * @return {string} The version string of the given key, if present.\n * Otherwise, the empty string.\n */\nfunction getVersionForKey(tuples, key) {\n // TODO(nnaze): Move to util if useful elsewhere.\n\n const pair = googArray.find(tuples, function(pair) {\n return key == pair[0];\n });\n\n return pair && pair[1] || '';\n}\n\nexports = {\n getVersion,\n isEdge,\n isGecko,\n isPresto,\n isTrident,\n isVersionOrHigher,\n isWebKit,\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A patched, standardized event object for browser events.\n *\n * <pre>\n * The patched event object contains the following members:\n * - type {string} Event type, e.g. 'click'\n * - target {Object} The element that actually triggered the event\n * - currentTarget {Object} The element the listener is attached to\n * - relatedTarget {Object} For mouseover and mouseout, the previous object\n * - offsetX {number} X-coordinate relative to target\n * - offsetY {number} Y-coordinate relative to target\n * - clientX {number} X-coordinate relative to viewport\n * - clientY {number} Y-coordinate relative to viewport\n * - screenX {number} X-coordinate relative to the edge of the screen\n * - screenY {number} Y-coordinate relative to the edge of the screen\n * - button {number} Mouse button. Use isButton() to test.\n * - keyCode {number} Key-code\n * - ctrlKey {boolean} Was ctrl key depressed\n * - altKey {boolean} Was alt key depressed\n * - shiftKey {boolean} Was shift key depressed\n * - metaKey {boolean} Was meta key depressed\n * - pointerId {number} Pointer ID\n * - pointerType {string} Pointer type, e.g. 'mouse', 'pen', or 'touch'\n * - defaultPrevented {boolean} Whether the default action has been prevented\n * - state {Object} History state object\n *\n * NOTE: The keyCode member contains the raw browser keyCode. For normalized\n * key and character code use {@link goog.events.KeyHandler}.\n * </pre>\n */\n\ngoog.provide('goog.events.BrowserEvent');\ngoog.provide('goog.events.BrowserEvent.MouseButton');\ngoog.provide('goog.events.BrowserEvent.PointerType');\n\ngoog.require('goog.debug');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.EventType');\ngoog.require('goog.reflect');\ngoog.require('goog.userAgent');\n\n/**\n * Accepts a browser event object and creates a patched, cross browser event\n * object.\n * The content of this object will not be initialized if no event object is\n * provided. If this is the case, init() needs to be invoked separately.\n * @param {Event=} opt_e Browser event object.\n * @param {EventTarget=} opt_currentTarget Current target for event.\n * @constructor\n * @extends {goog.events.Event}\n */\ngoog.events.BrowserEvent = function(opt_e, opt_currentTarget) {\n 'use strict';\n goog.events.BrowserEvent.base(this, 'constructor', opt_e ? opt_e.type : '');\n\n /**\n * Target that fired the event.\n * @override\n * @type {?Node}\n */\n this.target = null;\n\n /**\n * Node that had the listener attached.\n * @override\n * @type {?Node|undefined}\n */\n this.currentTarget = null;\n\n /**\n * For mouseover and mouseout events, the related object for the event.\n * @type {?Node}\n */\n this.relatedTarget = null;\n\n /**\n * X-coordinate relative to target.\n * @type {number}\n */\n this.offsetX = 0;\n\n /**\n * Y-coordinate relative to target.\n * @type {number}\n */\n this.offsetY = 0;\n\n /**\n * X-coordinate relative to the window.\n * @type {number}\n */\n this.clientX = 0;\n\n /**\n * Y-coordinate relative to the window.\n * @type {number}\n */\n this.clientY = 0;\n\n /**\n * X-coordinate relative to the monitor.\n * @type {number}\n */\n this.screenX = 0;\n\n /**\n * Y-coordinate relative to the monitor.\n * @type {number}\n */\n this.screenY = 0;\n\n /**\n * Which mouse button was pressed.\n * @type {number}\n */\n this.button = 0;\n\n /**\n * Key of key press.\n * @type {string}\n */\n this.key = '';\n\n /**\n * Keycode of key press.\n * @type {number}\n */\n this.keyCode = 0;\n\n /**\n * Keycode of key press.\n * @type {number}\n */\n this.charCode = 0;\n\n /**\n * Whether control was pressed at time of event.\n * @type {boolean}\n */\n this.ctrlKey = false;\n\n /**\n * Whether alt was pressed at time of event.\n * @type {boolean}\n */\n this.altKey = false;\n\n /**\n * Whether shift was pressed at time of event.\n * @type {boolean}\n */\n this.shiftKey = false;\n\n /**\n * Whether the meta key was pressed at time of event.\n * @type {boolean}\n */\n this.metaKey = false;\n\n /**\n * History state object, only set for PopState events where it's a copy of the\n * state object provided to pushState or replaceState.\n * @type {?Object}\n */\n this.state = null;\n\n /**\n * Whether the default platform modifier key was pressed at time of event.\n * (This is control for all platforms except Mac, where it's Meta.)\n * @type {boolean}\n */\n this.platformModifierKey = false;\n\n /**\n * @type {number}\n */\n this.pointerId = 0;\n\n /**\n * @type {string}\n */\n this.pointerType = '';\n\n /**\n * The browser event object.\n * @private {?Event}\n */\n this.event_ = null;\n\n if (opt_e) {\n this.init(opt_e, opt_currentTarget);\n }\n};\ngoog.inherits(goog.events.BrowserEvent, goog.events.Event);\n\n/**\n * @define {boolean} If true, use the layerX and layerY properties of a native\n * browser event over the offsetX and offsetY properties, which cause expensive\n * reflow. If layerX or layerY is not defined, offsetX and offsetY will be used\n * as usual.\n */\ngoog.events.BrowserEvent.USE_LAYER_XY_AS_OFFSET_XY =\n goog.define('goog.events.BrowserEvent.USE_LAYER_XY_AS_OFFSET_XY', false);\n\n\n/**\n * Normalized button constants for the mouse.\n * @enum {number}\n */\ngoog.events.BrowserEvent.MouseButton = {\n LEFT: 0,\n MIDDLE: 1,\n RIGHT: 2,\n BACK: 3,\n FORWARD: 4,\n};\n\n\n/**\n * Normalized pointer type constants for pointer events.\n * @enum {string}\n */\ngoog.events.BrowserEvent.PointerType = {\n MOUSE: 'mouse',\n PEN: 'pen',\n TOUCH: 'touch'\n};\n\n\n/**\n * Static data for mapping mouse buttons.\n * @type {!Array<number>}\n * @deprecated Use `goog.events.BrowserEvent.IE_BUTTON_MAP` instead.\n */\ngoog.events.BrowserEvent.IEButtonMap = goog.debug.freeze([\n 1, // LEFT\n 4, // MIDDLE\n 2 // RIGHT\n]);\n\n\n/**\n * Static data for mapping mouse buttons.\n * @const {!Array<number>}\n */\ngoog.events.BrowserEvent.IE_BUTTON_MAP = goog.events.BrowserEvent.IEButtonMap;\n\n\n/**\n * Static data for mapping MSPointerEvent types to PointerEvent types.\n * @const {!Object<number, goog.events.BrowserEvent.PointerType>}\n */\ngoog.events.BrowserEvent.IE_POINTER_TYPE_MAP = goog.debug.freeze({\n 2: goog.events.BrowserEvent.PointerType.TOUCH,\n 3: goog.events.BrowserEvent.PointerType.PEN,\n 4: goog.events.BrowserEvent.PointerType.MOUSE\n});\n\n\n/**\n * Accepts a browser event object and creates a patched, cross browser event\n * object.\n * @param {Event} e Browser event object.\n * @param {EventTarget=} opt_currentTarget Current target for event.\n */\ngoog.events.BrowserEvent.prototype.init = function(e, opt_currentTarget) {\n 'use strict';\n var type = this.type = e.type;\n\n /**\n * On touch devices use the first \"changed touch\" as the relevant touch.\n * @type {?Touch}\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\n var relevantTouch =\n e.changedTouches && e.changedTouches.length ? e.changedTouches[0] : null;\n\n // TODO(nicksantos): Change this.target to type EventTarget.\n this.target = /** @type {Node} */ (e.target) || e.srcElement;\n\n // TODO(nicksantos): Change this.currentTarget to type EventTarget.\n this.currentTarget = /** @type {Node} */ (opt_currentTarget);\n\n var relatedTarget = /** @type {Node} */ (e.relatedTarget);\n if (relatedTarget) {\n // There's a bug in FireFox where sometimes, relatedTarget will be a\n // chrome element, and accessing any property of it will get a permission\n // denied exception. See:\n // https://bugzilla.mozilla.org/show_bug.cgi?id=497780\n if (goog.userAgent.GECKO) {\n if (!goog.reflect.canAccessProperty(relatedTarget, 'nodeName')) {\n relatedTarget = null;\n }\n }\n } else if (type == goog.events.EventType.MOUSEOVER) {\n relatedTarget = e.fromElement;\n } else if (type == goog.events.EventType.MOUSEOUT) {\n relatedTarget = e.toElement;\n }\n\n this.relatedTarget = relatedTarget;\n\n if (relevantTouch) {\n this.clientX = relevantTouch.clientX !== undefined ? relevantTouch.clientX :\n relevantTouch.pageX;\n this.clientY = relevantTouch.clientY !== undefined ? relevantTouch.clientY :\n relevantTouch.pageY;\n this.screenX = relevantTouch.screenX || 0;\n this.screenY = relevantTouch.screenY || 0;\n } else {\n if (goog.events.BrowserEvent.USE_LAYER_XY_AS_OFFSET_XY) {\n this.offsetX = (e.layerX !== undefined) ? e.layerX : e.offsetX;\n this.offsetY = (e.layerY !== undefined) ? e.layerY : e.offsetY;\n } else {\n // Webkit emits a lame warning whenever layerX/layerY is accessed.\n // http://code.google.com/p/chromium/issues/detail?id=101733\n this.offsetX = (goog.userAgent.WEBKIT || e.offsetX !== undefined) ?\n e.offsetX :\n e.layerX;\n this.offsetY = (goog.userAgent.WEBKIT || e.offsetY !== undefined) ?\n e.offsetY :\n e.layerY;\n }\n this.clientX = e.clientX !== undefined ? e.clientX : e.pageX;\n this.clientY = e.clientY !== undefined ? e.clientY : e.pageY;\n this.screenX = e.screenX || 0;\n this.screenY = e.screenY || 0;\n }\n\n this.button = e.button;\n\n this.keyCode = e.keyCode || 0;\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n this.key = e.key || '';\n this.charCode = e.charCode || (type == 'keypress' ? e.keyCode : 0);\n this.ctrlKey = e.ctrlKey;\n this.altKey = e.altKey;\n this.shiftKey = e.shiftKey;\n this.metaKey = e.metaKey;\n this.platformModifierKey = goog.userAgent.MAC ? e.metaKey : e.ctrlKey;\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n this.pointerId = e.pointerId || 0;\n this.pointerType = goog.events.BrowserEvent.getPointerType_(e);\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n this.state = e.state;\n this.event_ = e;\n if (e.defaultPrevented) {\n // Sync native event state to internal state via super class, where default\n // prevention is implemented and managed.\n goog.events.BrowserEvent.superClass_.preventDefault.call(this);\n }\n};\n\n\n/**\n * Tests to see which button was pressed during the event. This is really only\n * useful in IE and Gecko browsers. And in IE, it's only useful for\n * mousedown/mouseup events, because click only fires for the left mouse button.\n *\n * Safari 2 only reports the left button being clicked, and uses the value '1'\n * instead of 0. Opera only reports a mousedown event for the middle button, and\n * no mouse events for the right button. Opera has default behavior for left and\n * middle click that can only be overridden via a configuration setting.\n *\n * There's a nice table of this mess at http://www.unixpapa.com/js/mouse.html.\n *\n * @param {goog.events.BrowserEvent.MouseButton} button The button\n * to test for.\n * @return {boolean} True if button was pressed.\n */\ngoog.events.BrowserEvent.prototype.isButton = function(button) {\n 'use strict';\n return this.event_.button == button;\n};\n\n\n/**\n * Whether this has an \"action\"-producing mouse button.\n *\n * By definition, this includes left-click on windows/linux, and left-click\n * without the ctrl key on Macs.\n *\n * @return {boolean} The result.\n */\ngoog.events.BrowserEvent.prototype.isMouseActionButton = function() {\n 'use strict';\n // Ctrl+click should never behave like a left-click on mac, regardless of\n // whether or not the browser will actually ever emit such an event. If\n // we see it, treat it like right-click always.\n return this.isButton(goog.events.BrowserEvent.MouseButton.LEFT) &&\n !(goog.userAgent.MAC && this.ctrlKey);\n};\n\n\n/**\n * @override\n */\ngoog.events.BrowserEvent.prototype.stopPropagation = function() {\n 'use strict';\n goog.events.BrowserEvent.superClass_.stopPropagation.call(this);\n if (this.event_.stopPropagation) {\n this.event_.stopPropagation();\n } else {\n this.event_.cancelBubble = true;\n }\n};\n\n\n/**\n * @override\n */\ngoog.events.BrowserEvent.prototype.preventDefault = function() {\n 'use strict';\n goog.events.BrowserEvent.superClass_.preventDefault.call(this);\n var be = this.event_;\n if (!be.preventDefault) {\n be.returnValue = false;\n } else {\n be.preventDefault();\n }\n};\n\n\n/**\n * @return {Event} The underlying browser event object.\n */\ngoog.events.BrowserEvent.prototype.getBrowserEvent = function() {\n 'use strict';\n return this.event_;\n};\n\n\n/**\n * Extracts the pointer type from the given event.\n * @param {!Event} e\n * @return {string} The pointer type, e.g. 'mouse', 'pen', or 'touch'.\n * @private\n */\ngoog.events.BrowserEvent.getPointerType_ = function(e) {\n 'use strict';\n if (typeof (e.pointerType) === 'string') {\n return e.pointerType;\n }\n // IE10 uses integer codes for pointer type.\n // https://msdn.microsoft.com/en-us/library/hh772359(v=vs.85).aspx\n return goog.events.BrowserEvent.IE_POINTER_TYPE_MAP[e.pointerType] || '';\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.provide('goog.events.EventType');\n\ngoog.require('goog.events.eventTypeHelpers');\ngoog.require('goog.userAgent');\n\n\n/**\n * Constants for event names.\n * @enum {string}\n */\ngoog.events.EventType = {\n // Mouse events\n CLICK: 'click',\n RIGHTCLICK: 'rightclick',\n DBLCLICK: 'dblclick',\n AUXCLICK: 'auxclick',\n MOUSEDOWN: 'mousedown',\n MOUSEUP: 'mouseup',\n MOUSEOVER: 'mouseover',\n MOUSEOUT: 'mouseout',\n MOUSEMOVE: 'mousemove',\n MOUSEENTER: 'mouseenter',\n MOUSELEAVE: 'mouseleave',\n\n // Non-existent event; will never fire. This exists as a mouse counterpart to\n // POINTERCANCEL.\n MOUSECANCEL: 'mousecancel',\n\n // Selection events.\n // https://www.w3.org/TR/selection-api/\n SELECTIONCHANGE: 'selectionchange',\n SELECTSTART: 'selectstart', // IE, Safari, Chrome\n\n // Wheel events\n // http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents\n WHEEL: 'wheel',\n\n // Key events\n KEYPRESS: 'keypress',\n KEYDOWN: 'keydown',\n KEYUP: 'keyup',\n\n // Focus\n BLUR: 'blur',\n FOCUS: 'focus',\n DEACTIVATE: 'deactivate', // IE only\n FOCUSIN: 'focusin',\n FOCUSOUT: 'focusout',\n\n // Forms\n CHANGE: 'change',\n RESET: 'reset',\n SELECT: 'select',\n SUBMIT: 'submit',\n INPUT: 'input',\n PROPERTYCHANGE: 'propertychange', // IE only\n\n // Drag and drop\n DRAGSTART: 'dragstart',\n DRAG: 'drag',\n DRAGENTER: 'dragenter',\n DRAGOVER: 'dragover',\n DRAGLEAVE: 'dragleave',\n DROP: 'drop',\n DRAGEND: 'dragend',\n\n // Touch events\n // Note that other touch events exist, but we should follow the W3C list here.\n // http://www.w3.org/TR/touch-events/#list-of-touchevent-types\n TOUCHSTART: 'touchstart',\n TOUCHMOVE: 'touchmove',\n TOUCHEND: 'touchend',\n TOUCHCANCEL: 'touchcancel',\n\n // Misc\n BEFOREUNLOAD: 'beforeunload',\n CONSOLEMESSAGE: 'consolemessage',\n CONTEXTMENU: 'contextmenu',\n DEVICECHANGE: 'devicechange',\n DEVICEMOTION: 'devicemotion',\n DEVICEORIENTATION: 'deviceorientation',\n DOMCONTENTLOADED: 'DOMContentLoaded',\n ERROR: 'error',\n HELP: 'help',\n LOAD: 'load',\n LOSECAPTURE: 'losecapture',\n ORIENTATIONCHANGE: 'orientationchange',\n READYSTATECHANGE: 'readystatechange',\n RESIZE: 'resize',\n SCROLL: 'scroll',\n UNLOAD: 'unload',\n\n // Media events\n CANPLAY: 'canplay',\n CANPLAYTHROUGH: 'canplaythrough',\n DURATIONCHANGE: 'durationchange',\n EMPTIED: 'emptied',\n ENDED: 'ended',\n LOADEDDATA: 'loadeddata',\n LOADEDMETADATA: 'loadedmetadata',\n PAUSE: 'pause',\n PLAY: 'play',\n PLAYING: 'playing',\n PROGRESS: 'progress',\n RATECHANGE: 'ratechange',\n SEEKED: 'seeked',\n SEEKING: 'seeking',\n STALLED: 'stalled',\n SUSPEND: 'suspend',\n TIMEUPDATE: 'timeupdate',\n VOLUMECHANGE: 'volumechange',\n WAITING: 'waiting',\n\n // Media Source Extensions events\n // https://www.w3.org/TR/media-source/#mediasource-events\n SOURCEOPEN: 'sourceopen',\n SOURCEENDED: 'sourceended',\n SOURCECLOSED: 'sourceclosed',\n // https://www.w3.org/TR/media-source/#sourcebuffer-events\n ABORT: 'abort',\n UPDATE: 'update',\n UPDATESTART: 'updatestart',\n UPDATEEND: 'updateend',\n\n // HTML 5 History events\n // See http://www.w3.org/TR/html5/browsers.html#event-definitions-0\n HASHCHANGE: 'hashchange',\n PAGEHIDE: 'pagehide',\n PAGESHOW: 'pageshow',\n POPSTATE: 'popstate',\n\n // Copy and Paste\n // Support is limited. Make sure it works on your favorite browser\n // before using.\n // http://www.quirksmode.org/dom/events/cutcopypaste.html\n COPY: 'copy',\n PASTE: 'paste',\n CUT: 'cut',\n BEFORECOPY: 'beforecopy',\n BEFORECUT: 'beforecut',\n BEFOREPASTE: 'beforepaste',\n\n // HTML5 online/offline events.\n // http://www.w3.org/TR/offline-webapps/#related\n ONLINE: 'online',\n OFFLINE: 'offline',\n\n // HTML 5 worker events\n MESSAGE: 'message',\n CONNECT: 'connect',\n\n // Service Worker Events - ServiceWorkerGlobalScope context\n // See https://w3c.github.io/ServiceWorker/#execution-context-events\n // Note: message event defined in worker events section\n INSTALL: 'install',\n ACTIVATE: 'activate',\n FETCH: 'fetch',\n FOREIGNFETCH: 'foreignfetch',\n MESSAGEERROR: 'messageerror',\n\n // Service Worker Events - Document context\n // See https://w3c.github.io/ServiceWorker/#document-context-events\n STATECHANGE: 'statechange',\n UPDATEFOUND: 'updatefound',\n CONTROLLERCHANGE: 'controllerchange',\n\n // CSS animation events.\n ANIMATIONSTART:\n goog.events.eventTypeHelpers.getVendorPrefixedName('AnimationStart'),\n ANIMATIONEND:\n goog.events.eventTypeHelpers.getVendorPrefixedName('AnimationEnd'),\n ANIMATIONITERATION:\n goog.events.eventTypeHelpers.getVendorPrefixedName('AnimationIteration'),\n\n // CSS transition events. Based on the browser support described at:\n // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility\n TRANSITIONEND:\n goog.events.eventTypeHelpers.getVendorPrefixedName('TransitionEnd'),\n\n // W3C Pointer Events\n // http://www.w3.org/TR/pointerevents/\n POINTERDOWN: 'pointerdown',\n POINTERUP: 'pointerup',\n POINTERCANCEL: 'pointercancel',\n POINTERMOVE: 'pointermove',\n POINTEROVER: 'pointerover',\n POINTEROUT: 'pointerout',\n POINTERENTER: 'pointerenter',\n POINTERLEAVE: 'pointerleave',\n GOTPOINTERCAPTURE: 'gotpointercapture',\n LOSTPOINTERCAPTURE: 'lostpointercapture',\n\n // IE specific events.\n // See http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx\n // Note: these events will be supplanted in IE11.\n MSGESTURECHANGE: 'MSGestureChange',\n MSGESTUREEND: 'MSGestureEnd',\n MSGESTUREHOLD: 'MSGestureHold',\n MSGESTURESTART: 'MSGestureStart',\n MSGESTURETAP: 'MSGestureTap',\n MSGOTPOINTERCAPTURE: 'MSGotPointerCapture',\n MSINERTIASTART: 'MSInertiaStart',\n MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture',\n MSPOINTERCANCEL: 'MSPointerCancel',\n MSPOINTERDOWN: 'MSPointerDown',\n MSPOINTERENTER: 'MSPointerEnter',\n MSPOINTERHOVER: 'MSPointerHover',\n MSPOINTERLEAVE: 'MSPointerLeave',\n MSPOINTERMOVE: 'MSPointerMove',\n MSPOINTEROUT: 'MSPointerOut',\n MSPOINTEROVER: 'MSPointerOver',\n MSPOINTERUP: 'MSPointerUp',\n\n // Native IMEs/input tools events.\n TEXT: 'text',\n // The textInput event is supported in IE9+, but only in lower case. All other\n // browsers use the camel-case event name.\n TEXTINPUT: goog.userAgent.IE ? 'textinput' : 'textInput',\n COMPOSITIONSTART: 'compositionstart',\n COMPOSITIONUPDATE: 'compositionupdate',\n COMPOSITIONEND: 'compositionend',\n\n // The beforeinput event is initially only supported in Safari. See\n // https://bugs.chromium.org/p/chromium/issues/detail?id=342670 for Chrome\n // implementation tracking.\n BEFOREINPUT: 'beforeinput',\n\n // Fullscreen API events. See https://fullscreen.spec.whatwg.org/.\n FULLSCREENCHANGE: 'fullscreenchange',\n // iOS-only fullscreen events. See\n // https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/ControllingMediaWithJavaScript/ControllingMediaWithJavaScript.html\n WEBKITBEGINFULLSCREEN: 'webkitbeginfullscreen',\n WEBKITENDFULLSCREEN: 'webkitendfullscreen',\n\n // Webview tag events\n // See https://developer.chrome.com/apps/tags/webview\n EXIT: 'exit',\n LOADABORT: 'loadabort',\n LOADCOMMIT: 'loadcommit',\n LOADREDIRECT: 'loadredirect',\n LOADSTART: 'loadstart',\n LOADSTOP: 'loadstop',\n RESPONSIVE: 'responsive',\n SIZECHANGED: 'sizechanged',\n UNRESPONSIVE: 'unresponsive',\n\n // HTML5 Page Visibility API. See details at\n // `goog.labs.dom.PageVisibilityMonitor`.\n VISIBILITYCHANGE: 'visibilitychange',\n\n // LocalStorage event.\n STORAGE: 'storage',\n\n // DOM Level 2 mutation events (deprecated).\n DOMSUBTREEMODIFIED: 'DOMSubtreeModified',\n DOMNODEINSERTED: 'DOMNodeInserted',\n DOMNODEREMOVED: 'DOMNodeRemoved',\n DOMNODEREMOVEDFROMDOCUMENT: 'DOMNodeRemovedFromDocument',\n DOMNODEINSERTEDINTODOCUMENT: 'DOMNodeInsertedIntoDocument',\n DOMATTRMODIFIED: 'DOMAttrModified',\n DOMCHARACTERDATAMODIFIED: 'DOMCharacterDataModified',\n\n // Print events.\n BEFOREPRINT: 'beforeprint',\n AFTERPRINT: 'afterprint',\n\n // Web app manifest events.\n BEFOREINSTALLPROMPT: 'beforeinstallprompt',\n APPINSTALLED: 'appinstalled',\n\n // Web Animation API (WAAPI) playback events\n // https://www.w3.org/TR/web-animations-1/#animation-playback-event-types\n CANCEL: 'cancel',\n FINISH: 'finish',\n REMOVE: 'remove'\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview An interface for a listenable JavaScript object.\n */\n\ngoog.provide('goog.events.Listenable');\n\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventLike');\ngoog.requireType('goog.events.ListenableKey');\n\n\n/**\n * A listenable interface. A listenable is an object with the ability\n * to dispatch/broadcast events to \"event listeners\" registered via\n * listen/listenOnce.\n *\n * The interface allows for an event propagation mechanism similar\n * to one offered by native browser event targets, such as\n * capture/bubble mechanism, stopping propagation, and preventing\n * default actions. Capture/bubble mechanism depends on the ancestor\n * tree constructed via `#getParentEventTarget`; this tree\n * must be directed acyclic graph. The meaning of default action(s)\n * in preventDefault is specific to a particular use case.\n *\n * Implementations that do not support capture/bubble or can not have\n * a parent listenable can simply not implement any ability to set the\n * parent listenable (and have `#getParentEventTarget` return\n * null).\n *\n * Implementation of this class can be used with or independently from\n * goog.events.\n *\n * Implementation must call `#addImplementation(implClass)`.\n *\n * @interface\n * @see goog.events\n * @see http://www.w3.org/TR/DOM-Level-2-Events/events.html\n */\ngoog.events.Listenable = function() {};\n\n\n/**\n * An expando property to indicate that an object implements\n * goog.events.Listenable.\n *\n * See addImplementation/isImplementedBy.\n *\n * @type {string}\n * @const\n */\ngoog.events.Listenable.IMPLEMENTED_BY_PROP =\n 'closure_listenable_' + ((Math.random() * 1e6) | 0);\n\n\n/**\n * Marks a given class (constructor) as an implementation of\n * Listenable, so that we can query that fact at runtime. The class\n * must have already implemented the interface.\n * @param {function(new:goog.events.Listenable,...)} cls The class constructor.\n * The corresponding class must have already implemented the interface.\n */\ngoog.events.Listenable.addImplementation = function(cls) {\n 'use strict';\n cls.prototype[goog.events.Listenable.IMPLEMENTED_BY_PROP] = true;\n};\n\n\n/**\n * @param {?Object} obj The object to check.\n * @return {boolean} Whether a given instance implements Listenable. The\n * class/superclass of the instance must call addImplementation.\n */\ngoog.events.Listenable.isImplementedBy = function(obj) {\n 'use strict';\n return !!(obj && obj[goog.events.Listenable.IMPLEMENTED_BY_PROP]);\n};\n\n\n/**\n * Adds an event listener. A listener can only be added once to an\n * object and if it is added again the key for the listener is\n * returned. Note that if the existing listener is a one-off listener\n * (registered via listenOnce), it will no longer be a one-off\n * listener after a call to listen().\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.listen = function(\n type, listener, opt_useCapture, opt_listenerScope) {};\n\n\n/**\n * Adds an event listener that is removed automatically after the\n * listener fired once.\n *\n * If an existing listener already exists, listenOnce will do\n * nothing. In particular, if the listener was previously registered\n * via listen(), listenOnce() will not turn the listener into a\n * one-off listener. Similarly, if there is already an existing\n * one-off listener, listenOnce does not modify the listeners (it is\n * still a once listener).\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.listenOnce = function(\n type, listener, opt_useCapture, opt_listenerScope) {};\n\n\n/**\n * Removes an event listener which was added with listen() or listenOnce().\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call\n * the listener.\n * @return {boolean} Whether any listener was removed.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.unlisten = function(\n type, listener, opt_useCapture, opt_listenerScope) {};\n\n\n/**\n * Removes an event listener which was added with listen() by the key\n * returned by listen().\n *\n * @param {!goog.events.ListenableKey} key The key returned by\n * listen() or listenOnce().\n * @return {boolean} Whether any listener was removed.\n */\ngoog.events.Listenable.prototype.unlistenByKey = function(key) {};\n\n\n/**\n * Dispatches an event (or event like object) and calls all listeners\n * listening for events of this type. The type of the event is decided by the\n * type property on the event object.\n *\n * If any of the listeners returns false OR calls preventDefault then this\n * function will return false. If one of the capture listeners calls\n * stopPropagation, then the bubble listeners won't fire.\n *\n * @param {?goog.events.EventLike} e Event object.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the listeners returns false) this will also return false.\n */\ngoog.events.Listenable.prototype.dispatchEvent = function(e) {};\n\n\n/**\n * Removes all listeners from this listenable. If type is specified,\n * it will only remove listeners of the particular type. otherwise all\n * registered listeners will be removed.\n *\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove,\n * default is to remove all types.\n * @return {number} Number of listeners removed.\n */\ngoog.events.Listenable.prototype.removeAllListeners = function(opt_type) {};\n\n\n/**\n * Returns the parent of this event target to use for capture/bubble\n * mechanism.\n *\n * NOTE(chrishenry): The name reflects the original implementation of\n * custom event target (`goog.events.EventTarget`). We decided\n * that changing the name is not worth it.\n *\n * @return {?goog.events.Listenable} The parent EventTarget or null if\n * there is no parent.\n */\ngoog.events.Listenable.prototype.getParentEventTarget = function() {};\n\n\n/**\n * Fires all registered listeners in this listenable for the given\n * type and capture mode, passing them the given eventObject. This\n * does not perform actual capture/bubble. Only implementors of the\n * interface should be using this.\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The type of the\n * listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @param {EVENTOBJ} eventObject The event object to fire.\n * @return {boolean} Whether all listeners succeeded without\n * attempting to prevent default behavior. If any listener returns\n * false or called goog.events.Event#preventDefault, this returns\n * false.\n * @template EVENTOBJ\n */\ngoog.events.Listenable.prototype.fireListeners = function(\n type, capture, eventObject) {};\n\n\n/**\n * Gets all listeners in this listenable for the given type and\n * capture mode.\n *\n * @param {string|!goog.events.EventId} type The type of the listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @return {!Array<!goog.events.ListenableKey>} An array of registered\n * listeners.\n * @template EVENTOBJ\n */\ngoog.events.Listenable.prototype.getListeners = function(type, capture) {};\n\n\n/**\n * Gets the goog.events.ListenableKey for the event or null if no such\n * listener is in use.\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The name of the event\n * without the 'on' prefix.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener The\n * listener function to get.\n * @param {boolean} capture Whether the listener is a capturing listener.\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {?goog.events.ListenableKey} the found listener or null if not found.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.getListener = function(\n type, listener, capture, opt_listenerScope) {};\n\n\n/**\n * Whether there is any active listeners matching the specified\n * signature. If either the type or capture parameters are\n * unspecified, the function will match on the remaining criteria.\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>=} opt_type Event type.\n * @param {boolean=} opt_capture Whether to check for capture or bubble\n * listeners.\n * @return {boolean} Whether there is any active listeners matching\n * the requested type and/or capture phase.\n * @template EVENTOBJ\n */\ngoog.events.Listenable.prototype.hasListener = function(\n opt_type, opt_capture) {};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview An interface that describes a single registered listener.\n */\ngoog.provide('goog.events.ListenableKey');\n\ngoog.requireType('goog.events.Listenable');\n\n\n/**\n * An interface that describes a single registered listener.\n * @interface\n */\ngoog.events.ListenableKey = function() {};\n\n\n/**\n * Counter used to create a unique key\n * @type {number}\n * @private\n */\ngoog.events.ListenableKey.counter_ = 0;\n\n\n/**\n * Reserves a key to be used for ListenableKey#key field.\n * @return {number} A number to be used to fill ListenableKey#key\n * field.\n */\ngoog.events.ListenableKey.reserveKey = function() {\n 'use strict';\n return ++goog.events.ListenableKey.counter_;\n};\n\n\n/**\n * The source event target.\n * @type {?Object|?goog.events.Listenable}\n */\ngoog.events.ListenableKey.prototype.src;\n\n\n/**\n * The event type the listener is listening to.\n * @type {string}\n */\ngoog.events.ListenableKey.prototype.type;\n\n\n/**\n * The listener function.\n * @type {function(?):?|{handleEvent:function(?):?}|null}\n */\ngoog.events.ListenableKey.prototype.listener;\n\n\n/**\n * Whether the listener works on capture phase.\n * @type {boolean}\n */\ngoog.events.ListenableKey.prototype.capture;\n\n\n/**\n * The 'this' object for the listener function's scope.\n * @type {?Object|undefined}\n */\ngoog.events.ListenableKey.prototype.handler;\n\n\n/**\n * A globally unique number to identify the key.\n * @type {number}\n */\ngoog.events.ListenableKey.prototype.key;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Listener object.\n * @see ../demos/events.html\n */\n\ngoog.provide('goog.events.Listener');\n\ngoog.require('goog.events.ListenableKey');\ngoog.requireType('goog.events.Listenable');\n\n\n\n/**\n * Simple class that stores information about a listener\n * @param {function(?):?} listener Callback function.\n * @param {Function} proxy Wrapper for the listener that patches the event.\n * @param {EventTarget|goog.events.Listenable} src Source object for\n * the event.\n * @param {string} type Event type.\n * @param {boolean} capture Whether in capture or bubble phase.\n * @param {Object=} opt_handler Object in whose context to execute the callback.\n * @implements {goog.events.ListenableKey}\n * @constructor\n */\ngoog.events.Listener = function(\n listener, proxy, src, type, capture, opt_handler) {\n 'use strict';\n if (goog.events.Listener.ENABLE_MONITORING) {\n this.creationStack = new Error().stack;\n }\n\n /** @override */\n this.listener = listener;\n\n /**\n * A wrapper over the original listener. This is used solely to\n * handle native browser events (it is used to simulate the capture\n * phase and to patch the event object).\n * @type {Function}\n */\n this.proxy = proxy;\n\n /**\n * Object or node that callback is listening to\n * @type {EventTarget|goog.events.Listenable}\n */\n this.src = src;\n\n /**\n * The event type.\n * @const {string}\n */\n this.type = type;\n\n /**\n * Whether the listener is being called in the capture or bubble phase\n * @const {boolean}\n */\n this.capture = !!capture;\n\n /**\n * Optional object whose context to execute the listener in\n * @type {Object|undefined}\n */\n this.handler = opt_handler;\n\n /**\n * The key of the listener.\n * @const {number}\n * @override\n */\n this.key = goog.events.ListenableKey.reserveKey();\n\n /**\n * Whether to remove the listener after it has been called.\n * @type {boolean}\n */\n this.callOnce = false;\n\n /**\n * Whether the listener has been removed.\n * @type {boolean}\n */\n this.removed = false;\n};\n\n\n/**\n * @define {boolean} Whether to enable the monitoring of the\n * goog.events.Listener instances. Switching on the monitoring is only\n * recommended for debugging because it has a significant impact on\n * performance and memory usage. If switched off, the monitoring code\n * compiles down to 0 bytes.\n */\ngoog.events.Listener.ENABLE_MONITORING =\n goog.define('goog.events.Listener.ENABLE_MONITORING', false);\n\n\n/**\n * If monitoring the goog.events.Listener instances is enabled, stores the\n * creation stack trace of the Disposable instance.\n * @type {string}\n */\ngoog.events.Listener.prototype.creationStack;\n\n\n/**\n * Marks this listener as removed. This also remove references held by\n * this listener object (such as listener and event source).\n */\ngoog.events.Listener.prototype.markAsRemoved = function() {\n 'use strict';\n this.removed = true;\n this.listener = null;\n this.proxy = null;\n this.src = null;\n this.handler = null;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A map of listeners that provides utility functions to\n * deal with listeners on an event target. Used by\n * `goog.events.EventTarget`.\n *\n * WARNING: Do not use this class from outside goog.events package.\n *\n */\n\ngoog.provide('goog.events.ListenerMap');\n\ngoog.require('goog.array');\ngoog.require('goog.events.Listener');\ngoog.require('goog.object');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.Listenable');\ngoog.requireType('goog.events.ListenableKey');\n\n\n\n/**\n * Creates a new listener map.\n * @param {EventTarget|goog.events.Listenable} src The src object.\n * @constructor\n * @final\n */\ngoog.events.ListenerMap = function(src) {\n 'use strict';\n /** @type {EventTarget|goog.events.Listenable} */\n this.src = src;\n\n /**\n * Maps of event type to an array of listeners.\n * @type {!Object<string, !Array<!goog.events.Listener>>}\n */\n this.listeners = {};\n\n /**\n * The count of types in this map that have registered listeners.\n * @private {number}\n */\n this.typeCount_ = 0;\n};\n\n\n/**\n * @return {number} The count of event types in this map that actually\n * have registered listeners.\n */\ngoog.events.ListenerMap.prototype.getTypeCount = function() {\n 'use strict';\n return this.typeCount_;\n};\n\n\n/**\n * @return {number} Total number of registered listeners.\n */\ngoog.events.ListenerMap.prototype.getListenerCount = function() {\n 'use strict';\n var count = 0;\n for (var type in this.listeners) {\n count += this.listeners[type].length;\n }\n return count;\n};\n\n\n/**\n * Adds an event listener. A listener can only be added once to an\n * object and if it is added again the key for the listener is\n * returned.\n *\n * Note that a one-off listener will not change an existing listener,\n * if any. On the other hand a normal listener will change existing\n * one-off listener to become a normal listener.\n *\n * @param {string|!goog.events.EventId} type The listener event type.\n * @param {!Function} listener This listener callback method.\n * @param {boolean} callOnce Whether the listener is a one-off\n * listener.\n * @param {boolean=} opt_useCapture The capture mode of the listener.\n * @param {Object=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n */\ngoog.events.ListenerMap.prototype.add = function(\n type, listener, callOnce, opt_useCapture, opt_listenerScope) {\n 'use strict';\n var typeStr = type.toString();\n var listenerArray = this.listeners[typeStr];\n if (!listenerArray) {\n listenerArray = this.listeners[typeStr] = [];\n this.typeCount_++;\n }\n\n var listenerObj;\n var index = goog.events.ListenerMap.findListenerIndex_(\n listenerArray, listener, opt_useCapture, opt_listenerScope);\n if (index > -1) {\n listenerObj = listenerArray[index];\n if (!callOnce) {\n // Ensure that, if there is an existing callOnce listener, it is no\n // longer a callOnce listener.\n listenerObj.callOnce = false;\n }\n } else {\n listenerObj = new goog.events.Listener(\n listener, null, this.src, typeStr, !!opt_useCapture, opt_listenerScope);\n listenerObj.callOnce = callOnce;\n listenerArray.push(listenerObj);\n }\n return listenerObj;\n};\n\n\n/**\n * Removes a matching listener.\n * @param {string|!goog.events.EventId} type The listener event type.\n * @param {!Function} listener This listener callback method.\n * @param {boolean=} opt_useCapture The capture mode of the listener.\n * @param {Object=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {boolean} Whether any listener was removed.\n */\ngoog.events.ListenerMap.prototype.remove = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n var typeStr = type.toString();\n if (!(typeStr in this.listeners)) {\n return false;\n }\n\n var listenerArray = this.listeners[typeStr];\n var index = goog.events.ListenerMap.findListenerIndex_(\n listenerArray, listener, opt_useCapture, opt_listenerScope);\n if (index > -1) {\n var listenerObj = listenerArray[index];\n listenerObj.markAsRemoved();\n goog.array.removeAt(listenerArray, index);\n if (listenerArray.length == 0) {\n delete this.listeners[typeStr];\n this.typeCount_--;\n }\n return true;\n }\n return false;\n};\n\n\n/**\n * Removes the given listener object.\n * @param {!goog.events.ListenableKey} listener The listener to remove.\n * @return {boolean} Whether the listener is removed.\n */\ngoog.events.ListenerMap.prototype.removeByKey = function(listener) {\n 'use strict';\n var type = listener.type;\n if (!(type in this.listeners)) {\n return false;\n }\n\n var removed = goog.array.remove(this.listeners[type], listener);\n if (removed) {\n /** @type {!goog.events.Listener} */ (listener).markAsRemoved();\n if (this.listeners[type].length == 0) {\n delete this.listeners[type];\n this.typeCount_--;\n }\n }\n return removed;\n};\n\n\n/**\n * Removes all listeners from this map. If opt_type is provided, only\n * listeners that match the given type are removed.\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove.\n * @return {number} Number of listeners removed.\n */\ngoog.events.ListenerMap.prototype.removeAll = function(opt_type) {\n 'use strict';\n var typeStr = opt_type && opt_type.toString();\n var count = 0;\n for (var type in this.listeners) {\n if (!typeStr || type == typeStr) {\n var listenerArray = this.listeners[type];\n for (var i = 0; i < listenerArray.length; i++) {\n ++count;\n listenerArray[i].markAsRemoved();\n }\n delete this.listeners[type];\n this.typeCount_--;\n }\n }\n return count;\n};\n\n\n/**\n * Gets all listeners that match the given type and capture mode. The\n * returned array is a copy (but the listener objects are not).\n * @param {string|!goog.events.EventId} type The type of the listeners\n * to retrieve.\n * @param {boolean} capture The capture mode of the listeners to retrieve.\n * @return {!Array<!goog.events.ListenableKey>} An array of matching\n * listeners.\n */\ngoog.events.ListenerMap.prototype.getListeners = function(type, capture) {\n 'use strict';\n var listenerArray = this.listeners[type.toString()];\n var rv = [];\n if (listenerArray) {\n for (var i = 0; i < listenerArray.length; ++i) {\n var listenerObj = listenerArray[i];\n if (listenerObj.capture == capture) {\n rv.push(listenerObj);\n }\n }\n }\n return rv;\n};\n\n\n/**\n * Gets the goog.events.ListenableKey for the event or null if no such\n * listener is in use.\n *\n * @param {string|!goog.events.EventId} type The type of the listener\n * to retrieve.\n * @param {!Function} listener The listener function to get.\n * @param {boolean} capture Whether the listener is a capturing listener.\n * @param {Object=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {goog.events.ListenableKey} the found listener or null if not found.\n */\ngoog.events.ListenerMap.prototype.getListener = function(\n type, listener, capture, opt_listenerScope) {\n 'use strict';\n var listenerArray = this.listeners[type.toString()];\n var i = -1;\n if (listenerArray) {\n i = goog.events.ListenerMap.findListenerIndex_(\n listenerArray, listener, capture, opt_listenerScope);\n }\n return i > -1 ? listenerArray[i] : null;\n};\n\n\n/**\n * Whether there is a matching listener. If either the type or capture\n * parameters are unspecified, the function will match on the\n * remaining criteria.\n *\n * @param {string|!goog.events.EventId=} opt_type The type of the listener.\n * @param {boolean=} opt_capture The capture mode of the listener.\n * @return {boolean} Whether there is an active listener matching\n * the requested type and/or capture phase.\n */\ngoog.events.ListenerMap.prototype.hasListener = function(\n opt_type, opt_capture) {\n 'use strict';\n var hasType = (opt_type !== undefined);\n var typeStr = hasType ? opt_type.toString() : '';\n var hasCapture = (opt_capture !== undefined);\n\n return goog.object.some(this.listeners, function(listenerArray, type) {\n 'use strict';\n for (var i = 0; i < listenerArray.length; ++i) {\n if ((!hasType || listenerArray[i].type == typeStr) &&\n (!hasCapture || listenerArray[i].capture == opt_capture)) {\n return true;\n }\n }\n\n return false;\n });\n};\n\n\n/**\n * Finds the index of a matching goog.events.Listener in the given\n * listenerArray.\n * @param {!Array<!goog.events.Listener>} listenerArray Array of listener.\n * @param {!Function} listener The listener function.\n * @param {boolean=} opt_useCapture The capture flag for the listener.\n * @param {Object=} opt_listenerScope The listener scope.\n * @return {number} The index of the matching listener within the\n * listenerArray.\n * @private\n */\ngoog.events.ListenerMap.findListenerIndex_ = function(\n listenerArray, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n for (var i = 0; i < listenerArray.length; ++i) {\n var listenerObj = listenerArray[i];\n if (!listenerObj.removed && listenerObj.listener == listener &&\n listenerObj.capture == !!opt_useCapture &&\n listenerObj.handler == opt_listenerScope) {\n return i;\n }\n }\n return -1;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for manipulating objects/maps/hashes.\n */\ngoog.module('goog.object');\ngoog.module.declareLegacyNamespace();\n\n/**\n * Calls a function for each element in an object/map/hash.\n * @param {?Object<K,V>} obj The object over which to iterate.\n * @param {function(this:T,V,?,?Object<K,V>):?} f The function to call for every\n * element. This function takes 3 arguments (the value, the key and the\n * object) and the return value is ignored.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {void}\n * @template T,K,V\n */\nfunction forEach(obj, f, opt_obj) {\n for (const key in obj) {\n f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);\n }\n}\n\n/**\n * Calls a function for each element in an object/map/hash. If that call returns\n * true, adds the element to a new object.\n * @param {?Object<K,V>} obj The object over which to iterate.\n * @param {function(this:T,V,?,?Object<K,V>):boolean} f The function to call for\n * every element. This function takes 3 arguments (the value, the key and\n * the object) and should return a boolean. If the return value is true the\n * element is added to the result object. If it is false the element is not\n * included.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {!Object<K,V>} a new object in which only elements that passed the\n * test are present.\n * @template T,K,V\n */\nfunction filter(obj, f, opt_obj) {\n const res = {};\n for (const key in obj) {\n if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n res[key] = obj[key];\n }\n }\n return res;\n}\n\n/**\n * For every element in an object/map/hash calls a function and inserts the\n * result into a new object.\n * @param {?Object<K,V>} obj The object over which to iterate.\n * @param {function(this:T,V,?,?Object<K,V>):R} f The function to call for every\n * element. This function takes 3 arguments (the value, the key and the\n * object) and should return something. The result will be inserted into a\n * new object.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {!Object<K,R>} a new object with the results from f.\n * @template T,K,V,R\n */\nfunction map(obj, f, opt_obj) {\n const res = {};\n for (const key in obj) {\n res[key] = f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);\n }\n return res;\n}\n\n/**\n * Calls a function for each element in an object/map/hash. If any\n * call returns true, returns true (without checking the rest). If\n * all calls return false, returns false.\n * @param {?Object<K,V>} obj The object to check.\n * @param {function(this:T,V,?,?Object<K,V>):boolean} f The function to call for\n * every element. This function takes 3 arguments (the value, the key and\n * the object) and should return a boolean.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {boolean} true if any element passes the test.\n * @template T,K,V\n */\nfunction some(obj, f, opt_obj) {\n for (const key in obj) {\n if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Calls a function for each element in an object/map/hash. If\n * all calls return true, returns true. If any call returns false, returns\n * false at this point and does not continue to check the remaining elements.\n * @param {?Object<K,V>} obj The object to check.\n * @param {?function(this:T,V,?,?Object<K,V>):boolean} f The function to call\n * for every element. This function takes 3 arguments (the value, the key\n * and the object) and should return a boolean.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {boolean} false if any element fails the test.\n * @template T,K,V\n */\nfunction every(obj, f, opt_obj) {\n for (const key in obj) {\n if (!f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Returns the number of key-value pairs in the object map.\n * @param {?Object} obj The object for which to get the number of key-value\n * pairs.\n * @return {number} The number of key-value pairs in the object map.\n */\nfunction getCount(obj) {\n let rv = 0;\n for (const key in obj) {\n rv++;\n }\n return rv;\n}\n\n/**\n * Returns one key from the object map, if any exists.\n * For map literals the returned key will be the first one in most of the\n * browsers (a know exception is Konqueror).\n * @param {?Object} obj The object to pick a key from.\n * @return {string|undefined} The key or undefined if the object is empty.\n */\nfunction getAnyKey(obj) {\n for (const key in obj) {\n return key;\n }\n}\n\n/**\n * Returns one value from the object map, if any exists.\n * For map literals the returned value will be the first one in most of the\n * browsers (a know exception is Konqueror).\n * @param {?Object<K,V>} obj The object to pick a value from.\n * @return {V|undefined} The value or undefined if the object is empty.\n * @template K,V\n */\nfunction getAnyValue(obj) {\n for (const key in obj) {\n return obj[key];\n }\n}\n\n/**\n * Whether the object/hash/map contains the given object as a value.\n * An alias for containsValue(obj, val).\n * @param {?Object<K,V>} obj The object in which to look for val.\n * @param {V} val The object for which to check.\n * @return {boolean} true if val is present.\n * @template K,V\n */\nfunction contains(obj, val) {\n return containsValue(obj, val);\n}\n\n/**\n * Returns the values of the object/map/hash.\n * @param {?Object<K,V>} obj The object from which to get the values.\n * @return {!Array<V>} The values in the object/map/hash.\n * @template K,V\n */\nfunction getValues(obj) {\n const res = [];\n let i = 0;\n for (const key in obj) {\n res[i++] = obj[key];\n }\n return res;\n}\n\n/**\n * Returns the keys of the object/map/hash.\n * @param {?Object} obj The object from which to get the keys.\n * @return {!Array<string>} Array of property keys.\n */\nfunction getKeys(obj) {\n const res = [];\n let i = 0;\n for (const key in obj) {\n res[i++] = key;\n }\n return res;\n}\n\n/**\n * Get a value from an object multiple levels deep. This is useful for\n * pulling values from deeply nested objects, such as JSON responses.\n * Example usage: getValueByKeys(jsonObj, 'foo', 'entries', 3)\n * @param {?Object} obj An object to get the value from. Can be array-like.\n * @param {...(string|number|!IArrayLike<number|string>)} var_args A number of\n * keys (as strings, or numbers, for array-like objects). Can also be\n * specified as a single array of keys.\n * @return {*} The resulting value. If, at any point, the value for a key in the\n * current object is null or undefined, returns undefined.\n */\nfunction getValueByKeys(obj, var_args) {\n const isArrayLike = goog.isArrayLike(var_args);\n const keys = isArrayLike ?\n /** @type {!IArrayLike<number|string>} */ (var_args) :\n arguments;\n\n // Start with the 2nd parameter for the variable parameters syntax.\n for (let i = isArrayLike ? 0 : 1; i < keys.length; i++) {\n if (obj == null) return undefined;\n obj = obj[keys[i]];\n }\n\n return obj;\n}\n\n/**\n * Whether the object/map/hash contains the given key.\n * @param {?Object} obj The object in which to look for key.\n * @param {?} key The key for which to check.\n * @return {boolean} true If the map contains the key.\n */\nfunction containsKey(obj, key) {\n return obj !== null && key in obj;\n}\n\n/**\n * Whether the object/map/hash contains the given value. This is O(n).\n * @param {?Object<K,V>} obj The object in which to look for val.\n * @param {V} val The value for which to check.\n * @return {boolean} true If the map contains the value.\n * @template K,V\n */\nfunction containsValue(obj, val) {\n for (const key in obj) {\n if (obj[key] == val) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Searches an object for an element that satisfies the given condition and\n * returns its key.\n * @param {?Object<K,V>} obj The object to search in.\n * @param {function(this:T,V,string,?Object<K,V>):boolean} f The function to\n * call for every element. Takes 3 arguments (the value, the key and the\n * object) and should return a boolean.\n * @param {T=} thisObj An optional \"this\" context for the function.\n * @return {string|undefined} The key of an element for which the function\n * returns true or undefined if no such element is found.\n * @template T,K,V\n */\nfunction findKey(obj, f, thisObj = undefined) {\n for (const key in obj) {\n if (f.call(/** @type {?} */ (thisObj), obj[key], key, obj)) {\n return key;\n }\n }\n return undefined;\n}\n\n/**\n * Searches an object for an element that satisfies the given condition and\n * returns its value.\n * @param {?Object<K,V>} obj The object to search in.\n * @param {function(this:T,V,string,?Object<K,V>):boolean} f The function to\n * call for every element. Takes 3 arguments (the value, the key and the\n * object) and should return a boolean.\n * @param {T=} thisObj An optional \"this\" context for the function.\n * @return {V} The value of an element for which the function returns true or\n * undefined if no such element is found.\n * @template T,K,V\n */\nfunction findValue(obj, f, thisObj = undefined) {\n const key = findKey(obj, f, thisObj);\n return key && obj[key];\n}\n\n/**\n * Whether the object/map/hash is empty.\n * @param {?Object} obj The object to test.\n * @return {boolean} true if obj is empty.\n */\nfunction isEmpty(obj) {\n for (const key in obj) {\n return false;\n }\n return true;\n}\n\n/**\n * Removes all key value pairs from the object/map/hash.\n * @param {?Object} obj The object to clear.\n * @return {void}\n */\nfunction clear(obj) {\n for (const i in obj) {\n delete obj[i];\n }\n}\n\n/**\n * Removes a key-value pair based on the key.\n * @param {?Object} obj The object from which to remove the key.\n * @param {?} key The key to remove.\n * @return {boolean} Whether an element was removed.\n */\nfunction remove(obj, key) {\n let rv;\n if (rv = key in /** @type {!Object} */ (obj)) {\n delete obj[key];\n }\n return rv;\n}\n\n/**\n * Adds a key-value pair to the object. Throws an exception if the key is\n * already in use. Use set if you want to change an existing pair.\n * @param {?Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {V} val The value to add.\n * @return {void}\n * @template K,V\n */\nfunction add(obj, key, val) {\n if (obj !== null && key in obj) {\n throw new Error(`The object already contains the key \"${key}\"`);\n }\n set(obj, key, val);\n}\n\n/**\n * Returns the value for the given key.\n * @param {?Object<K,V>} obj The object from which to get the value.\n * @param {string} key The key for which to get the value.\n * @param {R=} val The value to return if no item is found for the given key\n * (default is undefined).\n * @return {V|R|undefined} The value for the given key.\n * @template K,V,R\n */\nfunction get(obj, key, val = undefined) {\n if (obj !== null && key in obj) {\n return obj[key];\n }\n return val;\n}\n\n/**\n * Adds a key-value pair to the object/map/hash.\n * @param {?Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {V} value The value to add.\n * @template K,V\n * @return {void}\n */\nfunction set(obj, key, value) {\n obj[key] = value;\n}\n\n/**\n * Adds a key-value pair to the object/map/hash if it doesn't exist yet.\n * @param {?Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {V} value The value to add if the key wasn't present.\n * @return {V} The value of the entry at the end of the function.\n * @template K,V\n */\nfunction setIfUndefined(obj, key, value) {\n return key in /** @type {!Object} */ (obj) ? obj[key] : (obj[key] = value);\n}\n\n/**\n * Sets a key and value to an object if the key is not set. The value will be\n * the return value of the given function. If the key already exists, the\n * object will not be changed and the function will not be called (the function\n * will be lazily evaluated -- only called if necessary).\n * This function is particularly useful when used with an `Object` which is\n * acting as a cache.\n * @param {?Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {function():V} f The value to add if the key wasn't present.\n * @return {V} The value of the entry at the end of the function.\n * @template K,V\n */\nfunction setWithReturnValueIfNotSet(obj, key, f) {\n if (key in obj) {\n return obj[key];\n }\n\n const val = f();\n obj[key] = val;\n return val;\n}\n\n/**\n * Compares two objects for equality using === on the values.\n * @param {!Object<K,V>} a\n * @param {!Object<K,V>} b\n * @return {boolean}\n * @template K,V\n */\nfunction equals(a, b) {\n for (const k in a) {\n if (!(k in b) || a[k] !== b[k]) {\n return false;\n }\n }\n for (const k in b) {\n if (!(k in a)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Returns a shallow clone of the object.\n * @param {?Object<K,V>} obj Object to clone.\n * @return {!Object<K,V>} Clone of the input object.\n * @template K,V\n */\nfunction clone(obj) {\n const res = {};\n for (const key in obj) {\n res[key] = obj[key];\n }\n return res;\n}\n\n/**\n * Clones a value. The input may be an Object, Array, or basic type. Objects and\n * arrays will be cloned recursively.\n * WARNINGS:\n * <code>unsafeClone</code> does not detect reference loops. Objects\n * that refer to themselves will cause infinite recursion.\n * <code>unsafeClone</code> is unaware of unique identifiers, and\n * copies UIDs created by <code>getUid</code> into cloned results.\n * @param {T} obj The value to clone.\n * @return {T} A clone of the input value.\n * @template T\n */\nfunction unsafeClone(obj) {\n if (!obj || typeof obj !== 'object') return obj;\n if (typeof obj.clone === 'function') return obj.clone();\n if (typeof Map !== 'undefined' && obj instanceof Map) {\n return new Map(obj);\n } else if (typeof Set !== 'undefined' && obj instanceof Set) {\n return new Set(obj);\n } else if (obj instanceof Date) {\n return new Date(obj.getTime());\n }\n const clone = Array.isArray(obj) ? [] :\n typeof ArrayBuffer === 'function' &&\n typeof ArrayBuffer.isView === 'function' && ArrayBuffer.isView(obj) &&\n !(obj instanceof DataView) ?\n new obj.constructor(obj.length) :\n {};\n for (const key in obj) {\n clone[key] = unsafeClone(obj[key]);\n }\n return clone;\n}\n\n/**\n * Returns a new object in which all the keys and values are interchanged\n * (keys become values and values become keys). If multiple keys map to the\n * same value, the chosen transposed value is implementation-dependent.\n * @param {?Object} obj The object to transpose.\n * @return {!Object} The transposed object.\n */\nfunction transpose(obj) {\n const transposed = {};\n for (const key in obj) {\n transposed[obj[key]] = key;\n }\n return transposed;\n}\n\n/**\n * The names of the fields that are defined on Object.prototype.\n * @type {!Array<string>}\n */\nconst PROTOTYPE_FIELDS = [\n 'constructor',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'toLocaleString',\n 'toString',\n 'valueOf',\n];\n\n/**\n * Extends an object with another object.\n * This operates 'in-place'; it does not create a new Object.\n * Example:\n * var o = {};\n * extend(o, {a: 0, b: 1});\n * o; // {a: 0, b: 1}\n * extend(o, {b: 2, c: 3});\n * o; // {a: 0, b: 2, c: 3}\n * @param {?Object} target The object to modify. Existing properties will be\n * overwritten if they are also present in one of the objects in `var_args`.\n * @param {...(?Object|undefined)} var_args The objects from which values\n * will be copied.\n * @return {void}\n * @deprecated Prefer Object.assign\n */\nfunction extend(target, var_args) {\n let key;\n let source;\n for (let i = 1; i < arguments.length; i++) {\n source = arguments[i];\n for (key in source) {\n target[key] = source[key];\n }\n\n // For IE the for-in-loop does not contain any properties that are not\n // enumerable on the prototype object (for example isPrototypeOf from\n // Object.prototype) and it will also not include 'replace' on objects that\n // extend String and change 'replace' (not that it is common for anyone to\n // extend anything except Object).\n\n for (let j = 0; j < PROTOTYPE_FIELDS.length; j++) {\n key = PROTOTYPE_FIELDS[j];\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n}\n\n/**\n * Creates a new object built from the key-value pairs provided as arguments.\n * @param {...*} var_args If only one argument is provided and it is an array\n * then this is used as the arguments, otherwise even arguments are used as\n * the property names and odd arguments are used as the property values.\n * @return {!Object} The new object.\n * @throws {!Error} If there are uneven number of arguments or there is only one\n * non array argument.\n */\nfunction create(var_args) {\n const argLength = arguments.length;\n if (argLength == 1 && Array.isArray(arguments[0])) {\n return create.apply(null, arguments[0]);\n }\n\n if (argLength % 2) {\n throw new Error('Uneven number of arguments');\n }\n\n const rv = {};\n for (let i = 0; i < argLength; i += 2) {\n rv[arguments[i]] = arguments[i + 1];\n }\n return rv;\n}\n\n/**\n * Creates a new object where the property names come from the arguments but\n * the value is always set to true\n * @param {...*} var_args If only one argument is provided and it is an array\n * then this is used as the arguments, otherwise the arguments are used as\n * the property names.\n * @return {!Object} The new object.\n */\nfunction createSet(var_args) {\n const argLength = arguments.length;\n if (argLength == 1 && Array.isArray(arguments[0])) {\n return createSet.apply(null, arguments[0]);\n }\n\n const rv = {};\n for (let i = 0; i < argLength; i++) {\n rv[arguments[i]] = true;\n }\n return rv;\n}\n\n/**\n * Creates an immutable view of the underlying object, if the browser\n * supports immutable objects.\n * In default mode, writes to this view will fail silently. In strict mode,\n * they will throw an error.\n * @param {!Object<K,V>} obj An object.\n * @return {!Object<K,V>} An immutable view of that object, or the original\n * object if this browser does not support immutables.\n * @template K,V\n */\nfunction createImmutableView(obj) {\n let result = obj;\n if (Object.isFrozen && !Object.isFrozen(obj)) {\n result = Object.create(obj);\n Object.freeze(result);\n }\n return result;\n}\n\n/**\n * @param {!Object} obj An object.\n * @return {boolean} Whether this is an immutable view of the object.\n */\nfunction isImmutableView(obj) {\n return !!Object.isFrozen && Object.isFrozen(obj);\n}\n\n/**\n * Get all properties names on a given Object regardless of enumerability.\n * <p> If the browser does not support `Object.getOwnPropertyNames` nor\n * `Object.getPrototypeOf` then this is equivalent to using\n * `getKeys`\n * @param {?Object} obj The object to get the properties of.\n * @param {boolean=} includeObjectPrototype Whether properties defined on\n * `Object.prototype` should be included in the result.\n * @param {boolean=} includeFunctionPrototype Whether properties defined on\n * `Function.prototype` should be included in the result.\n * @return {!Array<string>}\n * @public\n */\nfunction getAllPropertyNames(\n obj, includeObjectPrototype = undefined,\n includeFunctionPrototype = undefined) {\n if (!obj) {\n return [];\n }\n\n // Naively use a for..in loop to get the property names if the browser doesn't\n // support any other APIs for getting it.\n if (!Object.getOwnPropertyNames || !Object.getPrototypeOf) {\n return getKeys(obj);\n }\n\n const visitedSet = {};\n\n // Traverse the prototype chain and add all properties to the visited set.\n let proto = obj;\n while (proto && (proto !== Object.prototype || !!includeObjectPrototype) &&\n (proto !== Function.prototype || !!includeFunctionPrototype)) {\n const names = Object.getOwnPropertyNames(proto);\n for (let i = 0; i < names.length; i++) {\n visitedSet[names[i]] = true;\n }\n proto = Object.getPrototypeOf(proto);\n }\n\n return getKeys(visitedSet);\n}\n\n/**\n * Given a ES5 or ES6 class reference, return its super class / super\n * constructor.\n * This should be used in rare cases where you need to walk up the inheritance\n * tree (this is generally a bad idea). But this work with ES5 and ES6 classes,\n * unlike relying on the superClass_ property.\n * Note: To start walking up the hierarchy from an instance call this with its\n * `constructor` property; e.g. `getSuperClass(instance.constructor)`.\n * @param {function(new: ?)} constructor\n * @return {?Object}\n */\nfunction getSuperClass(constructor) {\n const proto = Object.getPrototypeOf(constructor.prototype);\n return proto && proto.constructor;\n}\n\nexports = {\n add,\n clear,\n clone,\n contains,\n containsKey,\n containsValue,\n create,\n createImmutableView,\n createSet,\n equals,\n every,\n extend,\n filter,\n findKey,\n findValue,\n forEach,\n get,\n getAllPropertyNames,\n getAnyKey,\n getAnyValue,\n getCount,\n getKeys,\n getSuperClass,\n getValueByKeys,\n getValues,\n isEmpty,\n isImmutableView,\n map,\n remove,\n set,\n setIfUndefined,\n setWithReturnValueIfNotSet,\n some,\n transpose,\n unsafeClone,\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview An event manager for both native browser event\n * targets and custom JavaScript event targets\n * (`goog.events.Listenable`). This provides an abstraction\n * over browsers' event systems.\n *\n * It also provides a simulation of W3C event model's capture phase in\n * Internet Explorer (IE 8 and below). Caveat: the simulation does not\n * interact well with listeners registered directly on the elements\n * (bypassing goog.events) or even with listeners registered via\n * goog.events in a separate JS binary. In these cases, we provide\n * no ordering guarantees.\n *\n * The listeners will receive a \"patched\" event object. Such event object\n * contains normalized values for certain event properties that differs in\n * different browsers.\n *\n * Example usage:\n * <pre>\n * goog.events.listen(myNode, 'click', function(e) { alert('woo') });\n * goog.events.listen(myNode, 'mouseover', mouseHandler, true);\n * goog.events.unlisten(myNode, 'mouseover', mouseHandler, true);\n * goog.events.removeAll(myNode);\n * </pre>\n *\n * in IE and event object patching]\n *\n * @see ../demos/events.html\n * @see ../demos/event-propagation.html\n * @see ../demos/stopevent.html\n */\n\n// IMPLEMENTATION NOTES:\n// goog.events stores an auxiliary data structure on each EventTarget\n// source being listened on. This allows us to take advantage of GC,\n// having the data structure GC'd when the EventTarget is GC'd. This\n// GC behavior is equivalent to using W3C DOM Events directly.\n\ngoog.provide('goog.events');\ngoog.provide('goog.events.CaptureSimulationMode');\ngoog.provide('goog.events.Key');\ngoog.provide('goog.events.ListenableType');\n\ngoog.require('goog.asserts');\ngoog.require('goog.debug.entryPointRegistry');\ngoog.require('goog.events.BrowserEvent');\ngoog.require('goog.events.BrowserFeature');\ngoog.require('goog.events.Listenable');\ngoog.require('goog.events.ListenerMap');\ngoog.requireType('goog.debug.ErrorHandler');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventLike');\ngoog.requireType('goog.events.EventWrapper');\ngoog.requireType('goog.events.ListenableKey');\ngoog.requireType('goog.events.Listener');\n\n\n/**\n * @typedef {number|goog.events.ListenableKey}\n */\ngoog.events.Key;\n\n\n/**\n * @typedef {EventTarget|goog.events.Listenable}\n */\ngoog.events.ListenableType;\n\n\n/**\n * Property name on a native event target for the listener map\n * associated with the event target.\n * @private @const {string}\n */\ngoog.events.LISTENER_MAP_PROP_ = 'closure_lm_' + ((Math.random() * 1e6) | 0);\n\n\n/**\n * String used to prepend to IE event types.\n * @const\n * @private\n */\ngoog.events.onString_ = 'on';\n\n\n/**\n * Map of computed \"on<eventname>\" strings for IE event types. Caching\n * this removes an extra object allocation in goog.events.listen which\n * improves IE6 performance.\n * @const\n * @dict\n * @private\n */\ngoog.events.onStringMap_ = {};\n\n\n/**\n * @enum {number} Different capture simulation mode for IE8-.\n */\ngoog.events.CaptureSimulationMode = {\n /**\n * Does not perform capture simulation. Will asserts in IE8- when you\n * add capture listeners.\n */\n OFF_AND_FAIL: 0,\n\n /**\n * Does not perform capture simulation, silently ignore capture\n * listeners.\n */\n OFF_AND_SILENT: 1,\n\n /**\n * Performs capture simulation.\n */\n ON: 2\n};\n\n\n/**\n * @define {number} The capture simulation mode for IE8-. By default,\n * this is ON.\n */\ngoog.events.CAPTURE_SIMULATION_MODE =\n goog.define('goog.events.CAPTURE_SIMULATION_MODE', 2);\n\n\n/**\n * Estimated count of total native listeners.\n * @private {number}\n */\ngoog.events.listenerCountEstimate_ = 0;\n\n\n/**\n * Adds an event listener for a specific event on a native event\n * target (such as a DOM element) or an object that has implemented\n * {@link goog.events.Listenable}. A listener can only be added once\n * to an object and if it is added again the key for the listener is\n * returned. Note that if the existing listener is a one-off listener\n * (registered via listenOnce), it will no longer be a one-off\n * listener after a call to listen().\n *\n * @param {EventTarget|goog.events.Listenable} src The node to listen\n * to events on.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null}\n * listener Callback method, or an object with a handleEvent function.\n * WARNING: passing an Object is now softly deprecated.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {T=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.Key} Unique key for the listener.\n * @template T,EVENTOBJ\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.listen = function(src, type, listener, opt_options, opt_handler) {\n 'use strict';\n if (opt_options && opt_options.once) {\n return goog.events.listenOnce(\n src, type, listener, opt_options, opt_handler);\n }\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.listen(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n return src.listen(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n } else {\n return goog.events.listen_(\n /** @type {!EventTarget} */ (src), type, listener,\n /* callOnce */ false, opt_options, opt_handler);\n }\n};\n\n\n/**\n * Adds an event listener for a specific event on a native event\n * target. A listener can only be added once to an object and if it\n * is added again the key for the listener is returned.\n *\n * Note that a one-off listener will not change an existing listener,\n * if any. On the other hand a normal listener will change existing\n * one-off listener to become a normal listener.\n *\n * @param {EventTarget} src The node to listen to events on.\n * @param {string|?goog.events.EventId<EVENTOBJ>} type Event type.\n * @param {!Function} listener Callback function.\n * @param {boolean} callOnce Whether the listener is a one-off\n * listener or otherwise.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.ListenableKey} Unique key for the listener.\n * @template EVENTOBJ\n * @private\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.listen_ = function(\n src, type, listener, callOnce, opt_options, opt_handler) {\n 'use strict';\n if (!type) {\n throw new Error('Invalid event type');\n }\n\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n\n var listenerMap = goog.events.getListenerMap_(src);\n if (!listenerMap) {\n src[goog.events.LISTENER_MAP_PROP_] = listenerMap =\n new goog.events.ListenerMap(src);\n }\n\n var listenerObj = /** @type {goog.events.Listener} */ (\n listenerMap.add(type, listener, callOnce, capture, opt_handler));\n\n // If the listenerObj already has a proxy, it has been set up\n // previously. We simply return.\n if (listenerObj.proxy) {\n return listenerObj;\n }\n\n var proxy = goog.events.getProxy();\n listenerObj.proxy = proxy;\n\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n proxy.src = src;\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n proxy.listener = listenerObj;\n\n // Attach the proxy through the browser's API\n if (src.addEventListener) {\n // Don't pass an object as `capture` if the browser doesn't support that.\n if (!goog.events.BrowserFeature.PASSIVE_EVENTS) {\n opt_options = capture;\n }\n // Don't break tests that expect a boolean.\n if (opt_options === undefined) opt_options = false;\n src.addEventListener(type.toString(), proxy, opt_options);\n } else if (src.attachEvent) {\n // The else if above used to be an unconditional else. It would call\n // attachEvent come gws or high water. This would sometimes throw an\n // exception on IE11, spoiling the day of some callers. The previous\n // incarnation of this code, from 2007, indicates that it replaced an\n // earlier still version that caused excess allocations on IE6.\n src.attachEvent(goog.events.getOnString_(type.toString()), proxy);\n } else if (src.addListener && src.removeListener) {\n // In IE, MediaQueryList uses addListener() insteadd of addEventListener. In\n // Safari, there is no global for the MediaQueryList constructor, so we just\n // check whether the object \"looks like\" MediaQueryList.\n goog.asserts.assert(\n type === 'change', 'MediaQueryList only has a change event');\n src.addListener(proxy);\n } else {\n throw new Error('addEventListener and attachEvent are unavailable.');\n }\n\n goog.events.listenerCountEstimate_++;\n return listenerObj;\n};\n\n\n/**\n * Helper function for returning a proxy function.\n * @return {!Function} A new or reused function object.\n */\ngoog.events.getProxy = function() {\n 'use strict';\n const proxyCallbackFunction = goog.events.handleBrowserEvent_;\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n const f = function(eventObject) {\n return proxyCallbackFunction.call(f.src, f.listener, eventObject);\n };\n return f;\n};\n\n\n/**\n * Adds an event listener for a specific event on a native event\n * target (such as a DOM element) or an object that has implemented\n * {@link goog.events.Listenable}. After the event has fired the event\n * listener is removed from the target.\n *\n * If an existing listener already exists, listenOnce will do\n * nothing. In particular, if the listener was previously registered\n * via listen(), listenOnce() will not turn the listener into a\n * one-off listener. Similarly, if there is already an existing\n * one-off listener, listenOnce does not modify the listeners (it is\n * still a once listener).\n *\n * @param {EventTarget|goog.events.Listenable} src The node to listen\n * to events on.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null}\n * listener Callback method.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {T=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.Key} Unique key for the listener.\n * @template T,EVENTOBJ\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.listenOnce = function(\n src, type, listener, opt_options, opt_handler) {\n 'use strict';\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.listenOnce(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n return src.listenOnce(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n } else {\n return goog.events.listen_(\n /** @type {!EventTarget} */ (src), type, listener,\n /* callOnce */ true, opt_options, opt_handler);\n }\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.Listenable}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.Listenable} src The target to\n * listen to events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(this:T, ?):?|{handleEvent:function(?):?}|null} listener\n * Callback method, or an object with a handleEvent function.\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\n * false).\n * @param {T=} opt_handler Element in whose scope to call the listener.\n * @template T\n */\ngoog.events.listenWithWrapper = function(\n src, wrapper, listener, opt_capt, opt_handler) {\n 'use strict';\n wrapper.listen(src, listener, opt_capt, opt_handler);\n};\n\n\n/**\n * Removes an event listener which was added with listen().\n *\n * @param {EventTarget|goog.events.Listenable} src The target to stop\n * listening to events on.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types to unlisten to.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\n * listener function to remove.\n * @param {(boolean|!EventListenerOptions)=} opt_options\n * whether the listener is fired during the capture or bubble phase of the\n * event.\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n * @return {?boolean} indicating whether the listener was there to remove.\n * @template EVENTOBJ\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.unlisten = function(src, type, listener, opt_options, opt_handler) {\n 'use strict';\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.unlisten(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n return src.unlisten(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n }\n\n if (!src) {\n // TODO(chrishenry): We should tighten the API to only accept\n // non-null objects, or add an assertion here.\n return false;\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (src));\n if (listenerMap) {\n var listenerObj = listenerMap.getListener(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n if (listenerObj) {\n return goog.events.unlistenByKey(listenerObj);\n }\n }\n\n return false;\n};\n\n\n/**\n * Removes an event listener which was added with listen() by the key\n * returned by listen().\n *\n * @param {goog.events.Key} key The key returned by listen() for this\n * event listener.\n * @return {boolean} indicating whether the listener was there to remove.\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.unlistenByKey = function(key) {\n 'use strict';\n // TODO(chrishenry): Remove this check when tests that rely on this\n // are fixed.\n if (typeof key === 'number') {\n return false;\n }\n\n var listener = key;\n if (!listener || listener.removed) {\n return false;\n }\n\n var src = listener.src;\n if (goog.events.Listenable.isImplementedBy(src)) {\n return /** @type {!goog.events.Listenable} */ (src).unlistenByKey(listener);\n }\n\n var type = listener.type;\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n var proxy = listener.proxy;\n if (src.removeEventListener) {\n src.removeEventListener(type, proxy, listener.capture);\n } else if (src.detachEvent) {\n src.detachEvent(goog.events.getOnString_(type), proxy);\n } else if (src.addListener && src.removeListener) {\n src.removeListener(proxy);\n }\n goog.events.listenerCountEstimate_--;\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (src));\n // TODO(chrishenry): Try to remove this conditional and execute the\n // first branch always. This should be safe.\n if (listenerMap) {\n listenerMap.removeByKey(listener);\n if (listenerMap.getTypeCount() == 0) {\n // Null the src, just because this is simple to do (and useful\n // for IE <= 7).\n listenerMap.src = null;\n // We don't use delete here because IE does not allow delete\n // on a window object.\n src[goog.events.LISTENER_MAP_PROP_] = null;\n }\n } else {\n /** @type {!goog.events.Listener} */ (listener).markAsRemoved();\n }\n\n return true;\n};\n\n\n/**\n * Removes an event listener which was added with listenWithWrapper().\n *\n * @param {EventTarget|goog.events.Listenable} src The target to stop\n * listening to events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\n * listener function to remove.\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase of the\n * event.\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n */\ngoog.events.unlistenWithWrapper = function(\n src, wrapper, listener, opt_capt, opt_handler) {\n 'use strict';\n wrapper.unlisten(src, listener, opt_capt, opt_handler);\n};\n\n\n/**\n * Removes all listeners from an object. You can also optionally\n * remove listeners of a particular type.\n *\n * @param {Object|undefined} obj Object to remove listeners from. Must be an\n * EventTarget or a goog.events.Listenable.\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove.\n * Default is all types.\n * @return {number} Number of listeners removed.\n */\ngoog.events.removeAll = function(obj, opt_type) {\n 'use strict';\n // TODO(chrishenry): Change the type of obj to\n // (!EventTarget|!goog.events.Listenable).\n\n if (!obj) {\n return 0;\n }\n\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return /** @type {?} */ (obj).removeAllListeners(opt_type);\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (obj));\n if (!listenerMap) {\n return 0;\n }\n\n var count = 0;\n var typeStr = opt_type && opt_type.toString();\n for (var type in listenerMap.listeners) {\n if (!typeStr || type == typeStr) {\n // Clone so that we don't need to worry about unlistenByKey\n // changing the content of the ListenerMap.\n var listeners = listenerMap.listeners[type].concat();\n for (var i = 0; i < listeners.length; ++i) {\n if (goog.events.unlistenByKey(listeners[i])) {\n ++count;\n }\n }\n }\n }\n return count;\n};\n\n\n/**\n * Gets the listeners for a given object, type and capture phase.\n *\n * @param {Object} obj Object to get listeners for.\n * @param {string|!goog.events.EventId} type Event type.\n * @param {boolean} capture Capture phase?.\n * @return {!Array<!goog.events.Listener>} Array of listener objects.\n */\ngoog.events.getListeners = function(obj, type, capture) {\n 'use strict';\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return /** @type {!goog.events.Listenable} */ (obj).getListeners(\n type, capture);\n } else {\n if (!obj) {\n // TODO(chrishenry): We should tighten the API to accept\n // !EventTarget|goog.events.Listenable, and add an assertion here.\n return [];\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (obj));\n return listenerMap ? listenerMap.getListeners(type, capture) : [];\n }\n};\n\n\n/**\n * Gets the goog.events.Listener for the event or null if no such listener is\n * in use.\n *\n * @param {EventTarget|goog.events.Listenable} src The target from\n * which to get listeners.\n * @param {?string|!goog.events.EventId<EVENTOBJ>} type The type of the event.\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null} listener The\n * listener function to get.\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\n * whether the listener is fired during the\n * capture or bubble phase of the event.\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.ListenableKey} the found listener or null if not found.\n * @template EVENTOBJ\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.getListener = function(src, type, listener, opt_capt, opt_handler) {\n 'use strict';\n // TODO(chrishenry): Change type from ?string to string, or add assertion.\n type = /** @type {string} */ (type);\n listener = goog.events.wrapListener(listener);\n var capture = !!opt_capt;\n if (goog.events.Listenable.isImplementedBy(src)) {\n return src.getListener(type, listener, capture, opt_handler);\n }\n\n if (!src) {\n // TODO(chrishenry): We should tighten the API to only accept\n // non-null objects, or add an assertion here.\n return null;\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (src));\n if (listenerMap) {\n return listenerMap.getListener(type, listener, capture, opt_handler);\n }\n return null;\n};\n\n\n/**\n * Returns whether an event target has any active listeners matching the\n * specified signature. If either the type or capture parameters are\n * unspecified, the function will match on the remaining criteria.\n *\n * @param {EventTarget|goog.events.Listenable} obj Target to get\n * listeners for.\n * @param {string|!goog.events.EventId=} opt_type Event type.\n * @param {boolean=} opt_capture Whether to check for capture or bubble-phase\n * listeners.\n * @return {boolean} Whether an event target has one or more listeners matching\n * the requested type and/or capture phase.\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.hasListener = function(obj, opt_type, opt_capture) {\n 'use strict';\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return obj.hasListener(opt_type, opt_capture);\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (obj));\n return !!listenerMap && listenerMap.hasListener(opt_type, opt_capture);\n};\n\n\n/**\n * Provides a nice string showing the normalized event objects public members\n * @param {Object} e Event Object.\n * @return {string} String of the public members of the normalized event object.\n */\ngoog.events.expose = function(e) {\n 'use strict';\n var str = [];\n for (var key in e) {\n if (e[key] && e[key].id) {\n str.push(key + ' = ' + e[key] + ' (' + e[key].id + ')');\n } else {\n str.push(key + ' = ' + e[key]);\n }\n }\n return str.join('\\n');\n};\n\n\n/**\n * Returns a string with on prepended to the specified type. This is used for IE\n * which expects \"on\" to be prepended. This function caches the string in order\n * to avoid extra allocations in steady state.\n * @param {string} type Event type.\n * @return {string} The type string with 'on' prepended.\n * @private\n */\ngoog.events.getOnString_ = function(type) {\n 'use strict';\n if (type in goog.events.onStringMap_) {\n return goog.events.onStringMap_[type];\n }\n return goog.events.onStringMap_[type] = goog.events.onString_ + type;\n};\n\n\n/**\n * Fires an object's listeners of a particular type and phase\n *\n * @param {Object} obj Object whose listeners to call.\n * @param {string|!goog.events.EventId} type Event type.\n * @param {boolean} capture Which event phase.\n * @param {Object} eventObject Event object to be passed to listener.\n * @return {boolean} True if all listeners returned true else false.\n */\ngoog.events.fireListeners = function(obj, type, capture, eventObject) {\n 'use strict';\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return /** @type {!goog.events.Listenable} */ (obj).fireListeners(\n type, capture, eventObject);\n }\n\n return goog.events.fireListeners_(obj, type, capture, eventObject);\n};\n\n\n/**\n * Fires an object's listeners of a particular type and phase.\n * @param {Object} obj Object whose listeners to call.\n * @param {string|!goog.events.EventId} type Event type.\n * @param {boolean} capture Which event phase.\n * @param {Object} eventObject Event object to be passed to listener.\n * @return {boolean} True if all listeners returned true else false.\n * @private\n */\ngoog.events.fireListeners_ = function(obj, type, capture, eventObject) {\n 'use strict';\n /** @type {boolean} */\n var retval = true;\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {EventTarget} */ (obj));\n if (listenerMap) {\n // TODO(chrishenry): Original code avoids array creation when there\n // is no listener, so we do the same. If this optimization turns\n // out to be not required, we can replace this with\n // listenerMap.getListeners(type, capture) instead, which is simpler.\n var listenerArray = listenerMap.listeners[type.toString()];\n if (listenerArray) {\n listenerArray = listenerArray.concat();\n for (var i = 0; i < listenerArray.length; i++) {\n var listener = listenerArray[i];\n // We might not have a listener if the listener was removed.\n if (listener && listener.capture == capture && !listener.removed) {\n var result = goog.events.fireListener(listener, eventObject);\n retval = retval && (result !== false);\n }\n }\n }\n }\n return retval;\n};\n\n\n/**\n * Fires a listener with a set of arguments\n *\n * @param {goog.events.Listener} listener The listener object to call.\n * @param {Object} eventObject The event object to pass to the listener.\n * @return {*} Result of listener.\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.fireListener = function(listener, eventObject) {\n 'use strict';\n var listenerFn = listener.listener;\n var listenerHandler = listener.handler || listener.src;\n\n if (listener.callOnce) {\n goog.events.unlistenByKey(listener);\n }\n return listenerFn.call(listenerHandler, eventObject);\n};\n\n\n/**\n * Gets the total number of listeners currently in the system.\n * @return {number} Number of listeners.\n * @deprecated This returns estimated count, now that Closure no longer\n * stores a central listener registry. We still return an estimation\n * to keep existing listener-related tests passing. In the near future,\n * this function will be removed.\n */\ngoog.events.getTotalListenerCount = function() {\n 'use strict';\n return goog.events.listenerCountEstimate_;\n};\n\n\n/**\n * Dispatches an event (or event like object) and calls all listeners\n * listening for events of this type. The type of the event is decided by the\n * type property on the event object.\n *\n * If any of the listeners returns false OR calls preventDefault then this\n * function will return false. If one of the capture listeners calls\n * stopPropagation, then the bubble listeners won't fire.\n *\n * @param {goog.events.Listenable} src The event target.\n * @param {goog.events.EventLike} e Event object.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the handlers returns false) this will also return false.\n * If there are no handlers, or if all handlers return true, this returns\n * true.\n */\ngoog.events.dispatchEvent = function(src, e) {\n 'use strict';\n goog.asserts.assert(\n goog.events.Listenable.isImplementedBy(src),\n 'Can not use goog.events.dispatchEvent with ' +\n 'non-goog.events.Listenable instance.');\n return src.dispatchEvent(e);\n};\n\n\n/**\n * Installs exception protection for the browser event entry point using the\n * given error handler.\n *\n * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to\n * protect the entry point.\n */\ngoog.events.protectBrowserEventEntryPoint = function(errorHandler) {\n 'use strict';\n goog.events.handleBrowserEvent_ =\n errorHandler.protectEntryPoint(goog.events.handleBrowserEvent_);\n};\n\n\n/**\n * Handles an event and dispatches it to the correct listeners. This\n * function is a proxy for the real listener the user specified.\n *\n * @param {goog.events.Listener} listener The listener object.\n * @param {Event=} opt_evt Optional event object that gets passed in via the\n * native event handlers.\n * @return {*} Result of the event handler.\n * @this {EventTarget} The object or Element that fired the event.\n * @private\n */\ngoog.events.handleBrowserEvent_ = function(listener, opt_evt) {\n 'use strict';\n if (listener.removed) {\n return true;\n }\n\n // Otherwise, simply fire the listener.\n return goog.events.fireListener(\n listener, new goog.events.BrowserEvent(opt_evt, this));\n};\n\n\n/**\n * This is used to mark the IE event object so we do not do the Closure pass\n * twice for a bubbling event.\n * @param {Event} e The IE browser event.\n * @private\n */\ngoog.events.markIeEvent_ = function(e) {\n 'use strict';\n // Only the keyCode and the returnValue can be changed. We use keyCode for\n // non keyboard events.\n // event.returnValue is a bit more tricky. It is undefined by default. A\n // boolean false prevents the default action. In a window.onbeforeunload and\n // the returnValue is non undefined it will be alerted. However, we will only\n // modify the returnValue for keyboard events. We can get a problem if non\n // closure events sets the keyCode or the returnValue\n\n var useReturnValue = false;\n\n if (e.keyCode == 0) {\n // We cannot change the keyCode in case that srcElement is input[type=file].\n // We could test that that is the case but that would allocate 3 objects.\n // If we use try/catch we will only allocate extra objects in the case of a\n // failure.\n\n try {\n e.keyCode = -1;\n return;\n } catch (ex) {\n useReturnValue = true;\n }\n }\n\n if (useReturnValue ||\n /** @type {boolean|undefined} */ (e.returnValue) == undefined) {\n e.returnValue = true;\n }\n};\n\n\n/**\n * This is used to check if an IE event has already been handled by the Closure\n * system so we do not do the Closure pass twice for a bubbling event.\n * @param {Event} e The IE browser event.\n * @return {boolean} True if the event object has been marked.\n * @private\n */\ngoog.events.isMarkedIeEvent_ = function(e) {\n 'use strict';\n return e.keyCode < 0 || e.returnValue != undefined;\n};\n\n\n/**\n * Counter to create unique event ids.\n * @private {number}\n */\ngoog.events.uniqueIdCounter_ = 0;\n\n\n/**\n * Creates a unique event id.\n *\n * @param {string} identifier The identifier.\n * @return {string} A unique identifier.\n * @idGenerator {unique}\n */\ngoog.events.getUniqueId = function(identifier) {\n 'use strict';\n return identifier + '_' + goog.events.uniqueIdCounter_++;\n};\n\n\n/**\n * @param {EventTarget} src The source object.\n * @return {goog.events.ListenerMap} A listener map for the given\n * source object, or null if none exists.\n * @private\n */\ngoog.events.getListenerMap_ = function(src) {\n 'use strict';\n var listenerMap = src[goog.events.LISTENER_MAP_PROP_];\n // IE serializes the property as well (e.g. when serializing outer\n // HTML). So we must check that the value is of the correct type.\n return listenerMap instanceof goog.events.ListenerMap ? listenerMap : null;\n};\n\n\n/**\n * Expando property for listener function wrapper for Object with\n * handleEvent.\n * @private @const {string}\n */\ngoog.events.LISTENER_WRAPPER_PROP_ =\n '__closure_events_fn_' + ((Math.random() * 1e9) >>> 0);\n\n\n/**\n * @param {Object|Function} listener The listener function or an\n * object that contains handleEvent method.\n * @return {!Function} Either the original function or a function that\n * calls obj.handleEvent. If the same listener is passed to this\n * function more than once, the same function is guaranteed to be\n * returned.\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.wrapListener = function(listener) {\n 'use strict';\n goog.asserts.assert(listener, 'Listener can not be null.');\n\n if (typeof listener === 'function') {\n return listener;\n }\n\n goog.asserts.assert(\n listener.handleEvent, 'An object listener must have handleEvent method.');\n if (!listener[goog.events.LISTENER_WRAPPER_PROP_]) {\n listener[goog.events.LISTENER_WRAPPER_PROP_] = function(e) {\n 'use strict';\n return /** @type {?} */ (listener).handleEvent(e);\n };\n }\n return listener[goog.events.LISTENER_WRAPPER_PROP_];\n};\n\n\n// Register the browser event handler as an entry point, so that\n// it can be monitored for exception handling, etc.\ngoog.debug.entryPointRegistry.register(\n /**\n * @param {function(!Function): !Function} transformer The transforming\n * function.\n */\n function(transformer) {\n 'use strict';\n goog.events.handleBrowserEvent_ =\n transformer(goog.events.handleBrowserEvent_);\n });\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A disposable implementation of a custom\n * listenable/event target. See also: documentation for\n * `goog.events.Listenable`.\n *\n * @see ../demos/eventtarget.html\n * @see goog.events.Listenable\n */\n\ngoog.provide('goog.events.EventTarget');\n\ngoog.require('goog.Disposable');\ngoog.require('goog.asserts');\ngoog.require('goog.events');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.Listenable');\ngoog.require('goog.events.ListenerMap');\ngoog.require('goog.object');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventLike');\ngoog.requireType('goog.events.ListenableKey');\n\n\n\n/**\n * An implementation of `goog.events.Listenable` with full W3C\n * EventTarget-like support (capture/bubble mechanism, stopping event\n * propagation, preventing default actions).\n *\n * You may subclass this class to turn your class into a Listenable.\n *\n * Unless propagation is stopped, an event dispatched by an\n * EventTarget will bubble to the parent returned by\n * `getParentEventTarget`. To set the parent, call\n * `setParentEventTarget`. Subclasses that don't support\n * changing the parent can override the setter to throw an error.\n *\n * Example usage:\n * <pre>\n * var source = new goog.events.EventTarget();\n * function handleEvent(e) {\n * alert('Type: ' + e.type + '; Target: ' + e.target);\n * }\n * source.listen('foo', handleEvent);\n * // Or: goog.events.listen(source, 'foo', handleEvent);\n * ...\n * source.dispatchEvent('foo'); // will call handleEvent\n * ...\n * source.unlisten('foo', handleEvent);\n * // Or: goog.events.unlisten(source, 'foo', handleEvent);\n * </pre>\n *\n * @constructor\n * @extends {goog.Disposable}\n * @implements {goog.events.Listenable}\n */\ngoog.events.EventTarget = function() {\n 'use strict';\n goog.Disposable.call(this);\n\n /**\n * Maps of event type to an array of listeners.\n * @private {!goog.events.ListenerMap}\n */\n this.eventTargetListeners_ = new goog.events.ListenerMap(this);\n\n /**\n * The object to use for event.target. Useful when mixing in an\n * EventTarget to another object.\n * @private {!Object}\n */\n this.actualEventTarget_ = this;\n\n /**\n * Parent event target, used during event bubbling.\n *\n * TODO(chrishenry): Change this to goog.events.Listenable. This\n * currently breaks people who expect getParentEventTarget to return\n * goog.events.EventTarget.\n *\n * @private {?goog.events.EventTarget}\n */\n this.parentEventTarget_ = null;\n};\ngoog.inherits(goog.events.EventTarget, goog.Disposable);\ngoog.events.Listenable.addImplementation(goog.events.EventTarget);\n\n\n/**\n * An artificial cap on the number of ancestors you can have. This is mainly\n * for loop detection.\n * @const {number}\n * @private\n */\ngoog.events.EventTarget.MAX_ANCESTORS_ = 1000;\n\n\n/**\n * Returns the parent of this event target to use for bubbling.\n *\n * @return {goog.events.EventTarget} The parent EventTarget or null if\n * there is no parent.\n * @override\n */\ngoog.events.EventTarget.prototype.getParentEventTarget = function() {\n 'use strict';\n return this.parentEventTarget_;\n};\n\n\n/**\n * Sets the parent of this event target to use for capture/bubble\n * mechanism.\n * @param {goog.events.EventTarget} parent Parent listenable (null if none).\n */\ngoog.events.EventTarget.prototype.setParentEventTarget = function(parent) {\n 'use strict';\n this.parentEventTarget_ = parent;\n};\n\n\n/**\n * Adds an event listener to the event target. The same handler can only be\n * added once per the type. Even if you add the same handler multiple times\n * using the same type then it will only be called once when the event is\n * dispatched.\n *\n * @param {string|!goog.events.EventId} type The type of the event to listen for\n * @param {function(?):?|{handleEvent:function(?):?}|null} handler The function\n * to handle the event. The handler can also be an object that implements\n * the handleEvent method which takes the event object as argument.\n * @param {boolean=} opt_capture In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase\n * of the event.\n * @param {Object=} opt_handlerScope Object in whose scope to call\n * the listener.\n * @deprecated Use `#listen` instead, when possible. Otherwise, use\n * `goog.events.listen` if you are passing Object\n * (instead of Function) as handler.\n */\ngoog.events.EventTarget.prototype.addEventListener = function(\n type, handler, opt_capture, opt_handlerScope) {\n 'use strict';\n goog.events.listen(this, type, handler, opt_capture, opt_handlerScope);\n};\n\n\n/**\n * Removes an event listener from the event target. The handler must be the\n * same object as the one added. If the handler has not been added then\n * nothing is done.\n *\n * @param {string|!goog.events.EventId} type The type of the event to listen for\n * @param {function(?):?|{handleEvent:function(?):?}|null} handler The function\n * to handle the event. The handler can also be an object that implements\n * the handleEvent method which takes the event object as argument.\n * @param {boolean=} opt_capture In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase\n * of the event.\n * @param {Object=} opt_handlerScope Object in whose scope to call\n * the listener.\n * @deprecated Use `#unlisten` instead, when possible. Otherwise, use\n * `goog.events.unlisten` if you are passing Object\n * (instead of Function) as handler.\n */\ngoog.events.EventTarget.prototype.removeEventListener = function(\n type, handler, opt_capture, opt_handlerScope) {\n 'use strict';\n goog.events.unlisten(this, type, handler, opt_capture, opt_handlerScope);\n};\n\n\n/**\n * @param {?goog.events.EventLike} e Event object.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the listeners returns false) this will also return false.\n * @override\n */\ngoog.events.EventTarget.prototype.dispatchEvent = function(e) {\n 'use strict';\n this.assertInitialized_();\n\n var ancestorsTree, ancestor = this.getParentEventTarget();\n if (ancestor) {\n ancestorsTree = [];\n var ancestorCount = 1;\n for (; ancestor; ancestor = ancestor.getParentEventTarget()) {\n ancestorsTree.push(ancestor);\n goog.asserts.assert(\n (++ancestorCount < goog.events.EventTarget.MAX_ANCESTORS_),\n 'infinite loop');\n }\n }\n\n return goog.events.EventTarget.dispatchEventInternal_(\n this.actualEventTarget_, e, ancestorsTree);\n};\n\n\n/**\n * Removes listeners from this object. Classes that extend EventTarget may\n * need to override this method in order to remove references to DOM Elements\n * and additional listeners.\n * @override\n * @protected\n */\ngoog.events.EventTarget.prototype.disposeInternal = function() {\n 'use strict';\n goog.events.EventTarget.superClass_.disposeInternal.call(this);\n\n this.removeAllListeners();\n this.parentEventTarget_ = null;\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.listen = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n this.assertInitialized_();\n return this.eventTargetListeners_.add(\n String(type), listener, false /* callOnce */, opt_useCapture,\n opt_listenerScope);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.listenOnce = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n return this.eventTargetListeners_.add(\n String(type), listener, true /* callOnce */, opt_useCapture,\n opt_listenerScope);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call\n * the listener.\n * @return {boolean} Whether any listener was removed.\n * @template SCOPE,EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.unlisten = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n return this.eventTargetListeners_.remove(\n String(type), listener, opt_useCapture, opt_listenerScope);\n};\n\n\n/**\n * @param {!goog.events.ListenableKey} key The key returned by\n * listen() or listenOnce().\n * @return {boolean} Whether any listener was removed.\n * @override\n */\ngoog.events.EventTarget.prototype.unlistenByKey = function(key) {\n 'use strict';\n return this.eventTargetListeners_.removeByKey(key);\n};\n\n\n/**\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove,\n * default is to remove all types.\n * @return {number} Number of listeners removed.\n * @override\n */\ngoog.events.EventTarget.prototype.removeAllListeners = function(opt_type) {\n 'use strict';\n // TODO(chrishenry): Previously, removeAllListeners can be called on\n // uninitialized EventTarget, so we preserve that behavior. We\n // should remove this when usages that rely on that fact are purged.\n if (!this.eventTargetListeners_) {\n return 0;\n }\n return this.eventTargetListeners_.removeAll(opt_type);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The type of the\n * listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @param {EVENTOBJ} eventObject The event object to fire.\n * @return {boolean} Whether all listeners succeeded without\n * attempting to prevent default behavior. If any listener returns\n * false or called goog.events.Event#preventDefault, this returns\n * false.\n * @template EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.fireListeners = function(\n type, capture, eventObject) {\n 'use strict';\n // TODO(chrishenry): Original code avoids array creation when there\n // is no listener, so we do the same. If this optimization turns\n // out to be not required, we can replace this with\n // getListeners(type, capture) instead, which is simpler.\n var listenerArray = this.eventTargetListeners_.listeners[String(type)];\n if (!listenerArray) {\n return true;\n }\n listenerArray = listenerArray.concat();\n\n var rv = true;\n for (var i = 0; i < listenerArray.length; ++i) {\n var listener = listenerArray[i];\n // We might not have a listener if the listener was removed.\n if (listener && !listener.removed && listener.capture == capture) {\n var listenerFn = listener.listener;\n var listenerHandler = listener.handler || listener.src;\n\n if (listener.callOnce) {\n this.unlistenByKey(listener);\n }\n rv = listenerFn.call(listenerHandler, eventObject) !== false && rv;\n }\n }\n\n return rv && !eventObject.defaultPrevented;\n};\n\n\n/**\n * @param {string|!goog.events.EventId} type The type of the listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @return {!Array<!goog.events.ListenableKey>} An array of registered\n * listeners.\n * @template EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.getListeners = function(type, capture) {\n 'use strict';\n return this.eventTargetListeners_.getListeners(String(type), capture);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The name of the event\n * without the 'on' prefix.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener The\n * listener function to get.\n * @param {boolean} capture Whether the listener is a capturing listener.\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {?goog.events.ListenableKey} the found listener or null if not found.\n * @template SCOPE,EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.getListener = function(\n type, listener, capture, opt_listenerScope) {\n 'use strict';\n return this.eventTargetListeners_.getListener(\n String(type), listener, capture, opt_listenerScope);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>=} opt_type Event type.\n * @param {boolean=} opt_capture Whether to check for capture or bubble\n * listeners.\n * @return {boolean} Whether there is any active listeners matching\n * the requested type and/or capture phase.\n * @template EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.hasListener = function(\n opt_type, opt_capture) {\n 'use strict';\n var id = (opt_type !== undefined) ? String(opt_type) : undefined;\n return this.eventTargetListeners_.hasListener(id, opt_capture);\n};\n\n\n/**\n * Sets the target to be used for `event.target` when firing\n * event. Mainly used for testing. For example, see\n * `goog.testing.events.mixinListenable`.\n * @param {!Object} target The target.\n */\ngoog.events.EventTarget.prototype.setTargetForTesting = function(target) {\n 'use strict';\n this.actualEventTarget_ = target;\n};\n\n\n/**\n * Asserts that the event target instance is initialized properly.\n * @private\n */\ngoog.events.EventTarget.prototype.assertInitialized_ = function() {\n 'use strict';\n goog.asserts.assert(\n this.eventTargetListeners_,\n 'Event target is not initialized. Did you call the superclass ' +\n '(goog.events.EventTarget) constructor?');\n};\n\n\n/**\n * Dispatches the given event on the ancestorsTree.\n *\n * @param {!Object} target The target to dispatch on.\n * @param {goog.events.Event|Object|string} e The event object.\n * @param {Array<goog.events.Listenable>=} opt_ancestorsTree The ancestors\n * tree of the target, in reverse order from the closest ancestor\n * to the root event target. May be null if the target has no ancestor.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the listeners returns false) this will also return false.\n * @private\n */\ngoog.events.EventTarget.dispatchEventInternal_ = function(\n target, e, opt_ancestorsTree) {\n 'use strict';\n /** @suppress {missingProperties} */\n var type = e.type || /** @type {string} */ (e);\n\n // If accepting a string or object, create a custom event object so that\n // preventDefault and stopPropagation work with the event.\n if (typeof e === 'string') {\n e = new goog.events.Event(e, target);\n } else if (!(e instanceof goog.events.Event)) {\n var oldEvent = e;\n e = new goog.events.Event(type, target);\n goog.object.extend(e, oldEvent);\n } else {\n e.target = e.target || target;\n }\n\n var rv = true, currentTarget;\n\n // Executes all capture listeners on the ancestors, if any.\n if (opt_ancestorsTree) {\n for (var i = opt_ancestorsTree.length - 1;\n !e.hasPropagationStopped() && i >= 0; i--) {\n currentTarget = e.currentTarget = opt_ancestorsTree[i];\n rv = currentTarget.fireListeners(type, true, e) && rv;\n }\n }\n\n // Executes capture and bubble listeners on the target.\n if (!e.hasPropagationStopped()) {\n currentTarget = /** @type {?} */ (e.currentTarget = target);\n rv = currentTarget.fireListeners(type, true, e) && rv;\n if (!e.hasPropagationStopped()) {\n rv = currentTarget.fireListeners(type, false, e) && rv;\n }\n }\n\n // Executes all bubble listeners on the ancestors, if any.\n if (opt_ancestorsTree) {\n for (i = 0; !e.hasPropagationStopped() && i < opt_ancestorsTree.length;\n i++) {\n currentTarget = e.currentTarget = opt_ancestorsTree[i];\n rv = currentTarget.fireListeners(type, false, e) && rv;\n }\n }\n\n return rv;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview JSON utility functions.\n */\n\n\ngoog.provide('goog.json');\ngoog.provide('goog.json.Replacer');\ngoog.provide('goog.json.Reviver');\ngoog.provide('goog.json.Serializer');\n\n\n/**\n * @define {boolean} If true, use the native JSON parsing API.\n * NOTE: The default `goog.json.parse` implementation is able to handle\n * invalid JSON. JSPB used to produce invalid JSON which is not the case\n * anymore so this is safe to enable for parsing JSPB. Using native JSON is\n * faster and safer than the default implementation using `eval`.\n */\ngoog.json.USE_NATIVE_JSON = goog.define('goog.json.USE_NATIVE_JSON', false);\n\n\n/**\n * Tests if a string is an invalid JSON string. This only ensures that we are\n * not using any invalid characters\n * @param {string} s The string to test.\n * @return {boolean} True if the input is a valid JSON string.\n */\ngoog.json.isValid = function(s) {\n 'use strict';\n // All empty whitespace is not valid.\n if (/^\\s*$/.test(s)) {\n return false;\n }\n\n // This is taken from http://www.json.org/json2.js which is released to the\n // public domain.\n // Changes: We dissallow \\u2028 Line separator and \\u2029 Paragraph separator\n // inside strings. We also treat \\u2028 and \\u2029 as whitespace which they\n // are in the RFC but IE and Safari does not match \\s to these so we need to\n // include them in the reg exps in all places where whitespace is allowed.\n // We allowed \\x7f inside strings because some tools don't escape it,\n // e.g. http://www.json.org/java/org/json/JSONObject.java\n\n // Parsing happens in three stages. In the first stage, we run the text\n // against regular expressions that look for non-JSON patterns. We are\n // especially concerned with '()' and 'new' because they can cause invocation,\n // and '=' because it can cause mutation. But just to be safe, we want to\n // reject all unexpected forms.\n\n // We split the first stage into 4 regexp operations in order to work around\n // crippling inefficiencies in IE's and Safari's regexp engines. First we\n // replace all backslash pairs with '@' (a non-JSON character). Second, we\n // replace all simple value tokens with ']' characters, but only when followed\n // by a colon, comma, closing bracket or end of string. Third, we delete all\n // open brackets that follow a colon or comma or that begin the text. Finally,\n // we look to see that the remaining characters are only whitespace or ']' or\n // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.\n\n // Don't make these static since they have the global flag.\n const backslashesRe = /\\\\[\"\\\\\\/bfnrtu]/g;\n const simpleValuesRe =\n /(?:\"[^\"\\\\\\n\\r\\u2028\\u2029\\x00-\\x08\\x0a-\\x1f]*\"|true|false|null|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)[\\s\\u2028\\u2029]*(?=:|,|]|}|$)/g;\n const openBracketsRe = /(?:^|:|,)(?:[\\s\\u2028\\u2029]*\\[)+/g;\n const remainderRe = /^[\\],:{}\\s\\u2028\\u2029]*$/;\n\n return remainderRe.test(\n s.replace(backslashesRe, '@')\n .replace(simpleValuesRe, ']')\n .replace(openBracketsRe, ''));\n};\n\n/**\n * Logs a parsing error in `JSON.parse` solvable by using `eval`.\n * @private {function(string, !Error)} The first parameter is the error message,\n * the second is the exception thrown by `JSON.parse`.\n */\ngoog.json.errorLogger_ = () => {};\n\n\n/**\n * Sets an error logger to use if there's a recoverable parsing error.\n * @param {function(string, !Error)} errorLogger The first parameter is the\n * error message, the second is the exception thrown by `JSON.parse`.\n */\ngoog.json.setErrorLogger = function(errorLogger) {\n 'use strict';\n goog.json.errorLogger_ = errorLogger;\n};\n\n\n/**\n * Parses a JSON string and returns the result. This throws an exception if\n * the string is an invalid JSON string.\n *\n * Note that this is very slow on large strings. Use JSON.parse if possible.\n *\n * @param {*} s The JSON string to parse.\n * @throws Error if s is invalid JSON.\n * @return {Object} The object generated from the JSON string, or null.\n * @deprecated Use JSON.parse.\n */\ngoog.json.parse = goog.json.USE_NATIVE_JSON ?\n /** @type {function(*):Object} */ (goog.global['JSON']['parse']) :\n function(s) {\n 'use strict';\n let error;\n try {\n return goog.global['JSON']['parse'](s);\n } catch (ex) {\n error = ex;\n }\n const o = String(s);\n if (goog.json.isValid(o)) {\n\n try {\n const result = /** @type {?Object} */ (eval('(' + o + ')'));\n if (error) {\n goog.json.errorLogger_('Invalid JSON: ' + o, error);\n }\n return result;\n } catch (ex) {\n }\n }\n throw new Error('Invalid JSON string: ' + o);\n };\n\n\n/**\n * JSON replacer, as defined in Section 15.12.3 of the ES5 spec.\n * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3\n *\n * TODO(nicksantos): Array should also be a valid replacer.\n *\n * @typedef {function(this:Object, string, *): *}\n */\ngoog.json.Replacer;\n\n\n/**\n * JSON reviver, as defined in Section 15.12.2 of the ES5 spec.\n * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3\n *\n * @typedef {function(this:Object, string, *): *}\n */\ngoog.json.Reviver;\n\n\n/**\n * Serializes an object or a value to a JSON string.\n *\n * @param {*} object The object to serialize.\n * @param {?goog.json.Replacer=} opt_replacer A replacer function\n * called for each (key, value) pair that determines how the value\n * should be serialized. By defult, this just returns the value\n * and allows default serialization to kick in.\n * @throws Error if there are loops in the object graph.\n * @return {string} A JSON string representation of the input.\n */\ngoog.json.serialize = goog.json.USE_NATIVE_JSON ?\n /** @type {function(*, ?goog.json.Replacer=):string} */\n (goog.global['JSON']['stringify']) :\n function(object, opt_replacer) {\n 'use strict';\n // NOTE(nicksantos): Currently, we never use JSON.stringify.\n //\n // The last time I evaluated this, JSON.stringify had subtle bugs and\n // behavior differences on all browsers, and the performance win was not\n // large enough to justify all the issues. This may change in the future\n // as browser implementations get better.\n //\n // assertSerialize in json_test contains if branches for the cases\n // that fail.\n return new goog.json.Serializer(opt_replacer).serialize(object);\n };\n\n\n\n/**\n * Class that is used to serialize JSON objects to a string.\n * @param {?goog.json.Replacer=} opt_replacer Replacer.\n * @constructor\n */\ngoog.json.Serializer = function(opt_replacer) {\n 'use strict';\n /**\n * @type {goog.json.Replacer|null|undefined}\n * @private\n */\n this.replacer_ = opt_replacer;\n};\n\n\n/**\n * Serializes an object or a value to a JSON string.\n *\n * @param {*} object The object to serialize.\n * @throws Error if there are loops in the object graph.\n * @return {string} A JSON string representation of the input.\n */\ngoog.json.Serializer.prototype.serialize = function(object) {\n 'use strict';\n const sb = [];\n this.serializeInternal(object, sb);\n return sb.join('');\n};\n\n\n/**\n * Serializes a generic value to a JSON string\n * @protected\n * @param {*} object The object to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n * @throws Error if there are loops in the object graph.\n */\ngoog.json.Serializer.prototype.serializeInternal = function(object, sb) {\n 'use strict';\n if (object == null) {\n // undefined == null so this branch covers undefined as well as null\n sb.push('null');\n return;\n }\n\n if (typeof object == 'object') {\n if (Array.isArray(object)) {\n this.serializeArray(object, sb);\n return;\n } else if (\n object instanceof String || object instanceof Number ||\n object instanceof Boolean) {\n object = object.valueOf();\n // Fall through to switch below.\n } else {\n this.serializeObject_(/** @type {!Object} */ (object), sb);\n return;\n }\n }\n\n switch (typeof object) {\n case 'string':\n this.serializeString_(object, sb);\n break;\n case 'number':\n this.serializeNumber_(object, sb);\n break;\n case 'boolean':\n sb.push(String(object));\n break;\n case 'function':\n sb.push('null');\n break;\n default:\n throw new Error('Unknown type: ' + typeof object);\n }\n};\n\n\n/**\n * Character mappings used internally for goog.string.quote\n * @private\n * @type {!Object}\n */\ngoog.json.Serializer.charToJsonCharCache_ = {\n '\\\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n '/': '\\\\/',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n\n '\\x0B': '\\\\u000b' // '\\v' is not supported in JScript\n};\n\n\n/**\n * Regular expression used to match characters that need to be replaced.\n * The S60 browser has a bug where unicode characters are not matched by\n * regular expressions. The condition below detects such behaviour and\n * adjusts the regular expression accordingly.\n * @private\n * @type {!RegExp}\n */\ngoog.json.Serializer.charsToReplace_ = /\\uffff/.test('\\uffff') ?\n /[\\\\\\\"\\x00-\\x1f\\x7f-\\uffff]/g :\n /[\\\\\\\"\\x00-\\x1f\\x7f-\\xff]/g;\n\n\n/**\n * Serializes a string to a JSON string\n * @private\n * @param {string} s The string to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n */\ngoog.json.Serializer.prototype.serializeString_ = function(s, sb) {\n 'use strict';\n // The official JSON implementation does not work with international\n // characters.\n sb.push('\"', s.replace(goog.json.Serializer.charsToReplace_, function(c) {\n 'use strict';\n // caching the result improves performance by a factor 2-3\n let rv = goog.json.Serializer.charToJsonCharCache_[c];\n if (!rv) {\n rv = '\\\\u' + (c.charCodeAt(0) | 0x10000).toString(16).slice(1);\n goog.json.Serializer.charToJsonCharCache_[c] = rv;\n }\n return rv;\n }), '\"');\n};\n\n\n/**\n * Serializes a number to a JSON string\n * @private\n * @param {number} n The number to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n */\ngoog.json.Serializer.prototype.serializeNumber_ = function(n, sb) {\n 'use strict';\n sb.push(isFinite(n) && !isNaN(n) ? String(n) : 'null');\n};\n\n\n/**\n * Serializes an array to a JSON string\n * @param {Array<string>} arr The array to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n * @protected\n */\ngoog.json.Serializer.prototype.serializeArray = function(arr, sb) {\n 'use strict';\n const l = arr.length;\n sb.push('[');\n let sep = '';\n for (let i = 0; i < l; i++) {\n sb.push(sep);\n\n const value = arr[i];\n this.serializeInternal(\n this.replacer_ ? this.replacer_.call(arr, String(i), value) : value,\n sb);\n\n sep = ',';\n }\n sb.push(']');\n};\n\n\n/**\n * Serializes an object to a JSON string\n * @private\n * @param {!Object} obj The object to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n */\ngoog.json.Serializer.prototype.serializeObject_ = function(obj, sb) {\n 'use strict';\n sb.push('{');\n let sep = '';\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = obj[key];\n // Skip functions.\n if (typeof value != 'function') {\n sb.push(sep);\n this.serializeString_(key, sb);\n sb.push(':');\n\n this.serializeInternal(\n this.replacer_ ? this.replacer_.call(obj, key, value) : value, sb);\n\n sep = ',';\n }\n }\n }\n sb.push('}');\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.module('goog.async.WorkQueue');\ngoog.module.declareLegacyNamespace();\n\nconst FreeList = goog.require('goog.async.FreeList');\nconst {assert} = goog.require('goog.asserts');\n\n// TODO(johnlenz): generalize the WorkQueue if this is used by more\n// than goog.async.run.\n\n\n/**\n * A low GC workqueue. The key elements of this design:\n * - avoids the need for goog.bind or equivalent by carrying scope\n * - avoids the need for array reallocation by using a linked list\n * - minimizes work entry objects allocation by recycling objects\n * @final\n * @struct\n */\nclass WorkQueue {\n constructor() {\n this.workHead_ = null;\n this.workTail_ = null;\n }\n\n /**\n * @param {function()} fn\n * @param {Object|null|undefined} scope\n */\n add(fn, scope) {\n const item = this.getUnusedItem_();\n item.set(fn, scope);\n\n if (this.workTail_) {\n this.workTail_.next = item;\n this.workTail_ = item;\n } else {\n assert(!this.workHead_);\n this.workHead_ = item;\n this.workTail_ = item;\n }\n }\n\n /**\n * @return {?WorkItem}\n */\n remove() {\n let item = null;\n\n if (this.workHead_) {\n item = this.workHead_;\n this.workHead_ = this.workHead_.next;\n if (!this.workHead_) {\n this.workTail_ = null;\n }\n item.next = null;\n }\n return item;\n }\n\n /**\n * @param {!WorkItem} item\n */\n returnUnused(item) {\n WorkQueue.freelist_.put(item);\n }\n\n /**\n * @return {!WorkItem}\n * @private\n */\n getUnusedItem_() {\n return WorkQueue.freelist_.get();\n }\n}\n\n/** @define {number} The maximum number of entries to keep for recycling. */\nWorkQueue.DEFAULT_MAX_UNUSED =\n goog.define('goog.async.WorkQueue.DEFAULT_MAX_UNUSED', 100);\n\n/** @const @private {!FreeList<!WorkItem>} */\nWorkQueue.freelist_ = new FreeList(\n () => new WorkItem(), item => item.reset(), WorkQueue.DEFAULT_MAX_UNUSED);\n\n/**\n * @final\n * @struct\n */\nclass WorkItem {\n constructor() {\n /** @type {?function()} */\n this.fn = null;\n /** @type {?Object|null|undefined} */\n this.scope = null;\n /** @type {?WorkItem} */\n this.next = null;\n }\n\n /**\n * @param {function()} fn\n * @param {Object|null|undefined} scope\n */\n set(fn, scope) {\n this.fn = fn;\n this.scope = scope;\n this.next = null;\n }\n\n /** Reset the work item so they don't prevent GC before reuse */\n reset() {\n this.fn = null;\n this.scope = null;\n this.next = null;\n }\n}\n\nexports = WorkQueue;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\ngoog.module('goog.async.run');\ngoog.module.declareLegacyNamespace();\n\nconst WorkQueue = goog.require('goog.async.WorkQueue');\nconst asyncStackTag = goog.require('goog.debug.asyncStackTag');\nconst nextTick = goog.require('goog.async.nextTick');\nconst throwException = goog.require('goog.async.throwException');\n\n/**\n * @define {boolean} If true, use the global Promise to implement run\n * assuming either the native, or polyfill version will be used. Does still\n * permit tests to use forceNextTick.\n */\ngoog.ASSUME_NATIVE_PROMISE = goog.define('goog.ASSUME_NATIVE_PROMISE', false);\n\n/**\n * The function used to schedule work asynchronousely.\n * @private {function()}\n */\nlet schedule;\n\n/** @private {boolean} */\nlet workQueueScheduled = false;\n\n/** @type {!WorkQueue} */\nlet workQueue = new WorkQueue();\n\n/**\n * Fires the provided callback just before the current callstack unwinds, or as\n * soon as possible after the current JS execution context.\n * @param {function(this:THIS)} callback\n * @param {THIS=} context Object to use as the \"this value\" when calling the\n * provided function.\n * @template THIS\n */\nlet run = (callback, context = undefined) => {\n if (!schedule) {\n initializeRunner();\n }\n if (!workQueueScheduled) {\n // Nothing is currently scheduled, schedule it now.\n schedule();\n workQueueScheduled = true;\n }\n callback = asyncStackTag.wrap(callback, 'goog.async.run');\n\n workQueue.add(callback, context);\n};\n\n/** Initializes the function to use to process the work queue. */\nlet initializeRunner = () => {\n if (goog.ASSUME_NATIVE_PROMISE ||\n (goog.global.Promise && goog.global.Promise.resolve)) {\n // Use goog.global.Promise instead of just Promise because the relevant\n // externs may be missing, and don't alias it because this could confuse the\n // compiler into thinking the polyfill is required when it should be treated\n // as optional.\n const promise = goog.global.Promise.resolve(undefined);\n schedule = () => {\n promise.then(run.processWorkQueue);\n };\n } else {\n schedule = () => {\n nextTick(run.processWorkQueue);\n };\n }\n};\n\n/**\n * Forces run to use nextTick instead of Promise.\n * This should only be done in unit tests. It's useful because MockClock\n * replaces nextTick, but not the browser Promise implementation, so it allows\n * Promise-based code to be tested with MockClock.\n * However, we also want to run promises if the MockClock is no longer in\n * control so we schedule a backup \"setTimeout\" to the unmocked timeout if\n * provided.\n * @param {function(function())=} realSetTimeout\n */\nrun.forceNextTick = (realSetTimeout = undefined) => {\n schedule = () => {\n nextTick(run.processWorkQueue);\n if (realSetTimeout) {\n realSetTimeout(run.processWorkQueue);\n }\n };\n};\n\nif (goog.DEBUG) {\n /** Reset the work queue. Only available for tests in debug mode. */\n run.resetQueue = () => {\n workQueueScheduled = false;\n workQueue = new WorkQueue();\n };\n\n /** Resets the scheduler. Only available for tests in debug mode. */\n run.resetSchedulerForTest = () => {\n initializeRunner();\n };\n}\n\n/**\n * Run any pending run work items. This function is not intended\n * for general use, but for use by entry point handlers to run items ahead of\n * nextTick.\n */\nrun.processWorkQueue = () => {\n // NOTE: additional work queue items may be added while processing.\n let item = null;\n while (item = workQueue.remove()) {\n try {\n item.fn.call(item.scope);\n } catch (e) {\n throwException(e);\n }\n workQueue.returnUnused(item);\n }\n\n // There are no more work items, allow processing to be scheduled again.\n workQueueScheduled = false;\n};\n\nexports = run;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Simple freelist.\n *\n * An anterative to goog.structs.SimplePool, it imposes the requirement that the\n * objects in the list contain a \"next\" property that can be used to maintain\n * the pool.\n */\ngoog.module('goog.async.FreeList');\ngoog.module.declareLegacyNamespace();\n\n/** @template ITEM */\nclass FreeList {\n /**\n * @param {function():ITEM} create\n * @param {function(ITEM):void} reset\n * @param {number} limit\n */\n constructor(create, reset, limit) {\n /** @private @const {number} */\n this.limit_ = limit;\n /** @private @const {function()} */\n this.create_ = create;\n /** @private @const {function(ITEM):void} */\n this.reset_ = reset;\n\n /** @private {number} */\n this.occupants_ = 0;\n /** @private {ITEM} */\n this.head_ = null;\n }\n\n /** @return {ITEM} */\n get() {\n let item;\n if (this.occupants_ > 0) {\n this.occupants_--;\n item = this.head_;\n this.head_ = item.next;\n item.next = null;\n } else {\n item = this.create_();\n }\n return item;\n }\n\n /** @param {ITEM} item An item available for possible future reuse. */\n put(item) {\n this.reset_(item);\n if (this.occupants_ < this.limit_) {\n this.occupants_++;\n item.next = this.head_;\n this.head_ = item;\n }\n }\n\n /**\n * Visible for testing.\n * @return {number}\n * @package\n */\n occupants() {\n return this.occupants_;\n }\n}\n\nexports = FreeList;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for string manipulation.\n */\n\n\n/**\n * Namespace for string utilities\n */\ngoog.provide('goog.string');\ngoog.provide('goog.string.Unicode');\n\ngoog.require('goog.dom.safe');\ngoog.require('goog.html.uncheckedconversions');\ngoog.require('goog.string.Const');\ngoog.require('goog.string.internal');\n\n\n/**\n * @define {boolean} Enables HTML escaping of lowercase letter \"e\" which helps\n * with detection of double-escaping as this letter is frequently used.\n */\ngoog.string.DETECT_DOUBLE_ESCAPING =\n goog.define('goog.string.DETECT_DOUBLE_ESCAPING', false);\n\n\n/**\n * @define {boolean} Whether to force non-dom html unescaping.\n */\ngoog.string.FORCE_NON_DOM_HTML_UNESCAPING =\n goog.define('goog.string.FORCE_NON_DOM_HTML_UNESCAPING', false);\n\n\n/**\n * Common Unicode string characters.\n * @enum {string}\n */\ngoog.string.Unicode = {\n NBSP: '\\xa0',\n ZERO_WIDTH_SPACE: '\\u200b' // This is equivalent to <wbr>.\n};\n\n\n/**\n * Fast prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the start of `str`.\n * @return {boolean} True if `str` begins with `prefix`.\n */\ngoog.string.startsWith = goog.string.internal.startsWith;\n\n\n/**\n * Fast suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix`.\n */\ngoog.string.endsWith = goog.string.internal.endsWith;\n\n\n/**\n * Case-insensitive prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the end of `str`.\n * @return {boolean} True if `str` begins with `prefix` (ignoring\n * case).\n */\ngoog.string.caseInsensitiveStartsWith =\n goog.string.internal.caseInsensitiveStartsWith;\n\n\n/**\n * Case-insensitive suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix` (ignoring\n * case).\n */\ngoog.string.caseInsensitiveEndsWith =\n goog.string.internal.caseInsensitiveEndsWith;\n\n\n/**\n * Case-insensitive equality checker.\n * @param {string} str1 First string to check.\n * @param {string} str2 Second string to check.\n * @return {boolean} True if `str1` and `str2` are the same string,\n * ignoring case.\n */\ngoog.string.caseInsensitiveEquals = goog.string.internal.caseInsensitiveEquals;\n\n\n/**\n * Does simple python-style string substitution.\n * subs(\"foo%s hot%s\", \"bar\", \"dog\") becomes \"foobar hotdog\".\n * @param {string} str The string containing the pattern.\n * @param {...*} var_args The items to substitute into the pattern.\n * @return {string} A copy of `str` in which each occurrence of\n * {@code %s} has been replaced an argument from `var_args`.\n */\ngoog.string.subs = function(str, var_args) {\n 'use strict';\n const splitParts = str.split('%s');\n let returnString = '';\n\n const subsArguments = Array.prototype.slice.call(arguments, 1);\n while (subsArguments.length &&\n // Replace up to the last split part. We are inserting in the\n // positions between split parts.\n splitParts.length > 1) {\n returnString += splitParts.shift() + subsArguments.shift();\n }\n\n return returnString + splitParts.join('%s'); // Join unused '%s'\n};\n\n\n/**\n * Converts multiple whitespace chars (spaces, non-breaking-spaces, new lines\n * and tabs) to a single space, and strips leading and trailing whitespace.\n * @param {string} str Input string.\n * @return {string} A copy of `str` with collapsed whitespace.\n */\ngoog.string.collapseWhitespace = function(str) {\n 'use strict';\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return str.replace(/[\\s\\xa0]+/g, ' ').replace(/^\\s+|\\s+$/g, '');\n};\n\n\n/**\n * Checks if a string is empty or contains only whitespaces.\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty or whitespace only.\n */\ngoog.string.isEmptyOrWhitespace = goog.string.internal.isEmptyOrWhitespace;\n\n\n/**\n * Checks if a string is empty.\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty.\n */\ngoog.string.isEmptyString = function(str) {\n 'use strict';\n return str.length == 0;\n};\n\n\n/**\n * Checks if a string is empty or contains only whitespaces.\n *\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty or whitespace only.\n * @deprecated Use goog.string.isEmptyOrWhitespace instead.\n */\ngoog.string.isEmpty = goog.string.isEmptyOrWhitespace;\n\n\n/**\n * Checks if a string is null, undefined, empty or contains only whitespaces.\n * @param {*} str The string to check.\n * @return {boolean} Whether `str` is null, undefined, empty, or\n * whitespace only.\n * @deprecated Use goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str))\n * instead.\n */\ngoog.string.isEmptyOrWhitespaceSafe = function(str) {\n 'use strict';\n return goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str));\n};\n\n\n/**\n * Checks if a string is null, undefined, empty or contains only whitespaces.\n *\n * @param {*} str The string to check.\n * @return {boolean} Whether `str` is null, undefined, empty, or\n * whitespace only.\n * @deprecated Use goog.string.isEmptyOrWhitespace instead.\n */\ngoog.string.isEmptySafe = goog.string.isEmptyOrWhitespaceSafe;\n\n\n/**\n * Checks if a string is all breaking whitespace.\n * @param {string} str The string to check.\n * @return {boolean} Whether the string is all breaking whitespace.\n */\ngoog.string.isBreakingWhitespace = function(str) {\n 'use strict';\n return !/[^\\t\\n\\r ]/.test(str);\n};\n\n\n/**\n * Checks if a string contains all letters.\n * @param {string} str string to check.\n * @return {boolean} True if `str` consists entirely of letters.\n */\ngoog.string.isAlpha = function(str) {\n 'use strict';\n return !/[^a-zA-Z]/.test(str);\n};\n\n\n/**\n * Checks if a string contains only numbers.\n * @param {*} str string to check. If not a string, it will be\n * casted to one.\n * @return {boolean} True if `str` is numeric.\n */\ngoog.string.isNumeric = function(str) {\n 'use strict';\n return !/[^0-9]/.test(str);\n};\n\n\n/**\n * Checks if a string contains only numbers or letters.\n * @param {string} str string to check.\n * @return {boolean} True if `str` is alphanumeric.\n */\ngoog.string.isAlphaNumeric = function(str) {\n 'use strict';\n return !/[^a-zA-Z0-9]/.test(str);\n};\n\n\n/**\n * Checks if a character is a space character.\n * @param {string} ch Character to check.\n * @return {boolean} True if `ch` is a space.\n */\ngoog.string.isSpace = function(ch) {\n 'use strict';\n return ch == ' ';\n};\n\n\n/**\n * Checks if a character is a valid unicode character.\n * @param {string} ch Character to check.\n * @return {boolean} True if `ch` is a valid unicode character.\n */\ngoog.string.isUnicodeChar = function(ch) {\n 'use strict';\n return ch.length == 1 && ch >= ' ' && ch <= '~' ||\n ch >= '\\u0080' && ch <= '\\uFFFD';\n};\n\n\n/**\n * Takes a string and replaces newlines with a space. Multiple lines are\n * replaced with a single space.\n * @param {string} str The string from which to strip newlines.\n * @return {string} A copy of `str` stripped of newlines.\n */\ngoog.string.stripNewlines = function(str) {\n 'use strict';\n return str.replace(/(\\r\\n|\\r|\\n)+/g, ' ');\n};\n\n\n/**\n * Replaces Windows and Mac new lines with unix style: \\r or \\r\\n with \\n.\n * @param {string} str The string to in which to canonicalize newlines.\n * @return {string} `str` A copy of {@code} with canonicalized newlines.\n */\ngoog.string.canonicalizeNewlines = function(str) {\n 'use strict';\n return str.replace(/(\\r\\n|\\r|\\n)/g, '\\n');\n};\n\n\n/**\n * Normalizes whitespace in a string, replacing all whitespace chars with\n * a space.\n * @param {string} str The string in which to normalize whitespace.\n * @return {string} A copy of `str` with all whitespace normalized.\n */\ngoog.string.normalizeWhitespace = function(str) {\n 'use strict';\n return str.replace(/\\xa0|\\s/g, ' ');\n};\n\n\n/**\n * Normalizes spaces in a string, replacing all consecutive spaces and tabs\n * with a single space. Replaces non-breaking space with a space.\n * @param {string} str The string in which to normalize spaces.\n * @return {string} A copy of `str` with all consecutive spaces and tabs\n * replaced with a single space.\n */\ngoog.string.normalizeSpaces = function(str) {\n 'use strict';\n return str.replace(/\\xa0|[ \\t]+/g, ' ');\n};\n\n\n/**\n * Removes the breaking spaces from the left and right of the string and\n * collapses the sequences of breaking spaces in the middle into single spaces.\n * The original and the result strings render the same way in HTML.\n * @param {string} str A string in which to collapse spaces.\n * @return {string} Copy of the string with normalized breaking spaces.\n */\ngoog.string.collapseBreakingSpaces = function(str) {\n 'use strict';\n return str.replace(/[\\t\\r\\n ]+/g, ' ')\n .replace(/^[\\t\\r\\n ]+|[\\t\\r\\n ]+$/g, '');\n};\n\n\n/**\n * Trims white spaces to the left and right of a string.\n * @param {string} str The string to trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.trim = goog.string.internal.trim;\n\n\n/**\n * Trims whitespaces at the left end of a string.\n * @param {string} str The string to left trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.trimLeft = function(str) {\n 'use strict';\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return str.replace(/^[\\s\\xa0]+/, '');\n};\n\n\n/**\n * Trims whitespaces at the right end of a string.\n * @param {string} str The string to right trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.trimRight = function(str) {\n 'use strict';\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return str.replace(/[\\s\\xa0]+$/, '');\n};\n\n\n/**\n * A string comparator that ignores case.\n * -1 = str1 less than str2\n * 0 = str1 equals str2\n * 1 = str1 greater than str2\n *\n * @param {string} str1 The string to compare.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} The comparator result, as described above.\n */\ngoog.string.caseInsensitiveCompare =\n goog.string.internal.caseInsensitiveCompare;\n\n\n/**\n * Compares two strings interpreting their numeric substrings as numbers.\n *\n * @param {string} str1 First string.\n * @param {string} str2 Second string.\n * @param {!RegExp} tokenizerRegExp Splits a string into substrings of\n * non-negative integers, non-numeric characters and optionally fractional\n * numbers starting with a decimal point.\n * @return {number} Negative if str1 < str2, 0 is str1 == str2, positive if\n * str1 > str2.\n * @private\n */\ngoog.string.numberAwareCompare_ = function(str1, str2, tokenizerRegExp) {\n 'use strict';\n if (str1 == str2) {\n return 0;\n }\n if (!str1) {\n return -1;\n }\n if (!str2) {\n return 1;\n }\n\n // Using match to split the entire string ahead of time turns out to be faster\n // for most inputs than using RegExp.exec or iterating over each character.\n const tokens1 = str1.toLowerCase().match(tokenizerRegExp);\n const tokens2 = str2.toLowerCase().match(tokenizerRegExp);\n\n const count = Math.min(tokens1.length, tokens2.length);\n\n for (let i = 0; i < count; i++) {\n const a = tokens1[i];\n const b = tokens2[i];\n\n // Compare pairs of tokens, returning if one token sorts before the other.\n if (a != b) {\n // Only if both tokens are integers is a special comparison required.\n // Decimal numbers are sorted as strings (e.g., '.09' < '.1').\n const num1 = parseInt(a, 10);\n if (!isNaN(num1)) {\n const num2 = parseInt(b, 10);\n if (!isNaN(num2) && num1 - num2) {\n return num1 - num2;\n }\n }\n return a < b ? -1 : 1;\n }\n }\n\n // If one string is a substring of the other, the shorter string sorts first.\n if (tokens1.length != tokens2.length) {\n return tokens1.length - tokens2.length;\n }\n\n // The two strings must be equivalent except for case (perfect equality is\n // tested at the head of the function.) Revert to default ASCII string\n // comparison to stabilize the sort.\n return str1 < str2 ? -1 : 1;\n};\n\n\n/**\n * String comparison function that handles non-negative integer numbers in a\n * way humans might expect. Using this function, the string 'File 2.jpg' sorts\n * before 'File 10.jpg', and 'Version 1.9' before 'Version 1.10'. The comparison\n * is mostly case-insensitive, though strings that are identical except for case\n * are sorted with the upper-case strings before lower-case.\n *\n * This comparison function is up to 50x slower than either the default or the\n * case-insensitive compare. It should not be used in time-critical code, but\n * should be fast enough to sort several hundred short strings (like filenames)\n * with a reasonable delay.\n *\n * @param {string} str1 The string to compare in a numerically sensitive way.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than\n * 0 if str1 > str2.\n */\ngoog.string.intAwareCompare = function(str1, str2) {\n 'use strict';\n return goog.string.numberAwareCompare_(str1, str2, /\\d+|\\D+/g);\n};\n\n\n/**\n * String comparison function that handles non-negative integer and fractional\n * numbers in a way humans might expect. Using this function, the string\n * 'File 2.jpg' sorts before 'File 10.jpg', and '3.14' before '3.2'. Equivalent\n * to {@link goog.string.intAwareCompare} apart from the way how it interprets\n * dots.\n *\n * @param {string} str1 The string to compare in a numerically sensitive way.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than\n * 0 if str1 > str2.\n */\ngoog.string.floatAwareCompare = function(str1, str2) {\n 'use strict';\n return goog.string.numberAwareCompare_(str1, str2, /\\d+|\\.\\d+|\\D+/g);\n};\n\n\n/**\n * Alias for {@link goog.string.floatAwareCompare}.\n *\n * @param {string} str1\n * @param {string} str2\n * @return {number}\n */\ngoog.string.numerateCompare = goog.string.floatAwareCompare;\n\n\n/**\n * URL-encodes a string\n * @param {*} str The string to url-encode.\n * @return {string} An encoded copy of `str` that is safe for urls.\n * Note that '#', ':', and other characters used to delimit portions\n * of URLs *will* be encoded.\n */\ngoog.string.urlEncode = function(str) {\n 'use strict';\n return encodeURIComponent(String(str));\n};\n\n\n/**\n * URL-decodes the string. We need to specially handle '+'s because\n * the javascript library doesn't convert them to spaces.\n * @param {string} str The string to url decode.\n * @return {string} The decoded `str`.\n */\ngoog.string.urlDecode = function(str) {\n 'use strict';\n return decodeURIComponent(str.replace(/\\+/g, ' '));\n};\n\n\n/**\n * Converts \\n to <br>s or <br />s.\n * @param {string} str The string in which to convert newlines.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} A copy of `str` with converted newlines.\n */\ngoog.string.newLineToBr = goog.string.internal.newLineToBr;\n\n\n/**\n * Escapes double quote '\"' and single quote '\\'' characters in addition to\n * '&', '<', and '>' so that a string can be included in an HTML tag attribute\n * value within double or single quotes.\n *\n * It should be noted that > doesn't need to be escaped for the HTML or XML to\n * be valid, but it has been decided to escape it for consistency with other\n * implementations.\n *\n * With goog.string.DETECT_DOUBLE_ESCAPING, this function escapes also the\n * lowercase letter \"e\".\n *\n * NOTE(user):\n * HtmlEscape is often called during the generation of large blocks of HTML.\n * Using statics for the regular expressions and strings is an optimization\n * that can more than half the amount of time IE spends in this function for\n * large apps, since strings and regexes both contribute to GC allocations.\n *\n * Testing for the presence of a character before escaping increases the number\n * of function calls, but actually provides a speed increase for the average\n * case -- since the average case often doesn't require the escaping of all 4\n * characters and indexOf() is much cheaper than replace().\n * The worst case does suffer slightly from the additional calls, therefore the\n * opt_isLikelyToContainHtmlChars option has been included for situations\n * where all 4 HTML entities are very likely to be present and need escaping.\n *\n * Some benchmarks (times tended to fluctuate +-0.05ms):\n * FireFox IE6\n * (no chars / average (mix of cases) / all 4 chars)\n * no checks 0.13 / 0.22 / 0.22 0.23 / 0.53 / 0.80\n * indexOf 0.08 / 0.17 / 0.26 0.22 / 0.54 / 0.84\n * indexOf + re test 0.07 / 0.17 / 0.28 0.19 / 0.50 / 0.85\n *\n * An additional advantage of checking if replace actually needs to be called\n * is a reduction in the number of object allocations, so as the size of the\n * application grows the difference between the various methods would increase.\n *\n * @param {string} str string to be escaped.\n * @param {boolean=} opt_isLikelyToContainHtmlChars Don't perform a check to see\n * if the character needs replacing - use this option if you expect each of\n * the characters to appear often. Leave false if you expect few html\n * characters to occur in your strings, such as if you are escaping HTML.\n * @return {string} An escaped copy of `str`.\n */\ngoog.string.htmlEscape = function(str, opt_isLikelyToContainHtmlChars) {\n 'use strict';\n str = goog.string.internal.htmlEscape(str, opt_isLikelyToContainHtmlChars);\n if (goog.string.DETECT_DOUBLE_ESCAPING) {\n str = str.replace(goog.string.E_RE_, 'e');\n }\n return str;\n};\n\n\n/**\n * Regular expression that matches a lowercase letter \"e\", for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.E_RE_ = /e/g;\n\n\n/**\n * Unescapes an HTML string.\n *\n * @param {string} str The string to unescape.\n * @return {string} An unescaped copy of `str`.\n */\ngoog.string.unescapeEntities = function(str) {\n 'use strict';\n if (goog.string.contains(str, '&')) {\n // We are careful not to use a DOM if we do not have one or we explicitly\n // requested non-DOM html unescaping.\n if (!goog.string.FORCE_NON_DOM_HTML_UNESCAPING &&\n 'document' in goog.global) {\n return goog.string.unescapeEntitiesUsingDom_(str);\n } else {\n // Fall back on pure XML entities\n return goog.string.unescapePureXmlEntities_(str);\n }\n }\n return str;\n};\n\n\n/**\n * Unescapes a HTML string using the provided document.\n *\n * @param {string} str The string to unescape.\n * @param {!Document} document A document to use in escaping the string.\n * @return {string} An unescaped copy of `str`.\n */\ngoog.string.unescapeEntitiesWithDocument = function(str, document) {\n 'use strict';\n if (goog.string.contains(str, '&')) {\n return goog.string.unescapeEntitiesUsingDom_(str, document);\n }\n return str;\n};\n\n\n/**\n * Unescapes an HTML string using a DOM to resolve non-XML, non-numeric\n * entities. This function is XSS-safe and whitespace-preserving.\n * @private\n * @param {string} str The string to unescape.\n * @param {Document=} opt_document An optional document to use for creating\n * elements. If this is not specified then the default window.document\n * will be used.\n * @return {string} The unescaped `str` string.\n */\ngoog.string.unescapeEntitiesUsingDom_ = function(str, opt_document) {\n 'use strict';\n /** @type {!Object<string, string>} */\n const seen = {'&': '&', '<': '<', '>': '>', '"': '\"'};\n /** @type {!Element} */\n let div;\n if (opt_document) {\n div = opt_document.createElement('div');\n } else {\n div = goog.global.document.createElement('div');\n }\n // Match as many valid entity characters as possible. If the actual entity\n // happens to be shorter, it will still work as innerHTML will return the\n // trailing characters unchanged. Since the entity characters do not include\n // open angle bracket, there is no chance of XSS from the innerHTML use.\n // Since no whitespace is passed to innerHTML, whitespace is preserved.\n return str.replace(goog.string.HTML_ENTITY_PATTERN_, function(s, entity) {\n 'use strict';\n // Check for cached entity.\n let value = seen[s];\n if (value) {\n return value;\n }\n // Check for numeric entity.\n if (entity.charAt(0) == '#') {\n // Prefix with 0 so that hex entities (e.g. ) parse as hex numbers.\n const n = Number('0' + entity.slice(1));\n if (!isNaN(n)) {\n value = String.fromCharCode(n);\n }\n }\n // Fall back to innerHTML otherwise.\n if (!value) {\n // Append a non-entity character to avoid a bug in Webkit that parses\n // an invalid entity at the end of innerHTML text as the empty string.\n goog.dom.safe.setInnerHtml(\n div,\n goog.html.uncheckedconversions\n .safeHtmlFromStringKnownToSatisfyTypeContract(\n goog.string.Const.from('Single HTML entity.'), s + ' '));\n // Then remove the trailing character from the result.\n value = div.firstChild.nodeValue.slice(0, -1);\n }\n // Cache and return.\n return seen[s] = value;\n });\n};\n\n\n/**\n * Unescapes XML entities.\n * @private\n * @param {string} str The string to unescape.\n * @return {string} An unescaped copy of `str`.\n */\ngoog.string.unescapePureXmlEntities_ = function(str) {\n 'use strict';\n return str.replace(/&([^;]+);/g, function(s, entity) {\n 'use strict';\n switch (entity) {\n case 'amp':\n return '&';\n case 'lt':\n return '<';\n case 'gt':\n return '>';\n case 'quot':\n return '\"';\n default:\n if (entity.charAt(0) == '#') {\n // Prefix with 0 so that hex entities (e.g. ) parse as hex.\n const n = Number('0' + entity.slice(1));\n if (!isNaN(n)) {\n return String.fromCharCode(n);\n }\n }\n // For invalid entities we just return the entity\n return s;\n }\n });\n};\n\n\n/**\n * Regular expression that matches an HTML entity.\n * See also HTML5: Tokenization / Tokenizing character references.\n * @private\n * @type {!RegExp}\n */\ngoog.string.HTML_ENTITY_PATTERN_ = /&([^;\\s<&]+);?/g;\n\n\n/**\n * Do escaping of whitespace to preserve spatial formatting. We use character\n * entity #160 to make it safer for xml.\n * @param {string} str The string in which to escape whitespace.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} An escaped copy of `str`.\n */\ngoog.string.whitespaceEscape = function(str, opt_xml) {\n 'use strict';\n // This doesn't use goog.string.preserveSpaces for backwards compatibility.\n return goog.string.newLineToBr(str.replace(/ /g, '  '), opt_xml);\n};\n\n\n/**\n * Preserve spaces that would be otherwise collapsed in HTML by replacing them\n * with non-breaking space Unicode characters.\n * @param {string} str The string in which to preserve whitespace.\n * @return {string} A copy of `str` with preserved whitespace.\n */\ngoog.string.preserveSpaces = function(str) {\n 'use strict';\n return str.replace(/(^|[\\n ]) /g, '$1' + goog.string.Unicode.NBSP);\n};\n\n\n/**\n * Strip quote characters around a string. The second argument is a string of\n * characters to treat as quotes. This can be a single character or a string of\n * multiple character and in that case each of those are treated as possible\n * quote characters. For example:\n *\n * <pre>\n * goog.string.stripQuotes('\"abc\"', '\"`') --> 'abc'\n * goog.string.stripQuotes('`abc`', '\"`') --> 'abc'\n * </pre>\n *\n * @param {string} str The string to strip.\n * @param {string} quoteChars The quote characters to strip.\n * @return {string} A copy of `str` without the quotes.\n */\ngoog.string.stripQuotes = function(str, quoteChars) {\n 'use strict';\n const length = quoteChars.length;\n for (let i = 0; i < length; i++) {\n const quoteChar = length == 1 ? quoteChars : quoteChars.charAt(i);\n if (str.charAt(0) == quoteChar && str.charAt(str.length - 1) == quoteChar) {\n return str.substring(1, str.length - 1);\n }\n }\n return str;\n};\n\n\n/**\n * Truncates a string to a certain length and adds '...' if necessary. The\n * length also accounts for the ellipsis, so a maximum length of 10 and a string\n * 'Hello World!' produces 'Hello W...'.\n * @param {string} str The string to truncate.\n * @param {number} chars Max number of characters.\n * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped\n * characters from being cut off in the middle.\n * @return {string} The truncated `str` string.\n */\ngoog.string.truncate = function(str, chars, opt_protectEscapedCharacters) {\n 'use strict';\n if (opt_protectEscapedCharacters) {\n str = goog.string.unescapeEntities(str);\n }\n\n if (str.length > chars) {\n str = str.substring(0, chars - 3) + '...';\n }\n\n if (opt_protectEscapedCharacters) {\n str = goog.string.htmlEscape(str);\n }\n\n return str;\n};\n\n\n/**\n * Truncate a string in the middle, adding \"...\" if necessary,\n * and favoring the beginning of the string.\n * @param {string} str The string to truncate the middle of.\n * @param {number} chars Max number of characters.\n * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped\n * characters from being cutoff in the middle.\n * @param {number=} opt_trailingChars Optional number of trailing characters to\n * leave at the end of the string, instead of truncating as close to the\n * middle as possible.\n * @return {string} A truncated copy of `str`.\n */\ngoog.string.truncateMiddle = function(\n str, chars, opt_protectEscapedCharacters, opt_trailingChars) {\n 'use strict';\n if (opt_protectEscapedCharacters) {\n str = goog.string.unescapeEntities(str);\n }\n\n if (opt_trailingChars && str.length > chars) {\n if (opt_trailingChars > chars) {\n opt_trailingChars = chars;\n }\n const endPoint = str.length - opt_trailingChars;\n const startPoint = chars - opt_trailingChars;\n str = str.substring(0, startPoint) + '...' + str.substring(endPoint);\n } else if (str.length > chars) {\n // Favor the beginning of the string:\n let half = Math.floor(chars / 2);\n const endPos = str.length - half;\n half += chars % 2;\n str = str.substring(0, half) + '...' + str.substring(endPos);\n }\n\n if (opt_protectEscapedCharacters) {\n str = goog.string.htmlEscape(str);\n }\n\n return str;\n};\n\n\n/**\n * Special chars that need to be escaped for goog.string.quote.\n * @private {!Object<string, string>}\n */\ngoog.string.specialEscapeChars_ = {\n '\\0': '\\\\0',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n '\\x0B': '\\\\x0B', // '\\v' is not supported in JScript\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n // To support the use case of embedding quoted strings inside of script\n // tags, we have to make sure HTML comments and opening/closing script tags do\n // not appear in the resulting string. The specific strings that must be\n // escaped are documented at:\n // https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements\n '<': '\\\\u003C' // NOTE: JSON.parse crashes on '\\\\x3c'.\n};\n\n\n/**\n * Character mappings used internally for goog.string.escapeChar.\n * @private {!Object<string, string>}\n */\ngoog.string.jsEscapeCache_ = {\n '\\'': '\\\\\\''\n};\n\n\n/**\n * Encloses a string in double quotes and escapes characters so that the\n * string is a valid JS string. The resulting string is safe to embed in\n * `<script>` tags as \"<\" is escaped.\n * @param {string} s The string to quote.\n * @return {string} A copy of `s` surrounded by double quotes.\n */\ngoog.string.quote = function(s) {\n 'use strict';\n s = String(s);\n const sb = ['\"'];\n for (let i = 0; i < s.length; i++) {\n const ch = s.charAt(i);\n const cc = ch.charCodeAt(0);\n sb[i + 1] = goog.string.specialEscapeChars_[ch] ||\n ((cc > 31 && cc < 127) ? ch : goog.string.escapeChar(ch));\n }\n sb.push('\"');\n return sb.join('');\n};\n\n\n/**\n * Takes a string and returns the escaped string for that input string.\n * @param {string} str The string to escape.\n * @return {string} An escaped string representing `str`.\n */\ngoog.string.escapeString = function(str) {\n 'use strict';\n const sb = [];\n for (let i = 0; i < str.length; i++) {\n sb[i] = goog.string.escapeChar(str.charAt(i));\n }\n return sb.join('');\n};\n\n\n/**\n * Takes a character and returns the escaped string for that character. For\n * example escapeChar(String.fromCharCode(15)) -> \"\\\\x0E\".\n * @param {string} c The character to escape.\n * @return {string} An escaped string representing `c`.\n */\ngoog.string.escapeChar = function(c) {\n 'use strict';\n if (c in goog.string.jsEscapeCache_) {\n return goog.string.jsEscapeCache_[c];\n }\n\n if (c in goog.string.specialEscapeChars_) {\n return goog.string.jsEscapeCache_[c] = goog.string.specialEscapeChars_[c];\n }\n\n let rv = c;\n const cc = c.charCodeAt(0);\n if (cc > 31 && cc < 127) {\n rv = c;\n } else {\n // tab is 9 but handled above\n if (cc < 256) {\n rv = '\\\\x';\n if (cc < 16 || cc > 256) {\n rv += '0';\n }\n } else {\n rv = '\\\\u';\n if (cc < 4096) { // \\u1000\n rv += '0';\n }\n }\n rv += cc.toString(16).toUpperCase();\n }\n\n return goog.string.jsEscapeCache_[c] = rv;\n};\n\n\n/**\n * Determines whether a string contains a substring.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n */\ngoog.string.contains = goog.string.internal.contains;\n\n\n/**\n * Determines whether a string contains a substring, ignoring case.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n */\ngoog.string.caseInsensitiveContains =\n goog.string.internal.caseInsensitiveContains;\n\n\n/**\n * Returns the non-overlapping occurrences of ss in s.\n * If either s or ss evalutes to false, then returns zero.\n * @param {string} s The string to look in.\n * @param {string} ss The string to look for.\n * @return {number} Number of occurrences of ss in s.\n */\ngoog.string.countOf = function(s, ss) {\n 'use strict';\n return s && ss ? s.split(ss).length - 1 : 0;\n};\n\n\n/**\n * Removes a substring of a specified length at a specific\n * index in a string.\n * @param {string} s The base string from which to remove.\n * @param {number} index The index at which to remove the substring.\n * @param {number} stringLength The length of the substring to remove.\n * @return {string} A copy of `s` with the substring removed or the full\n * string if nothing is removed or the input is invalid.\n */\ngoog.string.removeAt = function(s, index, stringLength) {\n 'use strict';\n let resultStr = s;\n // If the index is greater or equal to 0 then remove substring\n if (index >= 0 && index < s.length && stringLength > 0) {\n resultStr = s.slice(0, index) + s.slice(index + stringLength);\n }\n return resultStr;\n};\n\n\n/**\n * Removes the first occurrence of a substring from a string.\n * @param {string} str The base string from which to remove.\n * @param {string} substr The string to remove.\n * @return {string} A copy of `str` with `substr` removed or the\n * full string if nothing is removed.\n */\ngoog.string.remove = function(str, substr) {\n 'use strict';\n return str.replace(substr, '');\n};\n\n\n/**\n * Removes all occurrences of a substring from a string.\n * @param {string} s The base string from which to remove.\n * @param {string} ss The string to remove.\n * @return {string} A copy of `s` with `ss` removed or the full\n * string if nothing is removed.\n */\ngoog.string.removeAll = function(s, ss) {\n 'use strict';\n const re = new RegExp(goog.string.regExpEscape(ss), 'g');\n return s.replace(re, '');\n};\n\n\n/**\n * Replaces all occurrences of a substring of a string with a new substring.\n * @param {string} s The base string from which to remove.\n * @param {string} ss The string to replace.\n * @param {string} replacement The replacement string.\n * @return {string} A copy of `s` with `ss` replaced by\n * `replacement` or the original string if nothing is replaced.\n */\ngoog.string.replaceAll = function(s, ss, replacement) {\n 'use strict';\n const re = new RegExp(goog.string.regExpEscape(ss), 'g');\n return s.replace(re, replacement.replace(/\\$/g, '$$$$'));\n};\n\n\n/**\n * Escapes characters in the string that are not safe to use in a RegExp.\n * @param {*} s The string to escape. If not a string, it will be casted\n * to one.\n * @return {string} A RegExp safe, escaped copy of `s`.\n */\ngoog.string.regExpEscape = function(s) {\n 'use strict';\n return String(s)\n .replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g, '\\\\$1')\n .replace(/\\x08/g, '\\\\x08');\n};\n\n\n/**\n * Repeats a string n times.\n * @param {string} string The string to repeat.\n * @param {number} length The number of times to repeat.\n * @return {string} A string containing `length` repetitions of\n * `string`.\n */\ngoog.string.repeat = (String.prototype.repeat) ? function(string, length) {\n 'use strict';\n // The native method is over 100 times faster than the alternative.\n return string.repeat(length);\n} : function(string, length) {\n 'use strict';\n return new Array(length + 1).join(string);\n};\n\n\n/**\n * Pads number to given length and optionally rounds it to a given precision.\n * For example:\n * <pre>padNumber(1.25, 2, 3) -> '01.250'\n * padNumber(1.25, 2) -> '01.25'\n * padNumber(1.25, 2, 1) -> '01.3'\n * padNumber(1.25, 0) -> '1.25'</pre>\n *\n * @param {number} num The number to pad.\n * @param {number} length The desired length.\n * @param {number=} opt_precision The desired precision.\n * @return {string} `num` as a string with the given options.\n */\ngoog.string.padNumber = function(num, length, opt_precision) {\n 'use strict';\n if (!Number.isFinite(num)) return String(num);\n let s =\n (opt_precision !== undefined) ? num.toFixed(opt_precision) : String(num);\n let index = s.indexOf('.');\n if (index === -1) {\n index = s.length;\n }\n const sign = s[0] === '-' ? '-' : '';\n if (sign) {\n s = s.substring(1);\n }\n return sign + goog.string.repeat('0', Math.max(0, length - index)) + s;\n};\n\n\n/**\n * Returns a string representation of the given object, with\n * null and undefined being returned as the empty string.\n *\n * @param {*} obj The object to convert.\n * @return {string} A string representation of the `obj`.\n */\ngoog.string.makeSafe = function(obj) {\n 'use strict';\n return obj == null ? '' : String(obj);\n};\n\n/**\n * Returns a string with at least 64-bits of randomness.\n *\n * Doesn't trust JavaScript's random function entirely. Uses a combination of\n * random and current timestamp, and then encodes the string in base-36 to\n * make it shorter.\n *\n * @return {string} A random string, e.g. sn1s7vb4gcic.\n */\ngoog.string.getRandomString = function() {\n 'use strict';\n const x = 2147483648;\n return Math.floor(Math.random() * x).toString(36) +\n Math.abs(Math.floor(Math.random() * x) ^ goog.now()).toString(36);\n};\n\n\n/**\n * Compares two version numbers.\n *\n * @param {string|number} version1 Version of first item.\n * @param {string|number} version2 Version of second item.\n *\n * @return {number} 1 if `version1` is higher.\n * 0 if arguments are equal.\n * -1 if `version2` is higher.\n */\ngoog.string.compareVersions = goog.string.internal.compareVersions;\n\n\n/**\n * String hash function similar to java.lang.String.hashCode().\n * The hash code for a string is computed as\n * s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],\n * where s[i] is the ith character of the string and n is the length of\n * the string. We mod the result to make it between 0 (inclusive) and 2^32\n * (exclusive).\n * @param {string} str A string.\n * @return {number} Hash value for `str`, between 0 (inclusive) and 2^32\n * (exclusive). The empty string returns 0.\n */\ngoog.string.hashCode = function(str) {\n 'use strict';\n let result = 0;\n for (let i = 0; i < str.length; ++i) {\n // Normalize to 4 byte range, 0 ... 2^32.\n result = (31 * result + str.charCodeAt(i)) >>> 0;\n }\n return result;\n};\n\n\n/**\n * The most recent unique ID. |0 is equivalent to Math.floor in this case.\n * @type {number}\n * @private\n */\ngoog.string.uniqueStringCounter_ = Math.random() * 0x80000000 | 0;\n\n\n/**\n * Generates and returns a string which is unique in the current document.\n * This is useful, for example, to create unique IDs for DOM elements.\n * @return {string} A unique id.\n */\ngoog.string.createUniqueString = function() {\n 'use strict';\n return 'goog_' + goog.string.uniqueStringCounter_++;\n};\n\n\n/**\n * Converts the supplied string to a number, which may be Infinity or NaN.\n * This function strips whitespace: (toNumber(' 123') === 123)\n * This function accepts scientific notation: (toNumber('1e1') === 10)\n *\n * This is better than JavaScript's built-in conversions because, sadly:\n * (Number(' ') === 0) and (parseFloat('123a') === 123)\n *\n * @param {string} str The string to convert.\n * @return {number} The number the supplied string represents, or NaN.\n */\ngoog.string.toNumber = function(str) {\n 'use strict';\n const num = Number(str);\n if (num == 0 && goog.string.isEmptyOrWhitespace(str)) {\n return NaN;\n }\n return num;\n};\n\n\n/**\n * Returns whether the given string is lower camel case (e.g. \"isFooBar\").\n *\n * Note that this assumes the string is entirely letters.\n * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms\n *\n * @param {string} str String to test.\n * @return {boolean} Whether the string is lower camel case.\n */\ngoog.string.isLowerCamelCase = function(str) {\n 'use strict';\n return /^[a-z]+([A-Z][a-z]*)*$/.test(str);\n};\n\n\n/**\n * Returns whether the given string is upper camel case (e.g. \"FooBarBaz\").\n *\n * Note that this assumes the string is entirely letters.\n * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms\n *\n * @param {string} str String to test.\n * @return {boolean} Whether the string is upper camel case.\n */\ngoog.string.isUpperCamelCase = function(str) {\n 'use strict';\n return /^([A-Z][a-z]*)+$/.test(str);\n};\n\n\n/**\n * Converts a string from selector-case to camelCase (e.g. from\n * \"multi-part-string\" to \"multiPartString\"), useful for converting\n * CSS selectors and HTML dataset keys to their equivalent JS properties.\n * @param {string} str The string in selector-case form.\n * @return {string} The string in camelCase form.\n */\ngoog.string.toCamelCase = function(str) {\n 'use strict';\n return String(str).replace(/\\-([a-z])/g, function(all, match) {\n 'use strict';\n return match.toUpperCase();\n });\n};\n\n\n/**\n * Converts a string from camelCase to selector-case (e.g. from\n * \"multiPartString\" to \"multi-part-string\"), useful for converting JS\n * style and dataset properties to equivalent CSS selectors and HTML keys.\n * @param {string} str The string in camelCase form.\n * @return {string} The string in selector-case form.\n */\ngoog.string.toSelectorCase = function(str) {\n 'use strict';\n return String(str).replace(/([A-Z])/g, '-$1').toLowerCase();\n};\n\n\n/**\n * Converts a string into TitleCase. First character of the string is always\n * capitalized in addition to the first letter of every subsequent word.\n * Words are delimited by one or more whitespaces by default. Custom delimiters\n * can optionally be specified to replace the default, which doesn't preserve\n * whitespace delimiters and instead must be explicitly included if needed.\n *\n * Default delimiter => \" \":\n * goog.string.toTitleCase('oneTwoThree') => 'OneTwoThree'\n * goog.string.toTitleCase('one two three') => 'One Two Three'\n * goog.string.toTitleCase(' one two ') => ' One Two '\n * goog.string.toTitleCase('one_two_three') => 'One_two_three'\n * goog.string.toTitleCase('one-two-three') => 'One-two-three'\n *\n * Custom delimiter => \"_-.\":\n * goog.string.toTitleCase('oneTwoThree', '_-.') => 'OneTwoThree'\n * goog.string.toTitleCase('one two three', '_-.') => 'One two three'\n * goog.string.toTitleCase(' one two ', '_-.') => ' one two '\n * goog.string.toTitleCase('one_two_three', '_-.') => 'One_Two_Three'\n * goog.string.toTitleCase('one-two-three', '_-.') => 'One-Two-Three'\n * goog.string.toTitleCase('one...two...three', '_-.') => 'One...Two...Three'\n * goog.string.toTitleCase('one. two. three', '_-.') => 'One. two. three'\n * goog.string.toTitleCase('one-two.three', '_-.') => 'One-Two.Three'\n *\n * @param {string} str String value in camelCase form.\n * @param {string=} opt_delimiters Custom delimiter character set used to\n * distinguish words in the string value. Each character represents a\n * single delimiter. When provided, default whitespace delimiter is\n * overridden and must be explicitly included if needed.\n * @return {string} String value in TitleCase form.\n */\ngoog.string.toTitleCase = function(str, opt_delimiters) {\n 'use strict';\n let delimiters = (typeof opt_delimiters === 'string') ?\n goog.string.regExpEscape(opt_delimiters) :\n '\\\\s';\n\n // For IE8, we need to prevent using an empty character set. Otherwise,\n // incorrect matching will occur.\n delimiters = delimiters ? '|[' + delimiters + ']+' : '';\n\n const regexp = new RegExp('(^' + delimiters + ')([a-z])', 'g');\n return str.replace(regexp, function(all, p1, p2) {\n 'use strict';\n return p1 + p2.toUpperCase();\n });\n};\n\n\n/**\n * Capitalizes a string, i.e. converts the first letter to uppercase\n * and all other letters to lowercase, e.g.:\n *\n * goog.string.capitalize('one') => 'One'\n * goog.string.capitalize('ONE') => 'One'\n * goog.string.capitalize('one two') => 'One two'\n *\n * Note that this function does not trim initial whitespace.\n *\n * @param {string} str String value to capitalize.\n * @return {string} String value with first letter in uppercase.\n */\ngoog.string.capitalize = function(str) {\n 'use strict';\n return String(str.charAt(0)).toUpperCase() +\n String(str.slice(1)).toLowerCase();\n};\n\n\n/**\n * Parse a string in decimal or hexidecimal ('0xFFFF') form.\n *\n * To parse a particular radix, please use parseInt(string, radix) directly. See\n * https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt\n *\n * This is a wrapper for the built-in parseInt function that will only parse\n * numbers as base 10 or base 16. Some JS implementations assume strings\n * starting with \"0\" are intended to be octal. ES3 allowed but discouraged\n * this behavior. ES5 forbids it. This function emulates the ES5 behavior.\n *\n * For more information, see Mozilla JS Reference: http://goo.gl/8RiFj\n *\n * @param {string|number|null|undefined} value The value to be parsed.\n * @return {number} The number, parsed. If the string failed to parse, this\n * will be NaN.\n */\ngoog.string.parseInt = function(value) {\n 'use strict';\n // Force finite numbers to strings.\n if (isFinite(value)) {\n value = String(value);\n }\n\n if (typeof value === 'string') {\n // If the string starts with '0x' or '-0x', parse as hex.\n return /^\\s*-?0x/i.test(value) ? parseInt(value, 16) : parseInt(value, 10);\n }\n\n return NaN;\n};\n\n\n/**\n * Splits a string on a separator a limited number of times.\n *\n * This implementation is more similar to Python or Java, where the limit\n * parameter specifies the maximum number of splits rather than truncating\n * the number of results.\n *\n * See http://docs.python.org/2/library/stdtypes.html#str.split\n * See JavaDoc: http://goo.gl/F2AsY\n * See Mozilla reference: http://goo.gl/dZdZs\n *\n * @param {string} str String to split.\n * @param {string} separator The separator.\n * @param {number} limit The limit to the number of splits. The resulting array\n * will have a maximum length of limit+1. Negative numbers are the same\n * as zero.\n * @return {!Array<string>} The string, split.\n */\ngoog.string.splitLimit = function(str, separator, limit) {\n 'use strict';\n const parts = str.split(separator);\n const returnVal = [];\n\n // Only continue doing this while we haven't hit the limit and we have\n // parts left.\n while (limit > 0 && parts.length) {\n returnVal.push(parts.shift());\n limit--;\n }\n\n // If there are remaining parts, append them to the end.\n if (parts.length) {\n returnVal.push(parts.join(separator));\n }\n\n return returnVal;\n};\n\n\n/**\n * Finds the characters to the right of the last instance of any separator\n *\n * This function is similar to goog.string.path.baseName, except it can take a\n * list of characters to split the string on. It will return the rightmost\n * grouping of characters to the right of any separator as a left-to-right\n * oriented string.\n *\n * @see goog.string.path.baseName\n * @param {string} str The string\n * @param {string|!Array<string>} separators A list of separator characters\n * @return {string} The last part of the string with respect to the separators\n */\ngoog.string.lastComponent = function(str, separators) {\n 'use strict';\n if (!separators) {\n return str;\n } else if (typeof separators == 'string') {\n separators = [separators];\n }\n\n let lastSeparatorIndex = -1;\n for (let i = 0; i < separators.length; i++) {\n if (separators[i] == '') {\n continue;\n }\n const currentSeparatorIndex = str.lastIndexOf(separators[i]);\n if (currentSeparatorIndex > lastSeparatorIndex) {\n lastSeparatorIndex = currentSeparatorIndex;\n }\n }\n if (lastSeparatorIndex == -1) {\n return str;\n }\n return str.slice(lastSeparatorIndex + 1);\n};\n\n\n/**\n * Computes the Levenshtein edit distance between two strings.\n * @param {string} a\n * @param {string} b\n * @return {number} The edit distance between the two strings.\n */\ngoog.string.editDistance = function(a, b) {\n 'use strict';\n const v0 = [];\n const v1 = [];\n\n if (a == b) {\n return 0;\n }\n\n if (!a.length || !b.length) {\n return Math.max(a.length, b.length);\n }\n\n for (let i = 0; i < b.length + 1; i++) {\n v0[i] = i;\n }\n\n for (let i = 0; i < a.length; i++) {\n v1[0] = i + 1;\n\n for (let j = 0; j < b.length; j++) {\n const cost = Number(a[i] != b[j]);\n // Cost for the substring is the minimum of adding one character, removing\n // one character, or a swap.\n v1[j + 1] = Math.min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost);\n }\n\n for (let j = 0; j < v0.length; j++) {\n v0[j] = v1[j];\n }\n }\n\n return v1[b.length];\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Wrapper class for handling XmlHttpRequests.\n *\n * One off requests can be sent through goog.net.XhrIo.send() or an\n * instance can be created to send multiple requests. Each request uses its\n * own XmlHttpRequest object and handles clearing of the event callback to\n * ensure no leaks.\n *\n * XhrIo is event based, it dispatches events on success, failure, finishing,\n * ready-state change, or progress (download and upload).\n *\n * The ready-state or timeout event fires first, followed by\n * a generic completed event. Then the abort, error, or success event\n * is fired as appropriate. Progress events are fired as they are\n * received. Lastly, the ready event will fire to indicate that the\n * object may be used to make another request.\n *\n * The error event may also be called before completed and\n * ready-state-change if the XmlHttpRequest.open() or .send() methods throw.\n *\n * This class does not support multiple requests, queuing, or prioritization.\n *\n * When progress events are supported by the browser, and progress is\n * enabled via .setProgressEventsEnabled(true), the\n * goog.net.EventType.PROGRESS event will be the re-dispatched browser\n * progress event. Additionally, a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event\n * will be fired for download and upload progress respectively.\n */\n\n\ngoog.provide('goog.net.XhrIo');\ngoog.provide('goog.net.XhrIo.ResponseType');\n\ngoog.require('goog.Timer');\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.debug.entryPointRegistry');\ngoog.require('goog.events.EventTarget');\ngoog.require('goog.json.hybrid');\ngoog.require('goog.log');\ngoog.require('goog.net.ErrorCode');\ngoog.require('goog.net.EventType');\ngoog.require('goog.net.HttpStatus');\ngoog.require('goog.net.XmlHttp');\ngoog.require('goog.object');\ngoog.require('goog.string');\ngoog.require('goog.uri.utils');\ngoog.require('goog.userAgent');\ngoog.requireType('goog.Uri');\ngoog.requireType('goog.debug.ErrorHandler');\ngoog.requireType('goog.net.XhrLike');\ngoog.requireType('goog.net.XmlHttpFactory');\n\ngoog.scope(function() {\n\n'use strict';\n/**\n * Basic class for handling XMLHttpRequests.\n * @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when\n * creating XMLHttpRequest objects.\n * @constructor\n * @extends {goog.events.EventTarget}\n */\ngoog.net.XhrIo = function(opt_xmlHttpFactory) {\n 'use strict';\n XhrIo.base(this, 'constructor');\n\n /**\n * Map of default headers to add to every request, use:\n * XhrIo.headers.set(name, value)\n * @type {!Map<string,string>}\n */\n this.headers = new Map();\n\n /**\n * Optional XmlHttpFactory\n * @private {goog.net.XmlHttpFactory}\n */\n this.xmlHttpFactory_ = opt_xmlHttpFactory || null;\n\n /**\n * Whether XMLHttpRequest is active. A request is active from the time send()\n * is called until onReadyStateChange() is complete, or error() or abort()\n * is called.\n * @private {boolean}\n */\n this.active_ = false;\n\n /**\n * The XMLHttpRequest object that is being used for the transfer.\n * @private {?goog.net.XhrLike.OrNative}\n */\n this.xhr_ = null;\n\n /**\n * The options to use with the current XMLHttpRequest object.\n * @private {?Object}\n */\n this.xhrOptions_ = null;\n\n /**\n * Last URL that was requested.\n * @private {string|goog.Uri}\n */\n this.lastUri_ = '';\n\n /**\n * Method for the last request.\n * @private {string}\n */\n this.lastMethod_ = '';\n\n /**\n * Last error code.\n * @private {!goog.net.ErrorCode}\n */\n this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;\n\n /**\n * Last error message.\n * @private {Error|string}\n */\n this.lastError_ = '';\n\n /**\n * Used to ensure that we don't dispatch an multiple ERROR events. This can\n * happen in IE when it does a synchronous load and one error is handled in\n * the ready state change and one is handled due to send() throwing an\n * exception.\n * @private {boolean}\n */\n this.errorDispatched_ = false;\n\n /**\n * Used to make sure we don't fire the complete event from inside a send call.\n * @private {boolean}\n */\n this.inSend_ = false;\n\n /**\n * Used in determining if a call to {@link #onReadyStateChange_} is from\n * within a call to this.xhr_.open.\n * @private {boolean}\n */\n this.inOpen_ = false;\n\n /**\n * Used in determining if a call to {@link #onReadyStateChange_} is from\n * within a call to this.xhr_.abort.\n * @private {boolean}\n */\n this.inAbort_ = false;\n\n /**\n * Number of milliseconds after which an incomplete request will be aborted\n * and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout\n * is set.\n * @private {number}\n */\n this.timeoutInterval_ = 0;\n\n /**\n * Timer to track request timeout.\n * @private {?number}\n */\n this.timeoutId_ = null;\n\n /**\n * The requested type for the response. The empty string means use the default\n * XHR behavior.\n * @private {goog.net.XhrIo.ResponseType}\n */\n this.responseType_ = ResponseType.DEFAULT;\n\n /**\n * Whether a \"credentialed\" request is to be sent (one that is aware of\n * cookies and authentication). This is applicable only for cross-domain\n * requests and more recent browsers that support this part of the HTTP Access\n * Control standard.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute\n *\n * @private {boolean}\n */\n this.withCredentials_ = false;\n\n /**\n * Whether progress events are enabled for this request. This is\n * disabled by default because setting a progress event handler\n * causes pre-flight OPTIONS requests to be sent for CORS requests,\n * even in cases where a pre-flight request would not otherwise be\n * sent.\n *\n * @see http://xhr.spec.whatwg.org/#security-considerations\n *\n * Note that this can cause problems for Firefox 22 and below, as an\n * older \"LSProgressEvent\" will be dispatched by the browser. That\n * progress event is no longer supported, and can lead to failures,\n * including throwing exceptions.\n *\n * @see http://bugzilla.mozilla.org/show_bug.cgi?id=845631\n * @see b/23469793\n *\n * @private {boolean}\n */\n this.progressEventsEnabled_ = false;\n\n /**\n * True if we can use XMLHttpRequest's timeout directly.\n * @private {boolean}\n */\n this.useXhr2Timeout_ = false;\n\n /**\n * Specification for Trust Token operations (issuance, signing, and\n * redemption).\n * @private {?TrustTokenAttributeType}\n */\n this.trustToken_ = null;\n};\ngoog.inherits(goog.net.XhrIo, goog.events.EventTarget);\n\nconst XhrIo = goog.net.XhrIo;\n\n/**\n * Response types that may be requested for XMLHttpRequests.\n * @enum {string}\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute\n */\ngoog.net.XhrIo.ResponseType = {\n DEFAULT: '',\n TEXT: 'text',\n DOCUMENT: 'document',\n // Not supported as of Chrome 10.0.612.1 dev\n BLOB: 'blob',\n ARRAY_BUFFER: 'arraybuffer',\n};\n\nconst ResponseType = goog.net.XhrIo.ResponseType;\n\n\n/**\n * A reference to the XhrIo logger\n * @private {?goog.log.Logger}\n * @const\n */\ngoog.net.XhrIo.prototype.logger_ = goog.log.getLogger('goog.net.XhrIo');\n\n\n/**\n * The Content-Type HTTP header name\n * @type {string}\n */\ngoog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type';\n\n\n/**\n * The Content-Transfer-Encoding HTTP header name\n * @type {string}\n */\ngoog.net.XhrIo.CONTENT_TRANSFER_ENCODING = 'Content-Transfer-Encoding';\n\n\n/**\n * The pattern matching the 'http' and 'https' URI schemes\n * @type {!RegExp}\n */\ngoog.net.XhrIo.HTTP_SCHEME_PATTERN = /^https?$/i;\n\nconst HTTP_SCHEME_PATTERN = goog.net.XhrIo.HTTP_SCHEME_PATTERN;\n\n\n/**\n * The methods that typically come along with form data. We set different\n * headers depending on whether the HTTP action is one of these.\n * @type {!Array<string>}\n */\ngoog.net.XhrIo.METHODS_WITH_FORM_DATA = ['POST', 'PUT'];\n\n\n/**\n * The Content-Type HTTP header value for a url-encoded form\n * @type {string}\n */\ngoog.net.XhrIo.FORM_CONTENT_TYPE =\n 'application/x-www-form-urlencoded;charset=utf-8';\n\n\n/**\n * The XMLHttpRequest Level two timeout delay ms property name.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\n *\n * @private {string}\n * @const\n */\ngoog.net.XhrIo.XHR2_TIMEOUT_ = 'timeout';\n\n\n/**\n * The XMLHttpRequest Level two ontimeout handler property name.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\n *\n * @private {string}\n * @const\n */\ngoog.net.XhrIo.XHR2_ON_TIMEOUT_ = 'ontimeout';\n\n\n/**\n * All non-disposed instances of goog.net.XhrIo created\n * by {@link goog.net.XhrIo.send} are in this Array.\n * @see goog.net.XhrIo.cleanup\n * @private {!Array<!goog.net.XhrIo>}\n */\ngoog.net.XhrIo.sendInstances_ = [];\n\n\n/**\n * Static send that creates a short lived instance of XhrIo to send the\n * request.\n * @see goog.net.XhrIo.cleanup\n * @param {string|goog.Uri} url Uri to make request to.\n * @param {?function(this:goog.net.XhrIo, ?)=} opt_callback Callback function\n * for when request is complete.\n * @param {string=} opt_method Send method, default: GET.\n * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}\n * opt_content Body data.\n * @param {(?Object|?goog.collections.maps.MapLike<string, string>)=}\n * opt_headers Map of headers to add to the request.\n * @param {number=} opt_timeoutInterval Number of milliseconds after which an\n * incomplete request will be aborted; 0 means no timeout is set.\n * @param {boolean=} opt_withCredentials Whether to send credentials with the\n * request. Default to false. See {@link goog.net.XhrIo#setWithCredentials}.\n * @return {!goog.net.XhrIo} The sent XhrIo.\n */\ngoog.net.XhrIo.send = function(\n url, opt_callback, opt_method, opt_content, opt_headers,\n opt_timeoutInterval, opt_withCredentials) {\n 'use strict';\n const x = new goog.net.XhrIo();\n goog.net.XhrIo.sendInstances_.push(x);\n if (opt_callback) {\n x.listen(goog.net.EventType.COMPLETE, opt_callback);\n }\n x.listenOnce(goog.net.EventType.READY, x.cleanupSend_);\n if (opt_timeoutInterval) {\n x.setTimeoutInterval(opt_timeoutInterval);\n }\n if (opt_withCredentials) {\n x.setWithCredentials(opt_withCredentials);\n }\n x.send(url, opt_method, opt_content, opt_headers);\n return x;\n};\n\n\n/**\n * Disposes all non-disposed instances of goog.net.XhrIo created by\n * {@link goog.net.XhrIo.send}.\n * {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance\n * it creates when the request completes or fails. However, if\n * the request never completes, then the goog.net.XhrIo is not disposed.\n * This can occur if the window is unloaded before the request completes.\n * We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo\n * it creates and make the client of {@link goog.net.XhrIo.send} be\n * responsible for disposing it in this case. However, this makes things\n * significantly more complicated for the client, and the whole point\n * of {@link goog.net.XhrIo.send} is that it's simple and easy to use.\n * Clients of {@link goog.net.XhrIo.send} should call\n * {@link goog.net.XhrIo.cleanup} when doing final\n * cleanup on window unload.\n */\ngoog.net.XhrIo.cleanup = function() {\n 'use strict';\n const instances = goog.net.XhrIo.sendInstances_;\n while (instances.length) {\n instances.pop().dispose();\n }\n};\n\n\n/**\n * Installs exception protection for all entry point introduced by\n * goog.net.XhrIo instances which are not protected by\n * {@link goog.debug.ErrorHandler#protectWindowSetTimeout},\n * {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or\n * {@link goog.events.protectBrowserEventEntryPoint}.\n *\n * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to\n * protect the entry point(s).\n */\ngoog.net.XhrIo.protectEntryPoints = function(errorHandler) {\n 'use strict';\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =\n errorHandler.protectEntryPoint(\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);\n};\n\n\n/**\n * Disposes of the specified goog.net.XhrIo created by\n * {@link goog.net.XhrIo.send} and removes it from\n * {@link goog.net.XhrIo.pendingStaticSendInstances_}.\n * @private\n */\ngoog.net.XhrIo.prototype.cleanupSend_ = function() {\n 'use strict';\n this.dispose();\n goog.array.remove(goog.net.XhrIo.sendInstances_, this);\n};\n\n\n/**\n * Returns the number of milliseconds after which an incomplete request will be\n * aborted, or 0 if no timeout is set.\n * @return {number} Timeout interval in milliseconds.\n */\ngoog.net.XhrIo.prototype.getTimeoutInterval = function() {\n 'use strict';\n return this.timeoutInterval_;\n};\n\n\n/**\n * Sets the number of milliseconds after which an incomplete request will be\n * aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no\n * timeout is set.\n * @param {number} ms Timeout interval in milliseconds; 0 means none.\n */\ngoog.net.XhrIo.prototype.setTimeoutInterval = function(ms) {\n 'use strict';\n this.timeoutInterval_ = Math.max(0, ms);\n};\n\n\n/**\n * Sets the desired type for the response. At time of writing, this is only\n * supported in very recent versions of WebKit (10.0.612.1 dev and later).\n *\n * If this is used, the response may only be accessed via {@link #getResponse}.\n *\n * @param {goog.net.XhrIo.ResponseType} type The desired type for the response.\n */\ngoog.net.XhrIo.prototype.setResponseType = function(type) {\n 'use strict';\n this.responseType_ = type;\n};\n\n\n/**\n * Gets the desired type for the response.\n * @return {goog.net.XhrIo.ResponseType} The desired type for the response.\n */\ngoog.net.XhrIo.prototype.getResponseType = function() {\n 'use strict';\n return this.responseType_;\n};\n\n\n/**\n * Sets whether a \"credentialed\" request that is aware of cookie and\n * authentication information should be made. This option is only supported by\n * browsers that support HTTP Access Control. As of this writing, this option\n * is not supported in IE.\n *\n * @param {boolean} withCredentials Whether this should be a \"credentialed\"\n * request.\n */\ngoog.net.XhrIo.prototype.setWithCredentials = function(withCredentials) {\n 'use strict';\n this.withCredentials_ = withCredentials;\n};\n\n\n/**\n * Gets whether a \"credentialed\" request is to be sent.\n * @return {boolean} The desired type for the response.\n */\ngoog.net.XhrIo.prototype.getWithCredentials = function() {\n 'use strict';\n return this.withCredentials_;\n};\n\n\n/**\n * Sets whether progress events are enabled for this request. Note\n * that progress events require pre-flight OPTIONS request handling\n * for CORS requests, and may cause trouble with older browsers. See\n * progressEventsEnabled_ for details.\n * @param {boolean} enabled Whether progress events should be enabled.\n */\ngoog.net.XhrIo.prototype.setProgressEventsEnabled = function(enabled) {\n 'use strict';\n this.progressEventsEnabled_ = enabled;\n};\n\n\n/**\n * Gets whether progress events are enabled.\n * @return {boolean} Whether progress events are enabled for this request.\n */\ngoog.net.XhrIo.prototype.getProgressEventsEnabled = function() {\n 'use strict';\n return this.progressEventsEnabled_;\n};\n\n/**\n * Specify a Trust Tokens operation to execute alongside the request.\n * @param {!TrustTokenAttributeType} trustToken a Trust Tokens operation to\n * execute.\n */\ngoog.net.XhrIo.prototype.setTrustToken = function(trustToken) {\n 'use strict';\n this.trustToken_ = trustToken;\n};\n\n/**\n * Instance send that actually uses XMLHttpRequest to make a server call.\n * @param {string|goog.Uri} url Uri to make request to.\n * @param {string=} opt_method Send method, default: GET.\n * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}\n * opt_content Body data.\n * @param {(?Object|?goog.collections.maps.MapLike<string, string>)=}\n * opt_headers Map of headers to add to the request.\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different\n * types of parameters for opt_headers.\n */\ngoog.net.XhrIo.prototype.send = function(\n url, opt_method, opt_content, opt_headers) {\n 'use strict';\n if (this.xhr_) {\n throw new Error(\n '[goog.net.XhrIo] Object is active with another request=' +\n this.lastUri_ + '; newUri=' + url);\n }\n\n const method = opt_method ? opt_method.toUpperCase() : 'GET';\n\n this.lastUri_ = url;\n this.lastError_ = '';\n this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;\n this.lastMethod_ = method;\n this.errorDispatched_ = false;\n this.active_ = true;\n\n // Use the factory to create the XHR object and options\n this.xhr_ = this.createXhr();\n this.xhrOptions_ = this.xmlHttpFactory_ ? this.xmlHttpFactory_.getOptions() :\n goog.net.XmlHttp.getOptions();\n\n // Set up the onreadystatechange callback\n this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this);\n\n // Set up upload/download progress events, if progress events are supported.\n if (this.getProgressEventsEnabled() && 'onprogress' in this.xhr_) {\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n this.xhr_.onprogress = goog.bind(function(e) {\n 'use strict';\n this.onProgressHandler_(e, true);\n }, this);\n if (this.xhr_.upload) {\n /**\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\n this.xhr_.upload.onprogress = goog.bind(this.onProgressHandler_, this);\n }\n }\n\n /**\n * Try to open the XMLHttpRequest (always async), if an error occurs here it\n * is generally permission denied\n */\n try {\n goog.log.fine(this.logger_, this.formatMsg_('Opening Xhr'));\n this.inOpen_ = true;\n this.xhr_.open(method, String(url), true); // Always async!\n this.inOpen_ = false;\n } catch (err) {\n goog.log.fine(\n this.logger_, this.formatMsg_('Error opening Xhr: ' + err.message));\n this.error_(goog.net.ErrorCode.EXCEPTION, err);\n return;\n }\n\n // We can't use null since this won't allow requests with form data to have a\n // content length specified which will cause some proxies to return a 411\n // error.\n const content = opt_content || '';\n\n const headers = new Map(this.headers);\n\n // Add headers specific to this request\n if (opt_headers) {\n if (Object.getPrototypeOf(opt_headers) === Object.prototype) {\n for (let key in opt_headers) {\n headers.set(key, opt_headers[key]);\n }\n } else if (\n typeof opt_headers.keys === 'function' &&\n typeof opt_headers.get === 'function') {\n for (const key of opt_headers.keys()) {\n headers.set(key, opt_headers.get(key));\n }\n } else {\n throw new Error(\n 'Unknown input type for opt_headers: ' + String(opt_headers));\n }\n }\n\n // Find whether a content type header is set, ignoring case.\n // HTTP header names are case-insensitive. See:\n // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2\n const contentTypeKey =\n Array.from(headers.keys())\n .find(\n header => goog.string.caseInsensitiveEquals(\n goog.net.XhrIo.CONTENT_TYPE_HEADER, header));\n\n const contentIsFormData =\n (goog.global['FormData'] && (content instanceof goog.global['FormData']));\n if (goog.array.contains(goog.net.XhrIo.METHODS_WITH_FORM_DATA, method) &&\n !contentTypeKey && !contentIsFormData) {\n // For requests typically with form data, default to the url-encoded form\n // content type unless this is a FormData request. For FormData,\n // the browser will automatically add a multipart/form-data content type\n // with an appropriate multipart boundary.\n headers.set(\n goog.net.XhrIo.CONTENT_TYPE_HEADER, goog.net.XhrIo.FORM_CONTENT_TYPE);\n }\n\n // Add the headers to the Xhr object\n for (const [key, value] of headers) {\n this.xhr_.setRequestHeader(key, value);\n }\n\n if (this.responseType_) {\n this.xhr_.responseType = this.responseType_;\n }\n // Set xhr_.withCredentials only when the value is different, or else in\n // synchronous XMLHtppRequest.open Firefox will throw an exception.\n // https://bugzilla.mozilla.org/show_bug.cgi?id=736340\n if ('withCredentials' in this.xhr_ &&\n this.xhr_.withCredentials !== this.withCredentials_) {\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n this.xhr_.withCredentials = this.withCredentials_;\n }\n\n if ('setTrustToken' in this.xhr_ && this.trustToken_) {\n try {\n this.xhr_.setTrustToken(this.trustToken_);\n } catch (err) {\n goog.log.fine(\n this.logger_, this.formatMsg_('Error SetTrustToken: ' + err.message));\n }\n }\n /**\n * Try to send the request, or other wise report an error (404 not found).\n */\n try {\n this.cleanUpTimeoutTimer_(); // Paranoid, should never be running.\n if (this.timeoutInterval_ > 0) {\n this.useXhr2Timeout_ = goog.net.XhrIo.shouldUseXhr2Timeout_(this.xhr_);\n goog.log.fine(\n this.logger_,\n this.formatMsg_(\n 'Will abort after ' + this.timeoutInterval_ +\n 'ms if incomplete, xhr2 ' + this.useXhr2Timeout_));\n if (this.useXhr2Timeout_) {\n this.xhr_[goog.net.XhrIo.XHR2_TIMEOUT_] = this.timeoutInterval_;\n this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] =\n goog.bind(this.timeout_, this);\n } else {\n this.timeoutId_ =\n goog.Timer.callOnce(this.timeout_, this.timeoutInterval_, this);\n }\n }\n goog.log.fine(this.logger_, this.formatMsg_('Sending request'));\n this.inSend_ = true;\n this.xhr_.send(content);\n this.inSend_ = false;\n\n } catch (err) {\n goog.log.fine(this.logger_, this.formatMsg_('Send error: ' + err.message));\n this.error_(goog.net.ErrorCode.EXCEPTION, err);\n }\n};\n\n\n/**\n * Determines if the argument is an XMLHttpRequest that supports the level 2\n * timeout value and event.\n *\n * Currently, FF 21.0 OS X has the fields but won't actually call the timeout\n * handler. Perhaps the confusion in the bug referenced below hasn't\n * entirely been resolved.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\n * @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816\n *\n * @param {!goog.net.XhrLike.OrNative} xhr The request.\n * @return {boolean} True if the request supports level 2 timeout.\n * @private\n */\ngoog.net.XhrIo.shouldUseXhr2Timeout_ = function(xhr) {\n 'use strict';\n return goog.userAgent.IE &&\n typeof xhr[goog.net.XhrIo.XHR2_TIMEOUT_] === 'number' &&\n xhr[goog.net.XhrIo.XHR2_ON_TIMEOUT_] !== undefined;\n};\n\n\n/**\n * Creates a new XHR object.\n * @return {!goog.net.XhrLike.OrNative} The newly created XHR object.\n * @protected\n */\ngoog.net.XhrIo.prototype.createXhr = function() {\n 'use strict';\n return this.xmlHttpFactory_ ? this.xmlHttpFactory_.createInstance() :\n goog.net.XmlHttp();\n};\n\n\n/**\n * The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_}\n * milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts\n * the request.\n * @private\n */\ngoog.net.XhrIo.prototype.timeout_ = function() {\n 'use strict';\n if (typeof goog == 'undefined') {\n // If goog is undefined then the callback has occurred as the application\n // is unloading and will error. Thus we let it silently fail.\n } else if (this.xhr_) {\n this.lastError_ =\n 'Timed out after ' + this.timeoutInterval_ + 'ms, aborting';\n this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT;\n goog.log.fine(this.logger_, this.formatMsg_(this.lastError_));\n this.dispatchEvent(goog.net.EventType.TIMEOUT);\n this.abort(goog.net.ErrorCode.TIMEOUT);\n }\n};\n\n\n/**\n * Something errorred, so inactivate, fire error callback and clean up\n * @param {goog.net.ErrorCode} errorCode The error code.\n * @param {Error} err The error object.\n * @private\n */\ngoog.net.XhrIo.prototype.error_ = function(errorCode, err) {\n 'use strict';\n this.active_ = false;\n if (this.xhr_) {\n this.inAbort_ = true;\n this.xhr_.abort(); // Ensures XHR isn't hung (FF)\n this.inAbort_ = false;\n }\n this.lastError_ = err;\n this.lastErrorCode_ = errorCode;\n this.dispatchErrors_();\n this.cleanUpXhr_();\n};\n\n\n/**\n * Dispatches COMPLETE and ERROR in case of an error. This ensures that we do\n * not dispatch multiple error events.\n * @private\n */\ngoog.net.XhrIo.prototype.dispatchErrors_ = function() {\n 'use strict';\n if (!this.errorDispatched_) {\n this.errorDispatched_ = true;\n this.dispatchEvent(goog.net.EventType.COMPLETE);\n this.dispatchEvent(goog.net.EventType.ERROR);\n }\n};\n\n\n/**\n * Abort the current XMLHttpRequest\n * @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use -\n * defaults to ABORT.\n */\ngoog.net.XhrIo.prototype.abort = function(opt_failureCode) {\n 'use strict';\n if (this.xhr_ && this.active_) {\n goog.log.fine(this.logger_, this.formatMsg_('Aborting'));\n this.active_ = false;\n this.inAbort_ = true;\n this.xhr_.abort();\n this.inAbort_ = false;\n this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT;\n this.dispatchEvent(goog.net.EventType.COMPLETE);\n this.dispatchEvent(goog.net.EventType.ABORT);\n this.cleanUpXhr_();\n }\n};\n\n\n/**\n * Nullifies all callbacks to reduce risks of leaks.\n * @override\n * @protected\n */\ngoog.net.XhrIo.prototype.disposeInternal = function() {\n 'use strict';\n if (this.xhr_) {\n // We explicitly do not call xhr_.abort() unless active_ is still true.\n // This is to avoid unnecessarily aborting a successful request when\n // dispose() is called in a callback triggered by a complete response, but\n // in which browser cleanup has not yet finished.\n // (See http://b/issue?id=1684217.)\n if (this.active_) {\n this.active_ = false;\n this.inAbort_ = true;\n this.xhr_.abort();\n this.inAbort_ = false;\n }\n this.cleanUpXhr_(true);\n }\n\n XhrIo.base(this, 'disposeInternal');\n};\n\n\n/**\n * Internal handler for the XHR object's readystatechange event. This method\n * checks the status and the readystate and fires the correct callbacks.\n * If the request has ended, the handlers are cleaned up and the XHR object is\n * nullified.\n * @private\n */\ngoog.net.XhrIo.prototype.onReadyStateChange_ = function() {\n 'use strict';\n if (this.isDisposed()) {\n // This method is the target of an untracked goog.Timer.callOnce().\n return;\n }\n if (!this.inOpen_ && !this.inSend_ && !this.inAbort_) {\n // Were not being called from within a call to this.xhr_.send\n // this.xhr_.abort, or this.xhr_.open, so this is an entry point\n this.onReadyStateChangeEntryPoint_();\n } else {\n this.onReadyStateChangeHelper_();\n }\n};\n\n\n/**\n * Used to protect the onreadystatechange handler entry point. Necessary\n * as {#onReadyStateChange_} maybe called from within send or abort, this\n * method is only called when {#onReadyStateChange_} is called as an\n * entry point.\n * {@see #protectEntryPoints}\n * @private\n */\ngoog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() {\n 'use strict';\n this.onReadyStateChangeHelper_();\n};\n\n\n/**\n * Helper for {@link #onReadyStateChange_}. This is used so that\n * entry point calls to {@link #onReadyStateChange_} can be routed through\n * {@link #onReadyStateChangeEntryPoint_}.\n * @private\n */\ngoog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() {\n 'use strict';\n if (!this.active_) {\n // can get called inside abort call\n return;\n }\n\n if (typeof goog == 'undefined') {\n // NOTE(user): If goog is undefined then the callback has occurred as the\n // application is unloading and will error. Thus we let it silently fail.\n\n } else if (\n this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] &&\n this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE &&\n this.getStatus() == 2) {\n // NOTE(user): In IE if send() errors on a *local* request the readystate\n // is still changed to COMPLETE. We need to ignore it and allow the\n // try/catch around send() to pick up the error.\n goog.log.fine(\n this.logger_,\n this.formatMsg_('Local request error detected and ignored'));\n\n } else {\n // In IE when the response has been cached we sometimes get the callback\n // from inside the send call and this usually breaks code that assumes that\n // XhrIo is asynchronous. If that is the case we delay the callback\n // using a timer.\n if (this.inSend_ &&\n this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) {\n goog.Timer.callOnce(this.onReadyStateChange_, 0, this);\n return;\n }\n\n this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE);\n\n // readyState indicates the transfer has finished\n if (this.isComplete()) {\n goog.log.fine(this.logger_, this.formatMsg_('Request complete'));\n\n this.active_ = false;\n\n try {\n // Call the specific callbacks for success or failure. Only call the\n // success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED)\n if (this.isSuccess()) {\n this.dispatchEvent(goog.net.EventType.COMPLETE);\n this.dispatchEvent(goog.net.EventType.SUCCESS);\n } else {\n this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR;\n this.lastError_ =\n this.getStatusText() + ' [' + this.getStatus() + ']';\n this.dispatchErrors_();\n }\n } finally {\n this.cleanUpXhr_();\n }\n }\n }\n};\n\n\n/**\n * Internal handler for the XHR object's onprogress event. Fires both a generic\n * PROGRESS event and either a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event to\n * allow specific binding for each XHR progress event.\n * @param {!ProgressEvent} e XHR progress event.\n * @param {boolean=} opt_isDownload Whether the current progress event is from a\n * download. Used to determine whether DOWNLOAD_PROGRESS or UPLOAD_PROGRESS\n * event should be dispatched.\n * @private\n */\ngoog.net.XhrIo.prototype.onProgressHandler_ = function(e, opt_isDownload) {\n 'use strict';\n goog.asserts.assert(\n e.type === goog.net.EventType.PROGRESS,\n 'goog.net.EventType.PROGRESS is of the same type as raw XHR progress.');\n this.dispatchEvent(\n goog.net.XhrIo.buildProgressEvent_(e, goog.net.EventType.PROGRESS));\n this.dispatchEvent(goog.net.XhrIo.buildProgressEvent_(\n e,\n opt_isDownload ? goog.net.EventType.DOWNLOAD_PROGRESS :\n goog.net.EventType.UPLOAD_PROGRESS));\n};\n\n\n/**\n * Creates a representation of the native ProgressEvent. IE doesn't support\n * constructing ProgressEvent via \"new\", and the alternatives (e.g.,\n * ProgressEvent.initProgressEvent) are non-standard or deprecated.\n * @param {!ProgressEvent} e XHR progress event.\n * @param {!goog.net.EventType} eventType The type of the event.\n * @return {!ProgressEvent} The progress event.\n * @private\n */\ngoog.net.XhrIo.buildProgressEvent_ = function(e, eventType) {\n 'use strict';\n return /** @type {!ProgressEvent} */ ({\n type: eventType,\n lengthComputable: e.lengthComputable,\n loaded: e.loaded,\n total: e.total,\n });\n};\n\n\n/**\n * Remove the listener to protect against leaks, and nullify the XMLHttpRequest\n * object.\n * @param {boolean=} opt_fromDispose If this is from the dispose (don't want to\n * fire any events).\n * @private\n */\ngoog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) {\n 'use strict';\n if (this.xhr_) {\n // Cancel any pending timeout event handler.\n this.cleanUpTimeoutTimer_();\n\n // Save reference so we can mark it as closed after the READY event. The\n // READY event may trigger another request, thus we must nullify this.xhr_\n const xhr = this.xhr_;\n const clearedOnReadyStateChange =\n this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ?\n () => {} :\n null;\n this.xhr_ = null;\n this.xhrOptions_ = null;\n\n if (!opt_fromDispose) {\n this.dispatchEvent(goog.net.EventType.READY);\n }\n\n try {\n // NOTE(user): Not nullifying in FireFox can still leak if the callbacks\n // are defined in the same scope as the instance of XhrIo. But, IE doesn't\n // allow you to set the onreadystatechange to NULL so nullFunction is\n // used.\n xhr.onreadystatechange = clearedOnReadyStateChange;\n } catch (e) {\n // This seems to occur with a Gears HTTP request. Delayed the setting of\n // this onreadystatechange until after READY is sent out and catching the\n // error to see if we can track down the problem.\n goog.log.error(\n this.logger_,\n 'Problem encountered resetting onreadystatechange: ' + e.message);\n }\n }\n};\n\n\n/**\n * Make sure the timeout timer isn't running.\n * @private\n */\ngoog.net.XhrIo.prototype.cleanUpTimeoutTimer_ = function() {\n 'use strict';\n if (this.xhr_ && this.useXhr2Timeout_) {\n this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] = null;\n }\n if (this.timeoutId_) {\n goog.Timer.clear(this.timeoutId_);\n this.timeoutId_ = null;\n }\n};\n\n\n/**\n * @return {boolean} Whether there is an active request.\n */\ngoog.net.XhrIo.prototype.isActive = function() {\n 'use strict';\n return !!this.xhr_;\n};\n\n\n/**\n * @return {boolean} Whether the request has completed.\n */\ngoog.net.XhrIo.prototype.isComplete = function() {\n 'use strict';\n return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;\n};\n\n\n/**\n * @return {boolean} Whether the request completed with a success.\n */\ngoog.net.XhrIo.prototype.isSuccess = function() {\n 'use strict';\n const status = this.getStatus();\n // A zero status code is considered successful for local files.\n return goog.net.HttpStatus.isSuccess(status) ||\n status === 0 && !this.isLastUriEffectiveSchemeHttp_();\n};\n\n\n/**\n * @return {boolean} whether the effective scheme of the last URI that was\n * fetched was 'http' or 'https'.\n * @private\n */\ngoog.net.XhrIo.prototype.isLastUriEffectiveSchemeHttp_ = function() {\n 'use strict';\n const scheme = goog.uri.utils.getEffectiveScheme(String(this.lastUri_));\n return HTTP_SCHEME_PATTERN.test(scheme);\n};\n\n\n/**\n * Get the readystate from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*.\n */\ngoog.net.XhrIo.prototype.getReadyState = function() {\n 'use strict';\n return this.xhr_ ?\n /** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) :\n goog.net.XmlHttp.ReadyState.UNINITIALIZED;\n};\n\n\n/**\n * Get the status from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @return {number} Http status.\n */\ngoog.net.XhrIo.prototype.getStatus = function() {\n 'use strict';\n /**\n * IE doesn't like you checking status until the readystate is greater than 2\n * (i.e. it is receiving or complete). The try/catch is used for when the\n * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.\n */\n try {\n return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?\n this.xhr_.status :\n -1;\n } catch (e) {\n return -1;\n }\n};\n\n\n/**\n * Get the status text from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @return {string} Status text.\n */\ngoog.net.XhrIo.prototype.getStatusText = function() {\n 'use strict';\n /**\n * IE doesn't like you checking status until the readystate is greater than 2\n * (i.e. it is receiving or complete). The try/catch is used for when the\n * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.\n */\n try {\n return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?\n this.xhr_.statusText :\n '';\n } catch (e) {\n goog.log.fine(this.logger_, 'Can not get status: ' + e.message);\n return '';\n }\n};\n\n\n/**\n * Get the last Uri that was requested\n * @return {string} Last Uri.\n */\ngoog.net.XhrIo.prototype.getLastUri = function() {\n 'use strict';\n return String(this.lastUri_);\n};\n\n\n/**\n * Get the response text from the Xhr object\n * Will only return correct result when called from the context of a callback.\n * @return {string} Result from the server, or '' if no result available.\n */\ngoog.net.XhrIo.prototype.getResponseText = function() {\n 'use strict';\n try {\n return this.xhr_ ? this.xhr_.responseText : '';\n } catch (e) {\n // http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute\n // states that responseText should return '' (and responseXML null)\n // when the state is not LOADING or DONE. Instead, IE can\n // throw unexpected exceptions, for example when a request is aborted\n // or no data is available yet.\n goog.log.fine(this.logger_, 'Can not get responseText: ' + e.message);\n return '';\n }\n};\n\n\n/**\n * Get the response body from the Xhr object. This property is only available\n * in IE since version 7 according to MSDN:\n * http://msdn.microsoft.com/en-us/library/ie/ms534368(v=vs.85).aspx\n * Will only return correct result when called from the context of a callback.\n *\n * One option is to construct a VBArray from the returned object and convert\n * it to a JavaScript array using the toArray method:\n * `(new window['VBArray'](xhrIo.getResponseBody())).toArray()`\n * This will result in an array of numbers in the range of [0..255]\n *\n * Another option is to use the VBScript CStr method to convert it into a\n * string as outlined in http://stackoverflow.com/questions/1919972\n *\n * @return {Object} Binary result from the server or null if not available.\n */\ngoog.net.XhrIo.prototype.getResponseBody = function() {\n 'use strict';\n try {\n if (this.xhr_ && 'responseBody' in this.xhr_) {\n return this.xhr_['responseBody'];\n }\n } catch (e) {\n // IE can throw unexpected exceptions, for example when a request is aborted\n // or no data is yet available.\n goog.log.fine(this.logger_, 'Can not get responseBody: ' + e.message);\n }\n return null;\n};\n\n\n/**\n * Get the response XML from the Xhr object\n * Will only return correct result when called from the context of a callback.\n * @return {Document} The DOM Document representing the XML file, or null\n * if no result available.\n */\ngoog.net.XhrIo.prototype.getResponseXml = function() {\n 'use strict';\n try {\n return this.xhr_ ? this.xhr_.responseXML : null;\n } catch (e) {\n goog.log.fine(this.logger_, 'Can not get responseXML: ' + e.message);\n return null;\n }\n};\n\n\n/**\n * Get the response and evaluates it as JSON from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for\n * stripping of the response before parsing. This needs to be set only if\n * your backend server prepends the same prefix string to the JSON response.\n * @throws Error if the response text is invalid JSON.\n * @return {Object|undefined} JavaScript object.\n */\ngoog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) {\n 'use strict';\n if (!this.xhr_) {\n return undefined;\n }\n\n let responseText = this.xhr_.responseText;\n if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) {\n responseText = responseText.substring(opt_xssiPrefix.length);\n }\n\n return goog.json.hybrid.parse(responseText);\n};\n\n\n/**\n * Get the response as the type specificed by {@link #setResponseType}. At time\n * of writing, this is only directly supported in very recent versions of WebKit\n * (10.0.612.1 dev and later). If the field is not supported directly, we will\n * try to emulate it.\n *\n * Emulating the response means following the rules laid out at\n * http://www.w3.org/TR/XMLHttpRequest/#the-response-attribute\n *\n * On browsers with no support for this (Chrome < 10, Firefox < 4, etc), only\n * response types of DEFAULT or TEXT may be used, and the response returned will\n * be the text response.\n *\n * On browsers with Mozilla's draft support for array buffers (Firefox 4, 5),\n * only response types of DEFAULT, TEXT, and ARRAY_BUFFER may be used, and the\n * response returned will be either the text response or the Mozilla\n * implementation of the array buffer response.\n *\n * On browsers will full support, any valid response type supported by the\n * browser may be used, and the response provided by the browser will be\n * returned.\n *\n * @return {*} The response.\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.net.XhrIo.prototype.getResponse = function() {\n 'use strict';\n try {\n if (!this.xhr_) {\n return null;\n }\n if ('response' in this.xhr_) {\n return this.xhr_.response;\n }\n switch (this.responseType_) {\n case ResponseType.DEFAULT:\n case ResponseType.TEXT:\n return this.xhr_.responseText;\n // DOCUMENT and BLOB don't need to be handled here because they are\n // introduced in the same spec that adds the .response field, and would\n // have been caught above.\n // ARRAY_BUFFER needs an implementation for Firefox 4, where it was\n // implemented using a draft spec rather than the final spec.\n case ResponseType.ARRAY_BUFFER:\n if ('mozResponseArrayBuffer' in this.xhr_) {\n return this.xhr_.mozResponseArrayBuffer;\n }\n }\n // Fell through to a response type that is not supported on this browser.\n goog.log.error(\n this.logger_,\n 'Response type ' + this.responseType_ + ' is not ' +\n 'supported on this browser');\n return null;\n } catch (e) {\n goog.log.fine(this.logger_, 'Can not get response: ' + e.message);\n return null;\n }\n};\n\n\n/**\n * Get the value of the response-header with the given name from the Xhr object\n * Will only return correct result when called from the context of a callback\n * and the request has completed\n * @param {string} key The name of the response-header to retrieve.\n * @return {string|undefined} The value of the response-header named key.\n */\ngoog.net.XhrIo.prototype.getResponseHeader = function(key) {\n 'use strict';\n if (!this.xhr_ || !this.isComplete()) {\n return undefined;\n }\n\n const value = this.xhr_.getResponseHeader(key);\n return value === null ? undefined : value;\n};\n\n\n/**\n * Gets the text of all the headers in the response.\n * Will only return correct result after ready state reaches `LOADED` (i.e.\n * `HEADERS_RECEIVED` as per MDN).\n * @return {string} The value of the response headers or empty string.\n */\ngoog.net.XhrIo.prototype.getAllResponseHeaders = function() {\n 'use strict';\n // getAllResponseHeaders can return null if no response has been received,\n // ensure we always return an empty string.\n return this.xhr_ &&\n this.getReadyState() >= goog.net.XmlHttp.ReadyState.LOADED ?\n (this.xhr_.getAllResponseHeaders() || '') :\n '';\n};\n\n\n/**\n * Returns all response headers as a key-value map.\n * Multiple values for the same header key can be combined into one,\n * separated by a comma and a space.\n * Note that the native getResponseHeader method for retrieving a single header\n * does a case insensitive match on the header name. This method does not\n * include any case normalization logic, it will just return a key-value\n * representation of the headers.\n * See: http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method\n * @return {!Object<string, string>} An object with the header keys as keys\n * and header values as values.\n */\ngoog.net.XhrIo.prototype.getResponseHeaders = function() {\n 'use strict';\n // TODO(user): Make this function parse headers as per the spec\n // (https://tools.ietf.org/html/rfc2616#section-4.2).\n\n const headersObject = {};\n const headersArray = this.getAllResponseHeaders().split('\\r\\n');\n for (let i = 0; i < headersArray.length; i++) {\n if (goog.string.isEmptyOrWhitespace(headersArray[i])) {\n continue;\n }\n const keyValue =\n goog.string.splitLimit(headersArray[i], ':', /* maxSplitCount= */ 1);\n const key = keyValue[0];\n let value = keyValue[1];\n\n if (typeof value !== 'string') {\n // There must be a value but it can be the empty string.\n continue;\n }\n\n // Whitespace at the start and end of the value is meaningless.\n value = value.trim();\n // The key should not contain whitespace but we currently ignore that.\n\n const values = headersObject[key] || [];\n headersObject[key] = values;\n values.push(value);\n }\n\n return goog.object.map(headersObject, function(values) {\n 'use strict';\n return values.join(', ');\n });\n};\n\n\n/**\n * Get the value of the response-header with the given name from the Xhr object.\n * As opposed to {@link #getResponseHeader}, this method does not require that\n * the request has completed.\n * @param {string} key The name of the response-header to retrieve.\n * @return {?string} The value of the response-header, or null if it is\n * unavailable.\n */\ngoog.net.XhrIo.prototype.getStreamingResponseHeader = function(key) {\n 'use strict';\n return this.xhr_ ? this.xhr_.getResponseHeader(key) : null;\n};\n\n\n/**\n * Gets the text of all the headers in the response. As opposed to\n * {@link #getAllResponseHeaders}, this method does not require that the request\n * has completed.\n * @return {string} The value of the response headers or empty string.\n */\ngoog.net.XhrIo.prototype.getAllStreamingResponseHeaders = function() {\n 'use strict';\n return this.xhr_ ? this.xhr_.getAllResponseHeaders() : '';\n};\n\n\n/**\n * Get the last error message\n * @return {!goog.net.ErrorCode} Last error code.\n */\ngoog.net.XhrIo.prototype.getLastErrorCode = function() {\n 'use strict';\n return this.lastErrorCode_;\n};\n\n\n/**\n * Get the last error message\n * @return {string} Last error message.\n */\ngoog.net.XhrIo.prototype.getLastError = function() {\n 'use strict';\n return typeof this.lastError_ === 'string' ? this.lastError_ :\n String(this.lastError_);\n};\n\n\n/**\n * Adds the last method, status and URI to the message. This is used to add\n * this information to the logging calls.\n * @param {string} msg The message text that we want to add the extra text to.\n * @return {string} The message with the extra text appended.\n * @private\n */\ngoog.net.XhrIo.prototype.formatMsg_ = function(msg) {\n 'use strict';\n return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' +\n this.getStatus() + ']';\n};\n\n\n// Register the xhr handler as an entry point, so that\n// it can be monitored for exception handling, etc.\ngoog.debug.entryPointRegistry.register(\n /**\n * @param {function(!Function): !Function} transformer The transforming\n * function.\n */\n function(transformer) {\n 'use strict';\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =\n transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);\n });\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Provides a function to throw an error without interrupting\n * the current execution context.\n */\n\ngoog.module('goog.async.throwException');\ngoog.module.declareLegacyNamespace();\n\n/**\n * Throw an item without interrupting the current execution context. For\n * example, if processing a group of items in a loop, sometimes it is useful\n * to report an error while still allowing the rest of the batch to be\n * processed.\n * @param {*} exception\n */\nfunction throwException(exception) {\n // Each throw needs to be in its own context.\n goog.global.setTimeout(() => {\n throw exception;\n }, 0);\n}\nexports = throwException;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A timer class to which other classes and objects can listen on.\n * This is only an abstraction above `setInterval`.\n *\n * @see ../demos/timers.html\n */\n\ngoog.provide('goog.Timer');\n\ngoog.require('goog.Promise');\ngoog.require('goog.events.EventTarget');\ngoog.requireType('goog.Thenable');\n\n\n\n/**\n * Class for handling timing events.\n *\n * @param {number=} opt_interval Number of ms between ticks (default: 1ms).\n * @param {Object=} opt_timerObject An object that has `setTimeout`,\n * `setInterval`, `clearTimeout` and `clearInterval`\n * (e.g., `window`).\n * @constructor\n * @extends {goog.events.EventTarget}\n */\ngoog.Timer = function(opt_interval, opt_timerObject) {\n 'use strict';\n goog.events.EventTarget.call(this);\n\n /**\n * Number of ms between ticks\n * @private {number}\n */\n this.interval_ = opt_interval || 1;\n\n /**\n * An object that implements `setTimeout`, `setInterval`,\n * `clearTimeout` and `clearInterval`. We default to the window\n * object. Changing this on {@link goog.Timer.prototype} changes the object\n * for all timer instances which can be useful if your environment has some\n * other implementation of timers than the `window` object.\n * @private {{setTimeout:!Function, clearTimeout:!Function}}\n */\n this.timerObject_ = /** @type {{setTimeout, clearTimeout}} */ (\n opt_timerObject || goog.Timer.defaultTimerObject);\n\n /**\n * Cached `tick_` bound to the object for later use in the timer.\n * @private {Function}\n * @const\n */\n this.boundTick_ = goog.bind(this.tick_, this);\n\n /**\n * Firefox browser often fires the timer event sooner (sometimes MUCH sooner)\n * than the requested timeout. So we compare the time to when the event was\n * last fired, and reschedule if appropriate. See also\n * {@link goog.Timer.intervalScale}.\n * @private {number}\n */\n this.last_ = goog.now();\n};\ngoog.inherits(goog.Timer, goog.events.EventTarget);\n\n\n/**\n * Maximum timeout value.\n *\n * Timeout values too big to fit into a signed 32-bit integer may cause overflow\n * in FF, Safari, and Chrome, resulting in the timeout being scheduled\n * immediately. It makes more sense simply not to schedule these timeouts, since\n * 24.8 days is beyond a reasonable expectation for the browser to stay open.\n *\n * @private {number}\n * @const\n */\ngoog.Timer.MAX_TIMEOUT_ = 2147483647;\n\n\n/**\n * A timer ID that cannot be returned by any known implementation of\n * `window.setTimeout`. Passing this value to `window.clearTimeout`\n * should therefore be a no-op.\n *\n * @private {number}\n * @const\n */\ngoog.Timer.INVALID_TIMEOUT_ID_ = -1;\n\n\n/**\n * Whether this timer is enabled\n * @type {boolean}\n */\ngoog.Timer.prototype.enabled = false;\n\n\n/**\n * An object that implements `setTimeout`, `setInterval`,\n * `clearTimeout` and `clearInterval`. We default to the global\n * object. Changing `goog.Timer.defaultTimerObject` changes the object for\n * all timer instances which can be useful if your environment has some other\n * implementation of timers you'd like to use.\n * @type {{setTimeout, clearTimeout}}\n */\ngoog.Timer.defaultTimerObject = goog.global;\n\n\n/**\n * Variable that controls the timer error correction. If the timer is called\n * before the requested interval times `intervalScale`, which often\n * happens on Mozilla, the timer is rescheduled.\n * @see {@link #last_}\n * @type {number}\n */\ngoog.Timer.intervalScale = 0.8;\n\n\n/**\n * Variable for storing the result of `setInterval`.\n * @private {?number}\n */\ngoog.Timer.prototype.timer_ = null;\n\n\n/**\n * Gets the interval of the timer.\n * @return {number} interval Number of ms between ticks.\n */\ngoog.Timer.prototype.getInterval = function() {\n 'use strict';\n return this.interval_;\n};\n\n\n/**\n * Sets the interval of the timer.\n * @param {number} interval Number of ms between ticks.\n */\ngoog.Timer.prototype.setInterval = function(interval) {\n 'use strict';\n this.interval_ = interval;\n if (this.timer_ && this.enabled) {\n // Stop and then start the timer to reset the interval.\n this.stop();\n this.start();\n } else if (this.timer_) {\n this.stop();\n }\n};\n\n\n/**\n * Callback for the `setTimeout` used by the timer.\n * @private\n */\ngoog.Timer.prototype.tick_ = function() {\n 'use strict';\n if (this.enabled) {\n var elapsed = goog.now() - this.last_;\n if (elapsed > 0 && elapsed < this.interval_ * goog.Timer.intervalScale) {\n this.timer_ = this.timerObject_.setTimeout(\n this.boundTick_, this.interval_ - elapsed);\n return;\n }\n\n // Prevents setInterval from registering a duplicate timeout when called\n // in the timer event handler.\n if (this.timer_) {\n this.timerObject_.clearTimeout(this.timer_);\n this.timer_ = null;\n }\n\n this.dispatchTick();\n // The timer could be stopped in the timer event handler.\n if (this.enabled) {\n // Stop and start to ensure there is always only one timeout even if\n // start is called in the timer event handler.\n this.stop();\n this.start();\n }\n }\n};\n\n\n/**\n * Dispatches the TICK event. This is its own method so subclasses can override.\n */\ngoog.Timer.prototype.dispatchTick = function() {\n 'use strict';\n this.dispatchEvent(goog.Timer.TICK);\n};\n\n\n/**\n * Starts the timer.\n */\ngoog.Timer.prototype.start = function() {\n 'use strict';\n this.enabled = true;\n\n // If there is no interval already registered, start it now\n if (!this.timer_) {\n // IMPORTANT!\n // window.setInterval in FireFox has a bug - it fires based on\n // absolute time, rather than on relative time. What this means\n // is that if a computer is sleeping/hibernating for 24 hours\n // and the timer interval was configured to fire every 1000ms,\n // then after the PC wakes up the timer will fire, in rapid\n // succession, 3600*24 times.\n // This bug is described here and is already fixed, but it will\n // take time to propagate, so for now I am switching this over\n // to setTimeout logic.\n // https://bugzilla.mozilla.org/show_bug.cgi?id=376643\n //\n this.timer_ = this.timerObject_.setTimeout(this.boundTick_, this.interval_);\n this.last_ = goog.now();\n }\n};\n\n\n/**\n * Stops the timer.\n */\ngoog.Timer.prototype.stop = function() {\n 'use strict';\n this.enabled = false;\n if (this.timer_) {\n this.timerObject_.clearTimeout(this.timer_);\n this.timer_ = null;\n }\n};\n\n\n/** @override */\ngoog.Timer.prototype.disposeInternal = function() {\n 'use strict';\n goog.Timer.superClass_.disposeInternal.call(this);\n this.stop();\n delete this.timerObject_;\n};\n\n\n/**\n * Constant for the timer's event type.\n * @const\n */\ngoog.Timer.TICK = 'tick';\n\n\n/**\n * Calls the given function once, after the optional pause.\n * <p>\n * The function is always called asynchronously, even if the delay is 0. This\n * is a common trick to schedule a function to run after a batch of browser\n * event processing.\n *\n * @param {function(this:SCOPE)|{handleEvent:function()}|null} listener Function\n * or object that has a handleEvent method.\n * @param {number=} opt_delay Milliseconds to wait; default is 0.\n * @param {SCOPE=} opt_handler Object in whose scope to call the listener.\n * @return {number} A handle to the timer ID.\n * @template SCOPE\n */\ngoog.Timer.callOnce = function(listener, opt_delay, opt_handler) {\n 'use strict';\n if (typeof listener === 'function') {\n if (opt_handler) {\n listener = goog.bind(listener, opt_handler);\n }\n } else if (listener && typeof listener.handleEvent == 'function') {\n // using typeof to prevent strict js warning\n listener = goog.bind(listener.handleEvent, listener);\n } else {\n throw new Error('Invalid listener argument');\n }\n\n if (Number(opt_delay) > goog.Timer.MAX_TIMEOUT_) {\n // Timeouts greater than MAX_INT return immediately due to integer\n // overflow in many browsers. Since MAX_INT is 24.8 days, just don't\n // schedule anything at all.\n return goog.Timer.INVALID_TIMEOUT_ID_;\n } else {\n return goog.Timer.defaultTimerObject.setTimeout(listener, opt_delay || 0);\n }\n};\n\n\n/**\n * Clears a timeout initiated by {@link #callOnce}.\n * @param {?number} timerId A timer ID.\n */\ngoog.Timer.clear = function(timerId) {\n 'use strict';\n goog.Timer.defaultTimerObject.clearTimeout(timerId);\n};\n\n\n/**\n * @param {number} delay Milliseconds to wait.\n * @param {(RESULT|goog.Thenable<RESULT>|Thenable)=} opt_result The value\n * with which the promise will be resolved.\n * @return {!goog.Promise<RESULT>} A promise that will be resolved after\n * the specified delay, unless it is canceled first.\n * @template RESULT\n */\ngoog.Timer.promise = function(delay, opt_result) {\n 'use strict';\n var timerKey = null;\n return new goog\n .Promise(function(resolve, reject) {\n 'use strict';\n timerKey = goog.Timer.callOnce(function() {\n 'use strict';\n resolve(opt_result);\n }, delay);\n if (timerKey == goog.Timer.INVALID_TIMEOUT_ID_) {\n reject(new Error('Failed to schedule timer.'));\n }\n })\n .thenCatch(function(error) {\n 'use strict';\n // Clear the timer. The most likely reason is \"cancel\" signal.\n goog.Timer.clear(timerKey);\n throw error;\n });\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Definition of the goog.async.Throttle class.\n *\n * @see ../demos/timers.html\n */\n\ngoog.module('goog.async.Throttle');\ngoog.module.declareLegacyNamespace();\n\nconst Disposable = goog.require('goog.Disposable');\nconst Timer = goog.require('goog.Timer');\n\n\n/**\n * Throttle will perform an action that is passed in no more than once\n * per interval (specified in milliseconds). If it gets multiple signals\n * to perform the action while it is waiting, it will only perform the action\n * once at the end of the interval.\n * @final\n * @template T\n */\nclass Throttle extends Disposable {\n /**\n * @param {function(this: T, ...?)} listener Function to callback when the\n * action is triggered.\n * @param {number} interval Interval over which to throttle. The listener can\n * only be called once per interval.\n * @param {T=} handler Object in whose scope to call the listener.\n */\n constructor(listener, interval, handler) {\n super();\n /**\n * Function to callback\n * @type {function(this: T, ...?)}\n * @private\n */\n this.listener_ = handler != null ? listener.bind(handler) : listener;\n\n /**\n * Interval for the throttle time\n * @type {number}\n * @private\n */\n this.interval_ = interval;\n\n /**\n * The last arguments passed into `fire`, or null if there is no pending\n * call.\n * @private {?IArrayLike}\n */\n this.args_ = null;\n\n /**\n * Indicates that the action is pending and needs to be fired.\n * @type {boolean}\n * @private\n */\n this.shouldFire_ = false;\n\n /**\n * Indicates the count of nested pauses currently in effect on the throttle.\n * When this count is not zero, fired actions will be postponed until the\n * throttle is resumed enough times to drop the pause count to zero.\n * @type {number}\n * @private\n */\n this.pauseCount_ = 0;\n\n /**\n * Timer for scheduling the next callback\n * @type {?number}\n * @private\n */\n this.timer_ = null;\n }\n\n /**\n * Notifies the throttle that the action has happened. It will throttle\n * the call so that the callback is not called too often according to the\n * interval parameter passed to the constructor, passing the arguments\n * from the last call of this function into the throttled function.\n * @param {...?} var_args Arguments to pass on to the throttled function.\n */\n fire(var_args) {\n this.args_ = arguments;\n if (!this.timer_ && !this.pauseCount_) {\n this.doAction_();\n } else {\n this.shouldFire_ = true;\n }\n }\n\n /**\n * Cancels any pending action callback. The throttle can be restarted by\n * calling {@link #fire}.\n */\n stop() {\n if (this.timer_) {\n Timer.clear(this.timer_);\n this.timer_ = null;\n this.shouldFire_ = false;\n this.args_ = null;\n }\n }\n\n /**\n * Pauses the throttle. All pending and future action callbacks will be\n * delayed until the throttle is resumed. Pauses can be nested.\n */\n pause() {\n this.pauseCount_++;\n }\n\n /**\n * Resumes the throttle. If doing so drops the pausing count to zero,\n * pending action callbacks will be executed as soon as possible, but\n * still no sooner than an interval's delay after the previous call.\n * Future action callbacks will be executed as normal.\n */\n resume() {\n this.pauseCount_--;\n if (!this.pauseCount_ && this.shouldFire_ && !this.timer_) {\n this.shouldFire_ = false;\n this.doAction_();\n }\n }\n\n /** @override */\n disposeInternal() {\n super.disposeInternal();\n this.stop();\n }\n\n /**\n * Handler for the timer to fire the throttle\n * @private\n */\n onTimer_() {\n this.timer_ = null;\n\n if (this.shouldFire_ && !this.pauseCount_) {\n this.shouldFire_ = false;\n this.doAction_();\n }\n }\n\n /**\n * Calls the callback\n * @private\n */\n doAction_() {\n this.timer_ = Timer.callOnce(() => this.onTimer_(), this.interval_);\n const args = this.args_;\n // release memory first so it always happens even if listener throws\n this.args_ = null;\n this.listener_.apply(null, args);\n }\n}\n\nexports = Throttle;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Class to create objects which want to handle multiple events\n * and have their listeners easily cleaned up via a dispose method.\n *\n * Example:\n * <pre>\n * function Something() {\n * Something.base(this);\n *\n * ... set up object ...\n *\n * // Add event listeners\n * this.listen(this.starEl, goog.events.EventType.CLICK, this.handleStar);\n * this.listen(this.headerEl, goog.events.EventType.CLICK, this.expand);\n * this.listen(this.collapseEl, goog.events.EventType.CLICK, this.collapse);\n * this.listen(this.infoEl, goog.events.EventType.MOUSEOVER, this.showHover);\n * this.listen(this.infoEl, goog.events.EventType.MOUSEOUT, this.hideHover);\n * }\n * goog.inherits(Something, goog.events.EventHandler);\n *\n * Something.prototype.disposeInternal = function() {\n * Something.base(this, 'disposeInternal');\n * goog.dom.removeNode(this.container);\n * };\n *\n *\n * // Then elsewhere:\n *\n * var activeSomething = null;\n * function openSomething() {\n * activeSomething = new Something();\n * }\n *\n * function closeSomething() {\n * if (activeSomething) {\n * activeSomething.dispose(); // Remove event listeners\n * activeSomething = null;\n * }\n * }\n * </pre>\n */\n\ngoog.provide('goog.events.EventHandler');\n\ngoog.require('goog.Disposable');\ngoog.require('goog.events');\ngoog.require('goog.object');\ngoog.requireType('goog.events.Event');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventTarget');\ngoog.requireType('goog.events.EventWrapper');\n\n\n\n/**\n * Super class for objects that want to easily manage a number of event\n * listeners. It allows a short cut to listen and also provides a quick way\n * to remove all events listeners belonging to this object.\n * @param {SCOPE=} opt_scope Object in whose scope to call the listeners.\n * @constructor\n * @extends {goog.Disposable}\n * @template SCOPE\n */\ngoog.events.EventHandler = function(opt_scope) {\n 'use strict';\n goog.Disposable.call(this);\n // TODO(mknichel): Rename this to this.scope_ and fix the classes in google3\n // that access this private variable. :(\n this.handler_ = opt_scope;\n\n /**\n * Keys for events that are being listened to.\n * @type {!Object<!goog.events.Key>}\n * @private\n */\n this.keys_ = {};\n};\ngoog.inherits(goog.events.EventHandler, goog.Disposable);\n\n\n/**\n * Utility array used to unify the cases of listening for an array of types\n * and listening for a single event, without using recursion or allocating\n * an array each time.\n * @type {!Array<string>}\n * @const\n * @private\n */\ngoog.events.EventHandler.typeArray_ = [];\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted then the\n * EventHandler's handleEvent method will be used.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\n * opt_fn Optional callback function to be used as the listener or an object\n * with handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listen = function(\n src, type, opt_fn, opt_options) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n return self.listen_(src, type, opt_fn, opt_options);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted then the\n * EventHandler's handleEvent method will be used.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}|\n * null|undefined} fn Optional callback function to be used as the\n * listener or an object with handleEvent function.\n * @param {boolean|!AddEventListenerOptions|undefined} options\n * @param {T} scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template T, EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listenWithScope = function(\n src, type, fn, options, scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Deprecate this function.\n return self.listen_(src, type, fn, options, scope);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted then the\n * EventHandler's handleEvent method will be used.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn\n * Optional callback function to be used as the listener or an object with\n * handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {Object=} opt_scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n * @private\n */\ngoog.events.EventHandler.prototype.listen_ = function(\n src, type, opt_fn, opt_options, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n if (!Array.isArray(type)) {\n if (type) {\n goog.events.EventHandler.typeArray_[0] = type.toString();\n }\n type = goog.events.EventHandler.typeArray_;\n }\n for (var i = 0; i < type.length; i++) {\n var listenerObj = goog.events.listen(\n src, type[i], opt_fn || self.handleEvent, opt_options || false,\n opt_scope || self.handler_ || self);\n\n if (!listenerObj) {\n // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT\n // (goog.events.CaptureSimulationMode) in IE8-, it will return null\n // value.\n return self;\n }\n\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n var key = listenerObj.key;\n self.keys_[key] = listenerObj;\n }\n\n return self;\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted, then the\n * EventHandler's handleEvent method will be used. After the event has fired the\n * event listener is removed from the target. If an array of event types is\n * provided, each event type will be listened to once.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\n * opt_fn\n * Optional callback function to be used as the listener or an object with\n * handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listenOnce = function(\n src, type, opt_fn, opt_options) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n return self.listenOnce_(src, type, opt_fn, opt_options);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted, then the\n * EventHandler's handleEvent method will be used. After the event has fired the\n * event listener is removed from the target. If an array of event types is\n * provided, each event type will be listened to once.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}|\n * null|undefined} fn Optional callback function to be used as the\n * listener or an object with handleEvent function.\n * @param {boolean|undefined} capture Optional whether to use capture phase.\n * @param {T} scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template T, EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listenOnceWithScope = function(\n src, type, fn, capture, scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Deprecate this function.\n return self.listenOnce_(src, type, fn, capture, scope);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted, then the\n * EventHandler's handleEvent method will be used. After the event has fired\n * the event listener is removed from the target. If an array of event types is\n * provided, each event type will be listened to once.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn\n * Optional callback function to be used as the listener or an object with\n * handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {Object=} opt_scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n * @private\n */\ngoog.events.EventHandler.prototype.listenOnce_ = function(\n src, type, opt_fn, opt_options, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n self.listenOnce_(src, type[i], opt_fn, opt_options, opt_scope);\n }\n } else {\n var listenerObj = goog.events.listenOnce(\n src, type, opt_fn || self.handleEvent, opt_options,\n opt_scope || self.handler_ || self);\n if (!listenerObj) {\n // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT\n // (goog.events.CaptureSimulationMode) in IE8-, it will return null\n // value.\n return self;\n }\n\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n var key = listenerObj.key;\n self.keys_[key] = listenerObj;\n }\n\n return self;\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.EventTarget}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\n * events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(this:SCOPE, ?):?|{handleEvent:function(?):?}|null} listener\n * Callback method, or an object with a handleEvent function.\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\n * false).\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template THIS\n */\ngoog.events.EventHandler.prototype.listenWithWrapper = function(\n src, wrapper, listener, opt_capt) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Remove the opt_scope from this function and then\n // templatize it.\n return self.listenWithWrapper_(src, wrapper, listener, opt_capt);\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.EventTarget}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\n * events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(this:T, ?):?|{handleEvent:function(this:T, ?):?}|null}\n * listener Optional callback function to be used as the\n * listener or an object with handleEvent function.\n * @param {boolean|undefined} capture Optional whether to use capture phase.\n * @param {T} scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template T, THIS\n */\ngoog.events.EventHandler.prototype.listenWithWrapperAndScope = function(\n src, wrapper, listener, capture, scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Deprecate this function.\n return self.listenWithWrapper_(src, wrapper, listener, capture, scope);\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.EventTarget}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\n * events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener Callback\n * method, or an object with a handleEvent function.\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\n * false).\n * @param {Object=} opt_scope Element in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template THIS\n * @private\n */\ngoog.events.EventHandler.prototype.listenWithWrapper_ = function(\n src, wrapper, listener, opt_capt, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n wrapper.listen(\n src, listener, opt_capt, opt_scope || self.handler_ || self, self);\n return self;\n};\n\n\n/**\n * @return {number} Number of listeners registered by this handler.\n */\ngoog.events.EventHandler.prototype.getListenerCount = function() {\n 'use strict';\n var count = 0;\n for (var key in this.keys_) {\n if (Object.prototype.hasOwnProperty.call(this.keys_, key)) {\n count++;\n }\n }\n return count;\n};\n\n\n/**\n * Unlistens on an event.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types to unlisten to.\n * @param {function(this:?, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\n * opt_fn Optional callback function to be used as the listener or an object\n * with handleEvent function.\n * @param {(boolean|!EventListenerOptions)=} opt_options\n * @param {Object=} opt_scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.unlisten = function(\n src, type, opt_fn, opt_options, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n self.unlisten(src, type[i], opt_fn, opt_options, opt_scope);\n }\n } else {\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n var listener = goog.events.getListener(\n src, type, opt_fn || self.handleEvent, capture,\n opt_scope || self.handler_ || self);\n\n if (listener) {\n goog.events.unlistenByKey(listener);\n delete self.keys_[listener.key];\n }\n }\n\n return self;\n};\n\n\n/**\n * Removes an event listener which was added with listenWithWrapper().\n *\n * @param {EventTarget|goog.events.EventTarget} src The target to stop\n * listening to events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\n * listener function to remove.\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase of the\n * event.\n * @param {Object=} opt_scope Element in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template THIS\n */\ngoog.events.EventHandler.prototype.unlistenWithWrapper = function(\n src, wrapper, listener, opt_capt, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n wrapper.unlisten(\n src, listener, opt_capt, opt_scope || self.handler_ || self, self);\n return self;\n};\n\n\n/**\n * Unlistens to all events.\n */\ngoog.events.EventHandler.prototype.removeAll = function() {\n 'use strict';\n goog.object.forEach(this.keys_, function(listenerObj, key) {\n 'use strict';\n if (this.keys_.hasOwnProperty(key)) {\n goog.events.unlistenByKey(listenerObj);\n }\n }, this);\n\n this.keys_ = {};\n};\n\n\n/**\n * Disposes of this EventHandler and removes all listeners that it registered.\n * @override\n * @protected\n */\ngoog.events.EventHandler.prototype.disposeInternal = function() {\n 'use strict';\n goog.events.EventHandler.superClass_.disposeInternal.call(this);\n this.removeAll();\n};\n\n\n/**\n * Default event handler\n * @param {goog.events.Event} e Event object.\n */\ngoog.events.EventHandler.prototype.handleEvent = function(e) {\n 'use strict';\n throw new Error('EventHandler.handleEvent not implemented');\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Provides a utility for tracing and debugging WebChannel\n * requests.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.WebChannelDebug');\n\ngoog.require('goog.json');\ngoog.require('goog.log');\ngoog.requireType('goog.Uri');\ngoog.requireType('goog.net.XmlHttp.ReadyState');\n\n\n\n/**\n * Logs and keeps a buffer of debugging info for the Channel.\n *\n * @constructor\n * @struct\n * @final\n */\ngoog.labs.net.webChannel.WebChannelDebug = function() {\n 'use strict';\n /**\n * The logger instance.\n * @const\n * @private {?goog.log.Logger}\n */\n this.logger_ = goog.log.getLogger('goog.labs.net.webChannel.WebChannelDebug');\n\n /**\n * Whether to enable redact. Defaults to true.\n * @private {boolean}\n */\n this.redactEnabled_ = true;\n};\n\n\ngoog.scope(function() {\n'use strict';\nvar WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\n\n\n/**\n * Turns off redact.\n */\nWebChannelDebug.prototype.disableRedact = function() {\n 'use strict';\n this.redactEnabled_ = false;\n};\n\n\n/**\n * Logs that the browser went offline during the lifetime of a request.\n * @param {goog.Uri} url The URL being requested.\n */\nWebChannelDebug.prototype.browserOfflineResponse = function(url) {\n 'use strict';\n this.info(function() {\n 'use strict';\n return 'BROWSER_OFFLINE: ' + url;\n });\n};\n\n\n/**\n * Logs an XmlHttp request..\n * @param {string} verb The request type (GET/POST).\n * @param {goog.Uri} uri The request destination.\n * @param {string|number|undefined} id The request id.\n * @param {number} attempt Which attempt # the request was.\n * @param {?string} postData The data posted in the request.\n */\nWebChannelDebug.prototype.xmlHttpChannelRequest = function(\n verb, uri, id, attempt, postData) {\n 'use strict';\n var self = this;\n this.info(function() {\n 'use strict';\n return 'XMLHTTP REQ (' + id + ') [attempt ' + attempt + ']: ' + verb +\n '\\n' + uri + '\\n' + self.maybeRedactPostData_(postData);\n });\n};\n\n\n/**\n * Logs the meta data received from an XmlHttp request.\n * @param {string} verb The request type (GET/POST).\n * @param {goog.Uri} uri The request destination.\n * @param {string|number|undefined} id The request id.\n * @param {number} attempt Which attempt # the request was.\n * @param {goog.net.XmlHttp.ReadyState} readyState The ready state.\n * @param {number} statusCode The HTTP status code.\n */\nWebChannelDebug.prototype.xmlHttpChannelResponseMetaData = function(\n verb, uri, id, attempt, readyState, statusCode) {\n 'use strict';\n this.info(function() {\n 'use strict';\n return 'XMLHTTP RESP (' + id + ') [ attempt ' + attempt + ']: ' + verb +\n '\\n' + uri + '\\n' + readyState + ' ' + statusCode;\n });\n};\n\n\n/**\n * Logs the response data received from an XmlHttp request.\n * @param {string|number|undefined} id The request id.\n * @param {?string} responseText The response text.\n * @param {?string=} opt_desc Optional request description.\n */\nWebChannelDebug.prototype.xmlHttpChannelResponseText = function(\n id, responseText, opt_desc) {\n 'use strict';\n var self = this;\n this.info(function() {\n 'use strict';\n return 'XMLHTTP TEXT (' + id + '): ' + self.redactResponse_(responseText) +\n (opt_desc ? ' ' + opt_desc : '');\n });\n};\n\n\n/**\n * Logs a request timeout.\n * @param {goog.Uri} uri The uri that timed out.\n */\nWebChannelDebug.prototype.timeoutResponse = function(uri) {\n 'use strict';\n this.info(function() {\n 'use strict';\n return 'TIMEOUT: ' + uri;\n });\n};\n\n\n/**\n * Logs a debug message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.debug = function(text) {\n 'use strict';\n goog.log.fine(this.logger_, text);\n};\n\n\n/**\n * Logs an exception\n * @param {Error} e The error or error event.\n * @param {goog.log.Loggable=} opt_msg The optional message,\n * defaults to 'Exception'.\n */\nWebChannelDebug.prototype.dumpException = function(e, opt_msg) {\n 'use strict';\n goog.log.error(this.logger_, opt_msg || 'Exception', e);\n};\n\n\n/**\n * Logs an info message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.info = function(text) {\n 'use strict';\n goog.log.info(this.logger_, text);\n};\n\n\n/**\n * Logs a warning message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.warning = function(text) {\n 'use strict';\n goog.log.warning(this.logger_, text);\n};\n\n\n/**\n * Logs a severe message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.severe = function(text) {\n 'use strict';\n goog.log.error(this.logger_, text);\n};\n\n\n/**\n * Removes potentially private data from a response so that we don't\n * accidentally save private and personal data to the server logs.\n * @param {?string} responseText A JSON response to clean.\n * @return {?string} The cleaned response.\n * @private\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\nWebChannelDebug.prototype.redactResponse_ = function(responseText) {\n 'use strict';\n if (!this.redactEnabled_) {\n return responseText;\n }\n\n if (!responseText) {\n return null;\n }\n\n try {\n var responseArray = JSON.parse(responseText);\n if (responseArray) {\n for (var i = 0; i < responseArray.length; i++) {\n if (Array.isArray(responseArray[i])) {\n this.maybeRedactArray_(responseArray[i]);\n }\n }\n }\n\n return goog.json.serialize(responseArray);\n } catch (e) {\n this.debug('Exception parsing expected JS array - probably was not JS');\n return responseText;\n }\n};\n\n\n/**\n * Removes data from a response array that may be sensitive.\n * @param {!Array<?>} array The array to clean.\n * @private\n */\nWebChannelDebug.prototype.maybeRedactArray_ = function(array) {\n 'use strict';\n if (array.length < 2) {\n return;\n }\n var dataPart = array[1];\n if (!Array.isArray(dataPart)) {\n return;\n }\n if (dataPart.length < 1) {\n return;\n }\n\n var type = dataPart[0];\n if (type != 'noop' && type != 'stop' && type != 'close') {\n // redact all fields in the array\n for (var i = 1; i < dataPart.length; i++) {\n dataPart[i] = '';\n }\n }\n};\n\n\n/**\n * Removes potentially private data from a request POST body so that we don't\n * accidentally save private and personal data to the server logs.\n * @param {?string} data The data string to clean.\n * @return {?string} The data string with sensitive data replaced by 'redacted'.\n * @private\n */\nWebChannelDebug.prototype.maybeRedactPostData_ = function(data) {\n 'use strict';\n if (!this.redactEnabled_) {\n return data;\n }\n\n if (!data) {\n return null;\n }\n var out = '';\n var params = data.split('&');\n for (var i = 0; i < params.length; i++) {\n var param = params[i];\n var keyValue = param.split('=');\n if (keyValue.length > 1) {\n var key = keyValue[0];\n var value = keyValue[1];\n\n var keyParts = key.split('_');\n if (keyParts.length >= 2 && keyParts[1] == 'type') {\n out += key + '=' + value + '&';\n } else {\n out += key + '=' +\n 'redacted' +\n '&';\n }\n }\n }\n return out;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Static utilities for collecting stats associated with\n * ChannelRequest.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.requestStats');\ngoog.provide('goog.labs.net.webChannel.requestStats.Event');\ngoog.provide('goog.labs.net.webChannel.requestStats.ServerReachability');\ngoog.provide('goog.labs.net.webChannel.requestStats.ServerReachabilityEvent');\ngoog.provide('goog.labs.net.webChannel.requestStats.Stat');\ngoog.provide('goog.labs.net.webChannel.requestStats.StatEvent');\ngoog.provide('goog.labs.net.webChannel.requestStats.TimingEvent');\n\ngoog.require('goog.events.Event');\ngoog.require('goog.events.EventTarget');\n\n\ngoog.scope(function() {\n'use strict';\nconst requestStats = goog.labs.net.webChannel.requestStats;\n\n\n/**\n * Events fired.\n * @const\n */\nrequestStats.Event = {};\n\n\n/**\n * Singleton event target for firing stat events\n * @type {?goog.events.EventTarget}\n * @private\n */\nrequestStats.eventTarget_ = null;\n\n/**\n * Singleton event target for firing stat events\n * @return {!goog.events.EventTarget}\n * @private\n */\nrequestStats.getStatEventTarget_ = function() {\n 'use strict';\n requestStats.eventTarget_ =\n requestStats.eventTarget_ || new goog.events.EventTarget();\n return requestStats.eventTarget_;\n};\n\n/**\n * The type of event that occurs every time some information about how reachable\n * the server is is discovered.\n */\nrequestStats.Event.SERVER_REACHABILITY_EVENT = 'serverreachability';\n\n\n/**\n * Types of events which reveal information about the reachability of the\n * server.\n * @enum {number}\n */\nrequestStats.ServerReachability = {\n REQUEST_MADE: 1,\n REQUEST_SUCCEEDED: 2,\n REQUEST_FAILED: 3,\n BACK_CHANNEL_ACTIVITY: 4 // any response data received\n};\n\n\n\n/**\n * Event class for SERVER_REACHABILITY_EVENT.\n *\n * @param {goog.events.EventTarget} target The stat event target for\n the channel.\n * @param {requestStats.ServerReachability} reachabilityType\n * The reachability event type.\n * @constructor\n * @extends {goog.events.Event}\n */\nrequestStats.ServerReachabilityEvent = function(target, reachabilityType) {\n 'use strict';\n goog.events.Event.call(\n this, requestStats.Event.SERVER_REACHABILITY_EVENT, target);\n\n /**\n * @type {requestStats.ServerReachability}\n */\n this.reachabilityType = reachabilityType;\n};\ngoog.inherits(requestStats.ServerReachabilityEvent, goog.events.Event);\n\n\n/**\n * Notify the channel that a particular fine grained network event has occurred.\n * Should be considered package-private.\n * @param {requestStats.ServerReachability} reachabilityType\n * The reachability event type.\n */\nrequestStats.notifyServerReachabilityEvent = function(reachabilityType) {\n 'use strict';\n const target = requestStats.getStatEventTarget_();\n target.dispatchEvent(\n new requestStats.ServerReachabilityEvent(target, reachabilityType));\n};\n\n\n/**\n * Stat Event that fires when things of interest happen that may be useful for\n * applications to know about for stats or debugging purposes.\n */\nrequestStats.Event.STAT_EVENT = 'statevent';\n\n\n/**\n * Enum that identifies events for statistics that are interesting to track.\n * @enum {number}\n */\nrequestStats.Stat = {\n /** Event indicating a new connection attempt. */\n CONNECT_ATTEMPT: 0,\n\n /** Event indicating a connection error due to a general network problem. */\n ERROR_NETWORK: 1,\n\n /**\n * Event indicating a connection error that isn't due to a general network\n * problem.\n */\n ERROR_OTHER: 2,\n\n /** Event indicating the start of test stage one. */\n TEST_STAGE_ONE_START: 3,\n\n /** Event indicating the start of test stage two. */\n TEST_STAGE_TWO_START: 4,\n\n /** Event indicating the first piece of test data was received. */\n TEST_STAGE_TWO_DATA_ONE: 5,\n\n /**\n * Event indicating that the second piece of test data was received and it was\n * received separately from the first.\n */\n TEST_STAGE_TWO_DATA_TWO: 6,\n\n /** Event indicating both pieces of test data were received simultaneously. */\n TEST_STAGE_TWO_DATA_BOTH: 7,\n\n /** Event indicating stage one of the test request failed. */\n TEST_STAGE_ONE_FAILED: 8,\n\n /** Event indicating stage two of the test request failed. */\n TEST_STAGE_TWO_FAILED: 9,\n\n /**\n * Event indicating that a buffering proxy is likely between the client and\n * the server.\n */\n PROXY: 10,\n\n /**\n * Event indicating that no buffering proxy is likely between the client and\n * the server.\n */\n NOPROXY: 11,\n\n /** Event indicating an unknown SID error. */\n REQUEST_UNKNOWN_SESSION_ID: 12,\n\n /** Event indicating a bad status code was received. */\n REQUEST_BAD_STATUS: 13,\n\n /** Event indicating incomplete data was received */\n REQUEST_INCOMPLETE_DATA: 14,\n\n /** Event indicating bad data was received */\n REQUEST_BAD_DATA: 15,\n\n /** Event indicating no data was received when data was expected. */\n REQUEST_NO_DATA: 16,\n\n /** Event indicating a request timeout. */\n REQUEST_TIMEOUT: 17,\n\n /**\n * Event indicating that the server never received our hanging GET and so it\n * is being retried.\n */\n BACKCHANNEL_MISSING: 18,\n\n /**\n * Event indicating that we have determined that our hanging GET is not\n * receiving data when it should be. Thus it is dead dead and will be retried.\n */\n BACKCHANNEL_DEAD: 19,\n\n /**\n * The browser declared itself offline during the lifetime of a request, or\n * was offline when a request was initially made.\n */\n BROWSER_OFFLINE: 20\n};\n\n\n\n/**\n * Event class for STAT_EVENT.\n *\n * @param {goog.events.EventTarget} eventTarget The stat event target for\n the channel.\n * @param {requestStats.Stat} stat The stat.\n * @constructor\n * @extends {goog.events.Event}\n */\nrequestStats.StatEvent = function(eventTarget, stat) {\n 'use strict';\n goog.events.Event.call(this, requestStats.Event.STAT_EVENT, eventTarget);\n\n /**\n * The stat\n * @type {requestStats.Stat}\n */\n this.stat = stat;\n};\ngoog.inherits(requestStats.StatEvent, goog.events.Event);\n\n\n/**\n * Returns the singleton event target for stat events.\n * @return {!goog.events.EventTarget} The event target for stat events.\n */\nrequestStats.getStatEventTarget = function() {\n 'use strict';\n return requestStats.getStatEventTarget_();\n};\n\n\n/**\n * Helper function to call the stat event callback.\n * @param {requestStats.Stat} stat The stat.\n */\nrequestStats.notifyStatEvent = function(stat) {\n 'use strict';\n const target = requestStats.getStatEventTarget_();\n target.dispatchEvent(new requestStats.StatEvent(target, stat));\n};\n\n\n/**\n * An event that fires when POST requests complete successfully, indicating\n * the size of the POST and the round trip time.\n */\nrequestStats.Event.TIMING_EVENT = 'timingevent';\n\n\n\n/**\n * Event class for requestStats.Event.TIMING_EVENT\n *\n * @param {goog.events.EventTarget} target The stat event target for\n the channel.\n * @param {number} size The number of characters in the POST data.\n * @param {number} rtt The total round trip time from POST to response in MS.\n * @param {number} retries The number of times the POST had to be retried.\n * @constructor\n * @extends {goog.events.Event}\n */\nrequestStats.TimingEvent = function(target, size, rtt, retries) {\n 'use strict';\n goog.events.Event.call(this, requestStats.Event.TIMING_EVENT, target);\n\n /**\n * @type {number}\n */\n this.size = size;\n\n /**\n * @type {number}\n */\n this.rtt = rtt;\n\n /**\n * @type {number}\n */\n this.retries = retries;\n};\ngoog.inherits(requestStats.TimingEvent, goog.events.Event);\n\n\n/**\n * Helper function to notify listeners about POST request performance.\n *\n * @param {number} size Number of characters in the POST data.\n * @param {number} rtt The amount of time from POST start to response.\n * @param {number} retries The number of times the POST had to be retried.\n */\nrequestStats.notifyTimingEvent = function(size, rtt, retries) {\n 'use strict';\n const target = requestStats.getStatEventTarget_();\n target.dispatchEvent(\n new requestStats.TimingEvent(target, size, rtt, retries));\n};\n\n\n/**\n * Allows the application to set an execution hooks for when a channel\n * starts processing requests. This is useful to track timing or logging\n * special information. The function takes no parameters and return void.\n * @param {Function} startHook The function for the start hook.\n */\nrequestStats.setStartThreadExecutionHook = function(startHook) {\n 'use strict';\n requestStats.startExecutionHook_ = startHook;\n};\n\n\n/**\n * Allows the application to set an execution hooks for when a channel\n * stops processing requests. This is useful to track timing or logging\n * special information. The function takes no parameters and return void.\n * @param {Function} endHook The function for the end hook.\n */\nrequestStats.setEndThreadExecutionHook = function(endHook) {\n 'use strict';\n requestStats.endExecutionHook_ = endHook;\n};\n\n\n/**\n * Application provided execution hook for the start hook.\n *\n * @type {Function}\n * @private\n */\nrequestStats.startExecutionHook_ = function() {};\n\n\n/**\n * Application provided execution hook for the end hook.\n *\n * @type {Function}\n * @private\n */\nrequestStats.endExecutionHook_ = function() {};\n\n\n/**\n * Helper function to call the start hook\n */\nrequestStats.onStartExecution = function() {\n 'use strict';\n requestStats.startExecutionHook_();\n};\n\n\n/**\n * Helper function to call the end hook\n */\nrequestStats.onEndExecution = function() {\n 'use strict';\n requestStats.endExecutionHook_();\n};\n\n\n/**\n * Wrapper around SafeTimeout which calls the start and end execution hooks\n * with a try...finally block.\n * @param {Function} fn The callback function.\n * @param {number} ms The time in MS for the timer.\n * @return {number} The ID of the timer.\n */\nrequestStats.setTimeout = function(fn, ms) {\n 'use strict';\n if (typeof fn !== 'function') {\n throw new Error('Fn must not be null and must be a function');\n }\n return goog.global.setTimeout(function() {\n 'use strict';\n requestStats.onStartExecution();\n try {\n fn();\n } finally {\n requestStats.onEndExecution();\n }\n }, ms);\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Error codes shared between goog.net.IframeIo and\n * goog.net.XhrIo.\n */\n\ngoog.provide('goog.net.ErrorCode');\n\n\n/**\n * Error codes\n * @enum {number}\n */\ngoog.net.ErrorCode = {\n\n /**\n * There is no error condition.\n */\n NO_ERROR: 0,\n\n /**\n * The most common error from iframeio, unfortunately, is that the browser\n * responded with an error page that is classed as a different domain. The\n * situations, are when a browser error page is shown -- 404, access denied,\n * DNS failure, connection reset etc.)\n *\n */\n ACCESS_DENIED: 1,\n\n /**\n * Currently the only case where file not found will be caused is when the\n * code is running on the local file system and a non-IE browser makes a\n * request to a file that doesn't exist.\n */\n FILE_NOT_FOUND: 2,\n\n /**\n * If Firefox shows a browser error page, such as a connection reset by\n * server or access denied, then it will fail silently without the error or\n * load handlers firing.\n */\n FF_SILENT_ERROR: 3,\n\n /**\n * Custom error provided by the client through the error check hook.\n */\n CUSTOM_ERROR: 4,\n\n /**\n * Exception was thrown while processing the request.\n */\n EXCEPTION: 5,\n\n /**\n * The Http response returned a non-successful http status code.\n */\n HTTP_ERROR: 6,\n\n /**\n * The request was aborted.\n */\n ABORT: 7,\n\n /**\n * The request timed out.\n */\n TIMEOUT: 8,\n\n /**\n * The resource is not available offline.\n */\n OFFLINE: 9,\n};\n\n\n/**\n * Returns a friendly error message for an error code. These messages are for\n * debugging and are not localized.\n * @param {goog.net.ErrorCode} errorCode An error code.\n * @return {string} A message for debugging.\n */\ngoog.net.ErrorCode.getDebugMessage = function(errorCode) {\n 'use strict';\n switch (errorCode) {\n case goog.net.ErrorCode.NO_ERROR:\n return 'No Error';\n\n case goog.net.ErrorCode.ACCESS_DENIED:\n return 'Access denied to content document';\n\n case goog.net.ErrorCode.FILE_NOT_FOUND:\n return 'File not found';\n\n case goog.net.ErrorCode.FF_SILENT_ERROR:\n return 'Firefox silently errored';\n\n case goog.net.ErrorCode.CUSTOM_ERROR:\n return 'Application custom error';\n\n case goog.net.ErrorCode.EXCEPTION:\n return 'An exception occurred';\n\n case goog.net.ErrorCode.HTTP_ERROR:\n return 'Http response at 400 or 500 level';\n\n case goog.net.ErrorCode.ABORT:\n return 'Request was aborted';\n\n case goog.net.ErrorCode.TIMEOUT:\n return 'Request timed out';\n\n case goog.net.ErrorCode.OFFLINE:\n return 'The resource is not available offline';\n\n default:\n return 'Unrecognized error code';\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Common events for the network classes.\n */\n\n\ngoog.provide('goog.net.EventType');\n\n\n/**\n * Event names for network events\n * @enum {string}\n */\ngoog.net.EventType = {\n COMPLETE: 'complete',\n SUCCESS: 'success',\n ERROR: 'error',\n ABORT: 'abort',\n READY: 'ready',\n READY_STATE_CHANGE: 'readystatechange',\n TIMEOUT: 'timeout',\n INCREMENTAL_DATA: 'incrementaldata',\n PROGRESS: 'progress',\n // DOWNLOAD_PROGRESS and UPLOAD_PROGRESS are special events dispatched by\n // goog.net.XhrIo to allow binding listeners specific to each type of\n // progress.\n DOWNLOAD_PROGRESS: 'downloadprogress',\n UPLOAD_PROGRESS: 'uploadprogress',\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Interface for a factory for creating XMLHttpRequest objects\n * and metadata about them.\n */\n\ngoog.provide('goog.net.XmlHttpFactory');\n\n/** @suppress {extraRequire} Typedef. */\ngoog.require('goog.net.XhrLike');\n\n\n\n/**\n * Abstract base class for an XmlHttpRequest factory.\n * @constructor\n */\ngoog.net.XmlHttpFactory = function() {};\n\n\n/**\n * Cache of options - we only actually call internalGetOptions once.\n * @type {?Object}\n * @private\n */\ngoog.net.XmlHttpFactory.prototype.cachedOptions_ = null;\n\n\n/**\n * @return {!goog.net.XhrLike.OrNative} A new XhrLike instance.\n */\ngoog.net.XmlHttpFactory.prototype.createInstance = goog.abstractMethod;\n\n\n/**\n * @return {Object} Options describing how xhr objects obtained from this\n * factory should be used.\n */\ngoog.net.XmlHttpFactory.prototype.getOptions = function() {\n 'use strict';\n return this.cachedOptions_ ||\n (this.cachedOptions_ = this.internalGetOptions());\n};\n\n\n/**\n * Override this method in subclasses to preserve the caching offered by\n * getOptions().\n * @return {Object} Options describing how xhr objects obtained from this\n * factory should be used.\n * @protected\n */\ngoog.net.XmlHttpFactory.prototype.internalGetOptions = goog.abstractMethod;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview The API spec for the WebChannel messaging library.\n *\n * Similar to HTML5 WebSocket, WebChannel offers an abstraction for\n * point-to-point socket-like communication between a browser client and\n * a remote origin.\n *\n * WebChannels are created via <code>WebChannel</code>. Multiple WebChannels\n * may be multiplexed over the same WebChannelTransport, which encapsulates\n * the underlying physical connectivity over standard wire protocols\n * such as HTTP.\n *\n * A WebChannel in turn represents a logical communication channel between\n * the client and server endpoint. A WebChannel remains open for as long\n * as the client or server endpoint allows.\n *\n * Messages are delivered in-order and reliably over the same WebChannel,\n * and the choice of the underlying wire protocols is completely transparent\n * to the API users.\n *\n * Note that we have no immediate plan to move this API out of labs. While\n * the implementation is production ready, the API is subject to change.\n */\n\ngoog.provide('goog.net.WebChannel');\ngoog.provide('goog.net.WebChannel.Options');\n\ngoog.require('goog.events');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.Listenable');\ngoog.require('goog.net.XmlHttpFactory');\n\n\n\n/**\n * A WebChannel represents a logical bi-directional channel over which the\n * client communicates with a remote server that holds the other endpoint\n * of the channel. A WebChannel is always created in the context of a shared\n * {@link WebChannelTransport} instance. It is up to the underlying client-side\n * and server-side implementations to decide how or when multiplexing is\n * to be enabled.\n *\n * @interface\n * @extends {goog.events.Listenable}\n */\ngoog.net.WebChannel = function() {};\n\n\n\n/**\n * This interface defines a pluggable API to allow WebChannel runtime to support\n * customized algorithms in order to recover from transient failures such as\n * those failures caused by network or proxies (intermediaries).\n *\n * The algorithm may also choose to fail-fast, e.g. switch the client to some\n * offline mode.\n *\n * Extra measurements and logging could also be implemented in the custom\n * module, which has the full knowledge of all the state transitions\n * (due to failures).\n *\n * A default algorithm will be provided by the webchannel library itself. Custom\n * algorithms are expected to be tailored to specific client platforms or\n * networking environments, e.g. mobile, cellular network.\n *\n * @interface\n */\ngoog.net.WebChannel.FailureRecovery = function() {};\n\n\n/**\n * Configuration spec for newly created WebChannel instances.\n *\n * WebChannels are configured in the context of the containing\n * {@link WebChannelTransport}. The configuration parameters are specified\n * when a new instance of WebChannel is created via {@link WebChannelTransport}.\n * @record\n */\ngoog.net.WebChannel.Options = function() {};\n\n/**\n * Transport-metadata support.\n *\n * Custom HTTP headers to be added to every message sent to the server. This\n * object is mutable, and custom headers may be changed, removed, or added\n * during the runtime after a channel has been opened.\n *\n * Custom headers may trigger CORS preflight. See other related options.\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.messageHeaders;\n\n/**\n * Transport-metadata support.\n *\n * Similar to messageHeaders, but any custom HTTP headers will be sent only once\n * when the channel is opened as part of the handshake request. Typical usage is\n * to send an auth header to the server, which only checks the auth header at\n * the time during the handshake when the channel is opened.\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.initMessageHeaders;\n\n/**\n * Sent as initMessageHeaders via X-WebChannel-Content-Type,\n * to inform the server the MIME type of WebChannel messages.\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.messageContentType;\n\n/**\n * Transport-metadata support.\n *\n * Custom url query parameters to be added to every message sent to the server.\n * This object is mutable, and custom parameters may be changed, removed or\n * added during the runtime after a channel has been opened.\n *\n * TODO: initMessageUrlParams\n * TODO: closeMessageUrlParams (custom url query params to be added to the\n * channel-close message. Custom headers are not supported due to the use of\n * SendBeacon)\n *\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.messageUrlParams;\n\n/**\n * Whether a special header should be added to\n * each message so that the server can dispatch webchannel messages without\n * knowing the URL path prefix. Defaults to false.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.clientProtocolHeaderRequired;\n\n/**\n * The maximum number of in-flight HTTP requests allowed\n * when SPDY is enabled. Currently we only detect SPDY in Chrome.\n * This parameter defaults to 10. When SPDY is not enabled, this parameter\n * will have no effect.\n * @type {number|undefined}\n */\ngoog.net.WebChannel.Options.prototype.concurrentRequestLimit;\n\n/**\n * Setting this to true to allow the use of sub-domains\n * (as configured by the server) to send XHRs with the CORS withCredentials\n * bit set to true.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.supportsCrossDomainXhr;\n\n/**\n * Whether to bypass v8 encoding of client-sent messages.\n * This defaults to false now due to legacy servers. New applications should\n * always configure this option to true.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.sendRawJson;\n\n/**\n * The URL parameter name that contains the session id (for sticky routing of\n * HTTP requests). When this param is specified, a server that supports this\n * option will respond with an opaque session id as part of the initial\n * handshake (via the X-HTTP-Session-Id header); and all the subsequent requests\n * will contain the httpSessionIdParam. This option will take precedence over\n * any duplicated parameter specified with messageUrlParams, whose value will be\n * ignored.\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.httpSessionIdParam;\n\n/**\n * The URL parameter name to allow custom HTTP\n * headers to be overwritten as a URL param to bypass CORS preflight.\n *\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.httpHeadersOverwriteParam;\n\n/**\n * Whether to encode Options.initMessageHeaders in the HTTP request body.\n * This option defaults to false. If true, Options.httpHeadersOverwriteParam\n * will be ignored.\n *\n * This option should not be set if Options.fastHandshake is set (which\n * uses GET for handshake).\n *\n * Web-only feature.\n *\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.encodeInitMessageHeaders;\n\n/**\n * Whether to force long-polling from client to server.\n * This defaults to false. Long-polling may be necessary when a (MITM) proxy\n * is buffering data sent by the server.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.forceLongPolling;\n\n/**\n * Whether to enable automatic detection of buffering proxies. In the presence\n * of any buffering proxy, webchannel will use long-polling to send messages\n * from the server to the client. This option defaults to false.\n * Currently when fastHandshake is enabled, this option will be ignored.\n * Compared to \"forceLongPolling\", this option may introduce up to 2-RTT\n * extra latency for delivering messages generated immediately after the\n * handshake.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.detectBufferingProxy;\n\n/**\n * This option informs the server the desired maximum timeout interval (in\n * Milliseconds) to complete a long-polling GET response, e.g. to accommodate\n * the timeout enforced by a proxy. The WebChannel server may adjust the\n * specified timeout or may ignore this client-configured timeout.\n * @type {number|undefined}\n */\ngoog.net.WebChannel.Options.prototype.longPollingTimeout;\n\n/**\n * Enable true 0-RTT message delivery, including\n * leveraging QUIC 0-RTT (which requires GET to be used). This option\n * defaults to false. Note it is allowed to send messages before Open event is\n * received, after a channel has been opened. In order to enable 0-RTT,\n * messages will be encoded as part of URL and therefore there needs be a size\n * limit for those initial messages that are sent immediately as part of the\n * GET handshake request. With sendRawJson=true, this limit is currently set\n * to 4K chars and data beyond this limit will be buffered till the handshake\n * (1-RTT) finishes. With sendRawJson=false, it's up to the application\n * to limit the amount of data that is sent as part of the handshake.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.fastHandshake;\n\n/**\n * Enable the blocking RPC semantics for the handshake:\n * 1) the completion of handshake is blocked by the server-side application\n * logic for handling the handshake (HTTP) request; 2) the client application\n * will inspect the handshake (HTTP) response headers as generated\n * by the server application (v.s. by only the webchannel runtime). This option\n * defaults to false.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.blockingHandshake;\n\n/**\n * Whether to disable logging redact. By default, redact is\n * enabled to remove any message payload or user-provided info\n * from closure logs.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.disableRedact;\n\n/**\n * Inform the server about the client profile to enable\n * customized configs that are optimized for certain clients or environments.\n * Currently this information is sent via X-WebChannel-Client-Profile header.\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.clientProfile;\n\n/**\n * The internal channel parameter name to allow\n * experimental channel configurations. Supported options include fastfail,\n * baseRetryDelayMs, retryDelaySeedMs, forwardChannelMaxRetries and\n * forwardChannelRequestTimeoutMs. Note that these options are subject to\n * change.\n * @type {!Object<string, boolean|number>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.internalChannelParams;\n\n/**\n * Allows the caller to override the factory used to create\n * XMLHttpRequest objects. This is introduced to disable CORS on firefox OS.\n * @type {!goog.net.XmlHttpFactory|undefined}\n */\ngoog.net.WebChannel.Options.prototype.xmlHttpFactory;\n\n/**\n * Client-side thresholds that decide when to refresh\n * an underlying HTTP request, to limit memory consumption due to XHR buffering\n * or compression context. The client-side thresholds should be significantly\n * smaller than the server-side thresholds. This allows the client to eliminate\n * any latency introduced by request refreshing, i.e. an RTT window during which\n * messages may be buffered on the server-side. Supported params include\n * totalBytesReceived, totalDurationMs.\n * @type {!Object<string, number>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.requestRefreshThresholds;\n\n/**\n * This is an experimental feature to use WHATWG Fetch/streams (when supported)\n * for the backchannel. If a custom 'xmlHttpFactory' is speficied, this option\n * will not be effective. This option defaults to false now and will eventually\n * be turned on by default.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.useFetchStreams;\n\n/**\n * Opt-in to enable Chrome origin trials from the WebChannel client. See\n * https://github.com/GoogleChrome/OriginTrials\n *\n * Origin trial history:\n * - fetch upload (11/2020 - 07/2021)\n * https://developers.chrome.com/origintrials/#/view_trial/3524066708417413121\n *\n * Participating in the origin trials will help Chrome to release new Web\n * platform features sooner, which will in turn help improve WebChannel\n * performance.\n *\n * Origin trials are not expected to interfere with WebChannel wire messages\n * and should not introduce any noticeable overhead.\n *\n * This is enabled by default with any on-going origin-trial.\n *\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.enableOriginTrials;\n\n\n/**\n * Types that are allowed as message data.\n *\n * Note that JS objects (sent by the client) can only have string encoded\n * values due to the limitation of the current wire protocol.\n *\n * Unicode strings (sent by the server) may or may not need be escaped, as\n * decided by the server.\n *\n * @typedef {(!ArrayBuffer|!Blob|!Object<string, !Object|string>|!Array|string)}\n */\ngoog.net.WebChannel.MessageData;\n\n\n/**\n * Open the WebChannel against the URI specified in the constructor.\n */\ngoog.net.WebChannel.prototype.open = goog.abstractMethod;\n\n\n/**\n * Close the WebChannel.\n *\n * This is a full close (shutdown) with no guarantee of FIFO delivery in respect\n * to any in-flight messages sent to the server.\n *\n * If you need such a guarantee, see the Half the halfClose() method.\n */\ngoog.net.WebChannel.prototype.close = goog.abstractMethod;\n\n\n/**\n * Half-close the WebChannel.\n *\n * Half-close semantics:\n * 1. delivered as a regular message in FIFO programming order\n * 2. the server is expected to return a half-close too (with or without\n * application involved), which will trigger a full close (shutdown)\n * on the client side\n * 3. for now, the half-close event defined for server-initiated\n * half-close is not exposed to the client application\n * 4. a client-side half-close may be triggered internally when the client\n * receives a half-close from the server; and the client is expected to\n * do a full close after the half-close is acked and delivered\n * on the server-side.\n * 5. Full close is always a forced one. See the close() method.\n *\n * New messages sent after halfClose() will be dropped.\n *\n * NOTE: This is not yet implemented, and will throw an exception if called.\n */\ngoog.net.WebChannel.prototype.halfClose = goog.abstractMethod;\n\n\n/**\n * Sends a message to the server that maintains the other endpoint of\n * the WebChannel.\n *\n * O-RTT behavior:\n * 1. messages sent before open() is called will always be delivered as\n * part of the handshake, i.e. with 0-RTT\n * 2. messages sent after open() is called but before the OPEN event\n * is received will be delivered as part of the handshake if\n * send() is called from the same execution context as open().\n * 3. otherwise, those messages will be buffered till the handshake\n * is completed (which will fire the OPEN event).\n *\n * @param {!goog.net.WebChannel.MessageData} message The message to send.\n */\ngoog.net.WebChannel.prototype.send = goog.abstractMethod;\n\n\n/**\n * Common events fired by WebChannels.\n * @enum {string}\n */\ngoog.net.WebChannel.EventType = {\n /** Dispatched when the channel is opened. */\n OPEN: goog.events.getUniqueId('open'),\n\n /** Dispatched when the channel is closed. */\n CLOSE: goog.events.getUniqueId('close'),\n\n /**\n * Dispatched when the channel is aborted due to errors.\n *\n * For backward compatibility reasons, a CLOSE event will also be\n * dispatched, following the ERROR event, which indicates that the channel\n * has been completely shutdown .\n */\n ERROR: goog.events.getUniqueId('error'),\n\n /** Dispatched when the channel has received a new message. */\n MESSAGE: goog.events.getUniqueId('message')\n};\n\n\n\n/**\n * The event interface for the MESSAGE event.\n *\n * @constructor\n * @extends {goog.events.Event}\n */\ngoog.net.WebChannel.MessageEvent = function() {\n 'use strict';\n goog.net.WebChannel.MessageEvent.base(\n this, 'constructor', goog.net.WebChannel.EventType.MESSAGE);\n};\ngoog.inherits(goog.net.WebChannel.MessageEvent, goog.events.Event);\n\n\n/**\n * The content of the message received from the server.\n *\n * @type {!goog.net.WebChannel.MessageData}\n */\ngoog.net.WebChannel.MessageEvent.prototype.data;\n\n\n/**\n * The metadata key when the MESSAGE event represents a metadata message.\n *\n * @type {string|undefined}\n */\ngoog.net.WebChannel.MessageEvent.prototype.metadataKey;\n\n\n/**\n * Metadata as HTTP status code. Typically sent before the channel is\n * half-closed by the server.\n *\n * @type {number|undefined}\n */\ngoog.net.WebChannel.MessageEvent.prototype.statusCode;\n\n\n/**\n * Metadata as HTTP headers. Typically sent before the channel is\n * half-closed by the server.\n *\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.MessageEvent.prototype.headers;\n\n\n/**\n * WebChannel level error conditions.\n *\n * Summary of error debugging and reporting in WebChannel:\n *\n * Network Error\n * 1. By default the webchannel library will set the error status to\n * NETWORK_ERROR when a channel has to be aborted or closed. NETWORK_ERROR\n * may be recovered by the application by retrying and opening a new channel.\n * 2. There may be lost messages (not acked by the server) when a channel is\n * aborted. Currently we don't have a public API to retrieve messages that\n * are waiting to be acked on the client side. File a bug if you think it\n * is useful to expose such an API.\n * 3. Details of why a channel fails are available via closure debug logs,\n * and stats events (see webchannel/requeststats.js). Those are internal\n * stats and are subject to change. File a bug if you think it's useful to\n * version and expose such stats as part of the WebChannel API.\n *\n * Server Error\n * 1. SERVER_ERROR is intended to indicate a non-recoverable condition, e.g.\n * when auth fails.\n * 2. We don't currently generate any such errors, because most of the time\n * it's the responsibility of upper-layer frameworks or the application\n * itself to indicate to the client why a webchannel has been failed\n * by the server.\n * 3. When a channel is failed by the server explicitly, we still signal\n * NETWORK_ERROR to the client. Explicit server failure may happen when the\n * server does a fail-over, or becomes overloaded, or conducts a forced\n * shutdown etc.\n * 4. We use some heuristic to decide if the network (aka cloud) is down\n * v.s. the actual server is down.\n *\n * RuntimeProperties.getLastStatusCode is a useful state that we expose to\n * the client to indicate the HTTP response status code of the last HTTP\n * request initiated by the WebChannel client library, for debugging\n * purposes only.\n *\n * See WebChannel.Options.backChannelFailureRecovery and\n * WebChannel.FailureRecovery to install a custom failure-recovery algorithm.\n *\n * @enum {number}\n */\ngoog.net.WebChannel.ErrorStatus = {\n /** No error has occurred. */\n OK: 0,\n\n /** Communication to the server has failed. */\n NETWORK_ERROR: 1,\n\n /** The server fails to accept or process the WebChannel. */\n SERVER_ERROR: 2\n};\n\n\n\n/**\n * The event interface for the ERROR event.\n *\n * @constructor\n * @extends {goog.events.Event}\n */\ngoog.net.WebChannel.ErrorEvent = function() {\n 'use strict';\n goog.net.WebChannel.ErrorEvent.base(\n this, 'constructor', goog.net.WebChannel.EventType.ERROR);\n};\ngoog.inherits(goog.net.WebChannel.ErrorEvent, goog.events.Event);\n\n\n/**\n * The error status.\n *\n * @type {!goog.net.WebChannel.ErrorStatus}\n */\ngoog.net.WebChannel.ErrorEvent.prototype.status;\n\n\n/**\n * @return {!goog.net.WebChannel.RuntimeProperties} The runtime properties\n * of the WebChannel instance.\n */\ngoog.net.WebChannel.prototype.getRuntimeProperties = goog.abstractMethod;\n\n\n\n/**\n * The runtime properties of the WebChannel instance.\n *\n * This class is defined for debugging and monitoring purposes, as well as for\n * runtime functions that the application may choose to manage by itself.\n *\n * @interface\n */\ngoog.net.WebChannel.RuntimeProperties = function() {};\n\n\n/**\n * @return {number} The effective limit for the number of concurrent HTTP\n * requests that are allowed to be made for sending messages from the client\n * to the server. When SPDY is not enabled, this limit will be one.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getConcurrentRequestLimit =\n goog.abstractMethod;\n\n\n/**\n * For applications that need support multiple channels (e.g. from\n * different tabs) to the same origin, use this method to decide if SPDY is\n * enabled and therefore it is safe to open multiple channels.\n *\n * If SPDY is disabled, the application may choose to limit the number of active\n * channels to one or use other means such as sub-domains to work around\n * the browser connection limit.\n *\n * @return {boolean} Whether SPDY is enabled for the origin against which\n * the channel is created.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.isSpdyEnabled =\n goog.abstractMethod;\n\n\n/**\n * @return {number} The number of requests (for sending messages to the server)\n * that are pending. If this number is approaching the value of\n * getConcurrentRequestLimit(), client-to-server message delivery may experience\n * a higher latency.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getPendingRequestCount =\n goog.abstractMethod;\n\n\n/**\n * For applications to query the current HTTP session id, sent by the server\n * during the initial handshake.\n *\n * @return {?string} the HTTP session id or null if no HTTP session is in use.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getHttpSessionId =\n goog.abstractMethod;\n\n\n/**\n * Experimental API.\n *\n * This method generates an in-band commit request to the server, which will\n * ack the commit request as soon as all messages sent prior to this commit\n * request have been committed by the application.\n *\n * Committing a message has a stronger semantics than delivering a message\n * to the application. Detail spec:\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * Timeout or cancellation is not supported and the application is expected to\n * abort the channel if the commit-ack fails to arrive in time.\n *\n * ===\n *\n * This is currently implemented only in the client layer and the commit\n * callback will be invoked after all the pending client-sent messages have been\n * delivered by the server-side webchannel endpoint. This semantics is\n * different and weaker than what's required for end-to-end ack which requires\n * the server application to ack the in-order delivery of messages that are sent\n * before the commit request is issued.\n *\n * Commit should only be called after the channel open event is received.\n * Duplicated commits are allowed and only the last callback is guaranteed.\n * Commit called after the channel has been closed will be ignored.\n *\n * @param {function()} callback The callback will be invoked once an\n * ack has been received for the current commit or any newly issued commit.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.commit = goog.abstractMethod;\n\n\n/**\n * This method may be used by the application to recover from a peer failure\n * or to enable sender-initiated flow-control.\n *\n * Detail spec: https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * Note that the caller should NOT modify the list of returned messages.\n *\n * @return {!Array<!goog.net.WebChannel.MessageData>} The list of messages that\n * have not received commit-ack from the server; or if no commit has been\n * issued, the list of messages that have not been delivered to the server\n * application.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getNonAckedMessages =\n goog.abstractMethod;\n\n\n/**\n * A low water-mark message count to notify the application when the\n * flow-control condition is cleared, that is, when the application is\n * able to send more messages.\n *\n * We expect the application to configure a high water-mark message count,\n * which is checked via getNonAckedMessageCount(). When the high water-mark\n * is exceeded, the application should install a callback via this method\n * to be notified when to start to send new messages.\n *\n * This is not yet implemented.\n *\n * @param {number} count The low water-mark count. It is an error to pass\n * a non-positive value.\n * @param {function()} callback The call back to notify the application\n * when NonAckedMessageCount is below the specified low water-mark count.\n * Any previously registered callback is cleared. This new callback will\n * be cleared once it has been fired, or when the channel is closed or aborted.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.notifyNonAckedMessageCount =\n goog.abstractMethod;\n\n\n/**\n * Experimental API.\n *\n * This method registers a callback to handle the commit request sent\n * by the server. Commit protocol spec:\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * This is not yet implemented.\n *\n * @param {function(!Object)} callback The callback will take an opaque\n * commitId which needs be passed back to the server when an ack-commit\n * response is generated by the client application, via ackCommit().\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.onCommit = goog.abstractMethod;\n\n\n/**\n * Experimental API.\n *\n * This method is used by the application to generate an ack-commit response\n * for the given commitId. Commit protocol spec:\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * This is not yet implemented.\n *\n * @param {!Object} commitId The commitId which denotes the commit request\n * from the server that needs be ack'ed.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.ackCommit = goog.abstractMethod;\n\n\n/**\n * Transport-metadata support.\n *\n * Responses from the channel-close (abort) message are not available.\n *\n * In future when client-side half-close is supported, its response headers\n * will be available via this API too.\n * @return {!Object<string, string>|undefined} The response headers received\n * with the non-200 HTTP status code that causes the channel to be aborted.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getLastResponseHeaders =\n goog.abstractMethod;\n\n/**\n * Transport-metadata support.\n *\n * TODO: getInitStatusCode (handshake)\n * TODO: getInitResponseHeaders (handshake)\n *\n * Note that response headers from client-initiated close (abort) are not\n * available.\n *\n * In future when client-initiated half-close is supported, its response status\n * will be available via this API.\n *\n * @return {number} The non-200 HTTP status code received that causes the\n * channel to be aborted.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getLastStatusCode =\n goog.abstractMethod;\n\n\n/**\n * Enum to indicate the current recovery state.\n *\n * @enum {string}\n */\ngoog.net.WebChannel.FailureRecovery.State = {\n /** Initial state. */\n INIT: 'init',\n\n /** Once a failure has been detected. */\n FAILED: 'failed',\n\n /**\n * Once a recovery operation has been issued, e.g. a new request to resume\n * communication.\n */\n RECOVERING: 'recovering',\n\n /** The channel has been closed. */\n CLOSED: 'closed'\n};\n\n\n/**\n * Enum to indicate different failure conditions as detected by the webchannel\n * runtime.\n *\n * This enum is to be used only between the runtime and FailureRecovery module,\n * and new states are expected to be introduced in future.\n *\n * @enum {string}\n */\ngoog.net.WebChannel.FailureRecovery.FailureCondition = {\n /**\n * The HTTP response returned a non-successful http status code.\n */\n HTTP_ERROR: 'http_error',\n\n /**\n * The request was aborted.\n */\n ABORT: 'abort',\n\n /**\n * The request timed out.\n */\n TIMEOUT: 'timeout',\n\n /**\n * Exception was thrown while processing the request/response.\n */\n EXCEPTION: 'exception'\n};\n\n\n/**\n * @return {!goog.net.WebChannel.FailureRecovery.State} the current state,\n * mainly for debugging use.\n */\ngoog.net.WebChannel.FailureRecovery.prototype.getState = goog.abstractMethod;\n\n\n/**\n * This method is for WebChannel runtime to set the current failure condition\n * and to provide a callback for the algorithm to signal to the runtime\n * when it is time to issue a recovery operation, e.g. a new request to the\n * server.\n *\n * Supported transitions include:\n * INIT->FAILED\n * FAILED->FAILED (re-entry ok)\n * RECOVERY->FAILED.\n *\n * Ignored if state == CLOSED.\n *\n * Advanced implementations are expected to track all the state transitions\n * and their timestamps for monitoring purposes.\n *\n * @param {!goog.net.WebChannel.FailureRecovery.FailureCondition} failure The\n * new failure condition generated by the WebChannel runtime.\n * @param {!Function} operation The callback function to the WebChannel\n * runtime to issue a recovery operation, e.g. a new request. E.g. the default\n * recovery algorithm will issue timeout-based recovery operations.\n * Post-condition for the callback: state transition to RECOVERING.\n *\n * @return {!goog.net.WebChannel.FailureRecovery.State} The updated state\n * as decided by the failure recovery module. Upon a recoverable failure event,\n * the state is transitioned to RECOVERING; or the state is transitioned to\n * FAILED which indicates a fail-fast decision for the runtime to execute.\n */\ngoog.net.WebChannel.FailureRecovery.prototype.setFailure = goog.abstractMethod;\n\n\n/**\n * The Webchannel runtime needs call this method when webchannel is closed or\n * aborted.\n *\n * Once the instance is closed, any access to the instance will be a no-op.\n */\ngoog.net.WebChannel.FailureRecovery.prototype.close = goog.abstractMethod;\n\n\n/**\n * A request header to indicate to the server the messaging protocol\n * each HTTP message is speaking.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_CLIENT_PROTOCOL = 'X-Client-Protocol';\n\n\n/**\n * The value for x-client-protocol when the messaging protocol is WebChannel.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL = 'webchannel';\n\n\n/**\n * A response header for the server to signal the wire-protocol that\n * the browser establishes with the server (or proxy), e.g. \"spdy\" (aka http/2)\n * \"quic\". This information avoids the need to use private APIs to decide if\n * HTTP requests are multiplexed etc.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_CLIENT_WIRE_PROTOCOL = 'X-Client-Wire-Protocol';\n\n\n/**\n * A response header for the server to send back the HTTP session id as part of\n * the initial handshake. The value of the HTTP session id is opaque to the\n * WebChannel protocol.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_HTTP_SESSION_ID = 'X-HTTP-Session-Id';\n\n\n/**\n * A response header for the server to send back any initial response data as a\n * header to avoid any possible buffering by an intermediary, which may\n * be undesired during the handshake.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_HTTP_INITIAL_RESPONSE = 'X-HTTP-Initial-Response';\n\n\n/**\n * A request header for specifying the content-type of WebChannel messages,\n * e.g. application-defined JSON encoding styles. Currently this header\n * is sent by the client via initMessageHeaders when the channel is opened.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE = 'X-WebChannel-Content-Type';\n\n\n/**\n * A request header for specifying the client profile in order to apply\n * customized config params on the server side, e.g. timeouts.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE = 'X-WebChannel-Client-Profile';\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Low level handling of XMLHttpRequest.\n */\n\ngoog.provide('goog.net.DefaultXmlHttpFactory');\ngoog.provide('goog.net.XmlHttp');\ngoog.provide('goog.net.XmlHttp.OptionType');\ngoog.provide('goog.net.XmlHttp.ReadyState');\ngoog.provide('goog.net.XmlHttpDefines');\n\ngoog.require('goog.asserts');\ngoog.require('goog.net.WrapperXmlHttpFactory');\ngoog.require('goog.net.XmlHttpFactory');\ngoog.requireType('goog.net.XhrLike');\n\n\n/**\n * Static class for creating XMLHttpRequest objects.\n * @return {!goog.net.XhrLike.OrNative} A new XMLHttpRequest object.\n */\ngoog.net.XmlHttp = function() {\n 'use strict';\n return goog.net.XmlHttp.factory_.createInstance();\n};\n\n\n/**\n * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to\n * true bypasses the ActiveX probing code.\n * NOTE(ruilopes): Due to the way JSCompiler works, this define *will not* strip\n * out the ActiveX probing code from binaries. To achieve this, use\n * `goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR` instead.\n * TODO(ruilopes): Collapse both defines.\n */\ngoog.net.XmlHttp.ASSUME_NATIVE_XHR =\n goog.define('goog.net.XmlHttp.ASSUME_NATIVE_XHR', false);\n\n\n/** @const */\ngoog.net.XmlHttpDefines = {};\n\n\n/**\n * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to\n * true eliminates the ActiveX probing code.\n */\ngoog.net.XmlHttpDefines.ASSUME_NATIVE_XHR =\n goog.define('goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR', false);\n\n\n/**\n * Gets the options to use with the XMLHttpRequest objects obtained using\n * the static methods.\n * @return {Object} The options.\n */\ngoog.net.XmlHttp.getOptions = function() {\n 'use strict';\n return goog.net.XmlHttp.factory_.getOptions();\n};\n\n\n/**\n * Type of options that an XmlHttp object can have.\n * @enum {number}\n */\ngoog.net.XmlHttp.OptionType = {\n /**\n * Whether a no-op function should be used to clear the onreadystatechange\n * handler instead of null.\n */\n USE_NULL_FUNCTION: 0,\n\n /**\n * NOTE(user): In IE if send() errors on a *local* request the readystate\n * is still changed to COMPLETE. We need to ignore it and allow the\n * try/catch around send() to pick up the error.\n */\n LOCAL_REQUEST_ERROR: 1,\n};\n\n\n/**\n * Status constants for XMLHTTP, matches:\n * https://msdn.microsoft.com/en-us/library/ms534361(v=vs.85).aspx\n * @enum {number}\n */\ngoog.net.XmlHttp.ReadyState = {\n /**\n * Constant for when xmlhttprequest.readyState is uninitialized\n */\n UNINITIALIZED: 0,\n\n /**\n * Constant for when xmlhttprequest.readyState is loading.\n */\n LOADING: 1,\n\n /**\n * Constant for when xmlhttprequest.readyState is loaded.\n */\n LOADED: 2,\n\n /**\n * Constant for when xmlhttprequest.readyState is in an interactive state.\n */\n INTERACTIVE: 3,\n\n /**\n * Constant for when xmlhttprequest.readyState is completed\n */\n COMPLETE: 4,\n};\n\n\n/**\n * The global factory instance for creating XMLHttpRequest objects.\n * @type {goog.net.XmlHttpFactory}\n * @private\n */\ngoog.net.XmlHttp.factory_;\n\n\n/**\n * Sets the factories for creating XMLHttpRequest objects and their options.\n * @param {Function} factory The factory for XMLHttpRequest objects.\n * @param {Function} optionsFactory The factory for options.\n * @deprecated Use setGlobalFactory instead.\n */\ngoog.net.XmlHttp.setFactory = function(factory, optionsFactory) {\n 'use strict';\n goog.net.XmlHttp.setGlobalFactory(new goog.net.WrapperXmlHttpFactory(\n goog.asserts.assert(factory), goog.asserts.assert(optionsFactory)));\n};\n\n\n/**\n * Sets the global factory object.\n * @param {!goog.net.XmlHttpFactory} factory New global factory object.\n */\ngoog.net.XmlHttp.setGlobalFactory = function(factory) {\n 'use strict';\n goog.net.XmlHttp.factory_ = factory;\n};\n\n\n\n/**\n * Default factory to use when creating xhr objects. You probably shouldn't be\n * instantiating this directly, but rather using it via goog.net.XmlHttp.\n * @extends {goog.net.XmlHttpFactory}\n * @constructor\n */\ngoog.net.DefaultXmlHttpFactory = function() {\n 'use strict';\n goog.net.XmlHttpFactory.call(this);\n};\ngoog.inherits(goog.net.DefaultXmlHttpFactory, goog.net.XmlHttpFactory);\n\n\n/** @override */\ngoog.net.DefaultXmlHttpFactory.prototype.createInstance = function() {\n 'use strict';\n const progId = this.getProgId_();\n if (progId) {\n return new ActiveXObject(progId);\n } else {\n return new XMLHttpRequest();\n }\n};\n\n\n/** @override */\ngoog.net.DefaultXmlHttpFactory.prototype.internalGetOptions = function() {\n 'use strict';\n const progId = this.getProgId_();\n const options = {};\n if (progId) {\n options[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] = true;\n options[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] = true;\n }\n return options;\n};\n\n\n/**\n * The ActiveX PROG ID string to use to create xhr's in IE. Lazily initialized.\n * @type {string|undefined}\n * @private\n */\ngoog.net.DefaultXmlHttpFactory.prototype.ieProgId_;\n\n\n/**\n * Initialize the private state used by other functions.\n * @return {string} The ActiveX PROG ID string to use to create xhr's in IE.\n * @private\n */\ngoog.net.DefaultXmlHttpFactory.prototype.getProgId_ = function() {\n 'use strict';\n if (goog.net.XmlHttp.ASSUME_NATIVE_XHR ||\n goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR) {\n return '';\n }\n\n // The following blog post describes what PROG IDs to use to create the\n // XMLHTTP object in Internet Explorer:\n // http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx\n // However we do not (yet) fully trust that this will be OK for old versions\n // of IE on Win9x so we therefore keep the last 2.\n if (!this.ieProgId_ && typeof XMLHttpRequest == 'undefined' &&\n typeof ActiveXObject != 'undefined') {\n // Candidate Active X types.\n const ACTIVE_X_IDENTS = [\n 'MSXML2.XMLHTTP.6.0',\n 'MSXML2.XMLHTTP.3.0',\n 'MSXML2.XMLHTTP',\n 'Microsoft.XMLHTTP',\n ];\n for (let i = 0; i < ACTIVE_X_IDENTS.length; i++) {\n const candidate = ACTIVE_X_IDENTS[i];\n\n try {\n new ActiveXObject(candidate);\n // NOTE(user): cannot assign progid and return candidate in one line\n // because JSCompiler complaings: BUG 658126\n this.ieProgId_ = candidate;\n return candidate;\n } catch (e) {\n // do nothing; try next choice\n }\n }\n\n // couldn't find any matches\n throw new Error(\n 'Could not create ActiveXObject. ActiveX might be disabled,' +\n ' or MSXML might not be installed');\n }\n\n return /** @type {string} */ (this.ieProgId_);\n};\n\n\n// Set the global factory to an instance of the default factory.\ngoog.net.XmlHttp.setGlobalFactory(new goog.net.DefaultXmlHttpFactory());\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Definition of the ChannelRequest class. The request\n * object encapsulates the logic for making a single request, either for the\n * forward channel, back channel, or test channel, to the server. It contains\n * the logic for the two types of transports we use:\n * XMLHTTP and Image request. It provides timeout detection. More transports\n * to be added in future, such as Fetch, WebSocket.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.ChannelRequest');\n\ngoog.require('goog.Timer');\ngoog.require('goog.asserts');\ngoog.require('goog.async.Throttle');\ngoog.require('goog.dispose');\ngoog.require('goog.events.EventHandler');\ngoog.require('goog.labs.net.webChannel.Channel');\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\ngoog.require('goog.labs.net.webChannel.environment');\ngoog.require('goog.labs.net.webChannel.requestStats');\ngoog.require('goog.net.ErrorCode');\ngoog.require('goog.net.EventType');\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.net.XmlHttp');\ngoog.require('goog.object');\ngoog.require('goog.string');\ngoog.require('goog.userAgent');\ngoog.requireType('goog.Uri');\ngoog.requireType('goog.events.Event');\ngoog.requireType('goog.labs.net.webChannel.Wire.QueuedMap');\ngoog.requireType('goog.net.XhrIo');\n\n\n\n/**\n * A new ChannelRequest is created for each request to the server.\n *\n * @param {goog.labs.net.webChannel.Channel} channel\n * The channel that owns this request.\n * @param {goog.labs.net.webChannel.WebChannelDebug} channelDebug A\n * WebChannelDebug to use for logging.\n * @param {string=} opt_sessionId The session id for the channel.\n * @param {string|number=} opt_requestId The request id for this request.\n * @param {number=} opt_retryId The retry id for this request.\n * @constructor\n * @struct\n * @final\n */\ngoog.labs.net.webChannel.ChannelRequest = function(\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {\n 'use strict';\n /**\n * The channel object that owns the request.\n * @private {goog.labs.net.webChannel.Channel}\n */\n this.channel_ = channel;\n\n /**\n * The channel debug to use for logging\n * @private {goog.labs.net.webChannel.WebChannelDebug}\n */\n this.channelDebug_ = channelDebug;\n\n /**\n * The Session ID for the channel.\n * @private {string|undefined}\n */\n this.sid_ = opt_sessionId;\n\n /**\n * The RID (request ID) for the request.\n * @private {string|number|undefined}\n */\n this.rid_ = opt_requestId;\n\n /**\n * The attempt number of the current request.\n * @private {number}\n */\n this.retryId_ = opt_retryId || 1;\n\n /**\n * An object to keep track of the channel request event listeners.\n * @private {!goog.events.EventHandler<\n * !goog.labs.net.webChannel.ChannelRequest>}\n */\n this.eventHandler_ = new goog.events.EventHandler(this);\n\n /**\n * The timeout in ms before failing the request.\n * @private {number}\n */\n this.timeout_ = goog.labs.net.webChannel.ChannelRequest.TIMEOUT_MS_;\n\n /**\n * A timer for polling responseText in browsers that don't fire\n * onreadystatechange during incremental loading of responseText.\n * @private {goog.Timer}\n */\n this.pollingTimer_ =\n new goog.Timer(goog.labs.net.webChannel.environment.getPollingInterval());\n\n /**\n * Extra HTTP headers to add to all the requests sent to the server.\n * @private {?Object}\n */\n this.extraHeaders_ = null;\n\n\n /**\n * Whether the request was successful. This is only set to true after the\n * request successfully completes.\n * @private {boolean}\n */\n this.successful_ = false;\n\n\n /**\n * The TimerID of the timer used to detect if the request has timed-out.\n * @type {?number}\n * @private\n */\n this.watchDogTimerId_ = null;\n\n /**\n * The time in the future when the request will timeout.\n * @private {?number}\n */\n this.watchDogTimeoutTime_ = null;\n\n /**\n * The time the request started.\n * @private {?number}\n */\n this.requestStartTime_ = null;\n\n /**\n * The type of request (XMLHTTP, IMG)\n * @private {?number}\n */\n this.type_ = null;\n\n /**\n * The base Uri for the request. The includes all the parameters except the\n * one that indicates the retry number.\n * @private {?goog.Uri}\n */\n this.baseUri_ = null;\n\n /**\n * The request Uri that was actually used for the most recent request attempt.\n * @private {?goog.Uri}\n */\n this.requestUri_ = null;\n\n /**\n * The post data, if the request is a post.\n * @private {?string}\n */\n this.postData_ = null;\n\n /**\n * An array of pending messages that we have either received a non-successful\n * response for, or no response at all, and which therefore may or may not\n * have been received by the server.\n * @private {!Array<goog.labs.net.webChannel.Wire.QueuedMap>}\n */\n this.pendingMessages_ = [];\n\n /**\n * The XhrLte request if the request is using XMLHTTP\n * @private {?goog.net.XhrIo}\n */\n this.xmlHttp_ = null;\n\n /**\n * The position of where the next unprocessed chunk starts in the response\n * text.\n * @private {number}\n */\n this.xmlHttpChunkStart_ = 0;\n\n /**\n * The verb (Get or Post) for the request.\n * @private {?string}\n */\n this.verb_ = null;\n\n /**\n * The last error if the request failed.\n * @private {?goog.labs.net.webChannel.ChannelRequest.Error}\n */\n this.lastError_ = null;\n\n /**\n * The response headers received along with the non-200 status.\n *\n * @private {!Object<string, string>|undefined}\n */\n this.errorResponseHeaders_ = undefined;\n\n /**\n * The last status code received.\n * @private {number}\n */\n this.lastStatusCode_ = -1;\n\n /**\n * Whether the request has been cancelled due to a call to cancel.\n * @private {boolean}\n */\n this.cancelled_ = false;\n\n /**\n * A throttle time in ms for readystatechange events for the backchannel.\n * Useful for throttling when ready state is INTERACTIVE (partial data).\n * If set to zero no throttle is used.\n *\n * See WebChannelBase.prototype.readyStateChangeThrottleMs_\n *\n * @private {number}\n */\n this.readyStateChangeThrottleMs_ = 0;\n\n /**\n * The throttle for readystatechange events for the current request, or null\n * if there is none.\n * @private {?goog.async.Throttle}\n */\n this.readyStateChangeThrottle_ = null;\n\n /**\n * Whether to the result is expected to be encoded for chunking and thus\n * requires decoding.\n * @private {boolean}\n */\n this.decodeChunks_ = false;\n\n /**\n * Whether to decode x-http-initial-response.\n * @private {boolean}\n */\n this.decodeInitialResponse_ = false;\n\n /**\n * Whether x-http-initial-response has been decoded (dispatched).\n * @private {boolean}\n */\n this.initialResponseDecoded_ = false;\n\n /**\n * Whether the first byte of response body has arrived, for a successful\n * response.\n * @private {boolean}\n */\n this.firstByteReceived_ = false;\n\n /**\n * The current state of fetch responses if webchannel is using WHATWG\n * fetch/streams.\n * @private {!goog.labs.net.webChannel.FetchResponseState}\n */\n this.fetchResponseState_ = new goog.labs.net.webChannel.FetchResponseState();\n};\n\n/**\n * A collection of fetch/stream properties.\n * @struct\n * @constructor\n */\ngoog.labs.net.webChannel.FetchResponseState = function() {\n 'use strict';\n /**\n * The TextDecoder for decoding Uint8Array responses from fetch request.\n * @type {?goog.global.TextDecoder}\n */\n this.textDecoder = null;\n\n /**\n * The unconsumed response text from the fetch requests.\n * @type {string}\n */\n this.responseBuffer = '';\n\n /**\n * Whether or not the response body has arrived.\n * @type {boolean}\n */\n this.responseArrivedForFetch = false;\n};\n\n\ngoog.scope(function() {\n'use strict';\nconst WebChannel = goog.net.WebChannel;\nconst Channel = goog.labs.net.webChannel.Channel;\nconst ChannelRequest = goog.labs.net.webChannel.ChannelRequest;\nconst FetchResponseState = goog.labs.net.webChannel.FetchResponseState;\nconst requestStats = goog.labs.net.webChannel.requestStats;\nconst WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\nconst environment = goog.labs.net.webChannel.environment;\n\n/**\n * Default timeout in MS for a request. The server must return data within this\n * time limit for the request to not timeout.\n * @private {number}\n */\nChannelRequest.TIMEOUT_MS_ = 45 * 1000;\n\n\n/**\n * Enum for channel requests type\n * @enum {number}\n * @private\n */\nChannelRequest.Type_ = {\n /**\n * XMLHTTP requests.\n */\n XML_HTTP: 1,\n\n /**\n * IMG requests.\n */\n CLOSE_REQUEST: 2\n};\n\n\n/**\n * Enum type for identifying an error.\n * @enum {number}\n */\nChannelRequest.Error = {\n /**\n * Errors due to a non-200 status code.\n */\n STATUS: 0,\n\n /**\n * Errors due to no data being returned.\n */\n NO_DATA: 1,\n\n /**\n * Errors due to a timeout.\n */\n TIMEOUT: 2,\n\n /**\n * Errors due to the server returning an unknown.\n */\n UNKNOWN_SESSION_ID: 3,\n\n /**\n * Errors due to bad data being received.\n */\n BAD_DATA: 4,\n\n /**\n * Errors due to the handler throwing an exception.\n */\n HANDLER_EXCEPTION: 5,\n\n /**\n * The browser declared itself offline during the request.\n */\n BROWSER_OFFLINE: 6\n};\n\n\n/**\n * Returns a useful error string for debugging based on the specified error\n * code.\n * @param {?ChannelRequest.Error} errorCode The error code.\n * @param {number} statusCode The HTTP status code.\n * @return {string} The error string for the given code combination.\n */\nChannelRequest.errorStringFromCode = function(errorCode, statusCode) {\n 'use strict';\n switch (errorCode) {\n case ChannelRequest.Error.STATUS:\n return 'Non-200 return code (' + statusCode + ')';\n case ChannelRequest.Error.NO_DATA:\n return 'XMLHTTP failure (no data)';\n case ChannelRequest.Error.TIMEOUT:\n return 'HttpConnection timeout';\n default:\n return 'Unknown error';\n }\n};\n\n\n/**\n * Sentinel value used to indicate an invalid chunk in a multi-chunk response.\n * @private {!Object}\n */\nChannelRequest.INVALID_CHUNK_ = {};\n\n\n/**\n * Sentinel value used to indicate an incomplete chunk in a multi-chunk\n * response.\n * @private {!Object}\n */\nChannelRequest.INCOMPLETE_CHUNK_ = {};\n\n\n/**\n * Returns whether XHR streaming is supported on this browser.\n *\n * @return {boolean} Whether XHR streaming is supported.\n * @see http://code.google.com/p/closure-library/issues/detail?id=346\n */\nChannelRequest.supportsXhrStreaming = function() {\n 'use strict';\n return !goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(10);\n};\n\n\n/**\n * Sets extra HTTP headers to add to all the requests sent to the server.\n *\n * @param {Object} extraHeaders The HTTP headers.\n */\nChannelRequest.prototype.setExtraHeaders = function(extraHeaders) {\n 'use strict';\n this.extraHeaders_ = extraHeaders;\n};\n\n\n/**\n * Overrides the default HTTP method.\n *\n * @param {string} verb The HTTP method\n */\nChannelRequest.prototype.setVerb = function(verb) {\n 'use strict';\n this.verb_ = verb;\n};\n\n\n/**\n * Sets the timeout for a request\n *\n * @param {number} timeout The timeout in MS for when we fail the request.\n */\nChannelRequest.prototype.setTimeout = function(timeout) {\n 'use strict';\n this.timeout_ = timeout;\n};\n\n\n/**\n * Sets the throttle for handling onreadystatechange events for the request.\n *\n * @param {number} throttle The throttle in ms. A value of zero indicates\n * no throttle.\n */\nChannelRequest.prototype.setReadyStateChangeThrottle = function(throttle) {\n 'use strict';\n this.readyStateChangeThrottleMs_ = throttle;\n};\n\n\n/**\n * Sets the pending messages that this request is handling.\n *\n * @param {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} pendingMessages\n * The pending messages for this request.\n */\nChannelRequest.prototype.setPendingMessages = function(pendingMessages) {\n 'use strict';\n this.pendingMessages_ = pendingMessages;\n};\n\n\n/**\n * Gets the pending messages that this request is handling, in case of a retry.\n *\n * @return {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} The pending\n * messages for this request.\n */\nChannelRequest.prototype.getPendingMessages = function() {\n 'use strict';\n return this.pendingMessages_;\n};\n\n\n/**\n * Uses XMLHTTP to send an HTTP POST to the server.\n *\n * @param {goog.Uri} uri The uri of the request.\n * @param {?string} postData The data for the post body.\n * @param {boolean} decodeChunks Whether to the result is expected to be\n * encoded for chunking and thus requires decoding.\n */\nChannelRequest.prototype.xmlHttpPost = function(uri, postData, decodeChunks) {\n 'use strict';\n this.type_ = ChannelRequest.Type_.XML_HTTP;\n this.baseUri_ = uri.clone().makeUnique();\n this.postData_ = postData;\n this.decodeChunks_ = decodeChunks;\n this.sendXmlHttp_(null /* hostPrefix */);\n};\n\n\n/**\n * Uses XMLHTTP to send an HTTP GET to the server.\n *\n * @param {goog.Uri} uri The uri of the request.\n * @param {boolean} decodeChunks Whether to the result is expected to be\n * encoded for chunking and thus requires decoding.\n * @param {?string} hostPrefix The host prefix, if we might be using a\n * secondary domain. Note that it should also be in the URL, adding this\n * won't cause it to be added to the URL.\n */\nChannelRequest.prototype.xmlHttpGet = function(uri, decodeChunks, hostPrefix) {\n 'use strict';\n this.type_ = ChannelRequest.Type_.XML_HTTP;\n this.baseUri_ = uri.clone().makeUnique();\n this.postData_ = null;\n this.decodeChunks_ = decodeChunks;\n\n this.sendXmlHttp_(hostPrefix);\n};\n\n\n/**\n * Sends a request via XMLHTTP according to the current state of the request\n * object.\n *\n * @param {?string} hostPrefix The host prefix, if we might be using a secondary\n * domain.\n * @private\n */\nChannelRequest.prototype.sendXmlHttp_ = function(hostPrefix) {\n 'use strict';\n this.requestStartTime_ = Date.now();\n this.ensureWatchDogTimer_();\n\n // clone the base URI to create the request URI. The request uri has the\n // attempt number as a parameter which helps in debugging.\n this.requestUri_ = this.baseUri_.clone();\n this.requestUri_.setParameterValues('t', this.retryId_);\n\n // send the request either as a POST or GET\n this.xmlHttpChunkStart_ = 0;\n const useSecondaryDomains = this.channel_.shouldUseSecondaryDomains();\n this.fetchResponseState_ = new FetchResponseState();\n // If the request is a GET request, start a backchannel to transfer streaming\n // data. Note that WebChannel GET request can also be used for closing the\n // channel as in method ChannelRequest#sendCloseRequest.\n // The second parameter of Channel#createXhrIo is JS only.\n this.xmlHttp_ = this.channel_.createXhrIo(\n useSecondaryDomains ? hostPrefix : null, !this.postData_);\n\n if (this.readyStateChangeThrottleMs_ > 0) {\n this.readyStateChangeThrottle_ = new goog.async.Throttle(\n goog.bind(this.xmlHttpHandler_, this, this.xmlHttp_),\n this.readyStateChangeThrottleMs_);\n }\n\n this.eventHandler_.listen(\n this.xmlHttp_, goog.net.EventType.READY_STATE_CHANGE,\n this.readyStateChangeHandler_);\n\n const headers =\n this.extraHeaders_ ? goog.object.clone(this.extraHeaders_) : {};\n if (this.postData_) {\n if (!this.verb_) {\n this.verb_ = 'POST';\n }\n headers['Content-Type'] = 'application/x-www-form-urlencoded';\n this.xmlHttp_.send(this.requestUri_, this.verb_, this.postData_, headers);\n } else {\n this.verb_ = 'GET';\n this.xmlHttp_.send(this.requestUri_, this.verb_, null, headers);\n }\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_MADE);\n this.channelDebug_.xmlHttpChannelRequest(\n this.verb_, this.requestUri_, this.rid_, this.retryId_, this.postData_);\n};\n\n\n/**\n * Handles a readystatechange event.\n * @param {goog.events.Event} evt The event.\n * @private\n */\nChannelRequest.prototype.readyStateChangeHandler_ = function(evt) {\n 'use strict';\n const xhr = /** @type {goog.net.XhrIo} */ (evt.target);\n const throttle = this.readyStateChangeThrottle_;\n if (throttle &&\n xhr.getReadyState() == goog.net.XmlHttp.ReadyState.INTERACTIVE) {\n // Only throttle in the partial data case.\n this.channelDebug_.debug('Throttling readystatechange.');\n throttle.fire();\n } else {\n // If we haven't throttled, just handle response directly.\n this.xmlHttpHandler_(xhr);\n }\n};\n\n\n/**\n * XmlHttp handler\n * @param {goog.net.XhrIo} xmlhttp The XhrIo object for the current request.\n * @private\n */\nChannelRequest.prototype.xmlHttpHandler_ = function(xmlhttp) {\n 'use strict';\n requestStats.onStartExecution();\n\n try {\n if (xmlhttp == this.xmlHttp_) {\n this.onXmlHttpReadyStateChanged_();\n } else {\n this.channelDebug_.warning(\n 'Called back with an ' +\n 'unexpected xmlhttp');\n }\n } catch (ex) {\n this.channelDebug_.debug('Failed call to OnXmlHttpReadyStateChanged_');\n if (this.hasResponseBody_()) {\n const channelRequest = this;\n this.channelDebug_.dumpException(ex, function() {\n 'use strict';\n return 'ResponseText: ' + channelRequest.xmlHttp_.getResponseText();\n });\n } else {\n this.channelDebug_.dumpException(ex, 'No response text');\n }\n } finally {\n requestStats.onEndExecution();\n }\n};\n\n\n/**\n * Called by the readystate handler for XMLHTTP requests.\n *\n * @private\n */\nChannelRequest.prototype.onXmlHttpReadyStateChanged_ = function() {\n 'use strict';\n const readyState = this.xmlHttp_.getReadyState();\n const errorCode = this.xmlHttp_.getLastErrorCode();\n const statusCode = this.xmlHttp_.getStatus();\n\n // we get partial results in browsers that support ready state interactive.\n // We also make sure that getResponseText is not null in interactive mode\n // before we continue.\n if (readyState < goog.net.XmlHttp.ReadyState.INTERACTIVE ||\n (readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE &&\n !environment.isPollingRequired() && // otherwise, go on to startPolling\n !this.hasResponseBody_())) {\n return; // not yet ready\n }\n\n // Dispatch any appropriate network events.\n if (!this.cancelled_ && readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&\n errorCode != goog.net.ErrorCode.ABORT) {\n // Pretty conservative, these are the only known scenarios which we'd\n // consider indicative of a truly non-functional network connection.\n if (errorCode == goog.net.ErrorCode.TIMEOUT || statusCode <= 0) {\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_FAILED);\n } else {\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_SUCCEEDED);\n }\n }\n\n // got some data so cancel the watchdog timer\n this.cancelWatchDogTimer_();\n\n const status = this.xmlHttp_.getStatus();\n this.lastStatusCode_ = status;\n const responseText = this.decodeXmlHttpResponse_();\n\n if (!this.hasResponseBody_()) {\n const channelRequest = this;\n this.channelDebug_.debug(function() {\n 'use strict';\n return 'No response text for uri ' + channelRequest.requestUri_ +\n ' status ' + status;\n });\n }\n this.successful_ = (status == 200);\n\n this.channelDebug_.xmlHttpChannelResponseMetaData(\n /** @type {string} */ (this.verb_), this.requestUri_, this.rid_,\n this.retryId_, readyState, status);\n\n if (!this.successful_) {\n this.errorResponseHeaders_ = this.xmlHttp_.getResponseHeaders();\n if (status == 400 && responseText.indexOf('Unknown SID') > 0) {\n // the server error string will include 'Unknown SID' which indicates the\n // server doesn't know about the session (maybe it got restarted, maybe\n // the user got moved to another server, etc.,). Handlers can special\n // case this error\n this.lastError_ = ChannelRequest.Error.UNKNOWN_SESSION_ID;\n requestStats.notifyStatEvent(\n requestStats.Stat.REQUEST_UNKNOWN_SESSION_ID);\n this.channelDebug_.warning('XMLHTTP Unknown SID (' + this.rid_ + ')');\n } else {\n this.lastError_ = ChannelRequest.Error.STATUS;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_STATUS);\n this.channelDebug_.warning(\n 'XMLHTTP Bad status ' + status + ' (' + this.rid_ + ')');\n }\n this.cleanup_();\n this.dispatchFailure_();\n return;\n }\n\n if (this.shouldCheckInitialResponse_()) {\n const initialResponse = this.getInitialResponse_();\n if (initialResponse) {\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, initialResponse,\n 'Initial handshake response via ' +\n WebChannel.X_HTTP_INITIAL_RESPONSE);\n this.initialResponseDecoded_ = true;\n this.safeOnRequestData_(initialResponse);\n } else {\n this.successful_ = false;\n this.lastError_ = ChannelRequest.Error.UNKNOWN_SESSION_ID; // fail-fast\n requestStats.notifyStatEvent(\n requestStats.Stat.REQUEST_UNKNOWN_SESSION_ID);\n this.channelDebug_.warning(\n 'XMLHTTP Missing X_HTTP_INITIAL_RESPONSE' +\n ' (' + this.rid_ + ')');\n this.cleanup_();\n this.dispatchFailure_();\n return;\n }\n }\n\n if (this.decodeChunks_) {\n this.decodeNextChunks_(readyState, responseText);\n if (environment.isPollingRequired() && this.successful_ &&\n readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE) {\n this.startPolling_();\n }\n } else {\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, responseText, null);\n this.safeOnRequestData_(responseText);\n }\n\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\n this.cleanup_();\n }\n\n if (!this.successful_) {\n return;\n }\n\n if (!this.cancelled_) {\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\n this.channel_.onRequestComplete(this);\n } else {\n // The default is false, the result from this callback shouldn't carry\n // over to the next callback, otherwise the request looks successful if\n // the watchdog timer gets called\n this.successful_ = false;\n this.ensureWatchDogTimer_();\n }\n }\n};\n\n\n/**\n * Whether we need check the initial-response header that is sent during the\n * fast handshake.\n *\n * @return {boolean} true if the initial-response header is yet to be processed.\n * @private\n */\nChannelRequest.prototype.shouldCheckInitialResponse_ = function() {\n 'use strict';\n return this.decodeInitialResponse_ && !this.initialResponseDecoded_;\n};\n\n\n/**\n * Queries the initial response header that is sent during the handshake.\n *\n * @return {?string} The non-empty header value or null.\n * @private\n */\nChannelRequest.prototype.getInitialResponse_ = function() {\n 'use strict';\n if (this.xmlHttp_) {\n const value = this.xmlHttp_.getStreamingResponseHeader(\n WebChannel.X_HTTP_INITIAL_RESPONSE);\n if (value && !goog.string.isEmptyOrWhitespace(value)) {\n return value;\n }\n }\n\n return null;\n};\n\n\n/**\n * Check if the initial response header has been handled.\n *\n * @return {boolean} true if X_HTTP_INITIAL_RESPONSE has been handled.\n */\nChannelRequest.prototype.isInitialResponseDecoded = function() {\n 'use strict';\n return this.initialResponseDecoded_;\n};\n\n\n/**\n * Decodes X_HTTP_INITIAL_RESPONSE if present.\n */\nChannelRequest.prototype.setDecodeInitialResponse = function() {\n 'use strict';\n this.decodeInitialResponse_ = true;\n};\n\n\n\n/**\n * Decodes the responses from XhrIo object.\n * @returns {string} responseText\n * @private\n */\nChannelRequest.prototype.decodeXmlHttpResponse_ = function() {\n 'use strict';\n if (!this.useFetchStreamsForResponse_()) {\n return this.xmlHttp_.getResponseText();\n }\n const responseChunks =\n /** @type {!Array<!Uint8Array>} */ (this.xmlHttp_.getResponse());\n let responseText = '';\n const responseLength = responseChunks.length;\n const requestCompleted =\n this.xmlHttp_.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;\n if (!this.fetchResponseState_.textDecoder) {\n if (typeof TextDecoder === 'undefined') {\n this.channelDebug_.severe(\n 'TextDecoder is not supported by this browser.');\n this.cleanup_();\n this.dispatchFailure_();\n return '';\n }\n this.fetchResponseState_.textDecoder = new goog.global.TextDecoder();\n }\n for (let i = 0; i < responseLength; i++) {\n this.fetchResponseState_.responseArrivedForFetch = true;\n const isLastChunk = requestCompleted && i == responseLength - 1;\n responseText += this.fetchResponseState_.textDecoder.decode(\n responseChunks[i], {stream: isLastChunk});\n }\n responseChunks.splice(0, responseLength);\n this.fetchResponseState_.responseBuffer += responseText;\n this.xmlHttpChunkStart_ = 0;\n return this.fetchResponseState_.responseBuffer;\n};\n\n\n/**\n * Whether or not the response has response body.\n * @private\n * @returns {boolean}\n */\nChannelRequest.prototype.hasResponseBody_ = function() {\n 'use strict';\n if (!this.xmlHttp_) {\n return false;\n }\n if (this.fetchResponseState_.responseArrivedForFetch) {\n return true;\n }\n return !(!this.xmlHttp_.getResponseText() && !this.xmlHttp_.getResponse());\n};\n\n/**\n * Whether or not the response body is streamed.\n * @private\n * @returns {boolean}\n */\nChannelRequest.prototype.useFetchStreamsForResponse_ = function() {\n 'use strict';\n if (!this.xmlHttp_) {\n return false;\n }\n return (\n this.verb_ == 'GET' && this.type_ != ChannelRequest.Type_.CLOSE_REQUEST &&\n this.channel_.usesFetchStreams());\n};\n\n\n/**\n * Resets the response buffer if the saved chunk has been processed.\n * @private\n * @param {string|!Object|undefined} chunkText\n */\nChannelRequest.prototype.maybeResetBuffer_ = function(chunkText) {\n 'use strict';\n if (this.useFetchStreamsForResponse_() &&\n chunkText != ChannelRequest.INCOMPLETE_CHUNK_ &&\n chunkText != ChannelRequest.INVALID_CHUNK_) {\n this.fetchResponseState_.responseBuffer = '';\n this.xmlHttpChunkStart_ = 0;\n }\n};\n\n\n/**\n * Decodes the next set of available chunks in the response.\n * @param {number} readyState The value of readyState.\n * @param {string} responseText The value of responseText.\n * @private\n */\nChannelRequest.prototype.decodeNextChunks_ = function(\n readyState, responseText) {\n 'use strict';\n let decodeNextChunksSuccessful = true;\n\n let chunkText;\n while (!this.cancelled_ && this.xmlHttpChunkStart_ < responseText.length) {\n chunkText = this.getNextChunk_(responseText);\n if (chunkText == ChannelRequest.INCOMPLETE_CHUNK_) {\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\n // should have consumed entire response when the request is done\n this.lastError_ = ChannelRequest.Error.BAD_DATA;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_INCOMPLETE_DATA);\n decodeNextChunksSuccessful = false;\n }\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, null, '[Incomplete Response]');\n break;\n } else if (chunkText == ChannelRequest.INVALID_CHUNK_) {\n this.lastError_ = ChannelRequest.Error.BAD_DATA;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_DATA);\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, responseText, '[Invalid Chunk]');\n decodeNextChunksSuccessful = false;\n break;\n } else {\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, /** @type {string} */ (chunkText), null);\n this.safeOnRequestData_(/** @type {string} */ (chunkText));\n }\n }\n\n this.maybeResetBuffer_(chunkText);\n\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&\n responseText.length == 0 &&\n !this.fetchResponseState_.responseArrivedForFetch) {\n // also an error if we didn't get any response\n this.lastError_ = ChannelRequest.Error.NO_DATA;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_NO_DATA);\n decodeNextChunksSuccessful = false;\n }\n\n this.successful_ = this.successful_ && decodeNextChunksSuccessful;\n\n if (!decodeNextChunksSuccessful) {\n // malformed response - we make this trigger retry logic\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, responseText, '[Invalid Chunked Response]');\n this.cleanup_();\n this.dispatchFailure_();\n } else {\n if (responseText.length > 0 && !this.firstByteReceived_) {\n this.firstByteReceived_ = true;\n this.channel_.onFirstByteReceived(this, responseText);\n }\n }\n};\n\n\n/**\n * Polls the response for new data.\n * @private\n */\nChannelRequest.prototype.pollResponse_ = function() {\n 'use strict';\n if (!this.xmlHttp_) {\n return; // already closed\n }\n const readyState = this.xmlHttp_.getReadyState();\n const responseText = this.xmlHttp_.getResponseText();\n if (this.xmlHttpChunkStart_ < responseText.length) {\n this.cancelWatchDogTimer_();\n this.decodeNextChunks_(readyState, responseText);\n if (this.successful_ &&\n readyState != goog.net.XmlHttp.ReadyState.COMPLETE) {\n this.ensureWatchDogTimer_();\n }\n }\n};\n\n\n/**\n * Starts a polling interval for changes to responseText of the\n * XMLHttpRequest, for browsers that don't fire onreadystatechange\n * as data comes in incrementally. This timer is disabled in\n * cleanup_().\n * @private\n */\nChannelRequest.prototype.startPolling_ = function() {\n 'use strict';\n this.eventHandler_.listen(\n this.pollingTimer_, goog.Timer.TICK, this.pollResponse_);\n this.pollingTimer_.start();\n};\n\n\n/**\n * Returns the next chunk of a chunk-encoded response. This is not standard\n * HTTP chunked encoding because browsers don't expose the chunk boundaries to\n * the application through XMLHTTP. So we have an additional chunk encoding at\n * the application level that lets us tell where the beginning and end of\n * individual responses are so that we can only try to eval a complete JS array.\n *\n * The encoding is the size of the chunk encoded as a decimal string followed\n * by a newline followed by the data.\n *\n * @param {string} responseText The response text from the XMLHTTP response.\n * @return {string|!Object} The next chunk string or a sentinel object\n * indicating a special condition.\n * @private\n */\nChannelRequest.prototype.getNextChunk_ = function(responseText) {\n 'use strict';\n const sizeStartIndex = this.xmlHttpChunkStart_;\n const sizeEndIndex = responseText.indexOf('\\n', sizeStartIndex);\n if (sizeEndIndex == -1) {\n return ChannelRequest.INCOMPLETE_CHUNK_;\n }\n\n const sizeAsString = responseText.substring(sizeStartIndex, sizeEndIndex);\n const size = Number(sizeAsString);\n if (isNaN(size)) {\n return ChannelRequest.INVALID_CHUNK_;\n }\n\n const chunkStartIndex = sizeEndIndex + 1;\n if (chunkStartIndex + size > responseText.length) {\n return ChannelRequest.INCOMPLETE_CHUNK_;\n }\n\n const chunkText = responseText.slice(chunkStartIndex, chunkStartIndex + size);\n this.xmlHttpChunkStart_ = chunkStartIndex + size;\n return chunkText;\n};\n\n\n/**\n * Uses an IMG tag or navigator.sendBeacon to send an HTTP get to the server.\n *\n * This is only currently used to terminate the connection, as an IMG tag is\n * the most reliable way to send something to the server while the page\n * is getting torn down.\n *\n * Navigator.sendBeacon is available on Chrome and Firefox as a formal\n * solution to ensure delivery without blocking window close. See\n * https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon\n *\n * For Chrome Apps, sendBeacon is always necessary due to Content Security\n * Policy (CSP) violation of using an IMG tag.\n *\n * For react-native, we use xhr to send the actual close request, and assume\n * there is no page-close issue with react-native.\n *\n * @param {goog.Uri} uri The uri to send a request to.\n */\nChannelRequest.prototype.sendCloseRequest = function(uri) {\n 'use strict';\n this.type_ = ChannelRequest.Type_.CLOSE_REQUEST;\n this.baseUri_ = uri.clone().makeUnique();\n\n let requestSent = false;\n\n if (goog.global.navigator && goog.global.navigator.sendBeacon) {\n try {\n // empty string body to avoid 413 error on chrome < 41\n requestSent =\n goog.global.navigator.sendBeacon(this.baseUri_.toString(), '');\n } catch {\n // Intentionally left empty; sendBeacon might throw TypeError in certain\n // unexpected cases.\n }\n }\n\n if (!requestSent && goog.global.Image) {\n const eltImg = new Image();\n eltImg.src = this.baseUri_;\n requestSent = true;\n }\n\n if (!requestSent) {\n // no handler is set to match the sendBeacon/Image behavior\n this.xmlHttp_ = this.channel_.createXhrIo(null);\n this.xmlHttp_.send(this.baseUri_);\n }\n\n this.requestStartTime_ = Date.now();\n this.ensureWatchDogTimer_();\n};\n\n\n/**\n * Cancels the request no matter what the underlying transport is.\n */\nChannelRequest.prototype.cancel = function() {\n 'use strict';\n this.cancelled_ = true;\n this.cleanup_();\n};\n\n\n/**\n * Resets the timeout.\n *\n * @param {number=} opt_timeout The new timeout\n */\nChannelRequest.prototype.resetTimeout = function(opt_timeout) {\n 'use strict';\n if (opt_timeout) {\n this.setTimeout(opt_timeout);\n }\n // restart only if a timer is currently set\n if (this.watchDogTimerId_) {\n this.cancelWatchDogTimer_();\n this.ensureWatchDogTimer_();\n }\n};\n\n\n/**\n * Ensures that there is watchdog timeout which is used to ensure that\n * the connection completes in time.\n *\n * @private\n */\nChannelRequest.prototype.ensureWatchDogTimer_ = function() {\n 'use strict';\n this.watchDogTimeoutTime_ = Date.now() + this.timeout_;\n this.startWatchDogTimer_(this.timeout_);\n};\n\n\n/**\n * Starts the watchdog timer which is used to ensure that the connection\n * completes in time.\n * @param {number} time The number of milliseconds to wait.\n * @private\n */\nChannelRequest.prototype.startWatchDogTimer_ = function(time) {\n 'use strict';\n if (this.watchDogTimerId_ != null) {\n // assertion\n throw new Error('WatchDog timer not null');\n }\n this.watchDogTimerId_ =\n requestStats.setTimeout(goog.bind(this.onWatchDogTimeout_, this), time);\n};\n\n\n/**\n * Cancels the watchdog timer if it has been started.\n *\n * @private\n */\nChannelRequest.prototype.cancelWatchDogTimer_ = function() {\n 'use strict';\n if (this.watchDogTimerId_) {\n goog.global.clearTimeout(this.watchDogTimerId_);\n this.watchDogTimerId_ = null;\n }\n};\n\n\n/**\n * Called when the watchdog timer is triggered. It also handles a case where it\n * is called too early which we suspect may be happening sometimes\n * (not sure why)\n *\n * @private\n */\nChannelRequest.prototype.onWatchDogTimeout_ = function() {\n 'use strict';\n this.watchDogTimerId_ = null;\n const now = Date.now();\n goog.asserts.assert(\n this.watchDogTimeoutTime_, 'WatchDog timeout time missing?');\n if (now - this.watchDogTimeoutTime_ >= 0) {\n this.handleTimeout_();\n } else {\n // got called too early for some reason\n this.channelDebug_.warning('WatchDog timer called too early');\n this.startWatchDogTimer_(this.watchDogTimeoutTime_ - now);\n }\n};\n\n\n/**\n * Called when the request has actually timed out. Will cleanup and notify the\n * channel of the failure.\n *\n * @private\n */\nChannelRequest.prototype.handleTimeout_ = function() {\n 'use strict';\n if (this.successful_) {\n // Should never happen.\n this.channelDebug_.severe(\n 'Received watchdog timeout even though request loaded successfully');\n }\n\n this.channelDebug_.timeoutResponse(this.requestUri_);\n\n // IMG or SendBeacon requests never notice if they were successful,\n // and always 'time out'. This fact says nothing about reachability.\n if (this.type_ != ChannelRequest.Type_.CLOSE_REQUEST) {\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_FAILED);\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_TIMEOUT);\n }\n\n this.cleanup_();\n\n // Set error and dispatch failure.\n // This is called for CLOSE_REQUEST too to ensure channel_.onRequestComplete.\n this.lastError_ = ChannelRequest.Error.TIMEOUT;\n this.dispatchFailure_();\n};\n\n\n/**\n * Notifies the channel that this request failed.\n * @private\n */\nChannelRequest.prototype.dispatchFailure_ = function() {\n 'use strict';\n if (this.channel_.isClosed() || this.cancelled_) {\n return;\n }\n\n this.channel_.onRequestComplete(this);\n};\n\n\n/**\n * Cleans up the objects used to make the request. This function is\n * idempotent.\n *\n * @private\n */\nChannelRequest.prototype.cleanup_ = function() {\n 'use strict';\n this.cancelWatchDogTimer_();\n\n goog.dispose(this.readyStateChangeThrottle_);\n this.readyStateChangeThrottle_ = null;\n\n // Stop the polling timer, if necessary.\n this.pollingTimer_.stop();\n\n // Unhook all event handlers.\n this.eventHandler_.removeAll();\n\n if (this.xmlHttp_) {\n // clear out this.xmlHttp_ before aborting so we handle getting reentered\n // inside abort\n const xmlhttp = this.xmlHttp_;\n this.xmlHttp_ = null;\n xmlhttp.abort();\n xmlhttp.dispose();\n }\n};\n\n\n/**\n * Indicates whether the request was successful. Only valid after the handler\n * is called to indicate completion of the request.\n *\n * @return {boolean} True if the request succeeded.\n */\nChannelRequest.prototype.getSuccess = function() {\n 'use strict';\n return this.successful_;\n};\n\n\n/**\n * If the request was not successful, returns the reason.\n *\n * @return {?ChannelRequest.Error} The last error.\n */\nChannelRequest.prototype.getLastError = function() {\n 'use strict';\n return this.lastError_;\n};\n\n\n/**\n * @return {!Object<string, string>|undefined} Response headers received\n * along with the non-200 status, as a key-value map.\n */\nChannelRequest.prototype.getErrorResponseHeaders = function() {\n 'use strict';\n return this.errorResponseHeaders_;\n};\n\n\n/**\n * Returns the status code of the last request.\n *\n * @return {number} The status code of the last request.\n */\nChannelRequest.prototype.getLastStatusCode = function() {\n 'use strict';\n return this.lastStatusCode_;\n};\n\n\n/**\n * Returns the session id for this channel.\n *\n * @return {string|undefined} The session ID.\n */\nChannelRequest.prototype.getSessionId = function() {\n 'use strict';\n return this.sid_;\n};\n\n\n/**\n * Returns the request id for this request. Each request has a unique request\n * id and the request IDs are a sequential increasing count.\n *\n * @return {string|number|undefined} The request ID.\n */\nChannelRequest.prototype.getRequestId = function() {\n 'use strict';\n return this.rid_;\n};\n\n\n/**\n * Returns the data for a post, if this request is a post.\n *\n * @return {?string} The POST data provided by the request initiator.\n */\nChannelRequest.prototype.getPostData = function() {\n 'use strict';\n return this.postData_;\n};\n\n\n/**\n * Returns the XhrIo request object.\n *\n * @return {?goog.net.XhrIo} Any XhrIo request created for this object.\n */\nChannelRequest.prototype.getXhr = function() {\n 'use strict';\n return this.xmlHttp_;\n};\n\n\n/**\n * Returns the time that the request started, if it has started.\n *\n * @return {?number} The time the request started, as returned by Date.now().\n */\nChannelRequest.prototype.getRequestStartTime = function() {\n 'use strict';\n return this.requestStartTime_;\n};\n\n\n/**\n * Helper to call the callback's onRequestData, which catches any\n * exception.\n * @param {string} data The request data.\n * @private\n */\nChannelRequest.prototype.safeOnRequestData_ = function(data) {\n 'use strict';\n try {\n this.channel_.onRequestData(this, data);\n const stats = requestStats.ServerReachability;\n requestStats.notifyServerReachabilityEvent(stats.BACK_CHANNEL_ACTIVITY);\n } catch (e) {\n // Dump debug info, but keep going without closing the channel.\n this.channelDebug_.dumpException(e, 'Error in httprequest callback');\n }\n};\n\n\n/**\n * Convenience factory method.\n *\n * @param {Channel} channel The channel object that owns this request.\n * @param {WebChannelDebug} channelDebug A WebChannelDebug to use for logging.\n * @param {string=} opt_sessionId The session id for the channel.\n * @param {string|number=} opt_requestId The request id for this request.\n * @param {number=} opt_retryId The retry id for this request.\n * @return {!ChannelRequest} The created channel request.\n */\nChannelRequest.createChannelRequest = function(\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {\n 'use strict';\n return new ChannelRequest(\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId);\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A single module to define user-agent specific environment\n * details.\n *\n */\n\ngoog.module('goog.labs.net.webChannel.environment');\n\ngoog.module.declareLegacyNamespace();\n\nvar userAgent = goog.require('goog.userAgent');\n\n\n/**\n * The default polling interval in millis for Edge.\n *\n * Currently on edge, new-chunk events may be not be fired (at all) if a new\n * chunk arrives within 50ms following the previous chunk. This may be fixed\n * in future, which requires changes to the whatwg spec too.\n *\n * @private @const {number}\n */\nvar EDGE_POLLING_INTERVAL_ = 125;\n\n\n/**\n * History:\n *\n * IE11 is still using Trident, the traditional engine for IE.\n * Edge is using EdgeHTML, a fork of Trident. We are seeing the same issue\n * on IE-11 (reported in 2017), so treat IE the same as Edge for now.\n *\n * We used to do polling for Opera (only) with an 250ms interval, because Opera\n * only fires readyState == INTERACTIVE once. Opera switched to WebKit in 2013,\n * and then to Blink (chrome).\n *\n * TODO(user): check the raw UA string to keep polling for old, mobile operas\n * that may still be affected. For old Opera, double the polling interval\n * to 250ms.\n *\n * @return {boolean} True if polling is required with XHR.\n */\nexports.isPollingRequired = function() {\n return userAgent.EDGE_OR_IE;\n};\n\n\n/**\n * How often to poll (in MS) for changes to responseText in browsers that don't\n * fire onreadystatechange during incremental loading of the response body.\n *\n * @return {number|undefined} The polling interval (MS) for the current U-A;\n * or undefined if polling is not supposed to be enabled.\n */\nexports.getPollingInterval = function() {\n if (userAgent.EDGE_OR_IE) {\n return EDGE_POLLING_INTERVAL_;\n }\n\n return undefined;\n};\n\n/**\n * Origin trial token for google.com\n *\n * https://developers.chrome.com/origintrials/#/trials\n *\n * http://googlechrome.github.io/OriginTrials/check-token.html\n * Origin: https://google.com:443\n * Matches Subdomains? Yes\n * Matches Third-party? Yes\n * Feature: FetchUploadStreaming\n * Up to Chrome 95 (ends with the rollout of next Chrome release), no later\n * than Nov 9, 2021\n *\n * Token for googleapis.com will be registered after google.com's is deployed.\n *\n */\nconst OT_TOKEN_GOOGLE_COM =\n 'A0eNbltY1nd4MP7XTHXnTxWogDL6mWTdgIIKfKOTJoUHNbFFMZQBoiHHjJ9UK9lgYndWFaxOWR7ld8uUjcWmcwIAAAB/eyJvcmlnaW4iOiJodHRwczovL2dvb2dsZS5jb206NDQzIiwiZmVhdHVyZSI6IkZldGNoVXBsb2FkU3RyZWFtaW5nIiwiZXhwaXJ5IjoxNjM2NTAyMzk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlfQ==';\n\n\n/**\n * Creates ReadableStream to upload\n * @return {!ReadableStream} ReadableStream to upload\n */\nfunction createStream() {\n const encoder = new goog.global.TextEncoder();\n return new goog.global.ReadableStream({\n start: controller => {\n for (const obj of ['test\\r\\n', 'test\\r\\n']) {\n controller.enqueue(encoder.encode(obj));\n }\n controller.close();\n }\n });\n}\n\n/**\n * Detect the user agent is chrome and its version is higher than M90.\n * This code is hard-coded from goog.labs.userAgent.browser to avoid file size\n * increasing.\n * @return {boolean} Whether the above is true.\n */\nfunction isChromeM90OrHigher() {\n const userAgentStr = function() {\n const navigator = goog.global.navigator;\n if (navigator) {\n const userAgent = navigator.userAgent;\n if (userAgent) {\n return userAgent;\n }\n }\n return '';\n }();\n\n const matchUserAgent = function(str) {\n return userAgentStr.indexOf(str) != -1;\n };\n\n if (!matchUserAgent('Chrome') || matchUserAgent('Edg')) {\n return false;\n }\n\n const match = /Chrome\\/(\\d+)/.exec(userAgentStr);\n const chromeVersion = parseInt(match[1], 10);\n return chromeVersion >= 90;\n}\n\n/**\n * Detect the URL origin is *.google.com.\n * @param {string} url The target URL.\n * @return {boolean} Whether the above is true.\n */\nfunction isUrlGoogle(url) {\n const match = /\\/\\/([^\\/]+)\\//.exec(url);\n if (!match) {\n return false;\n }\n const origin = match[1];\n return origin.endsWith('google.com');\n}\n\n/**\n * The flag to run the origin trials code only once.\n */\nlet isStartOriginTrialsCalled = false;\n\n/**\n * For Fetch/upload OT, make three requests against the server endpoint.\n * POST requests contain only dummy payload.\n *\n * https://developers.chrome.com/origintrials/#/view_trial/3524066708417413121\n *\n * This function is expected to be called from background during the handshake.\n * Exceptions will be logged by the caller.\n *\n * No stats or logs are collected on the client-side. To be disabled once the\n * OT is expired.\n *\n * @param {string} path The base URL path for the requests\n * @param {function(*)} logError A function to execute when exceptions are\n * caught.\n */\nexports.startOriginTrials = function(path, logError) {\n if (isStartOriginTrialsCalled) {\n return;\n }\n isStartOriginTrialsCalled = true;\n // NE: may need check if path has already contains query params?\n\n // Accept only Chrome M90 or later due to service worker support.\n if (!isChromeM90OrHigher()) {\n return;\n }\n\n // Accept only only google.com and subdoamins.\n if (!isUrlGoogle(path)) {\n return;\n }\n // Since 3P OT is not supported yet, we should check the current page matches\n // the path (absolute one?) to disable this OT for cross-origin calls\n if (!window || !window.document || !isUrlGoogle(window.document.URL)) {\n return;\n }\n\n // Enable origin trial by injecting OT <meta> tag\n const tokenElement =\n /** @type {! HTMLMetaElement} */ (document.createElement('meta'));\n tokenElement.httpEquiv = 'origin-trial';\n tokenElement.content = OT_TOKEN_GOOGLE_COM;\n // appendChild() synchronously enables OT.\n document.head.appendChild(tokenElement);\n\n // Check if fetch upload stream is actually enabled.\n // By the spec, Streaming request doesn't has the Content-Type header:\n // https://fetch.spec.whatwg.org/#concept-bodyinit-extract\n // If Chrome doesn't support Streaming, the body stream is converted to a\n // string \"[object ReadableStream]\" for fallback then it has \"Content-Type:\n // text/plain;charset=UTF-8\".\n const supportsRequestStreams = !new Request('', {\n body: new ReadableStream(),\n method: 'POST',\n }).headers.has('Content-Type');\n\n if (supportsRequestStreams) {\n logError('OriginTrial unexpected.');\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Base WebChannel implementation.\n */\n\n\ngoog.provide('goog.labs.net.webChannel.WebChannelBase');\n\ngoog.require('goog.Uri');\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.async.run');\ngoog.require('goog.collections.maps');\ngoog.require('goog.json');\ngoog.require('goog.labs.net.webChannel.Channel');\ngoog.require('goog.labs.net.webChannel.ChannelRequest');\ngoog.require('goog.labs.net.webChannel.ConnectionState');\ngoog.require('goog.labs.net.webChannel.ForwardChannelRequestPool');\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\ngoog.require('goog.labs.net.webChannel.Wire');\ngoog.require('goog.labs.net.webChannel.WireV8');\ngoog.require('goog.labs.net.webChannel.environment');\ngoog.require('goog.labs.net.webChannel.netUtils');\ngoog.require('goog.labs.net.webChannel.requestStats');\ngoog.require('goog.net.FetchXmlHttpFactory');\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.net.XhrIo');\ngoog.require('goog.net.XmlHttpFactory');\ngoog.require('goog.net.rpc.HttpCors');\ngoog.require('goog.object');\ngoog.require('goog.string');\ngoog.require('goog.structs');\n\ngoog.scope(function() {\n'use strict';\nconst WebChannel = goog.net.WebChannel;\nconst ChannelRequest = goog.labs.net.webChannel.ChannelRequest;\nconst ConnectionState = goog.labs.net.webChannel.ConnectionState;\nconst ForwardChannelRequestPool =\n goog.labs.net.webChannel.ForwardChannelRequestPool;\nconst WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\nconst Wire = goog.labs.net.webChannel.Wire;\nconst WireV8 = goog.labs.net.webChannel.WireV8;\nconst environment = goog.labs.net.webChannel.environment;\nconst netUtils = goog.labs.net.webChannel.netUtils;\nconst requestStats = goog.labs.net.webChannel.requestStats;\n\nconst httpCors = goog.module.get('goog.net.rpc.HttpCors');\n\n/**\n * @define {boolean} If WebChannel should compile with Origin Trial features.\n */\nconst ALLOW_ORIGIN_TRIAL_FEATURES =\n goog.define('goog.net.webChannel.ALLOW_ORIGIN_TRIAL_FEATURES', false);\n\n/**\n * Gets an internal channel parameter in a type-safe way.\n *\n * @param {string} paramName the key of the parameter to fetch.\n * @param {!T} defaultValue the default value to return\n * @param {!goog.net.WebChannel.Options=} options Configuration for the\n * WebChannel instance.\n * @return {T}\n * @template T\n */\nfunction getInternalChannelParam(paramName, defaultValue, options) {\n if (!options || !options.internalChannelParams) {\n return defaultValue;\n }\n return /** @type {T} */ (options.internalChannelParams[paramName]) ||\n defaultValue;\n}\n\n/**\n * This WebChannel implementation is branched off goog.net.BrowserChannel\n * for now. Ongoing changes to goog.net.BrowserChannel will be back\n * ported to this implementation as needed.\n *\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\n * WebChannel instance.\n * @param {number=} opt_clientVersion An application-specific version number\n * that is sent to the server when connected.\n * @param {!ConnectionState=} opt_conn Previously determined connection\n * conditions.\n * @constructor\n * @struct\n * @implements {goog.labs.net.webChannel.Channel}\n */\ngoog.labs.net.webChannel.WebChannelBase = function(\n opt_options, opt_clientVersion, opt_conn) {\n 'use strict';\n /**\n * The client library version (capabilities).\n * @private {number}\n */\n this.clientVersion_ = opt_clientVersion || 0;\n\n /**\n * The server library version (capabilities).\n * @private {number}\n */\n this.serverVersion_ = 0;\n\n\n /**\n * An array of queued maps that need to be sent to the server.\n * @private {!Array<Wire.QueuedMap>}\n */\n this.outgoingMaps_ = [];\n\n /**\n * The channel debug used for logging\n * @private {!WebChannelDebug}\n */\n this.channelDebug_ = new WebChannelDebug();\n\n /**\n * Connectivity state.\n * @private {!ConnectionState}\n */\n this.connState_ = opt_conn || new ConnectionState();\n\n /**\n * Extra HTTP headers to add to all the requests sent to the server.\n * @private {?Object}\n */\n this.extraHeaders_ = null;\n\n /**\n * Extra HTTP headers to add to the init request(s) sent to the server.\n * @private {?Object}\n */\n this.initHeaders_ = null;\n\n /**\n * @private {?string} The URL param name to overwrite custom HTTP headers\n * to bypass CORS preflight.\n */\n this.httpHeadersOverwriteParam_ = null;\n\n /**\n * Extra parameters to add to all the requests sent to the server.\n * @private {?Object}\n */\n this.extraParams_ = null;\n\n /**\n * Parameter name for the http session id.\n * @private {?string}\n */\n this.httpSessionIdParam_ = null;\n\n /**\n * The http session id, to be sent with httpSessionIdParam_ with each\n * request after the initial handshake.\n * @private {?string}\n */\n this.httpSessionId_ = null;\n\n /**\n * The ChannelRequest object for the backchannel.\n * @private {?ChannelRequest}\n */\n this.backChannelRequest_ = null;\n\n /**\n * The relative path (in the context of the page hosting the browser channel)\n * for making requests to the server.\n * @private {?string}\n */\n this.path_ = null;\n\n /**\n * The absolute URI for the forwardchannel request.\n * @private {?goog.Uri}\n */\n this.forwardChannelUri_ = null;\n\n /**\n * The absolute URI for the backchannel request.\n * @private {?goog.Uri}\n */\n this.backChannelUri_ = null;\n\n /**\n * A subdomain prefix for using a subdomain in IE for the backchannel\n * requests.\n * @private {?string}\n */\n this.hostPrefix_ = null;\n\n /**\n * Whether we allow the use of a subdomain in IE for the backchannel requests.\n * @private {boolean}\n */\n this.allowHostPrefix_ = true;\n\n /**\n * The next id to use for the RID (request identifier) parameter. This\n * identifier uniquely identifies the forward channel request.\n * @private {number}\n */\n this.nextRid_ = 0;\n\n /**\n * The id to use for the next outgoing map. This identifier uniquely\n * identifies a sent map.\n * @private {number}\n */\n this.nextMapId_ = 0;\n\n /**\n * Whether to fail forward-channel requests after one try or a few tries.\n * @private {boolean}\n */\n this.failFast_ = getInternalChannelParam('failFast', false, opt_options);\n\n /**\n * The handler that receive callbacks for state changes and data.\n * @private {?goog.labs.net.webChannel.WebChannelBase.Handler}\n */\n this.handler_ = null;\n\n /**\n * Timer identifier for asynchronously making a forward channel request.\n * This is set to true if the func is scheduled with async.run, which\n * is equivalent to setTimeout(0).\n * @private {?number|?boolean}\n */\n this.forwardChannelTimerId_ = null;\n\n /**\n * Timer identifier for asynchronously making a back channel request.\n * @private {?number}\n */\n this.backChannelTimerId_ = null;\n\n /**\n * Timer identifier for the timer that waits for us to retry the backchannel\n * in the case where it is dead and no longer receiving data.\n * @private {?number}\n */\n this.deadBackChannelTimerId_ = null;\n\n /**\n * Whether the client's network conditions can support streamed responses.\n * @private {?boolean}\n */\n this.enableStreaming_ = null;\n\n /**\n * Whether streaming mode is allowed. In certain debugging situations, it's\n * useful to disable this.\n * @private {boolean}\n */\n this.allowStreamingMode_ = true;\n\n /**\n * The array identifier of the last array received from the server for the\n * backchannel request.\n * @private {number}\n */\n this.lastArrayId_ = -1;\n\n /**\n * The array id of the last array sent by the server that we know about.\n * @private {number}\n */\n this.lastPostResponseArrayId_ = -1;\n\n /**\n * The non-200 status code received that causes the channel to be aborted.\n * @private {number}\n */\n this.errorResponseStatusCode_ = -1;\n\n /**\n * The response headers received along with the non-200 status.\n * @private {!Object<string, string>|undefined}\n */\n this.errorResponseHeaders_ = undefined;\n\n /**\n * Number of times we have retried the current forward channel request.\n * @private {number}\n */\n this.forwardChannelRetryCount_ = 0;\n\n /**\n * Number of times in a row that we have retried the current back channel\n * request and received no data.\n * @private {number}\n */\n this.backChannelRetryCount_ = 0;\n\n /**\n * The attempt id for the current back channel request. Starts at 1 and\n * increments for each reconnect. The server uses this to log if our\n * connection is flaky or not.\n * @private {number}\n */\n this.backChannelAttemptId_ = 0;\n\n /**\n * The base part of the time before firing next retry request. Default is 5\n * seconds. Note that a random delay is added (see {@link retryDelaySeedMs_})\n * for all retries, and linear backoff is applied to the sum for subsequent\n * retries.\n * @private {number}\n */\n this.baseRetryDelayMs_ =\n getInternalChannelParam('baseRetryDelayMs', 5 * 1000, opt_options);\n\n /**\n * A random time between 0 and this number of MS is added to the\n * {@link baseRetryDelayMs_}. Default is 10 seconds.\n * @private {number}\n */\n this.retryDelaySeedMs_ =\n getInternalChannelParam('retryDelaySeedMs', 10 * 1000, opt_options);\n\n /**\n * Maximum number of attempts to connect to the server for forward channel\n * requests. Defaults to 2.\n * @private {number}\n */\n this.forwardChannelMaxRetries_ =\n getInternalChannelParam('forwardChannelMaxRetries', 2, opt_options);\n\n /**\n * The timeout in milliseconds for a forward channel request. Defaults to 20\n * seconds. Note that part of this timeout can be randomized.\n * @private {number}\n */\n this.forwardChannelRequestTimeoutMs_ = getInternalChannelParam(\n 'forwardChannelRequestTimeoutMs', 20 * 1000, opt_options);\n\n /**\n * The custom factory used to create XMLHttpRequest objects.\n * @private {!goog.net.XmlHttpFactory | undefined}\n */\n this.xmlHttpFactory_ =\n (opt_options && opt_options.xmlHttpFactory) || undefined;\n\n /**\n * Whether or not this channel uses WHATWG Fetch/streams.\n * @private {boolean}\n */\n this.usesFetchStreams_ =\n (opt_options && opt_options.useFetchStreams) || false;\n\n /**\n * The timeout in milliseconds for a back channel request. Defaults to using\n * the timeout configured in ChannelRequest (45s). If server-side\n * keepaliveInterval is known to the client, set the backchannel request\n * timeout to 1.5 * keepaliveInterval (ms).\n *\n * @private {number|undefined}\n */\n this.backChannelRequestTimeoutMs_ = undefined;\n\n /**\n * A throttle time in ms for readystatechange events for the backchannel.\n * Useful for throttling when ready state is INTERACTIVE (partial data).\n *\n * This throttle is useful if the server sends large data chunks down the\n * backchannel. It prevents examining XHR partial data on every readystate\n * change event. This is useful because large chunks can trigger hundreds\n * of readystatechange events, each of which takes ~5ms or so to handle,\n * in turn making the UI unresponsive for a significant period.\n *\n * If set to zero no throttle is used.\n * @private {number}\n */\n this.readyStateChangeThrottleMs_ = 0;\n\n /**\n * Whether cross origin requests are supported for the channel.\n *\n * See {@link goog.net.XhrIo#setWithCredentials}.\n * @private {boolean}\n */\n this.supportsCrossDomainXhrs_ =\n (opt_options && opt_options.supportsCrossDomainXhr) || false;\n\n /**\n * The current session id.\n * @private {string}\n */\n this.sid_ = '';\n\n /**\n * The current ChannelRequest pool for the forward channel.\n * @private {!ForwardChannelRequestPool}\n */\n this.forwardChannelRequestPool_ = new ForwardChannelRequestPool(\n opt_options && opt_options.concurrentRequestLimit);\n\n /**\n * The V8 codec.\n * @private {!WireV8}\n */\n this.wireCodec_ = new WireV8();\n\n /**\n * Whether to turn on the fast handshake behavior.\n *\n * @private {boolean}\n */\n this.fastHandshake_ = (opt_options && opt_options.fastHandshake) || false;\n\n /**\n * Whether to encode initMessageHeaders in the body.\n *\n * @private {boolean}\n */\n this.encodeInitMessageHeaders_ =\n (opt_options && opt_options.encodeInitMessageHeaders) || false;\n\n if (this.fastHandshake_ && this.encodeInitMessageHeaders_) {\n this.channelDebug_.warning(\n 'Ignore encodeInitMessageHeaders because fastHandshake is set.');\n this.encodeInitMessageHeaders_ = false;\n }\n\n /**\n * Whether to signal to the server to enable blocking handshake.\n *\n * @private {boolean}\n */\n this.blockingHandshake_ =\n (opt_options && opt_options.blockingHandshake) || false;\n\n\n if (opt_options && opt_options.disableRedact) {\n this.channelDebug_.disableRedact();\n }\n\n if (opt_options && opt_options.forceLongPolling) {\n this.allowStreamingMode_ = false;\n }\n\n /**\n * Whether to detect buffering proxies.\n *\n * fastHandshake + detectBufferingProxy are yet to be implemented.\n *\n * @private {boolean}\n */\n this.detectBufferingProxy_ =\n (!this.fastHandshake_ && this.allowStreamingMode_ && opt_options &&\n opt_options.detectBufferingProxy) ||\n false;\n\n /**\n * Long polling timeout interval for the server to complete the handing GET.\n *\n * @private {number|undefined}\n */\n this.longPollingTimeout_ = undefined;\n\n if (opt_options && opt_options.longPollingTimeout &&\n opt_options.longPollingTimeout > 0) {\n this.longPollingTimeout_ = opt_options.longPollingTimeout;\n }\n\n /**\n * Callback when all the pending client-sent messages have been flushed.\n *\n * @private {function()|undefined}\n */\n this.forwardChannelFlushedCallback_ = undefined;\n\n /**\n * TODO(user): move all backchannel states to its own class similar to\n * forwardchannelrequestpool.js and log more stats.\n *\n * The estimated handshake RTT (ms) as measured from when the handshake\n * request is sent and when the handshake response headers are received.\n * If the value is 0, the RTT is unknown.\n *\n * @private {number}\n */\n this.handshakeRttMs_ = 0;\n\n /**\n * If BP detection is done or still in progress.\n * Should only be checked when detectBufferingProxy is turned on.\n * @private {boolean}\n */\n this.bpDetectionDone_ = false;\n\n /**\n * The timer for detecting buffering proxy. This needs be reset with each\n * backchannel request. If this is not null, bpDetectionDone_ == false.\n * @private {?number}\n */\n this.bpDetectionTimerId_ = null;\n\n /***\n * Whether to attempt Chrome Origin Trials as part of the handshake.\n * @private @const {boolean}\n */\n this.enableOriginTrials_ = ALLOW_ORIGIN_TRIAL_FEATURES &&\n (!opt_options || opt_options.enableOriginTrials !== false);\n\n /**\n * The array of non-acked maps at the time of channel close. Refer to\n * `getNonAckedMessagesWithClosedChannel()` API for definitions of non-acked\n * messages.\n *\n * @private {?Array<!Wire.QueuedMap>}\n */\n this.nonAckedMapsAtChannelClose_ = null;\n};\n\nconst WebChannelBase = goog.labs.net.webChannel.WebChannelBase;\n\n\n/**\n * The channel version that we negotiated with the server for this session.\n * Starts out as the version we request, and then is changed to the negotiated\n * version after the initial open.\n * @private {number}\n */\nWebChannelBase.prototype.channelVersion_ = Wire.LATEST_CHANNEL_VERSION;\n\n\n/**\n * Enum type for the channel state machine.\n * @enum {number}\n */\nWebChannelBase.State = {\n /** The channel is closed. */\n CLOSED: 0,\n\n /** The channel has been initialized but hasn't yet initiated a connection. */\n INIT: 1,\n\n /** The channel is in the process of opening a connection to the server. */\n OPENING: 2,\n\n /** The channel is open. */\n OPENED: 3\n};\n\n\n/**\n * The current state of the WebChannel.\n * @private {!WebChannelBase.State}\n */\nWebChannelBase.prototype.state_ = WebChannelBase.State.INIT;\n\n\n/**\n * The timeout in milliseconds for a forward channel request.\n * @type {number}\n */\nWebChannelBase.FORWARD_CHANNEL_RETRY_TIMEOUT = 20 * 1000;\n\n\n/**\n * Maximum number of attempts to connect to the server for back channel\n * requests.\n * @type {number}\n */\nWebChannelBase.BACK_CHANNEL_MAX_RETRIES = 3;\n\n\n/**\n * A number in MS of how long we guess the maxmium amount of time a round trip\n * to the server should take. In the future this could be substituted with a\n * real measurement of the RTT.\n * @type {number}\n */\nWebChannelBase.RTT_ESTIMATE = 3 * 1000;\n\n\n/**\n * When retrying for an inactive channel, we will multiply the total delay by\n * this number.\n * @type {number}\n */\nWebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR = 2;\n\n\n/**\n * Enum type for identifying an error.\n * @enum {number}\n */\nWebChannelBase.Error = {\n /** Value that indicates no error has occurred. */\n OK: 0,\n\n /** An error due to a request failing. */\n REQUEST_FAILED: 2,\n\n /** An error due to the user being logged out. */\n LOGGED_OUT: 4,\n\n /** An error due to server response which contains no data. */\n NO_DATA: 5,\n\n /** An error due to a server response indicating an unknown session id */\n UNKNOWN_SESSION_ID: 6,\n\n /** An error due to a server response requesting to stop the channel. */\n STOP: 7,\n\n /** A general network error. */\n NETWORK: 8,\n\n /** An error due to bad data being returned from the server. */\n BAD_DATA: 10,\n\n /** An error due to a response that is not parsable. */\n BAD_RESPONSE: 11\n};\n\n\n/**\n * Internal enum type for the two channel types.\n * @enum {number}\n * @private\n */\nWebChannelBase.ChannelType_ = {\n FORWARD_CHANNEL: 1,\n\n BACK_CHANNEL: 2\n};\n\n\n/**\n * The maximum number of maps that can be sent in one POST. Should match\n * MAX_MAPS_PER_REQUEST on the server code.\n * @type {number}\n * @private\n */\nWebChannelBase.MAX_MAPS_PER_REQUEST_ = 1000;\n\n\n/**\n * The maximum number of utf-8 chars that can be sent in one GET to enable 0-RTT\n * handshake.\n *\n * @const @private {number}\n */\nWebChannelBase.MAX_CHARS_PER_GET_ = 4 * 1024;\n\n\n/**\n * A guess at a cutoff at which to no longer assume the backchannel is dead\n * when we are slow to receive data. Number in bytes.\n *\n * Assumption: The worst bandwidth we work on is 50 kilobits/sec\n * 50kbits/sec * (1 byte / 8 bits) * 6 sec dead backchannel timeout\n * @type {number}\n */\nWebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF = 37500;\n\n\n/**\n * @return {number} The server version or 0 if undefined\n */\nWebChannelBase.prototype.getServerVersion = function() {\n 'use strict';\n return this.serverVersion_;\n};\n\n\n/**\n * @return {!ForwardChannelRequestPool} The forward channel request pool.\n */\nWebChannelBase.prototype.getForwardChannelRequestPool = function() {\n 'use strict';\n return this.forwardChannelRequestPool_;\n};\n\n\n/**\n * @return {!Object} The codec object.\n */\nWebChannelBase.prototype.getWireCodec = function() {\n 'use strict';\n return this.wireCodec_;\n};\n\n\n/**\n * Returns the logger.\n *\n * @return {!WebChannelDebug} The channel debug object.\n */\nWebChannelBase.prototype.getChannelDebug = function() {\n 'use strict';\n return this.channelDebug_;\n};\n\n\n/**\n * Sets the logger.\n *\n * @param {!WebChannelDebug} channelDebug The channel debug object.\n */\nWebChannelBase.prototype.setChannelDebug = function(channelDebug) {\n 'use strict';\n this.channelDebug_ = channelDebug;\n};\n\n\n/**\n * Starts the channel. This initiates connections to the server.\n *\n * @param {string} channelPath The path for the channel connection.\n * @param {!Object=} opt_extraParams Extra parameter keys and values to add to\n * the requests.\n * @param {string=} opt_oldSessionId Session ID from a previous session.\n * @param {number=} opt_oldArrayId The last array ID from a previous session.\n */\nWebChannelBase.prototype.connect = function(\n channelPath, opt_extraParams, opt_oldSessionId, opt_oldArrayId) {\n 'use strict';\n this.channelDebug_.debug('connect()');\n\n this.startOriginTrials_(channelPath);\n\n requestStats.notifyStatEvent(requestStats.Stat.CONNECT_ATTEMPT);\n\n this.path_ = channelPath;\n this.extraParams_ = opt_extraParams || {};\n\n // Attach parameters about the previous session if reconnecting.\n if (opt_oldSessionId && opt_oldArrayId !== undefined) {\n this.extraParams_['OSID'] = opt_oldSessionId;\n this.extraParams_['OAID'] = opt_oldArrayId;\n }\n\n this.enableStreaming_ = this.allowStreamingMode_;\n this.connectChannel_();\n};\n\n\n/**\n * Disconnects and closes the channel.\n */\nWebChannelBase.prototype.disconnect = function() {\n 'use strict';\n this.channelDebug_.debug('disconnect()');\n\n this.cancelRequests_();\n\n if (this.state_ == WebChannelBase.State.OPENED) {\n const rid = this.nextRid_++;\n const uri = this.forwardChannelUri_.clone();\n uri.setParameterValue('SID', this.sid_);\n uri.setParameterValue('RID', rid);\n uri.setParameterValue('TYPE', 'terminate');\n\n this.addAdditionalParams_(uri);\n\n const request = ChannelRequest.createChannelRequest(\n this, this.channelDebug_, this.sid_, rid);\n request.sendCloseRequest(uri);\n }\n\n this.onClose_();\n};\n\n\n/**\n * Returns the session id of the channel. Only available after the\n * channel has been opened.\n * @return {string} Session ID.\n */\nWebChannelBase.prototype.getSessionId = function() {\n 'use strict';\n return this.sid_;\n};\n\n\n/**\n * Starts the connection.\n * @private\n */\nWebChannelBase.prototype.connectChannel_ = function() {\n 'use strict';\n this.channelDebug_.debug('connectChannel_()');\n this.ensureInState_(WebChannelBase.State.INIT, WebChannelBase.State.CLOSED);\n this.forwardChannelUri_ =\n this.getForwardChannelUri(/** @type {string} */ (this.path_));\n this.ensureForwardChannel_();\n};\n\n\n/**\n * Starts the Origin Trials.\n * @param {string} channelPath The path for the channel connection.\n * @private\n */\nWebChannelBase.prototype.startOriginTrials_ = function(channelPath) {\n 'use strict';\n\n if (!this.enableOriginTrials_) {\n return;\n }\n\n this.channelDebug_.info('Origin Trials enabled.');\n goog.async.run(goog.bind(this.runOriginTrials_, this, channelPath));\n};\n\n\n/**\n * Runs the Origin Trials.\n * @param {string} channelPath The path for the channel connection.\n * @private\n */\nWebChannelBase.prototype.runOriginTrials_ = function(channelPath) {\n 'use strict';\n\n try {\n // Since startOriginTrials might throw exceptions asynchronously, we should\n // capture it in promise-catch.\n environment.startOriginTrials(channelPath, e => {\n this.channelDebug_.dumpException(\n /** @type {?Error} */ (e), 'Error in running origin trials');\n });\n this.channelDebug_.info('Origin Trials invoked: ' + channelPath);\n } catch (e) {\n this.channelDebug_.dumpException(e, 'Error in running origin trials');\n }\n};\n\n\n/**\n * Cancels backchannel request.\n * @private\n */\nWebChannelBase.prototype.cancelBackChannelRequest_ = function() {\n 'use strict';\n if (this.backChannelRequest_) {\n this.clearBpDetectionTimer_();\n this.backChannelRequest_.cancel();\n this.backChannelRequest_ = null;\n }\n};\n\n\n/**\n * Cancels all outstanding requests.\n * @private\n */\nWebChannelBase.prototype.cancelRequests_ = function() {\n 'use strict';\n this.cancelBackChannelRequest_();\n\n if (this.backChannelTimerId_) {\n goog.global.clearTimeout(this.backChannelTimerId_);\n this.backChannelTimerId_ = null;\n }\n\n this.clearDeadBackchannelTimer_();\n\n this.forwardChannelRequestPool_.cancel();\n\n if (this.forwardChannelTimerId_) {\n this.clearForwardChannelTimer_();\n }\n};\n\n\n/**\n * Clears the forward channel timer.\n * @private\n */\nWebChannelBase.prototype.clearForwardChannelTimer_ = function() {\n 'use strict';\n if (typeof this.forwardChannelTimerId_ === 'number') {\n goog.global.clearTimeout(this.forwardChannelTimerId_);\n }\n\n this.forwardChannelTimerId_ = null;\n};\n\n\n/**\n * Returns the extra HTTP headers to add to all the requests sent to the server.\n *\n * @return {Object} The HTTP headers, or null.\n */\nWebChannelBase.prototype.getExtraHeaders = function() {\n 'use strict';\n return this.extraHeaders_;\n};\n\n\n/**\n * Sets extra HTTP headers to add to all the requests sent to the server.\n *\n * @param {Object} extraHeaders The HTTP headers, or null.\n */\nWebChannelBase.prototype.setExtraHeaders = function(extraHeaders) {\n 'use strict';\n this.extraHeaders_ = extraHeaders;\n};\n\n\n/**\n * Returns the extra HTTP headers to add to the init requests\n * sent to the server.\n *\n * @return {Object} The HTTP headers, or null.\n */\nWebChannelBase.prototype.getInitHeaders = function() {\n 'use strict';\n return this.initHeaders_;\n};\n\n\n/**\n * Sets extra HTTP headers to add to the init requests sent to the server.\n *\n * @param {Object} initHeaders The HTTP headers, or null.\n */\nWebChannelBase.prototype.setInitHeaders = function(initHeaders) {\n 'use strict';\n this.initHeaders_ = initHeaders;\n};\n\n\n/**\n * Sets the URL param name to overwrite custom HTTP headers.\n *\n * @param {string} httpHeadersOverwriteParam The URL param name.\n */\nWebChannelBase.prototype.setHttpHeadersOverwriteParam = function(\n httpHeadersOverwriteParam) {\n 'use strict';\n this.httpHeadersOverwriteParam_ = httpHeadersOverwriteParam;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.setHttpSessionIdParam = function(httpSessionIdParam) {\n 'use strict';\n this.httpSessionIdParam_ = httpSessionIdParam;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getHttpSessionIdParam = function() {\n 'use strict';\n return this.httpSessionIdParam_;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.setHttpSessionId = function(httpSessionId) {\n 'use strict';\n this.httpSessionId_ = httpSessionId;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getHttpSessionId = function() {\n 'use strict';\n return this.httpSessionId_;\n};\n\n\n/**\n * Sets the throttle for handling onreadystatechange events for the request.\n *\n * @param {number} throttle The throttle in ms. A value of zero indicates\n * no throttle.\n */\nWebChannelBase.prototype.setReadyStateChangeThrottle = function(throttle) {\n 'use strict';\n this.readyStateChangeThrottleMs_ = throttle;\n};\n\n\n/**\n * Sets whether cross origin requests are supported for the channel.\n *\n * Setting this allows the creation of requests to secondary domains and\n * sends XHRs with the CORS withCredentials bit set to true.\n *\n * In order for cross-origin requests to work, the server will also need to set\n * CORS response headers as per:\n * https://developer.mozilla.org/en-US/docs/HTTP_access_control\n *\n * See {@link goog.net.XhrIo#setWithCredentials}.\n * @param {boolean} supportCrossDomain Whether cross domain XHRs are supported.\n */\nWebChannelBase.prototype.setSupportsCrossDomainXhrs = function(\n supportCrossDomain) {\n 'use strict';\n this.supportsCrossDomainXhrs_ = supportCrossDomain;\n};\n\n\n/**\n * Returns the handler used for channel callback events.\n *\n * @return {WebChannelBase.Handler} The handler.\n */\nWebChannelBase.prototype.getHandler = function() {\n 'use strict';\n return this.handler_;\n};\n\n\n/**\n * Sets the handler used for channel callback events.\n * @param {WebChannelBase.Handler} handler The handler to set.\n */\nWebChannelBase.prototype.setHandler = function(handler) {\n 'use strict';\n this.handler_ = handler;\n};\n\n\n/**\n * Returns whether the channel allows the use of a subdomain. There may be\n * cases where this isn't allowed.\n * @return {boolean} Whether a host prefix is allowed.\n */\nWebChannelBase.prototype.getAllowHostPrefix = function() {\n 'use strict';\n return this.allowHostPrefix_;\n};\n\n\n/**\n * Sets whether the channel allows the use of a subdomain. There may be cases\n * where this isn't allowed, for example, logging in with troutboard where\n * using a subdomain causes Apache to force the user to authenticate twice.\n * @param {boolean} allowHostPrefix Whether a host prefix is allowed.\n */\nWebChannelBase.prototype.setAllowHostPrefix = function(allowHostPrefix) {\n 'use strict';\n this.allowHostPrefix_ = allowHostPrefix;\n};\n\n\n/**\n * Returns whether the channel is buffered or not. This may be\n * queried in the WebChannelBase.okToMakeRequest() callback.\n *\n * @return {boolean} Whether the channel is buffered.\n */\nWebChannelBase.prototype.isBuffered = function() {\n 'use strict';\n return !this.enableStreaming_;\n};\n\n\n/**\n * Returns whether streaming mode is allowed. In certain debugging situations,\n * it's useful for the application to have a way to disable streaming mode for a\n * user.\n\n * @return {boolean} Whether streaming mode is allowed.\n */\nWebChannelBase.prototype.getAllowStreamingMode = function() {\n 'use strict';\n return this.allowStreamingMode_;\n};\n\n\n/**\n * Sets whether streaming mode is allowed. In certain debugging situations, it's\n * useful for the application to have a way to disable streaming mode for a\n * user.\n * @param {boolean} allowStreamingMode Whether streaming mode is allowed.\n */\nWebChannelBase.prototype.setAllowStreamingMode = function(allowStreamingMode) {\n 'use strict';\n this.allowStreamingMode_ = allowStreamingMode;\n};\n\n\n/**\n * Sends a request to the server. The format of the request is a Map data\n * structure of key/value pairs. These maps are then encoded in a format\n * suitable for the wire and then reconstituted as a Map data structure that\n * the server can process.\n * @param {!Object|!goog.collections.maps.MapLike} map The map to send.\n * @param {!Object=} opt_context The context associated with the map.\n */\nWebChannelBase.prototype.sendMap = function(map, opt_context) {\n 'use strict';\n goog.asserts.assert(\n this.state_ != WebChannelBase.State.CLOSED,\n 'Invalid operation: sending map when state is closed');\n\n // We can only send 1000 maps per POST, but typically we should never have\n // that much to send, so warn if we exceed that (we still send all the maps).\n if (this.outgoingMaps_.length == WebChannelBase.MAX_MAPS_PER_REQUEST_) {\n // severe() is temporary so that we get these uploaded and can figure out\n // what's causing them. Afterwards can change to warning().\n this.channelDebug_.severe(function() {\n 'use strict';\n return 'Already have ' + WebChannelBase.MAX_MAPS_PER_REQUEST_ +\n ' queued maps upon queueing ' + goog.json.serialize(map);\n });\n }\n\n this.outgoingMaps_.push(\n new Wire.QueuedMap(this.nextMapId_++, map, opt_context));\n\n // Messages need be buffered during OPENING to avoid server-side race\n if (this.state_ == WebChannelBase.State.OPENED) {\n this.ensureForwardChannel_();\n }\n};\n\n\n/**\n * When set to true, this changes the behavior of the forward channel so it\n * will not retry requests; it will fail after one network failure, and if\n * there was already one network failure, the request will fail immediately.\n * @param {boolean} failFast Whether or not to fail fast.\n */\nWebChannelBase.prototype.setFailFast = function(failFast) {\n 'use strict';\n this.failFast_ = failFast;\n this.channelDebug_.info('setFailFast: ' + failFast);\n if ((this.forwardChannelRequestPool_.hasPendingRequest() ||\n this.forwardChannelTimerId_) &&\n this.forwardChannelRetryCount_ > this.getForwardChannelMaxRetries()) {\n const self = this;\n this.channelDebug_.info(function() {\n 'use strict';\n return 'Retry count ' + self.forwardChannelRetryCount_ +\n ' > new maxRetries ' + self.getForwardChannelMaxRetries() +\n '. Fail immediately!';\n });\n\n if (!this.forwardChannelRequestPool_.forceComplete(\n goog.bind(this.onRequestComplete, this))) {\n // i.e., this.forwardChannelTimerId_\n this.clearForwardChannelTimer_();\n // The error code from the last failed request is gone, so just use a\n // generic one.\n this.signalError_(WebChannelBase.Error.REQUEST_FAILED);\n }\n }\n};\n\n\n/**\n * @return {number} The max number of forward-channel retries, which will be 0\n * in fail-fast mode.\n */\nWebChannelBase.prototype.getForwardChannelMaxRetries = function() {\n 'use strict';\n return this.failFast_ ? 0 : this.forwardChannelMaxRetries_;\n};\n\n\n/**\n * Sets the maximum number of attempts to connect to the server for forward\n * channel requests.\n * @param {number} retries The maximum number of attempts.\n */\nWebChannelBase.prototype.setForwardChannelMaxRetries = function(retries) {\n 'use strict';\n this.forwardChannelMaxRetries_ = retries;\n};\n\n\n/**\n * Sets the timeout for a forward channel request.\n * @param {number} timeoutMs The timeout in milliseconds.\n */\nWebChannelBase.prototype.setForwardChannelRequestTimeout = function(timeoutMs) {\n 'use strict';\n this.forwardChannelRequestTimeoutMs_ = timeoutMs;\n};\n\n\n/**\n * @return {number} The max number of back-channel retries, which is a constant.\n */\nWebChannelBase.prototype.getBackChannelMaxRetries = function() {\n 'use strict';\n // Back-channel retries is a constant.\n return WebChannelBase.BACK_CHANNEL_MAX_RETRIES;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.isClosed = function() {\n 'use strict';\n return this.state_ == WebChannelBase.State.CLOSED;\n};\n\n\n/**\n * Returns the channel state.\n * @return {WebChannelBase.State} The current state of the channel.\n */\nWebChannelBase.prototype.getState = function() {\n 'use strict';\n return this.state_;\n};\n\n\n/**\n * @return {!Object<string, string>|undefined} The response headers received\n * along with the non-200 status.\n */\nWebChannelBase.prototype.getLastResponseHeaders = function() {\n 'use strict';\n return this.errorResponseHeaders_;\n};\n\n\n/**\n * @return {number} The non-200 status code received that causes the channel to\n * be aborted.\n */\nWebChannelBase.prototype.getLastStatusCode = function() {\n 'use strict';\n return this.errorResponseStatusCode_;\n};\n\n\n/**\n * @return {number} The last array id received.\n */\nWebChannelBase.prototype.getLastArrayId = function() {\n 'use strict';\n return this.lastArrayId_;\n};\n\n\n/**\n * Returns whether there are outstanding requests servicing the channel.\n * @return {boolean} true if there are outstanding requests.\n */\nWebChannelBase.prototype.hasOutstandingRequests = function() {\n 'use strict';\n return this.getOutstandingRequests_() != 0;\n};\n\n\n/**\n * Returns the number of outstanding requests.\n * @return {number} The number of outstanding requests to the server.\n * @private\n */\nWebChannelBase.prototype.getOutstandingRequests_ = function() {\n 'use strict';\n let count = 0;\n if (this.backChannelRequest_) {\n count++;\n }\n count += this.forwardChannelRequestPool_.getRequestCount();\n return count;\n};\n\n\n/**\n * Ensures that a forward channel request is scheduled.\n * @private\n */\nWebChannelBase.prototype.ensureForwardChannel_ = function() {\n 'use strict';\n if (this.forwardChannelRequestPool_.isFull()) {\n // enough connection in process - no need to start a new request\n return;\n }\n\n if (this.forwardChannelTimerId_) {\n // no need to start a new request - one is already scheduled\n return;\n }\n\n // Use async.run instead of setTimeout(0) to avoid the 1s message delay\n // from chrome/firefox background tabs\n this.forwardChannelTimerId_ = true;\n goog.async.run(this.onStartForwardChannelTimer_, this);\n\n this.forwardChannelRetryCount_ = 0;\n};\n\n\n/**\n * Schedules a forward-channel retry for the specified request, unless the max\n * retries has been reached.\n * @param {!ChannelRequest} request The failed request to retry.\n * @return {boolean} true iff a retry was scheduled.\n * @private\n */\nWebChannelBase.prototype.maybeRetryForwardChannel_ = function(request) {\n 'use strict';\n if (this.forwardChannelRequestPool_.getRequestCount() >=\n this.forwardChannelRequestPool_.getMaxSize() -\n (this.forwardChannelTimerId_ ? 1 : 0)) {\n // Should be impossible to be called in this state.\n this.channelDebug_.severe('Unexpected retry request is scheduled.');\n return false;\n }\n\n if (this.forwardChannelTimerId_) {\n this.channelDebug_.debug(\n 'Use the retry request that is already scheduled.');\n this.outgoingMaps_ =\n request.getPendingMessages().concat(this.outgoingMaps_);\n return true;\n }\n\n // No retry for open_() and fail-fast\n if (this.state_ == WebChannelBase.State.INIT ||\n this.state_ == WebChannelBase.State.OPENING ||\n (this.forwardChannelRetryCount_ >= this.getForwardChannelMaxRetries())) {\n return false;\n }\n\n this.channelDebug_.debug('Going to retry POST');\n\n this.forwardChannelTimerId_ = requestStats.setTimeout(\n goog.bind(this.onStartForwardChannelTimer_, this, request),\n this.getRetryTime_(this.forwardChannelRetryCount_));\n this.forwardChannelRetryCount_++;\n return true;\n};\n\n\n/**\n * Timer callback for ensureForwardChannel\n * @param {ChannelRequest=} opt_retryRequest A failed request\n * to retry.\n * @private\n */\nWebChannelBase.prototype.onStartForwardChannelTimer_ = function(\n opt_retryRequest) {\n 'use strict';\n // null is possible if scheduled with async.run\n if (this.forwardChannelTimerId_) {\n this.forwardChannelTimerId_ = null;\n this.startForwardChannel_(opt_retryRequest);\n }\n};\n\n\n/**\n * Begins a new forward channel operation to the server.\n * @param {ChannelRequest=} opt_retryRequest A failed request to retry.\n * @private\n */\nWebChannelBase.prototype.startForwardChannel_ = function(opt_retryRequest) {\n 'use strict';\n this.channelDebug_.debug('startForwardChannel_');\n if (!this.okToMakeRequest_()) {\n return; // channel is cancelled\n } else if (this.state_ == WebChannelBase.State.INIT) {\n if (opt_retryRequest) {\n this.channelDebug_.severe('Not supposed to retry the open');\n return;\n }\n this.open_();\n this.state_ = WebChannelBase.State.OPENING;\n } else if (this.state_ == WebChannelBase.State.OPENED) {\n if (opt_retryRequest) {\n this.makeForwardChannelRequest_(opt_retryRequest);\n return;\n }\n\n if (this.outgoingMaps_.length == 0) {\n this.channelDebug_.debug(\n 'startForwardChannel_ returned: ' +\n 'nothing to send');\n // no need to start a new forward channel request\n return;\n }\n\n if (this.forwardChannelRequestPool_.isFull()) {\n // Should be impossible to be called in this state.\n this.channelDebug_.severe(\n 'startForwardChannel_ returned: ' +\n 'connection already in progress');\n return;\n }\n\n this.makeForwardChannelRequest_();\n this.channelDebug_.debug('startForwardChannel_ finished, sent request');\n }\n};\n\n\n/**\n * Establishes a new channel session with the server.\n * @private\n */\nWebChannelBase.prototype.open_ = function() {\n 'use strict';\n this.channelDebug_.debug('open_()');\n this.nextRid_ = Math.floor(Math.random() * 100000);\n\n const rid = this.nextRid_++;\n const request =\n ChannelRequest.createChannelRequest(this, this.channelDebug_, '', rid);\n\n // mix the init headers\n let extraHeaders = this.extraHeaders_;\n if (this.initHeaders_) {\n if (extraHeaders) {\n extraHeaders = goog.object.clone(extraHeaders);\n goog.object.extend(extraHeaders, this.initHeaders_);\n } else {\n extraHeaders = this.initHeaders_;\n }\n }\n\n if (this.httpHeadersOverwriteParam_ === null &&\n !this.encodeInitMessageHeaders_) {\n request.setExtraHeaders(extraHeaders);\n extraHeaders = null;\n }\n\n let requestText = this.dequeueOutgoingMaps_(\n request,\n this.fastHandshake_ ? this.getMaxNumMessagesForFastHandshake_() :\n WebChannelBase.MAX_MAPS_PER_REQUEST_);\n\n const uri = this.forwardChannelUri_.clone();\n uri.setParameterValue('RID', rid);\n\n if (this.clientVersion_ > 0) {\n uri.setParameterValue('CVER', this.clientVersion_);\n }\n\n // http-session-id to be generated as the response\n if (this.getHttpSessionIdParam()) {\n uri.setParameterValue(\n WebChannel.X_HTTP_SESSION_ID, this.getHttpSessionIdParam());\n }\n\n this.addAdditionalParams_(uri);\n\n if (extraHeaders) {\n if (this.encodeInitMessageHeaders_) {\n let encodedHeaders =\n httpCors.generateEncodedHttpHeadersOverwriteParam(extraHeaders);\n requestText = 'headers=' + encodedHeaders + '&' + requestText;\n } else if (this.httpHeadersOverwriteParam_) {\n httpCors.setHttpHeadersWithOverwriteParam(\n uri, this.httpHeadersOverwriteParam_, extraHeaders);\n } // else - should not happen\n }\n\n this.forwardChannelRequestPool_.addRequest(request);\n\n if (this.blockingHandshake_) {\n uri.setParameterValue('TYPE', 'init'); // default to blocking in future\n }\n\n // Check the option and use GET to enable QUIC 0-RTT\n if (this.fastHandshake_) {\n uri.setParameterValue('$req', requestText);\n\n // enable handshake upgrade\n uri.setParameterValue('SID', 'null');\n request.setDecodeInitialResponse();\n\n request.xmlHttpPost(uri, null, true); // Send as a GET\n } else {\n request.xmlHttpPost(uri, requestText, true);\n }\n};\n\n\n/**\n * @return {number} The number of raw JSON messages to be encoded\n * with the fast-handshake (GET) request, including zero. If messages are not\n * encoded as raw JSON data, return WebChannelBase.MAX_MAPS_PER_REQUEST_\n * @private\n */\nWebChannelBase.prototype.getMaxNumMessagesForFastHandshake_ = function() {\n 'use strict';\n let total = 0;\n for (let i = 0; i < this.outgoingMaps_.length; i++) {\n const map = this.outgoingMaps_[i];\n const size = map.getRawDataSize();\n if (size === undefined) {\n break;\n }\n total += size;\n\n if (total > WebChannelBase.MAX_CHARS_PER_GET_) {\n return i;\n }\n\n if (total === WebChannelBase.MAX_CHARS_PER_GET_ ||\n i === this.outgoingMaps_.length - 1) {\n return i + 1;\n }\n }\n\n return WebChannelBase.MAX_MAPS_PER_REQUEST_;\n};\n\n\n\n/**\n * Makes a forward channel request using XMLHTTP.\n * @param {!ChannelRequest=} opt_retryRequest A failed request to retry.\n * @private\n */\nWebChannelBase.prototype.makeForwardChannelRequest_ = function(\n opt_retryRequest) {\n 'use strict';\n let rid;\n if (opt_retryRequest) {\n rid = opt_retryRequest.getRequestId(); // Reuse the same RID for a retry\n } else {\n rid = this.nextRid_++;\n }\n\n const uri = this.forwardChannelUri_.clone();\n uri.setParameterValue('SID', this.sid_);\n uri.setParameterValue('RID', rid);\n uri.setParameterValue('AID', this.lastArrayId_);\n\n this.addAdditionalParams_(uri);\n\n if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {\n httpCors.setHttpHeadersWithOverwriteParam(\n uri, this.httpHeadersOverwriteParam_, this.extraHeaders_);\n }\n\n const request = ChannelRequest.createChannelRequest(\n this, this.channelDebug_, this.sid_, rid,\n this.forwardChannelRetryCount_ + 1);\n\n if (this.httpHeadersOverwriteParam_ === null) {\n request.setExtraHeaders(this.extraHeaders_);\n }\n\n let requestText;\n if (opt_retryRequest) {\n this.requeuePendingMaps_(opt_retryRequest);\n }\n requestText =\n this.dequeueOutgoingMaps_(request, WebChannelBase.MAX_MAPS_PER_REQUEST_);\n\n // Randomize from 50%-100% of the forward channel timeout to avoid\n // a big hit if servers happen to die at once.\n request.setTimeout(\n Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50) +\n Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50 * Math.random()));\n this.forwardChannelRequestPool_.addRequest(request);\n request.xmlHttpPost(uri, requestText, true);\n};\n\n\n/**\n * Adds additional query parameters from `extraParams_` and `handler_` to the\n * given URI.\n * @param {!goog.Uri} uri The URI to add the parameters to.\n * @private\n */\nWebChannelBase.prototype.addAdditionalParams_ = function(uri) {\n 'use strict';\n if (this.extraParams_) {\n goog.object.forEach(this.extraParams_, function(value, key) {\n 'use strict';\n uri.setParameterValue(key, value);\n });\n }\n\n if (this.handler_) {\n const params = this.handler_.getAdditionalParams(this);\n if (params) {\n goog.structs.forEach(params, function(value, key, coll) {\n 'use strict';\n uri.setParameterValue(key, value);\n });\n }\n }\n};\n\n\n/**\n * Returns the request text from the outgoing maps and resets it.\n * @param {!ChannelRequest} request The new request for sending the messages.\n * @param {number} maxNum The maximum number of messages to be encoded\n * @return {string} The encoded request text created from all the currently\n * queued outgoing maps.\n * @private\n */\nWebChannelBase.prototype.dequeueOutgoingMaps_ = function(request, maxNum) {\n 'use strict';\n const count = Math.min(this.outgoingMaps_.length, maxNum);\n\n const badMapHandler = this.handler_ ?\n goog.bind(this.handler_.badMapError, this.handler_, this) :\n null;\n const result = this.wireCodec_.encodeMessageQueue(\n this.outgoingMaps_, count, badMapHandler);\n\n request.setPendingMessages(this.outgoingMaps_.splice(0, count));\n\n return result;\n};\n\n\n/**\n * Requeues unacknowledged sent arrays for retransmission in the next forward\n * channel request.\n * @param {!ChannelRequest} retryRequest A failed request to retry.\n * @private\n */\nWebChannelBase.prototype.requeuePendingMaps_ = function(retryRequest) {\n 'use strict';\n this.outgoingMaps_ =\n retryRequest.getPendingMessages().concat(this.outgoingMaps_);\n};\n\n\n/**\n * Ensures there is a backchannel request for receiving data from the server.\n * @private\n */\nWebChannelBase.prototype.ensureBackChannel_ = function() {\n 'use strict';\n if (this.backChannelRequest_) {\n // already have one\n return;\n }\n\n if (this.backChannelTimerId_) {\n // no need to start a new request - one is already scheduled\n return;\n }\n\n this.backChannelAttemptId_ = 1;\n\n // Use async.run instead of setTimeout(0) to avoid the 1s message delay\n // from chrome/firefox background tabs\n // backChannelTimerId_ stays unset, as with setTimeout(0)\n goog.async.run(this.onStartBackChannelTimer_, this);\n\n this.backChannelRetryCount_ = 0;\n};\n\n\n/**\n * Schedules a back-channel retry, unless the max retries has been reached.\n * @return {boolean} true iff a retry was scheduled.\n * @private\n */\nWebChannelBase.prototype.maybeRetryBackChannel_ = function() {\n 'use strict';\n if (this.backChannelRequest_ || this.backChannelTimerId_) {\n // Should be impossible to be called in this state.\n this.channelDebug_.severe('Request already in progress');\n return false;\n }\n\n if (this.backChannelRetryCount_ >= this.getBackChannelMaxRetries()) {\n return false;\n }\n\n this.channelDebug_.debug('Going to retry GET');\n\n this.backChannelAttemptId_++;\n this.backChannelTimerId_ = requestStats.setTimeout(\n goog.bind(this.onStartBackChannelTimer_, this),\n this.getRetryTime_(this.backChannelRetryCount_));\n this.backChannelRetryCount_++;\n return true;\n};\n\n\n/**\n * Timer callback for ensureBackChannel_.\n * @private\n */\nWebChannelBase.prototype.onStartBackChannelTimer_ = function() {\n 'use strict';\n this.backChannelTimerId_ = null;\n this.startBackChannel_();\n\n if (!this.detectBufferingProxy_) {\n return;\n }\n\n if (this.bpDetectionDone_) {\n return;\n }\n\n if (this.backChannelRequest_ == null || this.handshakeRttMs_ <= 0) {\n this.channelDebug_.warning(\n 'Skip bpDetectionTimerId_ ' + this.backChannelRequest_ + ' ' +\n this.handshakeRttMs_);\n return;\n }\n\n // This goes with each new request until bpDetectionDone_\n const bpDetectionTimeout = 2 * this.handshakeRttMs_;\n this.channelDebug_.info('BP detection timer enabled: ' + bpDetectionTimeout);\n\n this.bpDetectionTimerId_ = requestStats.setTimeout(\n goog.bind(this.onBpDetectionTimer_, this), bpDetectionTimeout);\n};\n\n\n/**\n * Timer callback for bpDetection.\n * @private\n */\nWebChannelBase.prototype.onBpDetectionTimer_ = function() {\n 'use strict';\n if (!this.bpDetectionTimerId_) {\n this.channelDebug_.warning('Invalid operation.');\n return;\n }\n\n this.bpDetectionTimerId_ = null;\n this.channelDebug_.info('BP detection timeout reached.');\n\n goog.asserts.assert(\n this.backChannelRequest_ != null,\n 'Invalid state: no backchannel request');\n\n // We wait for extra response payload in addition to just headers to\n // cancel the timer.\n if (this.backChannelRequest_.getXhr() != null) {\n const responseData = this.backChannelRequest_.getXhr().getResponseText();\n if (responseData) {\n this.channelDebug_.warning(\n 'Timer should have been cancelled : ' + responseData);\n }\n }\n\n // Enable long-polling\n this.channelDebug_.info(\n 'Buffering proxy detected and switch to long-polling!');\n this.enableStreaming_ = false;\n\n this.bpDetectionDone_ = true;\n requestStats.notifyStatEvent(requestStats.Stat.PROXY);\n\n // Cancel the request and start a new one immediately\n this.cancelBackChannelRequest_();\n this.startBackChannel_();\n};\n\n\n/**\n * Clears the timer for BP detection.\n * @private\n */\nWebChannelBase.prototype.clearBpDetectionTimer_ = function() {\n 'use strict';\n if (this.bpDetectionTimerId_ != null) {\n this.channelDebug_.debug('Cancel the BP detection timer.');\n goog.global.clearTimeout(this.bpDetectionTimerId_);\n this.bpDetectionTimerId_ = null;\n }\n};\n\n\n/**\n * Begins a new back channel operation to the server.\n * @private\n */\nWebChannelBase.prototype.startBackChannel_ = function() {\n 'use strict';\n if (!this.okToMakeRequest_()) {\n // channel is cancelled\n return;\n }\n\n this.channelDebug_.debug('Creating new HttpRequest');\n this.backChannelRequest_ = ChannelRequest.createChannelRequest(\n this, this.channelDebug_, this.sid_, 'rpc', this.backChannelAttemptId_);\n\n if (this.httpHeadersOverwriteParam_ === null) {\n this.backChannelRequest_.setExtraHeaders(this.extraHeaders_);\n }\n\n this.backChannelRequest_.setReadyStateChangeThrottle(\n this.readyStateChangeThrottleMs_);\n const uri = this.backChannelUri_.clone();\n uri.setParameterValue('RID', 'rpc');\n uri.setParameterValue('SID', this.sid_);\n uri.setParameterValue('AID', this.lastArrayId_);\n\n uri.setParameterValue('CI', this.enableStreaming_ ? '0' : '1');\n if (!this.enableStreaming_ && this.longPollingTimeout_) {\n uri.setParameterValue('TO', this.longPollingTimeout_);\n }\n\n uri.setParameterValue('TYPE', 'xmlhttp');\n\n this.addAdditionalParams_(uri);\n\n if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {\n httpCors.setHttpHeadersWithOverwriteParam(\n uri, this.httpHeadersOverwriteParam_, this.extraHeaders_);\n }\n\n if (this.backChannelRequestTimeoutMs_) {\n this.backChannelRequest_.setTimeout(this.backChannelRequestTimeoutMs_);\n }\n\n this.backChannelRequest_.xmlHttpGet(\n uri, true /* decodeChunks */, this.hostPrefix_);\n\n this.channelDebug_.debug('New Request created');\n};\n\n\n/**\n * Gives the handler a chance to return an error code and stop channel\n * execution. A handler might want to do this to check that the user is still\n * logged in, for example.\n * @private\n * @return {boolean} If it's OK to make a request.\n */\nWebChannelBase.prototype.okToMakeRequest_ = function() {\n 'use strict';\n if (this.handler_) {\n const result = this.handler_.okToMakeRequest(this);\n if (result != WebChannelBase.Error.OK) {\n this.channelDebug_.debug(\n 'Handler returned error code from okToMakeRequest');\n this.signalError_(result);\n return false;\n }\n }\n return true;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.onFirstByteReceived = function(request, responseText) {\n 'use strict';\n if (this.backChannelRequest_ == request && this.detectBufferingProxy_) {\n if (!this.bpDetectionDone_) {\n this.channelDebug_.info(\n 'Great, no buffering proxy detected. Bytes received: ' +\n responseText.length);\n goog.asserts.assert(\n this.bpDetectionTimerId_, 'Timer should not have been cancelled.');\n this.clearBpDetectionTimer_();\n this.bpDetectionDone_ = true;\n requestStats.notifyStatEvent(requestStats.Stat.NOPROXY);\n }\n }\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.onRequestData = function(request, responseText) {\n 'use strict';\n if (this.state_ == WebChannelBase.State.CLOSED ||\n (this.backChannelRequest_ != request &&\n !this.forwardChannelRequestPool_.hasRequest(request))) {\n // either CLOSED or a request we don't know about (perhaps an old request)\n return;\n }\n\n // first to check if request has been upgraded to backchannel\n if (!request.isInitialResponseDecoded() &&\n this.forwardChannelRequestPool_.hasRequest(request) &&\n this.state_ == WebChannelBase.State.OPENED) {\n let response;\n try {\n response = this.wireCodec_.decodeMessage(responseText);\n } catch (ex) {\n response = null;\n }\n if (Array.isArray(response) && response.length == 3) {\n this.handlePostResponse_(/** @type {!Array<?>} */ (response), request);\n this.onForwardChannelFlushed_();\n } else {\n this.channelDebug_.debug('Bad POST response data returned');\n this.signalError_(WebChannelBase.Error.BAD_RESPONSE);\n }\n } else {\n if (request.isInitialResponseDecoded() ||\n this.backChannelRequest_ == request) {\n this.clearDeadBackchannelTimer_();\n }\n\n if (!goog.string.isEmptyOrWhitespace(responseText)) {\n let response = this.wireCodec_.decodeMessage(responseText);\n this.onInput_(/** @type {!Array<?>} */ (response), request);\n }\n }\n};\n\n\n/**\n * Checks if we need call the flush callback.\n *\n * @private\n */\nWebChannelBase.prototype.onForwardChannelFlushed_ = function() {\n 'use strict';\n if (this.forwardChannelRequestPool_.getRequestCount() <= 1) {\n if (this.forwardChannelFlushedCallback_) {\n try {\n this.forwardChannelFlushedCallback_();\n } catch (ex) {\n this.channelDebug_.dumpException(\n ex, 'Exception from forwardChannelFlushedCallback_ ');\n }\n // reset\n this.forwardChannelFlushedCallback_ = undefined;\n }\n }\n};\n\n\n/**\n * Handles a POST response from the server.\n * @param {Array<number>} responseValues The key value pairs in\n * the POST response.\n * @param {!ChannelRequest} forwardReq The forward channel request that\n * triggers this function call.\n * @private\n */\nWebChannelBase.prototype.handlePostResponse_ = function(\n responseValues, forwardReq) {\n 'use strict';\n // The first response value is set to 0 if server is missing backchannel.\n if (responseValues[0] == 0) {\n this.handleBackchannelMissing_(forwardReq);\n return;\n }\n this.lastPostResponseArrayId_ = responseValues[1];\n const outstandingArrays = this.lastPostResponseArrayId_ - this.lastArrayId_;\n if (0 < outstandingArrays) {\n const numOutstandingBackchannelBytes = responseValues[2];\n this.channelDebug_.debug(\n numOutstandingBackchannelBytes + ' bytes (in ' + outstandingArrays +\n ' arrays) are outstanding on the BackChannel');\n if (!this.shouldRetryBackChannel_(numOutstandingBackchannelBytes)) {\n return;\n }\n if (!this.deadBackChannelTimerId_) {\n // We expect to receive data within 2 RTTs or we retry the backchannel.\n this.deadBackChannelTimerId_ = requestStats.setTimeout(\n goog.bind(this.onBackChannelDead_, this),\n 2 * WebChannelBase.RTT_ESTIMATE);\n }\n }\n};\n\n\n/**\n * Handles a POST response from the server telling us that it has detected that\n * we have no hanging GET connection.\n * @param {!ChannelRequest} forwardReq The forward channel request that\n * triggers this function call.\n * @private\n * @suppress {strictPrimitiveOperators}\n */\nWebChannelBase.prototype.handleBackchannelMissing_ = function(forwardReq) {\n 'use strict';\n // As long as the back channel was started before the POST was sent,\n // we should retry the backchannel. We give a slight buffer of RTT_ESTIMATE\n // so as not to excessively retry the backchannel\n this.channelDebug_.debug('Server claims our backchannel is missing.');\n if (this.backChannelTimerId_) {\n this.channelDebug_.debug('But we are currently starting the request.');\n return;\n } else if (!this.backChannelRequest_) {\n this.channelDebug_.warning('We do not have a BackChannel established');\n } else if (\n this.backChannelRequest_.getRequestStartTime() +\n WebChannelBase.RTT_ESTIMATE <\n forwardReq.getRequestStartTime()) {\n this.clearDeadBackchannelTimer_();\n this.cancelBackChannelRequest_();\n } else {\n return;\n }\n this.maybeRetryBackChannel_();\n requestStats.notifyStatEvent(requestStats.Stat.BACKCHANNEL_MISSING);\n};\n\n\n/**\n * Determines whether we should start the process of retrying a possibly\n * dead backchannel.\n * @param {number} outstandingBytes The number of bytes for which the server has\n * not yet received acknowledgement.\n * @return {boolean} Whether to start the backchannel retry timer.\n * @private\n */\nWebChannelBase.prototype.shouldRetryBackChannel_ = function(outstandingBytes) {\n 'use strict';\n // Not too many outstanding bytes, not buffered and not after a retry.\n return outstandingBytes <\n WebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF &&\n !this.isBuffered() && this.backChannelRetryCount_ == 0;\n};\n\n\n/**\n * Decides which host prefix should be used, if any. If there is a handler,\n * allows the handler to validate a host prefix provided by the server, and\n * optionally override it.\n * @param {?string} serverHostPrefix The host prefix provided by the server.\n * @return {?string} The host prefix to actually use, if any. Will return null\n * if the use of host prefixes was disabled via setAllowHostPrefix().\n * @override\n */\nWebChannelBase.prototype.correctHostPrefix = function(serverHostPrefix) {\n 'use strict';\n if (this.allowHostPrefix_) {\n if (this.handler_) {\n return this.handler_.correctHostPrefix(serverHostPrefix);\n }\n return serverHostPrefix;\n }\n return null;\n};\n\n\n/**\n * Handles the timer that indicates that our backchannel is no longer able to\n * successfully receive data from the server.\n * @private\n */\nWebChannelBase.prototype.onBackChannelDead_ = function() {\n 'use strict';\n if (this.deadBackChannelTimerId_ != null) {\n this.deadBackChannelTimerId_ = null;\n this.cancelBackChannelRequest_();\n this.maybeRetryBackChannel_();\n requestStats.notifyStatEvent(requestStats.Stat.BACKCHANNEL_DEAD);\n }\n};\n\n\n/**\n * Clears the timer that indicates that our backchannel is no longer able to\n * successfully receive data from the server.\n * @private\n */\nWebChannelBase.prototype.clearDeadBackchannelTimer_ = function() {\n 'use strict';\n if (this.deadBackChannelTimerId_ != null) {\n goog.global.clearTimeout(this.deadBackChannelTimerId_);\n this.deadBackChannelTimerId_ = null;\n }\n};\n\n\n/**\n * Returns whether or not the given error/status combination is fatal or not.\n * On fatal errors we immediately close the session rather than retrying the\n * failed request.\n * @param {?ChannelRequest.Error} error The error code for the\n * failed request.\n * @param {number} statusCode The last HTTP status code.\n * @return {boolean} Whether or not the error is fatal.\n * @private\n */\nWebChannelBase.isFatalError_ = function(error, statusCode) {\n 'use strict';\n return error == ChannelRequest.Error.UNKNOWN_SESSION_ID ||\n (error == ChannelRequest.Error.STATUS && statusCode > 0);\n};\n\n\n/**\n * @override\n * @suppress {strictPrimitiveOperators}\n */\nWebChannelBase.prototype.onRequestComplete = function(request) {\n 'use strict';\n this.channelDebug_.debug('Request complete');\n let type;\n let pendingMessages = null;\n if (this.backChannelRequest_ == request) {\n this.clearDeadBackchannelTimer_();\n this.clearBpDetectionTimer_();\n this.backChannelRequest_ = null;\n type = WebChannelBase.ChannelType_.BACK_CHANNEL;\n } else if (this.forwardChannelRequestPool_.hasRequest(request)) {\n pendingMessages = request.getPendingMessages();\n this.forwardChannelRequestPool_.removeRequest(request);\n type = WebChannelBase.ChannelType_.FORWARD_CHANNEL;\n } else {\n // return if it was an old request from a previous session\n return;\n }\n\n if (this.state_ == WebChannelBase.State.CLOSED) {\n return;\n }\n\n if (request.getSuccess()) {\n if (type == WebChannelBase.ChannelType_.FORWARD_CHANNEL) {\n const size = request.getPostData() ? request.getPostData().length : 0;\n requestStats.notifyTimingEvent(\n size, Date.now() - request.getRequestStartTime(),\n this.forwardChannelRetryCount_);\n this.ensureForwardChannel_();\n this.onSuccess_(request);\n } else { // i.e., back-channel\n this.ensureBackChannel_();\n }\n return;\n }\n // Else unsuccessful. Fall through.\n\n const lastStatusCode = request.getLastStatusCode();\n const lastError = request.getLastError();\n if (!WebChannelBase.isFatalError_(lastError, lastStatusCode)) {\n // Maybe retry.\n const self = this;\n this.channelDebug_.debug(function() {\n 'use strict';\n return 'Maybe retrying, last error: ' +\n ChannelRequest.errorStringFromCode(\n lastError, self.errorResponseStatusCode_);\n });\n if (type == WebChannelBase.ChannelType_.FORWARD_CHANNEL) {\n if (this.maybeRetryForwardChannel_(request)) {\n return;\n }\n }\n if (type == WebChannelBase.ChannelType_.BACK_CHANNEL) {\n if (this.maybeRetryBackChannel_()) {\n return;\n }\n }\n // Else exceeded max retries. Fall through.\n this.channelDebug_.debug('Exceeded max number of retries');\n } else {\n // Else fatal error. Fall through and mark the pending maps as failed.\n this.channelDebug_.debug('Not retrying due to error type');\n\n if (lastStatusCode > 200) {\n this.errorResponseStatusCode_ = request.getLastStatusCode();\n this.errorResponseHeaders_ = request.getErrorResponseHeaders();\n }\n }\n\n // Abort the channel now\n\n // Record pending messages from the failed request\n if (pendingMessages && pendingMessages.length > 0) {\n this.forwardChannelRequestPool_.addPendingMessages(pendingMessages);\n }\n\n this.channelDebug_.debug('Error: HTTP request failed');\n switch (lastError) {\n case ChannelRequest.Error.NO_DATA:\n this.signalError_(WebChannelBase.Error.NO_DATA);\n break;\n case ChannelRequest.Error.BAD_DATA:\n this.signalError_(WebChannelBase.Error.BAD_DATA);\n break;\n case ChannelRequest.Error.UNKNOWN_SESSION_ID:\n this.signalError_(WebChannelBase.Error.UNKNOWN_SESSION_ID);\n break;\n default:\n this.signalError_(WebChannelBase.Error.REQUEST_FAILED);\n break;\n }\n};\n\n\n/**\n * @param {number} retryCount Number of retries so far.\n * @return {number} Time in ms before firing next retry request.\n * @private\n */\nWebChannelBase.prototype.getRetryTime_ = function(retryCount) {\n 'use strict';\n let retryTime = this.baseRetryDelayMs_ +\n Math.floor(Math.random() * this.retryDelaySeedMs_);\n if (!this.isActive()) {\n this.channelDebug_.debug('Inactive channel');\n retryTime = retryTime * WebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR;\n }\n // Backoff for subsequent retries\n retryTime *= retryCount;\n return retryTime;\n};\n\n\n/**\n * @param {number} baseDelayMs The base part of the retry delay, in ms.\n * @param {number} delaySeedMs A random delay between 0 and this is added to\n * the base part.\n */\nWebChannelBase.prototype.setRetryDelay = function(baseDelayMs, delaySeedMs) {\n 'use strict';\n this.baseRetryDelayMs_ = baseDelayMs;\n this.retryDelaySeedMs_ = delaySeedMs;\n};\n\n\n/**\n * Apply any handshake control headers.\n * @param {!ChannelRequest} request The underlying request object\n * @private\n */\nWebChannelBase.prototype.applyControlHeaders_ = function(request) {\n 'use strict';\n const xhr = request.getXhr();\n if (xhr) {\n const clientProtocol =\n xhr.getStreamingResponseHeader(WebChannel.X_CLIENT_WIRE_PROTOCOL);\n if (clientProtocol) {\n this.forwardChannelRequestPool_.applyClientProtocol(clientProtocol);\n }\n\n if (this.getHttpSessionIdParam()) {\n const httpSessionIdHeader =\n xhr.getStreamingResponseHeader(WebChannel.X_HTTP_SESSION_ID);\n if (httpSessionIdHeader) {\n this.setHttpSessionId(httpSessionIdHeader);\n // update the cached uri\n const httpSessionIdParam = this.getHttpSessionIdParam();\n\n this.forwardChannelUri_.setParameterValue(\n /** @type {string} */ (httpSessionIdParam), // never null\n httpSessionIdHeader);\n } else {\n this.channelDebug_.warning(\n 'Missing X_HTTP_SESSION_ID in the handshake response');\n }\n }\n }\n};\n\n\n/**\n * Processes the data returned by the server.\n * @param {!Array<!Array<?>>} respArray The response array returned\n * by the server.\n * @param {!ChannelRequest} request The underlying request object\n * @private\n * @suppress {strictPrimitiveOperators}\n */\nWebChannelBase.prototype.onInput_ = function(respArray, request) {\n 'use strict';\n const batch =\n this.handler_ && this.handler_.channelHandleMultipleArrays ? [] : null;\n for (let i = 0; i < respArray.length; i++) {\n let nextArray = respArray[i];\n this.lastArrayId_ = nextArray[0];\n nextArray = nextArray[1];\n if (this.state_ == WebChannelBase.State.OPENING) {\n if (nextArray[0] == 'c') {\n this.sid_ = nextArray[1];\n this.hostPrefix_ = this.correctHostPrefix(nextArray[2]);\n\n const negotiatedVersion = nextArray[3];\n if (negotiatedVersion != null) {\n this.channelVersion_ = negotiatedVersion;\n this.channelDebug_.info('VER=' + this.channelVersion_);\n }\n\n const negotiatedServerVersion = nextArray[4];\n if (negotiatedServerVersion != null) {\n this.serverVersion_ = negotiatedServerVersion;\n this.channelDebug_.info('SVER=' + this.serverVersion_);\n }\n\n // CVER=22\n const serverKeepaliveMs = nextArray[5];\n if (serverKeepaliveMs != null &&\n typeof serverKeepaliveMs === 'number' && serverKeepaliveMs > 0) {\n const timeout = 1.5 * serverKeepaliveMs;\n this.backChannelRequestTimeoutMs_ = timeout;\n this.channelDebug_.info('backChannelRequestTimeoutMs_=' + timeout);\n }\n\n this.applyControlHeaders_(request);\n\n this.state_ = WebChannelBase.State.OPENED;\n if (this.handler_) {\n this.handler_.channelOpened(this);\n }\n\n if (this.detectBufferingProxy_) {\n this.handshakeRttMs_ = Date.now() - request.getRequestStartTime();\n this.channelDebug_.info(\n 'Handshake RTT: ' + this.handshakeRttMs_ + 'ms');\n }\n\n this.startBackchannelAfterHandshake_(request);\n\n if (this.outgoingMaps_.length > 0) {\n this.ensureForwardChannel_();\n }\n } else if (nextArray[0] == 'stop' || nextArray[0] == 'close') {\n // treat close also as an abort\n this.signalError_(WebChannelBase.Error.STOP);\n }\n } else if (this.state_ == WebChannelBase.State.OPENED) {\n if (nextArray[0] == 'stop' || nextArray[0] == 'close') {\n if (batch && !(batch.length === 0)) {\n this.handler_.channelHandleMultipleArrays(this, batch);\n batch.length = 0;\n }\n if (nextArray[0] == 'stop') {\n this.signalError_(WebChannelBase.Error.STOP);\n } else {\n this.disconnect();\n }\n } else if (nextArray[0] == 'noop') {\n // ignore - noop to keep connection happy\n } else {\n if (batch) {\n batch.push(nextArray);\n } else if (this.handler_) {\n this.handler_.channelHandleArray(this, nextArray);\n }\n }\n // We have received useful data on the back-channel, so clear its retry\n // count. We do this because back-channels by design do not complete\n // quickly, so on a flaky connection we could have many fail to complete\n // fully but still deliver a lot of data before they fail. We don't want\n // to count such failures towards the retry limit, because we don't want\n // to give up on a session if we can still receive data.\n this.backChannelRetryCount_ = 0;\n }\n }\n if (batch && !(batch.length === 0)) {\n this.handler_.channelHandleMultipleArrays(this, batch);\n }\n};\n\n\n/**\n * Starts the backchannel after the handshake.\n *\n * @param {!ChannelRequest} request The underlying request object\n * @private\n */\nWebChannelBase.prototype.startBackchannelAfterHandshake_ = function(request) {\n 'use strict';\n this.backChannelUri_ = this.getBackChannelUri(\n this.hostPrefix_, /** @type {string} */ (this.path_));\n\n if (request.isInitialResponseDecoded()) {\n this.channelDebug_.debug('Upgrade the handshake request to a backchannel.');\n this.forwardChannelRequestPool_.removeRequest(request);\n request.resetTimeout(this.backChannelRequestTimeoutMs_);\n this.backChannelRequest_ = request;\n } else {\n this.ensureBackChannel_();\n }\n};\n\n\n/**\n * Helper to ensure the channel is in the expected state.\n * @param {...number} var_args The channel must be in one of the indicated\n * states.\n * @private\n */\nWebChannelBase.prototype.ensureInState_ = function(var_args) {\n 'use strict';\n goog.asserts.assert(\n goog.array.contains(arguments, this.state_),\n 'Unexpected channel state: %s', this.state_);\n};\n\n\n/**\n * Signals an error has occurred.\n * @param {WebChannelBase.Error} error The error code for the failure.\n * @private\n */\nWebChannelBase.prototype.signalError_ = function(error) {\n 'use strict';\n this.channelDebug_.info('Error code ' + error);\n if (error == WebChannelBase.Error.REQUEST_FAILED) {\n // Create a separate Internet connection to check\n // if it's a server error or user's network error.\n let imageUri = null;\n if (this.handler_) {\n imageUri = this.handler_.getNetworkTestImageUri(this);\n }\n netUtils.testNetwork(goog.bind(this.testNetworkCallback_, this), imageUri);\n } else {\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_OTHER);\n }\n this.onError_(error);\n};\n\n\n/**\n * Callback for netUtils.testNetwork during error handling.\n * @param {boolean} networkUp Whether the network is up.\n * @private\n */\nWebChannelBase.prototype.testNetworkCallback_ = function(networkUp) {\n 'use strict';\n if (networkUp) {\n this.channelDebug_.info('Successfully pinged google.com');\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_OTHER);\n } else {\n this.channelDebug_.info('Failed to ping google.com');\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_NETWORK);\n // Do not call onError_ again to eliminate duplicated Error events.\n }\n};\n\n\n/**\n * Called when messages have been successfully sent from the queue.\n * @param {!ChannelRequest} request The request object\n * @private\n */\nWebChannelBase.prototype.onSuccess_ = function(request) {\n 'use strict';\n if (this.handler_) {\n this.handler_.channelSuccess(this, request);\n }\n};\n\n\n/**\n * Called when we've determined the final error for a channel. It closes the\n * notifiers the handler of the error and closes the channel.\n * @param {WebChannelBase.Error} error The error code for the failure.\n * @private\n */\nWebChannelBase.prototype.onError_ = function(error) {\n 'use strict';\n this.channelDebug_.debug('HttpChannel: error - ' + error);\n this.state_ = WebChannelBase.State.CLOSED;\n if (this.handler_) {\n this.handler_.channelError(this, error);\n }\n this.onClose_();\n this.cancelRequests_();\n};\n\n\n/**\n * Called when the channel has been closed. It notifiers the handler of the\n * event, and reports any pending or undelivered maps.\n * @private\n */\nWebChannelBase.prototype.onClose_ = function() {\n 'use strict';\n this.state_ = WebChannelBase.State.CLOSED;\n this.nonAckedMapsAtChannelClose_ = [];\n if (this.handler_) {\n const pendingMessages =\n this.forwardChannelRequestPool_.getPendingMessages();\n\n if (pendingMessages.length == 0 && this.outgoingMaps_.length == 0) {\n this.handler_.channelClosed(this);\n } else {\n this.channelDebug_.debug(\n () => 'Number of undelivered maps' +\n ', pending: ' + pendingMessages.length +\n ', outgoing: ' + this.outgoingMaps_.length);\n\n goog.array.extend(this.nonAckedMapsAtChannelClose_, pendingMessages);\n goog.array.extend(this.nonAckedMapsAtChannelClose_, this.outgoingMaps_);\n\n this.forwardChannelRequestPool_.clearPendingMessages();\n\n const copyOfUndeliveredMaps = goog.array.clone(this.outgoingMaps_);\n this.outgoingMaps_.length = 0;\n\n this.handler_.channelClosed(this, pendingMessages, copyOfUndeliveredMaps);\n }\n }\n};\n\n/**\n * @return {!Array<!Wire.QueuedMap>} Returns the list of non-acked maps, both\n * during an active channel or after the channel is closed. Refer to the\n * `getNonAckedMessages()` API for definitions of non-acked messages.\n */\nWebChannelBase.prototype.getNonAckedMaps = function() {\n if (this.state_ == WebChannelBase.State.CLOSED) {\n goog.asserts.assert(\n this.nonAckedMapsAtChannelClose_ != null,\n 'nonAckedMapsAtChannelClose_ is not set after channel close.');\n return this.nonAckedMapsAtChannelClose_;\n }\n\n // The underlying message objects are not cloned and thus exposes a mutability\n // risk, but is chosen to make strict equality (i.e. ===) checks possible for\n // callers.\n let unAckedMaps = [];\n goog.array.extend(\n unAckedMaps, this.forwardChannelRequestPool_.getPendingMessages());\n goog.array.extend(unAckedMaps, this.outgoingMaps_);\n\n return unAckedMaps;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getForwardChannelUri = function(path) {\n 'use strict';\n const uri = this.createDataUri(null, path);\n this.channelDebug_.debug('GetForwardChannelUri: ' + uri);\n return uri;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getConnectionState = function() {\n 'use strict';\n return this.connState_;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getBackChannelUri = function(hostPrefix, path) {\n 'use strict';\n const uri = this.createDataUri(\n this.shouldUseSecondaryDomains() ? hostPrefix : null, path);\n this.channelDebug_.debug('GetBackChannelUri: ' + uri);\n return uri;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.createDataUri = function(\n hostPrefix, path, opt_overridePort) {\n 'use strict';\n let uri = goog.Uri.parse(path);\n const uriAbsolute = (uri.getDomain() != '');\n if (uriAbsolute) {\n if (hostPrefix) {\n uri.setDomain(hostPrefix + '.' + uri.getDomain());\n }\n\n uri.setPort(opt_overridePort || uri.getPort());\n } else {\n const locationPage = goog.global.location;\n let hostName;\n if (hostPrefix) {\n hostName = hostPrefix + '.' + locationPage.hostname;\n } else {\n hostName = locationPage.hostname;\n }\n\n const port = opt_overridePort || +locationPage.port;\n\n uri = goog.Uri.create(locationPage.protocol, null, hostName, port, path);\n }\n\n const param = this.getHttpSessionIdParam();\n const value = this.getHttpSessionId();\n if (param && value) {\n uri.setParameterValue(param, value);\n }\n\n // Add the protocol version to the URI.\n uri.setParameterValue('VER', this.channelVersion_);\n\n this.addAdditionalParams_(uri);\n\n return uri;\n};\n\n/**\n * @override\n * @param {?string} hostPrefix The host prefix, if we need an XhrIo object\n * capable of calling a secondary domain.\n * @param {boolean=} isStreaming Whether or not fetch/streams are enabled for\n * the underlying HTTP request.\n * @return {!goog.net.XhrIo} A new XhrIo object.\n */\nWebChannelBase.prototype.createXhrIo = function(hostPrefix, isStreaming) {\n 'use strict';\n if (hostPrefix && !this.supportsCrossDomainXhrs_) {\n throw new Error('Can\\'t create secondary domain capable XhrIo object.');\n }\n let xhr;\n if (isStreaming && this.usesFetchStreams_ && !this.xmlHttpFactory_) {\n xhr = new goog.net.XhrIo(\n new goog.net.FetchXmlHttpFactory({streamBinaryChunks: true}));\n } else {\n xhr = new goog.net.XhrIo(this.xmlHttpFactory_);\n }\n xhr.setWithCredentials(this.supportsCrossDomainXhrs_);\n return xhr;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.isActive = function() {\n 'use strict';\n return !!this.handler_ && this.handler_.isActive(this);\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.shouldUseSecondaryDomains = function() {\n 'use strict';\n return this.supportsCrossDomainXhrs_;\n};\n\n\n/**\n * Sets (overwrites) the forward channel flush callback.\n *\n * @param {function()} callback The callback to be invoked.\n */\nWebChannelBase.prototype.setForwardChannelFlushCallback = function(callback) {\n 'use strict';\n this.forwardChannelFlushedCallback_ = callback;\n};\n\n\n/**\n * Abstract base class for the channel handler\n * @constructor\n * @struct\n */\nWebChannelBase.Handler = function() {};\n\n\n/**\n * Callback handler for when a batch of response arrays is received from the\n * server. When null, batched dispatching is disabled.\n * @type {?function(!WebChannelBase, !Array<!Array<?>>)}\n */\nWebChannelBase.Handler.prototype.channelHandleMultipleArrays = null;\n\n\n/**\n * Whether it's okay to make a request to the server. A handler can return\n * false if the channel should fail. For example, if the user has logged out,\n * the handler may want all requests to fail immediately.\n * @param {WebChannelBase} channel The channel.\n * @return {WebChannelBase.Error} An error code. The code should\n * return WebChannelBase.Error.OK to indicate it's okay. Any other\n * error code will cause a failure.\n */\nWebChannelBase.Handler.prototype.okToMakeRequest = function(channel) {\n 'use strict';\n return WebChannelBase.Error.OK;\n};\n\n\n/**\n * Indicates the WebChannel has successfully negotiated with the server\n * and can now send and receive data.\n * @param {WebChannelBase} channel The channel.\n */\nWebChannelBase.Handler.prototype.channelOpened = function(channel) {};\n\n\n/**\n * New input is available for the application to process.\n *\n * @param {WebChannelBase} channel The channel.\n * @param {!Array<?>|!Object} array The data array.\n */\nWebChannelBase.Handler.prototype.channelHandleArray = function(\n channel, array) {};\n\n\n/**\n * Indicates messages that have been successfully sent on the channel.\n *\n * @param {WebChannelBase} channel The channel.\n * @param {!ChannelRequest} request The request object that contains\n * the pending messages that have been successfully delivered to the server.\n */\nWebChannelBase.Handler.prototype.channelSuccess = function(channel, request) {};\n\n\n/**\n * Indicates an error occurred on the WebChannel.\n *\n * @param {WebChannelBase} channel The channel.\n * @param {WebChannelBase.Error} error The error code.\n */\nWebChannelBase.Handler.prototype.channelError = function(channel, error) {};\n\n\n/**\n * Indicates the WebChannel is closed. Also notifies about which maps,\n * if any, that may not have been delivered to the server.\n * @param {WebChannelBase} channel The channel.\n * @param {Array<Wire.QueuedMap>=} opt_pendingMaps The\n * array of pending maps, which may or may not have been delivered to the\n * server.\n * @param {Array<Wire.QueuedMap>=} opt_undeliveredMaps\n * The array of undelivered maps, which have definitely not been delivered\n * to the server.\n */\nWebChannelBase.Handler.prototype.channelClosed = function(\n channel, opt_pendingMaps, opt_undeliveredMaps) {};\n\n\n/**\n * Gets any parameters that should be added at the time another connection is\n * made to the server.\n * @param {WebChannelBase} channel The channel.\n * @return {!Object} Extra parameter keys and values to add to the requests.\n */\nWebChannelBase.Handler.prototype.getAdditionalParams = function(channel) {\n 'use strict';\n return {};\n};\n\n\n/**\n * Gets the URI of an image that can be used to test network connectivity.\n * @param {WebChannelBase} channel The channel.\n * @return {goog.Uri?} A custom URI to load for the network test.\n */\nWebChannelBase.Handler.prototype.getNetworkTestImageUri = function(channel) {\n 'use strict';\n return null;\n};\n\n\n/**\n * Gets whether this channel is currently active. This is used to determine the\n * length of time to wait before retrying.\n * @param {WebChannelBase} channel The channel.\n * @return {boolean} Whether the channel is currently active.\n */\nWebChannelBase.Handler.prototype.isActive = function(channel) {\n 'use strict';\n return true;\n};\n\n/**\n * Whether or not this channel uses WHATWG Fetch/streams.\n * @override\n * @return {boolean}\n */\nWebChannelBase.prototype.usesFetchStreams = function() {\n 'use strict';\n return this.usesFetchStreams_;\n};\n\n\n/**\n * Called by the channel if enumeration of the map throws an exception.\n * @param {WebChannelBase} channel The channel.\n * @param {Object} map The map that can't be enumerated.\n */\nWebChannelBase.Handler.prototype.badMapError = function(channel, map) {};\n\n\n/**\n * Allows the handler to override a host prefix provided by the server. Will\n * be called whenever the channel has received such a prefix and is considering\n * its use.\n * @param {?string} serverHostPrefix The host prefix provided by the server.\n * @return {?string} The host prefix the client should use.\n */\nWebChannelBase.Handler.prototype.correctHostPrefix = function(\n serverHostPrefix) {\n 'use strict';\n return serverHostPrefix;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Class for parsing and formatting URIs.\n *\n * This package is deprecated in favour of the Closure URL package (goog.url)\n * when manipulating URIs for use by a browser. This package uses regular\n * expressions to parse a potential URI which can fall out of sync with how a\n * browser will actually interpret the URI. See\n * `goog.uri.utils.setUrlPackageSupportLoggingHandler` for one way to identify\n * URIs that should instead be parsed using the URL package.\n *\n * Use goog.Uri(string) to parse a URI string. Use goog.Uri.create(...) to\n * create a new instance of the goog.Uri object from Uri parts.\n *\n * e.g: <code>var myUri = new goog.Uri(window.location);</code>\n *\n * Implements RFC 3986 for parsing/formatting URIs.\n * http://www.ietf.org/rfc/rfc3986.txt\n *\n * Some changes have been made to the interface (more like .NETs), though the\n * internal representation is now of un-encoded parts, this will change the\n * behavior slightly.\n */\n\ngoog.provide('goog.Uri');\ngoog.provide('goog.Uri.QueryData');\n\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.string');\ngoog.require('goog.structs');\ngoog.require('goog.uri.utils');\ngoog.require('goog.uri.utils.ComponentIndex');\ngoog.require('goog.uri.utils.StandardQueryParam');\n\n\n\n/**\n * This class contains setters and getters for the parts of the URI.\n * The <code>getXyz</code>/<code>setXyz</code> methods return the decoded part\n * -- so<code>goog.Uri.parse('/foo%20bar').getPath()</code> will return the\n * decoded path, <code>/foo bar</code>.\n *\n * Reserved characters (see RFC 3986 section 2.2) can be present in\n * their percent-encoded form in scheme, domain, and path URI components and\n * will not be auto-decoded. For example:\n * <code>goog.Uri.parse('rel%61tive/path%2fto/resource').getPath()</code> will\n * return <code>relative/path%2fto/resource</code>.\n *\n * The constructor accepts an optional unparsed, raw URI string. The parser\n * is relaxed, so special characters that aren't escaped but don't cause\n * ambiguities will not cause parse failures.\n *\n * All setters return <code>this</code> and so may be chained, a la\n * <code>goog.Uri.parse('/foo').setFragment('part').toString()</code>.\n *\n * @param {*=} opt_uri Optional string URI to parse\n * (use goog.Uri.create() to create a URI from parts), or if\n * a goog.Uri is passed, a clone is created.\n * @param {boolean=} opt_ignoreCase If true, #getParameterValue will ignore\n * the case of the parameter name.\n *\n * @throws URIError If opt_uri is provided and URI is malformed (that is,\n * if decodeURIComponent fails on any of the URI components).\n * @constructor\n * @struct\n */\ngoog.Uri = function(opt_uri, opt_ignoreCase) {\n 'use strict';\n /**\n * Scheme such as \"http\".\n * @private {string}\n */\n this.scheme_ = '';\n\n /**\n * User credentials in the form \"username:password\".\n * @private {string}\n */\n this.userInfo_ = '';\n\n /**\n * Domain part, e.g. \"www.google.com\".\n * @private {string}\n */\n this.domain_ = '';\n\n /**\n * Port, e.g. 8080.\n * @private {?number}\n */\n this.port_ = null;\n\n /**\n * Path, e.g. \"/tests/img.png\".\n * @private {string}\n */\n this.path_ = '';\n\n /**\n * The fragment without the #.\n * @private {string}\n */\n this.fragment_ = '';\n\n /**\n * Whether or not this Uri should be treated as Read Only.\n * @private {boolean}\n */\n this.isReadOnly_ = false;\n\n /**\n * Whether or not to ignore case when comparing query params.\n * @private {boolean}\n */\n this.ignoreCase_ = false;\n\n /**\n * Object representing query data.\n * @private {!goog.Uri.QueryData}\n */\n this.queryData_;\n\n // Parse in the uri string\n var m;\n if (opt_uri instanceof goog.Uri) {\n this.ignoreCase_ = (opt_ignoreCase !== undefined) ? opt_ignoreCase :\n opt_uri.getIgnoreCase();\n this.setScheme(opt_uri.getScheme());\n this.setUserInfo(opt_uri.getUserInfo());\n this.setDomain(opt_uri.getDomain());\n this.setPort(opt_uri.getPort());\n this.setPath(opt_uri.getPath());\n this.setQueryData(opt_uri.getQueryData().clone());\n this.setFragment(opt_uri.getFragment());\n } else if (opt_uri && (m = goog.uri.utils.split(String(opt_uri)))) {\n this.ignoreCase_ = !!opt_ignoreCase;\n\n // Set the parts -- decoding as we do so.\n // COMPATIBILITY NOTE - In IE, unmatched fields may be empty strings,\n // whereas in other browsers they will be undefined.\n this.setScheme(m[goog.uri.utils.ComponentIndex.SCHEME] || '', true);\n this.setUserInfo(m[goog.uri.utils.ComponentIndex.USER_INFO] || '', true);\n this.setDomain(m[goog.uri.utils.ComponentIndex.DOMAIN] || '', true);\n this.setPort(m[goog.uri.utils.ComponentIndex.PORT]);\n this.setPath(m[goog.uri.utils.ComponentIndex.PATH] || '', true);\n this.setQueryData(m[goog.uri.utils.ComponentIndex.QUERY_DATA] || '', true);\n this.setFragment(m[goog.uri.utils.ComponentIndex.FRAGMENT] || '', true);\n\n } else {\n this.ignoreCase_ = !!opt_ignoreCase;\n this.queryData_ = new goog.Uri.QueryData(null, this.ignoreCase_);\n }\n};\n\n\n/**\n * Parameter name added to stop caching.\n * @type {string}\n */\ngoog.Uri.RANDOM_PARAM = goog.uri.utils.StandardQueryParam.RANDOM;\n\n\n/**\n * @return {string} The string form of the url.\n * @override\n */\ngoog.Uri.prototype.toString = function() {\n 'use strict';\n var out = [];\n\n var scheme = this.getScheme();\n if (scheme) {\n out.push(\n goog.Uri.encodeSpecialChars_(\n scheme, goog.Uri.reDisallowedInSchemeOrUserInfo_, true),\n ':');\n }\n\n var domain = this.getDomain();\n if (domain || scheme == 'file') {\n out.push('//');\n\n var userInfo = this.getUserInfo();\n if (userInfo) {\n out.push(\n goog.Uri.encodeSpecialChars_(\n userInfo, goog.Uri.reDisallowedInSchemeOrUserInfo_, true),\n '@');\n }\n\n out.push(goog.Uri.removeDoubleEncoding_(goog.string.urlEncode(domain)));\n\n var port = this.getPort();\n if (port != null) {\n out.push(':', String(port));\n }\n }\n\n var path = this.getPath();\n if (path) {\n if (this.hasDomain() && path.charAt(0) != '/') {\n out.push('/');\n }\n out.push(goog.Uri.encodeSpecialChars_(\n path,\n path.charAt(0) == '/' ? goog.Uri.reDisallowedInAbsolutePath_ :\n goog.Uri.reDisallowedInRelativePath_,\n true));\n }\n\n var query = this.getEncodedQuery();\n if (query) {\n out.push('?', query);\n }\n\n var fragment = this.getFragment();\n if (fragment) {\n out.push(\n '#',\n goog.Uri.encodeSpecialChars_(\n fragment, goog.Uri.reDisallowedInFragment_));\n }\n return out.join('');\n};\n\n\n/**\n * Resolves the given relative URI (a goog.Uri object), using the URI\n * represented by this instance as the base URI.\n *\n * There are several kinds of relative URIs:<br>\n * 1. foo - replaces the last part of the path, the whole query and fragment<br>\n * 2. /foo - replaces the path, the query and fragment<br>\n * 3. //foo - replaces everything from the domain on. foo is a domain name<br>\n * 4. ?foo - replace the query and fragment<br>\n * 5. #foo - replace the fragment only\n *\n * Additionally, if relative URI has a non-empty path, all \"..\" and \".\"\n * segments will be resolved, as described in RFC 3986.\n *\n * @param {!goog.Uri} relativeUri The relative URI to resolve.\n * @return {!goog.Uri} The resolved URI.\n */\ngoog.Uri.prototype.resolve = function(relativeUri) {\n 'use strict';\n var absoluteUri = this.clone();\n\n // we satisfy these conditions by looking for the first part of relativeUri\n // that is not blank and applying defaults to the rest\n\n var overridden = relativeUri.hasScheme();\n\n if (overridden) {\n absoluteUri.setScheme(relativeUri.getScheme());\n } else {\n overridden = relativeUri.hasUserInfo();\n }\n\n if (overridden) {\n absoluteUri.setUserInfo(relativeUri.getUserInfo());\n } else {\n overridden = relativeUri.hasDomain();\n }\n\n if (overridden) {\n absoluteUri.setDomain(relativeUri.getDomain());\n } else {\n overridden = relativeUri.hasPort();\n }\n\n var path = relativeUri.getPath();\n if (overridden) {\n absoluteUri.setPort(relativeUri.getPort());\n } else {\n overridden = relativeUri.hasPath();\n if (overridden) {\n // resolve path properly\n if (path.charAt(0) != '/') {\n // path is relative\n if (this.hasDomain() && !this.hasPath()) {\n // RFC 3986, section 5.2.3, case 1\n path = '/' + path;\n } else {\n // RFC 3986, section 5.2.3, case 2\n var lastSlashIndex = absoluteUri.getPath().lastIndexOf('/');\n if (lastSlashIndex != -1) {\n path = absoluteUri.getPath().slice(0, lastSlashIndex + 1) + path;\n }\n }\n }\n path = goog.Uri.removeDotSegments(path);\n }\n }\n\n if (overridden) {\n absoluteUri.setPath(path);\n } else {\n overridden = relativeUri.hasQuery();\n }\n\n if (overridden) {\n absoluteUri.setQueryData(relativeUri.getQueryData().clone());\n } else {\n overridden = relativeUri.hasFragment();\n }\n\n if (overridden) {\n absoluteUri.setFragment(relativeUri.getFragment());\n }\n\n return absoluteUri;\n};\n\n\n/**\n * Clones the URI instance.\n * @return {!goog.Uri} New instance of the URI object.\n */\ngoog.Uri.prototype.clone = function() {\n 'use strict';\n return new goog.Uri(this);\n};\n\n\n/**\n * @return {string} The encoded scheme/protocol for the URI.\n */\ngoog.Uri.prototype.getScheme = function() {\n 'use strict';\n return this.scheme_;\n};\n\n\n/**\n * Sets the scheme/protocol.\n * @throws URIError If opt_decode is true and newScheme is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newScheme New scheme value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setScheme = function(newScheme, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.scheme_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newScheme, true) : newScheme;\n\n // remove an : at the end of the scheme so somebody can pass in\n // window.location.protocol\n if (this.scheme_) {\n this.scheme_ = this.scheme_.replace(/:$/, '');\n }\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the scheme has been set.\n */\ngoog.Uri.prototype.hasScheme = function() {\n 'use strict';\n return !!this.scheme_;\n};\n\n\n/**\n * @return {string} The decoded user info.\n */\ngoog.Uri.prototype.getUserInfo = function() {\n 'use strict';\n return this.userInfo_;\n};\n\n\n/**\n * Sets the userInfo.\n * @throws URIError If opt_decode is true and newUserInfo is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newUserInfo New userInfo value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setUserInfo = function(newUserInfo, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.userInfo_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newUserInfo) : newUserInfo;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the user info has been set.\n */\ngoog.Uri.prototype.hasUserInfo = function() {\n 'use strict';\n return !!this.userInfo_;\n};\n\n\n/**\n * @return {string} The decoded domain.\n */\ngoog.Uri.prototype.getDomain = function() {\n 'use strict';\n return this.domain_;\n};\n\n\n/**\n * Sets the domain.\n * @throws URIError If opt_decode is true and newDomain is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newDomain New domain value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setDomain = function(newDomain, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.domain_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newDomain, true) : newDomain;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the domain has been set.\n */\ngoog.Uri.prototype.hasDomain = function() {\n 'use strict';\n return !!this.domain_;\n};\n\n\n/**\n * @return {?number} The port number.\n */\ngoog.Uri.prototype.getPort = function() {\n 'use strict';\n return this.port_;\n};\n\n\n/**\n * Sets the port number.\n * @param {*} newPort Port number. Will be explicitly casted to a number.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setPort = function(newPort) {\n 'use strict';\n this.enforceReadOnly();\n\n if (newPort) {\n newPort = Number(newPort);\n if (isNaN(newPort) || newPort < 0) {\n throw new Error('Bad port number ' + newPort);\n }\n this.port_ = newPort;\n } else {\n this.port_ = null;\n }\n\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the port has been set.\n */\ngoog.Uri.prototype.hasPort = function() {\n 'use strict';\n return this.port_ != null;\n};\n\n\n/**\n * @return {string} The decoded path.\n */\ngoog.Uri.prototype.getPath = function() {\n 'use strict';\n return this.path_;\n};\n\n\n/**\n * Sets the path.\n * @throws URIError If opt_decode is true and newPath is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newPath New path value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setPath = function(newPath, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.path_ = opt_decode ? goog.Uri.decodeOrEmpty_(newPath, true) : newPath;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the path has been set.\n */\ngoog.Uri.prototype.hasPath = function() {\n 'use strict';\n return !!this.path_;\n};\n\n\n/**\n * @return {boolean} Whether the query string has been set.\n */\ngoog.Uri.prototype.hasQuery = function() {\n 'use strict';\n return this.queryData_.toString() !== '';\n};\n\n\n/**\n * Sets the query data.\n * @param {goog.Uri.QueryData|string|undefined} queryData QueryData object.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * Applies only if queryData is a string.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setQueryData = function(queryData, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n\n if (queryData instanceof goog.Uri.QueryData) {\n this.queryData_ = queryData;\n this.queryData_.setIgnoreCase(this.ignoreCase_);\n } else {\n if (!opt_decode) {\n // QueryData accepts encoded query string, so encode it if\n // opt_decode flag is not true.\n queryData = goog.Uri.encodeSpecialChars_(\n queryData, goog.Uri.reDisallowedInQuery_);\n }\n this.queryData_ = new goog.Uri.QueryData(queryData, this.ignoreCase_);\n }\n\n return this;\n};\n\n\n/**\n * Sets the URI query.\n * @param {string} newQuery New query value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setQuery = function(newQuery, opt_decode) {\n 'use strict';\n return this.setQueryData(newQuery, opt_decode);\n};\n\n\n/**\n * @return {string} The encoded URI query, not including the ?.\n */\ngoog.Uri.prototype.getEncodedQuery = function() {\n 'use strict';\n return this.queryData_.toString();\n};\n\n\n/**\n * @return {string} The decoded URI query, not including the ?.\n */\ngoog.Uri.prototype.getDecodedQuery = function() {\n 'use strict';\n return this.queryData_.toDecodedString();\n};\n\n\n/**\n * Returns the query data.\n * @return {!goog.Uri.QueryData} QueryData object.\n */\ngoog.Uri.prototype.getQueryData = function() {\n 'use strict';\n return this.queryData_;\n};\n\n\n/**\n * @return {string} The encoded URI query, not including the ?.\n *\n * Warning: This method, unlike other getter methods, returns encoded\n * value, instead of decoded one.\n */\ngoog.Uri.prototype.getQuery = function() {\n 'use strict';\n return this.getEncodedQuery();\n};\n\n\n/**\n * Sets the value of the named query parameters, clearing previous values for\n * that key.\n *\n * @param {string} key The parameter to set.\n * @param {*} value The new value. Value does not need to be encoded.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setParameterValue = function(key, value) {\n 'use strict';\n this.enforceReadOnly();\n this.queryData_.set(key, value);\n return this;\n};\n\n\n/**\n * Sets the values of the named query parameters, clearing previous values for\n * that key. Not new values will currently be moved to the end of the query\n * string.\n *\n * So, <code>goog.Uri.parse('foo?a=b&c=d&e=f').setParameterValues('c', ['new'])\n * </code> yields <tt>foo?a=b&e=f&c=new</tt>.</p>\n *\n * @param {string} key The parameter to set.\n * @param {*} values The new values. If values is a single\n * string then it will be treated as the sole value. Values do not need to\n * be encoded.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setParameterValues = function(key, values) {\n 'use strict';\n this.enforceReadOnly();\n\n if (!Array.isArray(values)) {\n values = [String(values)];\n }\n\n this.queryData_.setValues(key, values);\n\n return this;\n};\n\n\n/**\n * Returns the value<b>s</b> for a given cgi parameter as a list of decoded\n * query parameter values.\n * @param {string} name The parameter to get values for.\n * @return {!Array<?>} The values for a given cgi parameter as a list of\n * decoded query parameter values.\n */\ngoog.Uri.prototype.getParameterValues = function(name) {\n 'use strict';\n return this.queryData_.getValues(name);\n};\n\n\n/**\n * Returns the first value for a given cgi parameter or undefined if the given\n * parameter name does not appear in the query string.\n * @param {string} paramName Unescaped parameter name.\n * @return {string|undefined} The first value for a given cgi parameter or\n * undefined if the given parameter name does not appear in the query\n * string.\n */\ngoog.Uri.prototype.getParameterValue = function(paramName) {\n 'use strict';\n return /** @type {string|undefined} */ (this.queryData_.get(paramName));\n};\n\n\n/**\n * @return {string} The URI fragment, not including the #.\n */\ngoog.Uri.prototype.getFragment = function() {\n 'use strict';\n return this.fragment_;\n};\n\n\n/**\n * Sets the URI fragment.\n * @throws URIError If opt_decode is true and newFragment is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newFragment New fragment value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setFragment = function(newFragment, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.fragment_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newFragment) : newFragment;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the URI has a fragment set.\n */\ngoog.Uri.prototype.hasFragment = function() {\n 'use strict';\n return !!this.fragment_;\n};\n\n\n/**\n * Returns true if this has the same domain as that of uri2.\n * @param {!goog.Uri} uri2 The URI object to compare to.\n * @return {boolean} true if same domain; false otherwise.\n */\ngoog.Uri.prototype.hasSameDomainAs = function(uri2) {\n 'use strict';\n return ((!this.hasDomain() && !uri2.hasDomain()) ||\n this.getDomain() == uri2.getDomain()) &&\n ((!this.hasPort() && !uri2.hasPort()) ||\n this.getPort() == uri2.getPort());\n};\n\n\n/**\n * Adds a random parameter to the Uri.\n * @return {!goog.Uri} Reference to this Uri object.\n */\ngoog.Uri.prototype.makeUnique = function() {\n 'use strict';\n this.enforceReadOnly();\n this.setParameterValue(goog.Uri.RANDOM_PARAM, goog.string.getRandomString());\n\n return this;\n};\n\n\n/**\n * Removes the named query parameter.\n *\n * @param {string} key The parameter to remove.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.removeParameter = function(key) {\n 'use strict';\n this.enforceReadOnly();\n this.queryData_.remove(key);\n return this;\n};\n\n\n/**\n * Sets whether Uri is read only. If this goog.Uri is read-only,\n * enforceReadOnly_ will be called at the start of any function that may modify\n * this Uri.\n * @param {boolean} isReadOnly whether this goog.Uri should be read only.\n * @return {!goog.Uri} Reference to this Uri object.\n */\ngoog.Uri.prototype.setReadOnly = function(isReadOnly) {\n 'use strict';\n this.isReadOnly_ = isReadOnly;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the URI is read only.\n */\ngoog.Uri.prototype.isReadOnly = function() {\n 'use strict';\n return this.isReadOnly_;\n};\n\n\n/**\n * Checks if this Uri has been marked as read only, and if so, throws an error.\n * This should be called whenever any modifying function is called.\n */\ngoog.Uri.prototype.enforceReadOnly = function() {\n 'use strict';\n if (this.isReadOnly_) {\n throw new Error('Tried to modify a read-only Uri');\n }\n};\n\n\n/**\n * Sets whether to ignore case.\n * NOTE: If there are already key/value pairs in the QueryData, and\n * ignoreCase_ is set to false, the keys will all be lower-cased.\n * @param {boolean} ignoreCase whether this goog.Uri should ignore case.\n * @return {!goog.Uri} Reference to this Uri object.\n */\ngoog.Uri.prototype.setIgnoreCase = function(ignoreCase) {\n 'use strict';\n this.ignoreCase_ = ignoreCase;\n if (this.queryData_) {\n this.queryData_.setIgnoreCase(ignoreCase);\n }\n return this;\n};\n\n\n/**\n * @return {boolean} Whether to ignore case.\n */\ngoog.Uri.prototype.getIgnoreCase = function() {\n 'use strict';\n return this.ignoreCase_;\n};\n\n\n//==============================================================================\n// Static members\n//==============================================================================\n\n\n/**\n * Creates a uri from the string form. Basically an alias of new goog.Uri().\n * If a Uri object is passed to parse then it will return a clone of the object.\n *\n * @throws URIError If parsing the URI is malformed. The passed URI components\n * should all be parseable by decodeURIComponent.\n * @param {*} uri Raw URI string or instance of Uri\n * object.\n * @param {boolean=} opt_ignoreCase Whether to ignore the case of parameter\n * names in #getParameterValue.\n * @return {!goog.Uri} The new URI object.\n */\ngoog.Uri.parse = function(uri, opt_ignoreCase) {\n 'use strict';\n return uri instanceof goog.Uri ? uri.clone() :\n new goog.Uri(uri, opt_ignoreCase);\n};\n\n\n/**\n * Creates a new goog.Uri object from unencoded parts.\n *\n * @param {?string=} opt_scheme Scheme/protocol or full URI to parse.\n * @param {?string=} opt_userInfo username:password.\n * @param {?string=} opt_domain www.google.com.\n * @param {?number=} opt_port 9830.\n * @param {?string=} opt_path /some/path/to/a/file.html.\n * @param {string|goog.Uri.QueryData=} opt_query a=1&b=2.\n * @param {?string=} opt_fragment The fragment without the #.\n * @param {boolean=} opt_ignoreCase Whether to ignore parameter name case in\n * #getParameterValue.\n *\n * @return {!goog.Uri} The new URI object.\n */\ngoog.Uri.create = function(\n opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_query,\n opt_fragment, opt_ignoreCase) {\n 'use strict';\n var uri = new goog.Uri(null, opt_ignoreCase);\n\n // Only set the parts if they are defined and not empty strings.\n opt_scheme && uri.setScheme(opt_scheme);\n opt_userInfo && uri.setUserInfo(opt_userInfo);\n opt_domain && uri.setDomain(opt_domain);\n opt_port && uri.setPort(opt_port);\n opt_path && uri.setPath(opt_path);\n opt_query && uri.setQueryData(opt_query);\n opt_fragment && uri.setFragment(opt_fragment);\n\n return uri;\n};\n\n\n/**\n * Resolves a relative Uri against a base Uri, accepting both strings and\n * Uri objects.\n *\n * @param {*} base Base Uri.\n * @param {*} rel Relative Uri.\n * @return {!goog.Uri} Resolved uri.\n */\ngoog.Uri.resolve = function(base, rel) {\n 'use strict';\n if (!(base instanceof goog.Uri)) {\n base = goog.Uri.parse(base);\n }\n\n if (!(rel instanceof goog.Uri)) {\n rel = goog.Uri.parse(rel);\n }\n\n return base.resolve(rel);\n};\n\n\n/**\n * Removes dot segments in given path component, as described in\n * RFC 3986, section 5.2.4.\n *\n * @param {string} path A non-empty path component.\n * @return {string} Path component with removed dot segments.\n */\ngoog.Uri.removeDotSegments = function(path) {\n 'use strict';\n if (path == '..' || path == '.') {\n return '';\n\n } else if (\n !goog.string.contains(path, './') && !goog.string.contains(path, '/.')) {\n // This optimization detects uris which do not contain dot-segments,\n // and as a consequence do not require any processing.\n return path;\n\n } else {\n var leadingSlash = goog.string.startsWith(path, '/');\n var segments = path.split('/');\n var out = [];\n\n for (var pos = 0; pos < segments.length;) {\n var segment = segments[pos++];\n\n if (segment == '.') {\n if (leadingSlash && pos == segments.length) {\n out.push('');\n }\n } else if (segment == '..') {\n if (out.length > 1 || out.length == 1 && out[0] != '') {\n out.pop();\n }\n if (leadingSlash && pos == segments.length) {\n out.push('');\n }\n } else {\n out.push(segment);\n leadingSlash = true;\n }\n }\n\n return out.join('/');\n }\n};\n\n\n/**\n * Decodes a value or returns the empty string if it isn't defined or empty.\n * @throws URIError If decodeURIComponent fails to decode val.\n * @param {string|undefined} val Value to decode.\n * @param {boolean=} opt_preserveReserved If true, restricted characters will\n * not be decoded.\n * @return {string} Decoded value.\n * @private\n */\ngoog.Uri.decodeOrEmpty_ = function(val, opt_preserveReserved) {\n 'use strict';\n // Don't use UrlDecode() here because val is not a query parameter.\n if (!val) {\n return '';\n }\n\n // decodeURI has the same output for '%2f' and '%252f'. We double encode %25\n // so that we can distinguish between the 2 inputs. This is later undone by\n // removeDoubleEncoding_.\n return opt_preserveReserved ? decodeURI(val.replace(/%25/g, '%2525')) :\n decodeURIComponent(val);\n};\n\n\n/**\n * If unescapedPart is non null, then escapes any characters in it that aren't\n * valid characters in a url and also escapes any special characters that\n * appear in extra.\n *\n * @param {*} unescapedPart The string to encode.\n * @param {RegExp} extra A character set of characters in [\\01-\\177].\n * @param {boolean=} opt_removeDoubleEncoding If true, remove double percent\n * encoding.\n * @return {?string} null iff unescapedPart == null.\n * @private\n */\ngoog.Uri.encodeSpecialChars_ = function(\n unescapedPart, extra, opt_removeDoubleEncoding) {\n 'use strict';\n if (typeof unescapedPart === 'string') {\n var encoded = encodeURI(unescapedPart).replace(extra, goog.Uri.encodeChar_);\n if (opt_removeDoubleEncoding) {\n // encodeURI double-escapes %XX sequences used to represent restricted\n // characters in some URI components, remove the double escaping here.\n encoded = goog.Uri.removeDoubleEncoding_(encoded);\n }\n return encoded;\n }\n return null;\n};\n\n\n/**\n * Converts a character in [\\01-\\177] to its unicode character equivalent.\n * @param {string} ch One character string.\n * @return {string} Encoded string.\n * @private\n */\ngoog.Uri.encodeChar_ = function(ch) {\n 'use strict';\n var n = ch.charCodeAt(0);\n return '%' + ((n >> 4) & 0xf).toString(16) + (n & 0xf).toString(16);\n};\n\n\n/**\n * Removes double percent-encoding from a string.\n * @param {string} doubleEncodedString String\n * @return {string} String with double encoding removed.\n * @private\n */\ngoog.Uri.removeDoubleEncoding_ = function(doubleEncodedString) {\n 'use strict';\n return doubleEncodedString.replace(/%25([0-9a-fA-F]{2})/g, '%$1');\n};\n\n\n/**\n * Regular expression for characters that are disallowed in the scheme or\n * userInfo part of the URI.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInSchemeOrUserInfo_ = /[#\\/\\?@]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in a relative path.\n * Colon is included due to RFC 3986 3.3.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInRelativePath_ = /[\\#\\?:]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in an absolute path.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInAbsolutePath_ = /[\\#\\?]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in the query.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInQuery_ = /[\\#\\?@]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in the fragment.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInFragment_ = /#/g;\n\n\n/**\n * Checks whether two URIs have the same domain.\n * @param {string} uri1String First URI string.\n * @param {string} uri2String Second URI string.\n * @return {boolean} true if the two URIs have the same domain; false otherwise.\n */\ngoog.Uri.haveSameDomain = function(uri1String, uri2String) {\n 'use strict';\n // Differs from goog.uri.utils.haveSameDomain, since this ignores scheme.\n // TODO(gboyer): Have this just call goog.uri.util.haveSameDomain.\n var pieces1 = goog.uri.utils.split(uri1String);\n var pieces2 = goog.uri.utils.split(uri2String);\n return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==\n pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&\n pieces1[goog.uri.utils.ComponentIndex.PORT] ==\n pieces2[goog.uri.utils.ComponentIndex.PORT];\n};\n\n\n\n/**\n * Class used to represent URI query parameters. It is essentially a hash of\n * name-value pairs, though a name can be present more than once.\n *\n * Has the same interface as the collections in goog.structs.\n *\n * @param {?string=} opt_query Optional encoded query string to parse into\n * the object.\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\n * name in #get.\n * @constructor\n * @struct\n * @final\n */\ngoog.Uri.QueryData = function(opt_query, opt_ignoreCase) {\n 'use strict';\n /**\n * The map containing name/value or name/array-of-values pairs.\n * May be null if it requires parsing from the query string.\n *\n * We need to use a Map because we cannot guarantee that the key names will\n * not be problematic for IE.\n *\n * @private {?Map<string, !Array<*>>}\n */\n this.keyMap_ = null;\n\n /**\n * The number of params, or null if it requires computing.\n * @private {?number}\n */\n this.count_ = null;\n\n /**\n * Encoded query string, or null if it requires computing from the key map.\n * @private {?string}\n */\n this.encodedQuery_ = opt_query || null;\n\n /**\n * If true, ignore the case of the parameter name in #get.\n * @private {boolean}\n */\n this.ignoreCase_ = !!opt_ignoreCase;\n};\n\n\n/**\n * If the underlying key map is not yet initialized, it parses the\n * query string and fills the map with parsed data.\n * @private\n */\ngoog.Uri.QueryData.prototype.ensureKeyMapInitialized_ = function() {\n 'use strict';\n if (!this.keyMap_) {\n this.keyMap_ = /** @type {!Map<string, !Array<*>>} */ (new Map());\n this.count_ = 0;\n if (this.encodedQuery_) {\n var self = this;\n goog.uri.utils.parseQueryData(this.encodedQuery_, function(name, value) {\n 'use strict';\n self.add(goog.string.urlDecode(name), value);\n });\n }\n }\n};\n\n\n/**\n * Creates a new query data instance from a map of names and values.\n *\n * @param {!goog.collections.maps.MapLike<string, ?>|!Object} map Map of string\n * parameter names to parameter value. If parameter value is an array, it is\n * treated as if the key maps to each individual value in the\n * array.\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\n * name in #get.\n * @return {!goog.Uri.QueryData} The populated query data instance.\n */\ngoog.Uri.QueryData.createFromMap = function(map, opt_ignoreCase) {\n 'use strict';\n var keys = goog.structs.getKeys(map);\n if (typeof keys == 'undefined') {\n throw new Error('Keys are undefined');\n }\n\n var queryData = new goog.Uri.QueryData(null, opt_ignoreCase);\n var values = goog.structs.getValues(map);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = values[i];\n if (!Array.isArray(value)) {\n queryData.add(key, value);\n } else {\n queryData.setValues(key, value);\n }\n }\n return queryData;\n};\n\n\n/**\n * Creates a new query data instance from parallel arrays of parameter names\n * and values. Allows for duplicate parameter names. Throws an error if the\n * lengths of the arrays differ.\n *\n * @param {!Array<string>} keys Parameter names.\n * @param {!Array<?>} values Parameter values.\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\n * name in #get.\n * @return {!goog.Uri.QueryData} The populated query data instance.\n */\ngoog.Uri.QueryData.createFromKeysValues = function(\n keys, values, opt_ignoreCase) {\n 'use strict';\n if (keys.length != values.length) {\n throw new Error('Mismatched lengths for keys/values');\n }\n var queryData = new goog.Uri.QueryData(null, opt_ignoreCase);\n for (var i = 0; i < keys.length; i++) {\n queryData.add(keys[i], values[i]);\n }\n return queryData;\n};\n\n\n/**\n * @return {?number} The number of parameters.\n */\ngoog.Uri.QueryData.prototype.getCount = function() {\n 'use strict';\n this.ensureKeyMapInitialized_();\n return this.count_;\n};\n\n\n/**\n * Adds a key value pair.\n * @param {string} key Name.\n * @param {*} value Value.\n * @return {!goog.Uri.QueryData} Instance of this object.\n */\ngoog.Uri.QueryData.prototype.add = function(key, value) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n this.invalidateCache_();\n\n key = this.getKeyName_(key);\n var values = this.keyMap_.get(key);\n if (!values) {\n this.keyMap_.set(key, (values = []));\n }\n values.push(value);\n this.count_ = goog.asserts.assertNumber(this.count_) + 1;\n return this;\n};\n\n\n/**\n * Removes all the params with the given key.\n * @param {string} key Name.\n * @return {boolean} Whether any parameter was removed.\n */\ngoog.Uri.QueryData.prototype.remove = function(key) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n\n key = this.getKeyName_(key);\n if (this.keyMap_.has(key)) {\n this.invalidateCache_();\n\n // Decrement parameter count.\n this.count_ =\n goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length;\n return this.keyMap_.delete(key);\n }\n return false;\n};\n\n\n/**\n * Clears the parameters.\n */\ngoog.Uri.QueryData.prototype.clear = function() {\n 'use strict';\n this.invalidateCache_();\n this.keyMap_ = null;\n this.count_ = 0;\n};\n\n\n/**\n * @return {boolean} Whether we have any parameters.\n */\ngoog.Uri.QueryData.prototype.isEmpty = function() {\n 'use strict';\n this.ensureKeyMapInitialized_();\n return this.count_ == 0;\n};\n\n\n/**\n * Whether there is a parameter with the given name\n * @param {string} key The parameter name to check for.\n * @return {boolean} Whether there is a parameter with the given name.\n */\ngoog.Uri.QueryData.prototype.containsKey = function(key) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n key = this.getKeyName_(key);\n return this.keyMap_.has(key);\n};\n\n\n/**\n * Whether there is a parameter with the given value.\n * @param {*} value The value to check for.\n * @return {boolean} Whether there is a parameter with the given value.\n */\ngoog.Uri.QueryData.prototype.containsValue = function(value) {\n 'use strict';\n // NOTE(arv): This solution goes through all the params even if it was the\n // first param. We can get around this by not reusing code or by switching to\n // iterators.\n var vals = this.getValues();\n return goog.array.contains(vals, value);\n};\n\n\n/**\n * Runs a callback on every key-value pair in the map, including duplicate keys.\n * This won't maintain original order when duplicate keys are interspersed (like\n * getKeys() / getValues()).\n * @param {function(this:SCOPE, ?, string, !goog.Uri.QueryData)} f\n * @param {SCOPE=} opt_scope The value of \"this\" inside f.\n * @template SCOPE\n */\ngoog.Uri.QueryData.prototype.forEach = function(f, opt_scope) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n this.keyMap_.forEach(function(values, key) {\n 'use strict';\n values.forEach(function(value) {\n 'use strict';\n f.call(opt_scope, value, key, this);\n }, this);\n }, this);\n};\n\n\n/**\n * Returns all the keys of the parameters. If a key is used multiple times\n * it will be included multiple times in the returned array\n * @return {!Array<string>} All the keys of the parameters.\n */\ngoog.Uri.QueryData.prototype.getKeys = function() {\n 'use strict';\n this.ensureKeyMapInitialized_();\n // We need to get the values to know how many keys to add.\n const vals = Array.from(this.keyMap_.values());\n const keys = Array.from(this.keyMap_.keys());\n const rv = [];\n for (let i = 0; i < keys.length; i++) {\n const val = vals[i];\n for (let j = 0; j < val.length; j++) {\n rv.push(keys[i]);\n }\n }\n return rv;\n};\n\n\n/**\n * Returns all the values of the parameters with the given name. If the query\n * data has no such key this will return an empty array. If no key is given\n * all values wil be returned.\n * @param {string=} opt_key The name of the parameter to get the values for.\n * @return {!Array<?>} All the values of the parameters with the given name.\n */\ngoog.Uri.QueryData.prototype.getValues = function(opt_key) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n let rv = [];\n if (typeof opt_key === 'string') {\n if (this.containsKey(opt_key)) {\n rv = rv.concat(this.keyMap_.get(this.getKeyName_(opt_key)));\n }\n } else {\n // Return all values.\n const values = Array.from(this.keyMap_.values());\n for (let i = 0; i < values.length; i++) {\n rv = rv.concat(values[i]);\n }\n }\n return rv;\n};\n\n\n/**\n * Sets a key value pair and removes all other keys with the same value.\n *\n * @param {string} key Name.\n * @param {*} value Value.\n * @return {!goog.Uri.QueryData} Instance of this object.\n */\ngoog.Uri.QueryData.prototype.set = function(key, value) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n this.invalidateCache_();\n\n // TODO(chrishenry): This could be better written as\n // this.remove(key), this.add(key, value), but that would reorder\n // the key (since the key is first removed and then added at the\n // end) and we would have to fix unit tests that depend on key\n // ordering.\n key = this.getKeyName_(key);\n if (this.containsKey(key)) {\n this.count_ =\n goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length;\n }\n this.keyMap_.set(key, [value]);\n this.count_ = goog.asserts.assertNumber(this.count_) + 1;\n return this;\n};\n\n\n/**\n * Returns the first value associated with the key. If the query data has no\n * such key this will return undefined or the optional default.\n * @param {string} key The name of the parameter to get the value for.\n * @param {*=} opt_default The default value to return if the query data\n * has no such key.\n * @return {*} The first string value associated with the key, or opt_default\n * if there's no value.\n */\ngoog.Uri.QueryData.prototype.get = function(key, opt_default) {\n 'use strict';\n if (!key) {\n return opt_default;\n }\n var values = this.getValues(key);\n return values.length > 0 ? String(values[0]) : opt_default;\n};\n\n\n/**\n * Sets the values for a key. If the key already exists, this will\n * override all of the existing values that correspond to the key.\n * @param {string} key The key to set values for.\n * @param {!Array<?>} values The values to set.\n */\ngoog.Uri.QueryData.prototype.setValues = function(key, values) {\n 'use strict';\n this.remove(key);\n\n if (values.length > 0) {\n this.invalidateCache_();\n this.keyMap_.set(this.getKeyName_(key), goog.array.clone(values));\n this.count_ = goog.asserts.assertNumber(this.count_) + values.length;\n }\n};\n\n\n/**\n * @return {string} Encoded query string.\n * @override\n */\ngoog.Uri.QueryData.prototype.toString = function() {\n 'use strict';\n if (this.encodedQuery_) {\n return this.encodedQuery_;\n }\n\n if (!this.keyMap_) {\n return '';\n }\n\n const sb = [];\n\n // In the past, we use this.getKeys() and this.getVals(), but that\n // generates a lot of allocations as compared to simply iterating\n // over the keys.\n const keys = Array.from(this.keyMap_.keys());\n for (var i = 0; i < keys.length; i++) {\n const key = keys[i];\n const encodedKey = goog.string.urlEncode(key);\n const val = this.getValues(key);\n for (var j = 0; j < val.length; j++) {\n var param = encodedKey;\n // Ensure that null and undefined are encoded into the url as\n // literal strings.\n if (val[j] !== '') {\n param += '=' + goog.string.urlEncode(val[j]);\n }\n sb.push(param);\n }\n }\n\n return this.encodedQuery_ = sb.join('&');\n};\n\n\n/**\n * @throws URIError If URI is malformed (that is, if decodeURIComponent fails on\n * any of the URI components).\n * @return {string} Decoded query string.\n */\ngoog.Uri.QueryData.prototype.toDecodedString = function() {\n 'use strict';\n return goog.Uri.decodeOrEmpty_(this.toString());\n};\n\n\n/**\n * Invalidate the cache.\n * @private\n */\ngoog.Uri.QueryData.prototype.invalidateCache_ = function() {\n 'use strict';\n this.encodedQuery_ = null;\n};\n\n\n/**\n * Removes all keys that are not in the provided list. (Modifies this object.)\n * @param {Array<string>} keys The desired keys.\n * @return {!goog.Uri.QueryData} a reference to this object.\n */\ngoog.Uri.QueryData.prototype.filterKeys = function(keys) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n this.keyMap_.forEach(function(value, key) {\n 'use strict';\n if (!goog.array.contains(keys, key)) {\n this.remove(key);\n }\n }, this);\n return this;\n};\n\n\n/**\n * Clone the query data instance.\n * @return {!goog.Uri.QueryData} New instance of the QueryData object.\n */\ngoog.Uri.QueryData.prototype.clone = function() {\n 'use strict';\n var rv = new goog.Uri.QueryData();\n rv.encodedQuery_ = this.encodedQuery_;\n if (this.keyMap_) {\n rv.keyMap_ = /** @type {!Map<string, !Array<*>>} */ (new Map(this.keyMap_));\n rv.count_ = this.count_;\n }\n return rv;\n};\n\n\n/**\n * Helper function to get the key name from a JavaScript object. Converts\n * the object to a string, and to lower case if necessary.\n * @private\n * @param {*} arg The object to get a key name from.\n * @return {string} valid key name which can be looked up in #keyMap_.\n */\ngoog.Uri.QueryData.prototype.getKeyName_ = function(arg) {\n 'use strict';\n var keyName = String(arg);\n if (this.ignoreCase_) {\n keyName = keyName.toLowerCase();\n }\n return keyName;\n};\n\n\n/**\n * Ignore case in parameter names.\n * NOTE: If there are already key/value pairs in the QueryData, and\n * ignoreCase_ is set to false, the keys will all be lower-cased.\n * @param {boolean} ignoreCase whether this goog.Uri should ignore case.\n */\ngoog.Uri.QueryData.prototype.setIgnoreCase = function(ignoreCase) {\n 'use strict';\n var resetKeys = ignoreCase && !this.ignoreCase_;\n if (resetKeys) {\n this.ensureKeyMapInitialized_();\n this.invalidateCache_();\n this.keyMap_.forEach(function(value, key) {\n 'use strict';\n var lowerCase = key.toLowerCase();\n if (key != lowerCase) {\n this.remove(key);\n this.setValues(lowerCase, value);\n }\n }, this);\n }\n this.ignoreCase_ = ignoreCase;\n};\n\n\n/**\n * Extends a query data object with another query data or map like object. This\n * operates 'in-place', it does not create a new QueryData object.\n *\n * @param {...(?goog.Uri.QueryData|?goog.collections.maps.MapLike<?,\n * ?>|?Object)} var_args The object from which key value pairs will be\n * copied. Note: does not accept null.\n * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different\n * types of parameters.\n */\ngoog.Uri.QueryData.prototype.extend = function(var_args) {\n 'use strict';\n for (var i = 0; i < arguments.length; i++) {\n var data = arguments[i];\n goog.structs.forEach(data, function(value, key) {\n 'use strict';\n this.add(key, value);\n }, this);\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview The dispose method is used to clean up references and\n * resources.\n */\n\ngoog.module('goog.dispose');\ngoog.module.declareLegacyNamespace();\n\n/**\n * Calls `dispose` on the argument if it supports it. If obj is not an\n * object with a dispose() method, this is a no-op.\n * @param {*} obj The object to dispose of.\n */\nfunction dispose(obj) {\n if (obj && typeof obj.dispose == 'function') {\n obj.dispose();\n }\n}\nexports = dispose;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Codec functions of the v8 wire protocol. Eventually we'd want\n * to support pluggable wire-format to improve wire efficiency and to enable\n * binary encoding. Such support will require an interface class, which\n * will be added later.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.WireV8');\n\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.json');\ngoog.require('goog.json.NativeJsonProcessor');\ngoog.require('goog.labs.net.webChannel.Wire');\ngoog.require('goog.structs');\ngoog.requireType('goog.string.Parser');\n\n\n\n/**\n * The v8 codec class.\n *\n * @constructor\n * @struct\n */\ngoog.labs.net.webChannel.WireV8 = function() {\n 'use strict';\n /**\n * Parser for a response payload. The parser should return an array.\n * @private {!goog.string.Parser}\n */\n this.parser_ = new goog.json.NativeJsonProcessor();\n};\n\n\ngoog.scope(function() {\n'use strict';\nconst WireV8 = goog.labs.net.webChannel.WireV8;\nconst Wire = goog.labs.net.webChannel.Wire;\n\n\n/**\n * Encodes a standalone message into the wire format.\n *\n * May throw exception if the message object contains any invalid elements.\n *\n * @param {!Object|!goog.collections.maps.MapLike} message The message data.\n * V8 only support JS objects (or Map).\n * @param {!Array<string>} buffer The text buffer to write the message to.\n * @param {string=} opt_prefix The prefix for each field of the object.\n */\nWireV8.prototype.encodeMessage = function(message, buffer, opt_prefix) {\n 'use strict';\n const prefix = opt_prefix || '';\n try {\n goog.structs.forEach(message, function(value, key) {\n 'use strict';\n let encodedValue = value;\n if (goog.isObject(value)) {\n encodedValue = goog.json.serialize(value);\n } // keep the fast-path for primitive types\n buffer.push(prefix + key + '=' + encodeURIComponent(encodedValue));\n });\n } catch (ex) {\n // We send a map here because lots of the retry logic relies on map IDs,\n // so we have to send something (possibly redundant).\n buffer.push(\n prefix + 'type' +\n '=' + encodeURIComponent('_badmap'));\n throw ex;\n }\n};\n\n\n/**\n * Encodes all the buffered messages of the forward channel.\n *\n * @param {!Array<Wire.QueuedMap>} messageQueue The message data.\n * V8 only support JS objects.\n * @param {number} count The number of messages to be encoded.\n * @param {?function(!Object)} badMapHandler Callback for bad messages.\n * @return {string} the encoded messages\n */\nWireV8.prototype.encodeMessageQueue = function(\n messageQueue, count, badMapHandler) {\n 'use strict';\n let offset = -1;\n while (true) {\n const sb = ['count=' + count];\n // To save a bit of bandwidth, specify the base mapId and the rest as\n // offsets from it.\n if (offset == -1) {\n if (count > 0) {\n offset = messageQueue[0].mapId;\n sb.push('ofs=' + offset);\n } else {\n offset = 0;\n }\n } else {\n sb.push('ofs=' + offset);\n }\n let done = true;\n for (let i = 0; i < count; i++) {\n let mapId = messageQueue[i].mapId;\n const map = messageQueue[i].map;\n mapId -= offset;\n if (mapId < 0) {\n // redo the encoding in case of retry/reordering, plus extra space\n offset = Math.max(0, messageQueue[i].mapId - 100);\n done = false;\n continue;\n }\n try {\n this.encodeMessage(map, sb, 'req' + mapId + '_');\n } catch (ex) {\n if (badMapHandler) {\n badMapHandler(map);\n }\n }\n }\n if (done) {\n return sb.join('&');\n }\n }\n};\n\n\n/**\n * Decodes a standalone message received from the wire. May throw exception\n * if text is ill-formatted.\n *\n * Must be valid JSON as it is insecure to use eval() to decode JS literals;\n * and eval() is disallowed in Chrome apps too.\n *\n * Invalid JS literals include null array elements, quotas etc.\n *\n * @param {string} messageText The string content as received from the wire.\n * @return {*} The decoded message object.\n */\nWireV8.prototype.decodeMessage = function(messageText) {\n 'use strict';\n const response = this.parser_.parse(messageText);\n goog.asserts.assert(Array.isArray(response)); // throw exception\n return response;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A pool of forward channel requests to enable real-time\n * messaging from the client to server.\n *\n */\n\ngoog.module('goog.labs.net.webChannel.ForwardChannelRequestPool');\n\ngoog.module.declareLegacyNamespace();\n\nconst ChannelRequest = goog.require('goog.labs.net.webChannel.ChannelRequest');\nconst Wire = goog.require('goog.labs.net.webChannel.Wire');\nconst array = goog.require('goog.array');\nconst googString = goog.require('goog.string');\n\n\n/**\n * This class represents the state of all forward channel requests.\n *\n * @param {number=} opt_maxPoolSize The maximum pool size.\n *\n * @struct @constructor @final\n */\nconst ForwardChannelRequestPool = function(opt_maxPoolSize) {\n /**\n * The max pool size as configured.\n *\n * @private {number}\n */\n this.maxPoolSizeConfigured_ =\n opt_maxPoolSize || ForwardChannelRequestPool.MAX_POOL_SIZE_;\n\n /**\n * The current size limit of the request pool. This limit is meant to be\n * read-only after the channel is fully opened.\n *\n * If SPDY or HTTP2 is enabled, set it to the max pool size, which is also\n * configurable.\n *\n * @private {number}\n */\n this.maxSize_ = ForwardChannelRequestPool.isSpdyOrHttp2Enabled_() ?\n this.maxPoolSizeConfigured_ :\n 1;\n\n /**\n * The container for all the pending request objects.\n *\n * @private {?Set<?ChannelRequest>}\n */\n this.requestPool_ = null;\n\n if (this.maxSize_ > 1) {\n this.requestPool_ = new Set();\n }\n\n /**\n * The single request object when the pool size is limited to one.\n *\n * @private {?ChannelRequest}\n */\n this.request_ = null;\n\n /**\n * Saved pending messages when the pool is cancelled.\n *\n * @private {!Array<Wire.QueuedMap>}\n */\n this.pendingMessages_ = [];\n};\n\n\n/**\n * The default size limit of the request pool.\n *\n * @private {number}\n */\nForwardChannelRequestPool.MAX_POOL_SIZE_ = 10;\n\n\n/**\n * @return {boolean} True if SPDY or HTTP2 is enabled. Uses chrome-specific APIs\n * as a fallback and will always return false for other browsers where\n * PerformanceNavigationTiming is not available.\n * @private\n */\nForwardChannelRequestPool.isSpdyOrHttp2Enabled_ = function() {\n if (goog.global.PerformanceNavigationTiming) {\n const entrys = /** @type {!Array<!PerformanceNavigationTiming>} */ (\n goog.global.performance.getEntriesByType('navigation'));\n return entrys.length > 0 &&\n (entrys[0].nextHopProtocol == 'hq' ||\n entrys[0].nextHopProtocol == 'h2');\n }\n return !!(\n goog.global.chrome && goog.global.chrome.loadTimes &&\n goog.global.chrome.loadTimes() &&\n goog.global.chrome.loadTimes().wasFetchedViaSpdy);\n};\n\n\n/**\n * Once we know the client protocol (from the handshake), check if we need\n * enable the request pool accordingly. This is more robust than using\n * browser-internal APIs (specific to Chrome).\n *\n * @param {string} clientProtocol The client protocol\n */\nForwardChannelRequestPool.prototype.applyClientProtocol = function(\n clientProtocol) {\n if (this.requestPool_) {\n return;\n }\n\n if (googString.contains(clientProtocol, 'spdy') ||\n googString.contains(clientProtocol, 'quic') ||\n googString.contains(clientProtocol, 'h2')) {\n this.maxSize_ = this.maxPoolSizeConfigured_;\n this.requestPool_ = new Set();\n if (this.request_) {\n this.addRequest(this.request_);\n this.request_ = null;\n }\n }\n};\n\n\n/**\n * @return {boolean} True if the pool is full.\n */\nForwardChannelRequestPool.prototype.isFull = function() {\n if (this.request_) {\n return true;\n }\n\n if (this.requestPool_) {\n return this.requestPool_.size >= this.maxSize_;\n }\n\n return false;\n};\n\n\n/**\n * @return {number} The current size limit.\n */\nForwardChannelRequestPool.prototype.getMaxSize = function() {\n return this.maxSize_;\n};\n\n\n/**\n * @return {number} The number of pending requests in the pool.\n */\nForwardChannelRequestPool.prototype.getRequestCount = function() {\n if (this.request_) {\n return 1;\n }\n\n if (this.requestPool_) {\n return this.requestPool_.size;\n }\n\n return 0;\n};\n\n\n/**\n * @param {ChannelRequest} req The channel request.\n * @return {boolean} True if the request is a included inside the pool.\n */\nForwardChannelRequestPool.prototype.hasRequest = function(req) {\n if (this.request_) {\n return this.request_ == req;\n }\n\n if (this.requestPool_) {\n return this.requestPool_.has(req);\n }\n\n return false;\n};\n\n\n/**\n * Adds a new request to the pool.\n *\n * @param {!ChannelRequest} req The new channel request.\n */\nForwardChannelRequestPool.prototype.addRequest = function(req) {\n if (this.requestPool_) {\n this.requestPool_.add(req);\n } else {\n this.request_ = req;\n }\n};\n\n\n/**\n * Removes the given request from the pool.\n *\n * @param {ChannelRequest} req The channel request.\n * @return {boolean} Whether the request has been removed from the pool.\n */\nForwardChannelRequestPool.prototype.removeRequest = function(req) {\n if (this.request_ && this.request_ == req) {\n this.request_ = null;\n return true;\n }\n\n if (this.requestPool_ && this.requestPool_.has(req)) {\n this.requestPool_.delete(req);\n return true;\n }\n\n return false;\n};\n\n\n/**\n * Clears the pool and cancel all the pending requests.\n */\nForwardChannelRequestPool.prototype.cancel = function() {\n // save any pending messages\n this.pendingMessages_ = this.getPendingMessages();\n\n if (this.request_) {\n this.request_.cancel();\n this.request_ = null;\n return;\n }\n\n if (this.requestPool_ && this.requestPool_.size !== 0) {\n for (const val of this.requestPool_.values()) {\n val.cancel();\n }\n this.requestPool_.clear();\n }\n};\n\n\n/**\n * @return {boolean} Whether there are any pending requests.\n */\nForwardChannelRequestPool.prototype.hasPendingRequest = function() {\n return (this.request_ != null) ||\n (this.requestPool_ != null && this.requestPool_.size !== 0);\n};\n\n\n/**\n * @return {!Array<Wire.QueuedMap>} All the pending messages from the pool,\n * as a new array.\n */\nForwardChannelRequestPool.prototype.getPendingMessages = function() {\n if (this.request_ != null) {\n return this.pendingMessages_.concat(this.request_.getPendingMessages());\n }\n\n if (this.requestPool_ != null && this.requestPool_.size !== 0) {\n let result = this.pendingMessages_;\n for (const val of this.requestPool_.values()) {\n result = result.concat(val.getPendingMessages());\n }\n return result;\n }\n\n return array.clone(this.pendingMessages_);\n};\n\n\n/**\n * Records pending messages, e.g. when a request receives a failed response.\n *\n * @param {!Array<Wire.QueuedMap>} messages Pending messages.\n */\nForwardChannelRequestPool.prototype.addPendingMessages = function(messages) {\n this.pendingMessages_ = this.pendingMessages_.concat(messages);\n};\n\n\n/**\n * Clears any recorded pending messages.\n */\nForwardChannelRequestPool.prototype.clearPendingMessages = function() {\n this.pendingMessages_.length = 0;\n};\n\n\n/**\n * Cancels all pending requests and force the completion of channel requests.\n *\n * Need go through the standard onRequestComplete logic to expose the max-retry\n * failure in the standard way.\n *\n * @param {function(!ChannelRequest)} onComplete The completion callback.\n * @return {boolean} true if any request has been forced to complete.\n */\nForwardChannelRequestPool.prototype.forceComplete = function(onComplete) {\n if (this.request_ != null) {\n this.request_.cancel();\n onComplete(this.request_);\n return true;\n }\n\n if (this.requestPool_ && this.requestPool_.size !== 0) {\n for (const val of this.requestPool_.values()) {\n val.cancel();\n onComplete(val);\n }\n return true;\n }\n\n return false;\n};\n\nexports = ForwardChannelRequestPool;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Generics method for collection-like classes and objects.\n *\n *\n * This file contains functions to work with collections. It supports using\n * Map, Set, Array and Object and other classes that implement collection-like\n * methods.\n * @suppress {strictMissingProperties}\n */\n\n\ngoog.provide('goog.structs');\n\ngoog.require('goog.array');\ngoog.require('goog.object');\n\n\n// We treat an object as a dictionary if it has getKeys or it is an object that\n// isn't arrayLike.\n\n\n/**\n * Returns the number of values in the collection-like object.\n * @param {Object} col The collection-like object.\n * @return {number} The number of values in the collection-like object.\n */\ngoog.structs.getCount = function(col) {\n 'use strict';\n if (col.getCount && typeof col.getCount == 'function') {\n return col.getCount();\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return col.length;\n }\n return goog.object.getCount(col);\n};\n\n\n/**\n * Returns the values of the collection-like object.\n * @param {Object} col The collection-like object.\n * @return {!Array<?>} The values in the collection-like object.\n */\ngoog.structs.getValues = function(col) {\n 'use strict';\n if (col.getValues && typeof col.getValues == 'function') {\n return col.getValues();\n }\n // ES6 Map and Set both define a values function that returns an iterator.\n // The typeof check allows the compiler to remove the Map and Set polyfills\n // if they are otherwise unused throughout the entire binary.\n if ((typeof Map !== 'undefined' && col instanceof Map) ||\n (typeof Set !== 'undefined' && col instanceof Set)) {\n return Array.from(col.values());\n }\n if (typeof col === 'string') {\n return col.split('');\n }\n if (goog.isArrayLike(col)) {\n var rv = [];\n var l = col.length;\n for (var i = 0; i < l; i++) {\n rv.push(col[i]);\n }\n return rv;\n }\n return goog.object.getValues(col);\n};\n\n\n/**\n * Returns the keys of the collection. Some collections have no notion of\n * keys/indexes and this function will return undefined in those cases.\n * @param {Object} col The collection-like object.\n * @return {!Array|undefined} The keys in the collection.\n */\ngoog.structs.getKeys = function(col) {\n 'use strict';\n if (col.getKeys && typeof col.getKeys == 'function') {\n return col.getKeys();\n }\n // if we have getValues but no getKeys we know this is a key-less collection\n if (col.getValues && typeof col.getValues == 'function') {\n return undefined;\n }\n // ES6 Map and Set both define a keys function that returns an iterator. For\n // Sets this iterates over the same values as the values iterator.\n // The typeof check allows the compiler to remove the Map and Set polyfills\n // if they are otherwise unused throughout the entire binary.\n if (typeof Map !== 'undefined' && col instanceof Map) {\n return Array.from(col.keys());\n }\n // Unlike the native Set, goog.structs.Set does not expose keys as the values.\n if (typeof Set !== 'undefined' && col instanceof Set) {\n return undefined;\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n var rv = [];\n var l = col.length;\n for (var i = 0; i < l; i++) {\n rv.push(i);\n }\n return rv;\n }\n\n return goog.object.getKeys(col);\n};\n\n\n/**\n * Whether the collection contains the given value. This is O(n) and uses\n * equals (==) to test the existence.\n * @param {Object} col The collection-like object.\n * @param {*} val The value to check for.\n * @return {boolean} True if the map contains the value.\n */\ngoog.structs.contains = function(col, val) {\n 'use strict';\n if (col.contains && typeof col.contains == 'function') {\n return col.contains(val);\n }\n if (col.containsValue && typeof col.containsValue == 'function') {\n return col.containsValue(val);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return goog.array.contains(/** @type {!Array<?>} */ (col), val);\n }\n return goog.object.containsValue(col, val);\n};\n\n\n/**\n * Whether the collection is empty.\n * @param {Object} col The collection-like object.\n * @return {boolean} True if empty.\n */\ngoog.structs.isEmpty = function(col) {\n 'use strict';\n if (col.isEmpty && typeof col.isEmpty == 'function') {\n return col.isEmpty();\n }\n\n // We do not use goog.string.isEmptyOrWhitespace because here we treat the\n // string as\n // collection and as such even whitespace matters\n\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return /** @type {!Array<?>} */ (col).length === 0;\n }\n return goog.object.isEmpty(col);\n};\n\n\n/**\n * Removes all the elements from the collection.\n * @param {Object} col The collection-like object.\n * @return {void}\n */\ngoog.structs.clear = function(col) {\n 'use strict';\n // NOTE(arv): This should not contain strings because strings are immutable\n if (col.clear && typeof col.clear == 'function') {\n col.clear();\n } else if (goog.isArrayLike(col)) {\n goog.array.clear(/** @type {IArrayLike<?>} */ (col));\n } else {\n goog.object.clear(col);\n }\n};\n\n\n/**\n * Calls a function for each value in a collection. The function takes\n * three arguments; the value, the key and the collection.\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):?} f The function to call for every value.\n * This function takes\n * 3 arguments (the value, the key or undefined if the collection has no\n * notion of keys, and the collection) and the return value is irrelevant.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {void}\n * @template T,S\n * @deprecated Use a more specific method, e.g. native Array.prototype.forEach,\n * or for-of.\n */\ngoog.structs.forEach = function(col, f, opt_obj) {\n 'use strict';\n if (col.forEach && typeof col.forEach == 'function') {\n col.forEach(f, opt_obj);\n } else if (goog.isArrayLike(col) || typeof col === 'string') {\n Array.prototype.forEach.call(/** @type {!Array<?>} */ (col), f, opt_obj);\n } else {\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n for (var i = 0; i < l; i++) {\n f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col);\n }\n }\n};\n\n\n/**\n * Calls a function for every value in the collection. When a call returns true,\n * adds the value to a new collection (Array is returned by default).\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\n * value. This function takes\n * 3 arguments (the value, the key or undefined if the collection has no\n * notion of keys, and the collection) and should return a Boolean. If the\n * return value is true the value is added to the result collection. If it\n * is false the value is not included.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {!Object|!Array<?>} A new collection where the passed values are\n * present. If col is a key-less collection an array is returned. If col\n * has keys and values a plain old JS object is returned.\n * @template T,S\n */\ngoog.structs.filter = function(col, f, opt_obj) {\n 'use strict';\n if (typeof col.filter == 'function') {\n return col.filter(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.filter.call(\n /** @type {!Array<?>} */ (col), f, opt_obj);\n }\n\n var rv;\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n if (keys) {\n rv = {};\n for (var i = 0; i < l; i++) {\n if (f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col)) {\n rv[keys[i]] = values[i];\n }\n }\n } else {\n // We should not use Array#filter here since we want to make sure that\n // the index is undefined as well as make sure that col is passed to the\n // function.\n rv = [];\n for (var i = 0; i < l; i++) {\n if (f.call(opt_obj, values[i], undefined, col)) {\n rv.push(values[i]);\n }\n }\n }\n return rv;\n};\n\n\n/**\n * Calls a function for every value in the collection and adds the result into a\n * new collection (defaults to creating a new Array).\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):V} f The function to call for every value.\n * This function takes 3 arguments (the value, the key or undefined if the\n * collection has no notion of keys, and the collection) and should return\n * something. The result will be used as the value in the new collection.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {!Object<V>|!Array<V>} A new collection with the new values. If\n * col is a key-less collection an array is returned. If col has keys and\n * values a plain old JS object is returned.\n * @template T,S,V\n */\ngoog.structs.map = function(col, f, opt_obj) {\n 'use strict';\n if (typeof col.map == 'function') {\n return col.map(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.map.call(/** @type {!Array<?>} */ (col), f, opt_obj);\n }\n\n var rv;\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n if (keys) {\n rv = {};\n for (var i = 0; i < l; i++) {\n rv[keys[i]] = f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col);\n }\n } else {\n // We should not use Array#map here since we want to make sure that\n // the index is undefined as well as make sure that col is passed to the\n // function.\n rv = [];\n for (var i = 0; i < l; i++) {\n rv[i] = f.call(/** @type {?} */ (opt_obj), values[i], undefined, col);\n }\n }\n return rv;\n};\n\n\n/**\n * Calls f for each value in a collection. If any call returns true this returns\n * true (without checking the rest). If all returns false this returns false.\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\n * value. This function takes 3 arguments (the value, the key or undefined\n * if the collection has no notion of keys, and the collection) and should\n * return a boolean.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {boolean} True if any value passes the test.\n * @template T,S\n */\ngoog.structs.some = function(col, f, opt_obj) {\n 'use strict';\n if (typeof col.some == 'function') {\n return col.some(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.some.call(\n /** @type {!Array<?>} */ (col), f, opt_obj);\n }\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) {\n return true;\n }\n }\n return false;\n};\n\n\n/**\n * Calls f for each value in a collection. If all calls return true this return\n * true this returns true. If any returns false this returns false at this point\n * and does not continue to check the remaining values.\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\n * value. This function takes 3 arguments (the value, the key or\n * undefined if the collection has no notion of keys, and the collection)\n * and should return a boolean.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {boolean} True if all key-value pairs pass the test.\n * @template T,S\n */\ngoog.structs.every = function(col, f, opt_obj) {\n 'use strict';\n if (typeof col.every == 'function') {\n return col.every(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.every.call(\n /** @type {!Array<?>} */ (col), f, opt_obj);\n }\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (!f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) {\n return false;\n }\n }\n return true;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Simple utilities for dealing with URI strings.\n *\n * This package is deprecated in favour of the Closure URL package (goog.url)\n * when manipulating URIs for use by a browser. This package uses regular\n * expressions to parse a potential URI which can fall out of sync with how a\n * browser will actually interpret the URI. See\n * `goog.uri.utils.setUrlPackageSupportLoggingHandler` for one way to identify\n * URIs that should instead be parsed using the URL package.\n *\n * This is intended to be a lightweight alternative to constructing goog.Uri\n * objects. Whereas goog.Uri adds several kilobytes to the binary regardless\n * of how much of its functionality you use, this is designed to be a set of\n * mostly-independent utilities so that the compiler includes only what is\n * necessary for the task. Estimated savings of porting is 5k pre-gzip and\n * 1.5k post-gzip. To ensure the savings remain, future developers should\n * avoid adding new functionality to existing functions, but instead create\n * new ones and factor out shared code.\n *\n * Many of these utilities have limited functionality, tailored to common\n * cases. The query parameter utilities assume that the parameter keys are\n * already encoded, since most keys are compile-time alphanumeric strings. The\n * query parameter mutation utilities also do not tolerate fragment identifiers.\n *\n * By design, these functions can be slower than goog.Uri equivalents.\n * Repeated calls to some of functions may be quadratic in behavior for IE,\n * although the effect is somewhat limited given the 2kb limit.\n *\n * One advantage of the limited functionality here is that this approach is\n * less sensitive to differences in URI encodings than goog.Uri, since these\n * functions operate on strings directly, rather than decoding them and\n * then re-encoding.\n *\n * Uses features of RFC 3986 for parsing/formatting URIs:\n * http://www.ietf.org/rfc/rfc3986.txt\n */\n\ngoog.provide('goog.uri.utils');\ngoog.provide('goog.uri.utils.ComponentIndex');\ngoog.provide('goog.uri.utils.QueryArray');\ngoog.provide('goog.uri.utils.QueryValue');\ngoog.provide('goog.uri.utils.StandardQueryParam');\n\ngoog.require('goog.asserts');\ngoog.require('goog.string');\n\n\n/**\n * Character codes inlined to avoid object allocations due to charCode.\n * @enum {number}\n * @private\n */\ngoog.uri.utils.CharCode_ = {\n AMPERSAND: 38,\n EQUAL: 61,\n HASH: 35,\n QUESTION: 63\n};\n\n\n/**\n * Builds a URI string from already-encoded parts.\n *\n * No encoding is performed. Any component may be omitted as either null or\n * undefined.\n *\n * @param {?string=} opt_scheme The scheme such as 'http'.\n * @param {?string=} opt_userInfo The user name before the '@'.\n * @param {?string=} opt_domain The domain such as 'www.google.com', already\n * URI-encoded.\n * @param {(string|number|null)=} opt_port The port number.\n * @param {?string=} opt_path The path, already URI-encoded. If it is not\n * empty, it must begin with a slash.\n * @param {?string=} opt_queryData The URI-encoded query data.\n * @param {?string=} opt_fragment The URI-encoded fragment identifier.\n * @return {string} The fully combined URI.\n */\ngoog.uri.utils.buildFromEncodedParts = function(\n opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData,\n opt_fragment) {\n 'use strict';\n var out = '';\n\n if (opt_scheme) {\n out += opt_scheme + ':';\n }\n\n if (opt_domain) {\n out += '//';\n\n if (opt_userInfo) {\n out += opt_userInfo + '@';\n }\n\n out += opt_domain;\n\n if (opt_port) {\n out += ':' + opt_port;\n }\n }\n\n if (opt_path) {\n out += opt_path;\n }\n\n if (opt_queryData) {\n out += '?' + opt_queryData;\n }\n\n if (opt_fragment) {\n out += '#' + opt_fragment;\n }\n\n return out;\n};\n\n\n/**\n * A regular expression for breaking a URI into its component parts.\n *\n * {@link http://www.ietf.org/rfc/rfc3986.txt} says in Appendix B\n * As the \"first-match-wins\" algorithm is identical to the \"greedy\"\n * disambiguation method used by POSIX regular expressions, it is natural and\n * commonplace to use a regular expression for parsing the potential five\n * components of a URI reference.\n *\n * The following line is the regular expression for breaking-down a\n * well-formed URI reference into its components.\n *\n * <pre>\n * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?\n * 12 3 4 5 6 7 8 9\n * </pre>\n *\n * The numbers in the second line above are only to assist readability; they\n * indicate the reference points for each subexpression (i.e., each paired\n * parenthesis). We refer to the value matched for subexpression <n> as $<n>.\n * For example, matching the above expression to\n * <pre>\n * http://www.ics.uci.edu/pub/ietf/uri/#Related\n * </pre>\n * results in the following subexpression matches:\n * <pre>\n * $1 = http:\n * $2 = http\n * $3 = //www.ics.uci.edu\n * $4 = www.ics.uci.edu\n * $5 = /pub/ietf/uri/\n * $6 = <undefined>\n * $7 = <undefined>\n * $8 = #Related\n * $9 = Related\n * </pre>\n * where <undefined> indicates that the component is not present, as is the\n * case for the query component in the above example. Therefore, we can\n * determine the value of the five components as\n * <pre>\n * scheme = $2\n * authority = $4\n * path = $5\n * query = $7\n * fragment = $9\n * </pre>\n *\n * The regular expression has been modified slightly to expose the\n * userInfo, domain, and port separately from the authority.\n * The modified version yields\n * <pre>\n * $1 = http scheme\n * $2 = <undefined> userInfo -\\\n * $3 = www.ics.uci.edu domain | authority\n * $4 = <undefined> port -/\n * $5 = /pub/ietf/uri/ path\n * $6 = <undefined> query without ?\n * $7 = Related fragment without #\n * </pre>\n *\n * TODO(user): separate out the authority terminating characters once this\n * file is moved to ES6.\n * @type {!RegExp}\n * @private\n */\ngoog.uri.utils.splitRe_ = new RegExp(\n '^' + // Anchor against the entire string.\n '(?:' +\n '([^:/?#.]+)' + // scheme - ignore special characters\n // used by other URL parts such as :,\n // ?, /, #, and .\n ':)?' +\n '(?://' +\n '(?:([^\\\\\\\\/?#]*)@)?' + // userInfo\n '([^\\\\\\\\/?#]*?)' + // domain\n '(?::([0-9]+))?' + // port\n '(?=[\\\\\\\\/?#]|$)' + // authority-terminating character.\n ')?' +\n '([^?#]+)?' + // path\n '(?:\\\\?([^#]*))?' + // query\n '(?:#([\\\\s\\\\S]*))?' + // fragment. Can't use '.*' with 's' flag as Firefox\n // doesn't support the flag, and can't use an\n // \"everything set\" ([^]) as IE10 doesn't match any\n // characters with it.\n '$');\n\n\n/**\n * The index of each URI component in the return value of goog.uri.utils.split.\n * @enum {number}\n */\ngoog.uri.utils.ComponentIndex = {\n SCHEME: 1,\n USER_INFO: 2,\n DOMAIN: 3,\n PORT: 4,\n PATH: 5,\n QUERY_DATA: 6,\n FRAGMENT: 7\n};\n\n/**\n * @type {?function(string)}\n * @private\n */\ngoog.uri.utils.urlPackageSupportLoggingHandler_ = null;\n\n/**\n * @param {?function(string)} handler The handler function to call when a URI\n * with a protocol that is better supported by the Closure URL package is\n * detected.\n */\ngoog.uri.utils.setUrlPackageSupportLoggingHandler = function(handler) {\n 'use strict';\n goog.uri.utils.urlPackageSupportLoggingHandler_ = handler;\n};\n\n/**\n * Splits a URI into its component parts.\n *\n * Each component can be accessed via the component indices; for example:\n * <pre>\n * goog.uri.utils.split(someStr)[goog.uri.utils.ComponentIndex.QUERY_DATA];\n * </pre>\n *\n * @param {string} uri The URI string to examine.\n * @return {!Array<string|undefined>} Each component still URI-encoded.\n * Each component that is present will contain the encoded value, whereas\n * components that are not present will be undefined or empty, depending\n * on the browser's regular expression implementation. Never null, since\n * arbitrary strings may still look like path names.\n */\ngoog.uri.utils.split = function(uri) {\n 'use strict';\n // See @return comment -- never null.\n var result = /** @type {!Array<string|undefined>} */ (\n uri.match(goog.uri.utils.splitRe_));\n if (goog.uri.utils.urlPackageSupportLoggingHandler_ &&\n ['http', 'https', 'ws', 'wss',\n 'ftp'].indexOf(result[goog.uri.utils.ComponentIndex.SCHEME]) >= 0) {\n goog.uri.utils.urlPackageSupportLoggingHandler_(uri);\n }\n return result;\n};\n\n\n/**\n * @param {?string} uri A possibly null string.\n * @param {boolean=} opt_preserveReserved If true, percent-encoding of RFC-3986\n * reserved characters will not be removed.\n * @return {?string} The string URI-decoded, or null if uri is null.\n * @private\n */\ngoog.uri.utils.decodeIfPossible_ = function(uri, opt_preserveReserved) {\n 'use strict';\n if (!uri) {\n return uri;\n }\n\n return opt_preserveReserved ? decodeURI(uri) : decodeURIComponent(uri);\n};\n\n\n/**\n * Gets a URI component by index.\n *\n * It is preferred to use the getPathEncoded() variety of functions ahead,\n * since they are more readable.\n *\n * @param {goog.uri.utils.ComponentIndex} componentIndex The component index.\n * @param {string} uri The URI to examine.\n * @return {?string} The still-encoded component, or null if the component\n * is not present.\n * @private\n */\ngoog.uri.utils.getComponentByIndex_ = function(componentIndex, uri) {\n 'use strict';\n // Convert undefined, null, and empty string into null.\n return goog.uri.utils.split(uri)[componentIndex] || null;\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The protocol or scheme, or null if none. Does not\n * include trailing colons or slashes.\n */\ngoog.uri.utils.getScheme = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.SCHEME, uri);\n};\n\n\n/**\n * Gets the effective scheme for the URL. If the URL is relative then the\n * scheme is derived from the page's location.\n * @param {string} uri The URI to examine.\n * @return {string} The protocol or scheme, always lower case.\n */\ngoog.uri.utils.getEffectiveScheme = function(uri) {\n 'use strict';\n var scheme = goog.uri.utils.getScheme(uri);\n if (!scheme && goog.global.self && goog.global.self.location) {\n var protocol = goog.global.self.location.protocol;\n scheme = protocol.slice(0, -1);\n }\n // NOTE: When called from a web worker in Firefox 3.5, location may be null.\n // All other browsers with web workers support self.location from the worker.\n return scheme ? scheme.toLowerCase() : '';\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The user name still encoded, or null if none.\n */\ngoog.uri.utils.getUserInfoEncoded = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.USER_INFO, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded user info, or null if none.\n */\ngoog.uri.utils.getUserInfo = function(uri) {\n 'use strict';\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getUserInfoEncoded(uri));\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The domain name still encoded, or null if none.\n */\ngoog.uri.utils.getDomainEncoded = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.DOMAIN, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded domain, or null if none.\n */\ngoog.uri.utils.getDomain = function(uri) {\n 'use strict';\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getDomainEncoded(uri), true /* opt_preserveReserved */);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?number} The port number, or null if none.\n */\ngoog.uri.utils.getPort = function(uri) {\n 'use strict';\n // Coerce to a number. If the result of getComponentByIndex_ is null or\n // non-numeric, the number coersion yields NaN. This will then return\n // null for all non-numeric cases (though also zero, which isn't a relevant\n // port number).\n return Number(\n goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.PORT, uri)) ||\n null;\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The path still encoded, or null if none. Includes the\n * leading slash, if any.\n */\ngoog.uri.utils.getPathEncoded = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.PATH, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded path, or null if none. Includes the leading\n * slash, if any.\n */\ngoog.uri.utils.getPath = function(uri) {\n 'use strict';\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getPathEncoded(uri), true /* opt_preserveReserved */);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The query data still encoded, or null if none. Does not\n * include the question mark itself.\n */\ngoog.uri.utils.getQueryData = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.QUERY_DATA, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The fragment identifier, or null if none. Does not\n * include the hash mark itself.\n */\ngoog.uri.utils.getFragmentEncoded = function(uri) {\n 'use strict';\n // The hash mark may not appear in any other part of the URL.\n var hashIndex = uri.indexOf('#');\n return hashIndex < 0 ? null : uri.slice(hashIndex + 1);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @param {?string} fragment The encoded fragment identifier, or null if none.\n * Does not include the hash mark itself.\n * @return {string} The URI with the fragment set.\n */\ngoog.uri.utils.setFragmentEncoded = function(uri, fragment) {\n 'use strict';\n return goog.uri.utils.removeFragment(uri) + (fragment ? '#' + fragment : '');\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded fragment identifier, or null if none. Does\n * not include the hash mark.\n */\ngoog.uri.utils.getFragment = function(uri) {\n 'use strict';\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getFragmentEncoded(uri));\n};\n\n\n/**\n * Extracts everything up to the port of the URI.\n * @param {string} uri The URI string.\n * @return {string} Everything up to and including the port.\n */\ngoog.uri.utils.getHost = function(uri) {\n 'use strict';\n var pieces = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n pieces[goog.uri.utils.ComponentIndex.SCHEME],\n pieces[goog.uri.utils.ComponentIndex.USER_INFO],\n pieces[goog.uri.utils.ComponentIndex.DOMAIN],\n pieces[goog.uri.utils.ComponentIndex.PORT]);\n};\n\n\n/**\n * Returns the origin for a given URL.\n * @param {string} uri The URI string.\n * @return {string} Everything up to and including the port.\n */\ngoog.uri.utils.getOrigin = function(uri) {\n 'use strict';\n var pieces = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n pieces[goog.uri.utils.ComponentIndex.SCHEME], null /* opt_userInfo */,\n pieces[goog.uri.utils.ComponentIndex.DOMAIN],\n pieces[goog.uri.utils.ComponentIndex.PORT]);\n};\n\n\n/**\n * Extracts the path of the URL and everything after.\n * @param {string} uri The URI string.\n * @return {string} The URI, starting at the path and including the query\n * parameters and fragment identifier.\n */\ngoog.uri.utils.getPathAndAfter = function(uri) {\n 'use strict';\n var pieces = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n null, null, null, null, pieces[goog.uri.utils.ComponentIndex.PATH],\n pieces[goog.uri.utils.ComponentIndex.QUERY_DATA],\n pieces[goog.uri.utils.ComponentIndex.FRAGMENT]);\n};\n\n\n/**\n * Gets the URI with the fragment identifier removed.\n * @param {string} uri The URI to examine.\n * @return {string} Everything preceding the hash mark.\n */\ngoog.uri.utils.removeFragment = function(uri) {\n 'use strict';\n // The hash mark may not appear in any other part of the URL.\n var hashIndex = uri.indexOf('#');\n return hashIndex < 0 ? uri : uri.slice(0, hashIndex);\n};\n\n\n/**\n * Ensures that two URI's have the exact same domain, scheme, and port.\n *\n * Unlike the version in goog.Uri, this checks protocol, and therefore is\n * suitable for checking against the browser's same-origin policy.\n *\n * @param {string} uri1 The first URI.\n * @param {string} uri2 The second URI.\n * @return {boolean} Whether they have the same scheme, domain and port.\n */\ngoog.uri.utils.haveSameDomain = function(uri1, uri2) {\n 'use strict';\n var pieces1 = goog.uri.utils.split(uri1);\n var pieces2 = goog.uri.utils.split(uri2);\n return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==\n pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&\n pieces1[goog.uri.utils.ComponentIndex.SCHEME] ==\n pieces2[goog.uri.utils.ComponentIndex.SCHEME] &&\n pieces1[goog.uri.utils.ComponentIndex.PORT] ==\n pieces2[goog.uri.utils.ComponentIndex.PORT];\n};\n\n\n/**\n * Asserts that there are no fragment or query identifiers, only in uncompiled\n * mode.\n * @param {string} uri The URI to examine.\n * @private\n */\ngoog.uri.utils.assertNoFragmentsOrQueries_ = function(uri) {\n 'use strict';\n goog.asserts.assert(\n uri.indexOf('#') < 0 && uri.indexOf('?') < 0,\n 'goog.uri.utils: Fragment or query identifiers are not supported: [%s]',\n uri);\n};\n\n\n/**\n * Supported query parameter values by the parameter serializing utilities.\n *\n * If a value is null or undefined, the key-value pair is skipped, as an easy\n * way to omit parameters conditionally. Non-array parameters are converted\n * to a string and URI encoded. Array values are expanded into multiple\n * &key=value pairs, with each element stringized and URI-encoded.\n *\n * @typedef {*}\n */\ngoog.uri.utils.QueryValue;\n\n\n/**\n * An array representing a set of query parameters with alternating keys\n * and values.\n *\n * Keys are assumed to be URI encoded already and live at even indices. See\n * goog.uri.utils.QueryValue for details on how parameter values are encoded.\n *\n * Example:\n * <pre>\n * var data = [\n * // Simple param: ?name=BobBarker\n * 'name', 'BobBarker',\n * // Conditional param -- may be omitted entirely.\n * 'specialDietaryNeeds', hasDietaryNeeds() ? getDietaryNeeds() : null,\n * // Multi-valued param: &house=LosAngeles&house=NewYork&house=null\n * 'house', ['LosAngeles', 'NewYork', null]\n * ];\n * </pre>\n *\n * @typedef {!Array<string|goog.uri.utils.QueryValue>}\n */\ngoog.uri.utils.QueryArray;\n\n\n/**\n * Parses encoded query parameters and calls callback function for every\n * parameter found in the string.\n *\n * Missing value of parameter (e.g. “…&key&…”) is treated as if the value was an\n * empty string. Keys may be empty strings (e.g. “…&=value&…”) which also means\n * that “…&=&…” and “…&&…” will result in an empty key and value.\n *\n * @param {string} encodedQuery Encoded query string excluding question mark at\n * the beginning.\n * @param {function(string, string)} callback Function called for every\n * parameter found in query string. The first argument (name) will not be\n * urldecoded (so the function is consistent with buildQueryData), but the\n * second will. If the parameter has no value (i.e. “=” was not present)\n * the second argument (value) will be an empty string.\n */\ngoog.uri.utils.parseQueryData = function(encodedQuery, callback) {\n 'use strict';\n if (!encodedQuery) {\n return;\n }\n var pairs = encodedQuery.split('&');\n for (var i = 0; i < pairs.length; i++) {\n var indexOfEquals = pairs[i].indexOf('=');\n var name = null;\n var value = null;\n if (indexOfEquals >= 0) {\n name = pairs[i].substring(0, indexOfEquals);\n value = pairs[i].substring(indexOfEquals + 1);\n } else {\n name = pairs[i];\n }\n callback(name, value ? goog.string.urlDecode(value) : '');\n }\n};\n\n\n/**\n * Split the URI into 3 parts where the [1] is the queryData without a leading\n * '?'. For example, the URI http://foo.com/bar?a=b#abc returns\n * ['http://foo.com/bar','a=b','#abc'].\n * @param {string} uri The URI to parse.\n * @return {!Array<string>} An array representation of uri of length 3 where the\n * middle value is the queryData without a leading '?'.\n * @private\n */\ngoog.uri.utils.splitQueryData_ = function(uri) {\n 'use strict';\n // Find the query data and hash.\n var hashIndex = uri.indexOf('#');\n if (hashIndex < 0) {\n hashIndex = uri.length;\n }\n var questionIndex = uri.indexOf('?');\n var queryData;\n if (questionIndex < 0 || questionIndex > hashIndex) {\n questionIndex = hashIndex;\n queryData = '';\n } else {\n queryData = uri.substring(questionIndex + 1, hashIndex);\n }\n return [uri.slice(0, questionIndex), queryData, uri.slice(hashIndex)];\n};\n\n\n/**\n * Join an array created by splitQueryData_ back into a URI.\n * @param {!Array<string>} parts A URI in the form generated by splitQueryData_.\n * @return {string} The joined URI.\n * @private\n */\ngoog.uri.utils.joinQueryData_ = function(parts) {\n 'use strict';\n return parts[0] + (parts[1] ? '?' + parts[1] : '') + parts[2];\n};\n\n\n/**\n * @param {string} queryData\n * @param {string} newData\n * @return {string}\n * @private\n */\ngoog.uri.utils.appendQueryData_ = function(queryData, newData) {\n 'use strict';\n if (!newData) {\n return queryData;\n }\n return queryData ? queryData + '&' + newData : newData;\n};\n\n\n/**\n * @param {string} uri\n * @param {string} queryData\n * @return {string}\n * @private\n */\ngoog.uri.utils.appendQueryDataToUri_ = function(uri, queryData) {\n 'use strict';\n if (!queryData) {\n return uri;\n }\n var parts = goog.uri.utils.splitQueryData_(uri);\n parts[1] = goog.uri.utils.appendQueryData_(parts[1], queryData);\n return goog.uri.utils.joinQueryData_(parts);\n};\n\n\n/**\n * Appends key=value pairs to an array, supporting multi-valued objects.\n * @param {*} key The key prefix.\n * @param {goog.uri.utils.QueryValue} value The value to serialize.\n * @param {!Array<string>} pairs The array to which the 'key=value' strings\n * should be appended.\n * @private\n */\ngoog.uri.utils.appendKeyValuePairs_ = function(key, value, pairs) {\n 'use strict';\n goog.asserts.assertString(key);\n if (Array.isArray(value)) {\n // Convince the compiler it's an array.\n goog.asserts.assertArray(value);\n for (var j = 0; j < value.length; j++) {\n // Convert to string explicitly, to short circuit the null and array\n // logic in this function -- this ensures that null and undefined get\n // written as literal 'null' and 'undefined', and arrays don't get\n // expanded out but instead encoded in the default way.\n goog.uri.utils.appendKeyValuePairs_(key, String(value[j]), pairs);\n }\n } else if (value != null) {\n // Skip a top-level null or undefined entirely.\n pairs.push(\n key +\n // Check for empty string. Zero gets encoded into the url as literal\n // strings. For empty string, skip the equal sign, to be consistent\n // with UriBuilder.java.\n (value === '' ? '' : '=' + goog.string.urlEncode(value)));\n }\n};\n\n\n/**\n * Builds a query data string from a sequence of alternating keys and values.\n * Currently generates \"&key&\" for empty args.\n *\n * @param {!IArrayLike<string|goog.uri.utils.QueryValue>} keysAndValues\n * Alternating keys and values. See the QueryArray typedef.\n * @param {number=} opt_startIndex A start offset into the arary, defaults to 0.\n * @return {string} The encoded query string, in the form 'a=1&b=2'.\n */\ngoog.uri.utils.buildQueryData = function(keysAndValues, opt_startIndex) {\n 'use strict';\n goog.asserts.assert(\n Math.max(keysAndValues.length - (opt_startIndex || 0), 0) % 2 == 0,\n 'goog.uri.utils: Key/value lists must be even in length.');\n\n var params = [];\n for (var i = opt_startIndex || 0; i < keysAndValues.length; i += 2) {\n var key = /** @type {string} */ (keysAndValues[i]);\n goog.uri.utils.appendKeyValuePairs_(key, keysAndValues[i + 1], params);\n }\n return params.join('&');\n};\n\n\n/**\n * Builds a query data string from a map.\n * Currently generates \"&key&\" for empty args.\n *\n * @param {!Object<string, goog.uri.utils.QueryValue>} map An object where keys\n * are URI-encoded parameter keys, and the values are arbitrary types\n * or arrays. Keys with a null value are dropped.\n * @return {string} The encoded query string, in the form 'a=1&b=2'.\n */\ngoog.uri.utils.buildQueryDataFromMap = function(map) {\n 'use strict';\n var params = [];\n for (var key in map) {\n goog.uri.utils.appendKeyValuePairs_(key, map[key], params);\n }\n return params.join('&');\n};\n\n\n/**\n * Appends URI parameters to an existing URI.\n *\n * The variable arguments may contain alternating keys and values. Keys are\n * assumed to be already URI encoded. The values should not be URI-encoded,\n * and will instead be encoded by this function.\n * <pre>\n * appendParams('http://www.foo.com?existing=true',\n * 'key1', 'value1',\n * 'key2', 'value?willBeEncoded',\n * 'key3', ['valueA', 'valueB', 'valueC'],\n * 'key4', null);\n * result: 'http://www.foo.com?existing=true&' +\n * 'key1=value1&' +\n * 'key2=value%3FwillBeEncoded&' +\n * 'key3=valueA&key3=valueB&key3=valueC'\n * </pre>\n *\n * A single call to this function will not exhibit quadratic behavior in IE,\n * whereas multiple repeated calls may, although the effect is limited by\n * fact that URL's generally can't exceed 2kb.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {...(goog.uri.utils.QueryArray|goog.uri.utils.QueryValue)}\n * var_args\n * An array or argument list conforming to goog.uri.utils.QueryArray.\n * @return {string} The URI with all query parameters added.\n */\ngoog.uri.utils.appendParams = function(uri, var_args) {\n 'use strict';\n var queryData = arguments.length == 2 ?\n goog.uri.utils.buildQueryData(arguments[1], 0) :\n goog.uri.utils.buildQueryData(arguments, 1);\n return goog.uri.utils.appendQueryDataToUri_(uri, queryData);\n};\n\n\n/**\n * Appends query parameters from a map.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {!Object<goog.uri.utils.QueryValue>} map An object where keys are\n * URI-encoded parameter keys, and the values are arbitrary types or arrays.\n * Keys with a null value are dropped.\n * @return {string} The new parameters.\n */\ngoog.uri.utils.appendParamsFromMap = function(uri, map) {\n 'use strict';\n var queryData = goog.uri.utils.buildQueryDataFromMap(map);\n return goog.uri.utils.appendQueryDataToUri_(uri, queryData);\n};\n\n\n/**\n * Appends a single URI parameter.\n *\n * Repeated calls to this can exhibit quadratic behavior in IE6 due to the\n * way string append works, though it should be limited given the 2kb limit.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {string} key The key, which must already be URI encoded.\n * @param {*=} opt_value The value, which will be stringized and encoded\n * (assumed not already to be encoded). If omitted, undefined, or null, the\n * key will be added as a valueless parameter.\n * @return {string} The URI with the query parameter added.\n */\ngoog.uri.utils.appendParam = function(uri, key, opt_value) {\n 'use strict';\n var value = (opt_value != null) ? '=' + goog.string.urlEncode(opt_value) : '';\n return goog.uri.utils.appendQueryDataToUri_(uri, key + value);\n};\n\n\n/**\n * Finds the next instance of a query parameter with the specified name.\n *\n * Does not instantiate any objects.\n *\n * @param {string} uri The URI to search. May contain a fragment identifier\n * if opt_hashIndex is specified.\n * @param {number} startIndex The index to begin searching for the key at. A\n * match may be found even if this is one character after the ampersand.\n * @param {string} keyEncoded The URI-encoded key.\n * @param {number} hashOrEndIndex Index to stop looking at. If a hash\n * mark is present, it should be its index, otherwise it should be the\n * length of the string.\n * @return {number} The position of the first character in the key's name,\n * immediately after either a question mark or a dot.\n * @private\n */\ngoog.uri.utils.findParam_ = function(\n uri, startIndex, keyEncoded, hashOrEndIndex) {\n 'use strict';\n var index = startIndex;\n var keyLength = keyEncoded.length;\n\n // Search for the key itself and post-filter for surronuding punctuation,\n // rather than expensively building a regexp.\n while ((index = uri.indexOf(keyEncoded, index)) >= 0 &&\n index < hashOrEndIndex) {\n var precedingChar = uri.charCodeAt(index - 1);\n // Ensure that the preceding character is '&' or '?'.\n if (precedingChar == goog.uri.utils.CharCode_.AMPERSAND ||\n precedingChar == goog.uri.utils.CharCode_.QUESTION) {\n // Ensure the following character is '&', '=', '#', or NaN\n // (end of string).\n var followingChar = uri.charCodeAt(index + keyLength);\n if (!followingChar || followingChar == goog.uri.utils.CharCode_.EQUAL ||\n followingChar == goog.uri.utils.CharCode_.AMPERSAND ||\n followingChar == goog.uri.utils.CharCode_.HASH) {\n return index;\n }\n }\n index += keyLength + 1;\n }\n\n return -1;\n};\n\n\n/**\n * Regular expression for finding a hash mark or end of string.\n * @type {RegExp}\n * @private\n */\ngoog.uri.utils.hashOrEndRe_ = /#|$/;\n\n\n/**\n * Determines if the URI contains a specific key.\n *\n * Performs no object instantiations.\n *\n * @param {string} uri The URI to process. May contain a fragment\n * identifier.\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\n * @return {boolean} Whether the key is present.\n */\ngoog.uri.utils.hasParam = function(uri, keyEncoded) {\n 'use strict';\n return goog.uri.utils.findParam_(\n uri, 0, keyEncoded, uri.search(goog.uri.utils.hashOrEndRe_)) >= 0;\n};\n\n\n/**\n * Gets the first value of a query parameter.\n * @param {string} uri The URI to process. May contain a fragment.\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\n * @return {?string} The first value of the parameter (URI-decoded), or null\n * if the parameter is not found.\n */\ngoog.uri.utils.getParamValue = function(uri, keyEncoded) {\n 'use strict';\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\n var foundIndex =\n goog.uri.utils.findParam_(uri, 0, keyEncoded, hashOrEndIndex);\n\n if (foundIndex < 0) {\n return null;\n } else {\n var endPosition = uri.indexOf('&', foundIndex);\n if (endPosition < 0 || endPosition > hashOrEndIndex) {\n endPosition = hashOrEndIndex;\n }\n // Progress forth to the end of the \"key=\" or \"key&\" substring.\n foundIndex += keyEncoded.length + 1;\n return goog.string.urlDecode(\n uri.slice(foundIndex, endPosition !== -1 ? endPosition : 0));\n }\n};\n\n\n/**\n * Gets all values of a query parameter.\n * @param {string} uri The URI to process. May contain a fragment.\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\n * @return {!Array<string>} All URI-decoded values with the given key.\n * If the key is not found, this will have length 0, but never be null.\n */\ngoog.uri.utils.getParamValues = function(uri, keyEncoded) {\n 'use strict';\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\n var position = 0;\n var foundIndex;\n var result = [];\n\n while ((foundIndex = goog.uri.utils.findParam_(\n uri, position, keyEncoded, hashOrEndIndex)) >= 0) {\n // Find where this parameter ends, either the '&' or the end of the\n // query parameters.\n position = uri.indexOf('&', foundIndex);\n if (position < 0 || position > hashOrEndIndex) {\n position = hashOrEndIndex;\n }\n\n // Progress forth to the end of the \"key=\" or \"key&\" substring.\n foundIndex += keyEncoded.length + 1;\n result.push(\n goog.string.urlDecode(uri.slice(foundIndex, Math.max(position, 0))));\n }\n\n return result;\n};\n\n\n/**\n * Regexp to find trailing question marks and ampersands.\n * @type {RegExp}\n * @private\n */\ngoog.uri.utils.trailingQueryPunctuationRe_ = /[?&]($|#)/;\n\n\n/**\n * Removes all instances of a query parameter.\n * @param {string} uri The URI to process. Must not contain a fragment.\n * @param {string} keyEncoded The URI-encoded key.\n * @return {string} The URI with all instances of the parameter removed.\n */\ngoog.uri.utils.removeParam = function(uri, keyEncoded) {\n 'use strict';\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\n var position = 0;\n var foundIndex;\n var buffer = [];\n\n // Look for a query parameter.\n while ((foundIndex = goog.uri.utils.findParam_(\n uri, position, keyEncoded, hashOrEndIndex)) >= 0) {\n // Get the portion of the query string up to, but not including, the ?\n // or & starting the parameter.\n buffer.push(uri.substring(position, foundIndex));\n // Progress to immediately after the '&'. If not found, go to the end.\n // Avoid including the hash mark.\n position = Math.min(\n (uri.indexOf('&', foundIndex) + 1) || hashOrEndIndex, hashOrEndIndex);\n }\n\n // Append everything that is remaining.\n buffer.push(uri.slice(position));\n\n // Join the buffer, and remove trailing punctuation that remains.\n return buffer.join('').replace(\n goog.uri.utils.trailingQueryPunctuationRe_, '$1');\n};\n\n\n/**\n * Replaces all existing definitions of a parameter with a single definition.\n *\n * Repeated calls to this can exhibit quadratic behavior due to the need to\n * find existing instances and reconstruct the string, though it should be\n * limited given the 2kb limit. Consider using appendParams or setParamsFromMap\n * to update multiple parameters in bulk.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {string} keyEncoded The key, which must already be URI encoded.\n * @param {*} value The value, which will be stringized and encoded (assumed\n * not already to be encoded).\n * @return {string} The URI with the query parameter added.\n */\ngoog.uri.utils.setParam = function(uri, keyEncoded, value) {\n 'use strict';\n return goog.uri.utils.appendParam(\n goog.uri.utils.removeParam(uri, keyEncoded), keyEncoded, value);\n};\n\n\n/**\n * Effeciently set or remove multiple query parameters in a URI. Order of\n * unchanged parameters will not be modified, all updated parameters will be\n * appended to the end of the query. Params with values of null or undefined are\n * removed.\n *\n * @param {string} uri The URI to process.\n * @param {!Object<string, goog.uri.utils.QueryValue>} params A list of\n * parameters to update. If null or undefined, the param will be removed.\n * @return {string} An updated URI where the query data has been updated with\n * the params.\n */\ngoog.uri.utils.setParamsFromMap = function(uri, params) {\n 'use strict';\n var parts = goog.uri.utils.splitQueryData_(uri);\n var queryData = parts[1];\n var buffer = [];\n if (queryData) {\n queryData.split('&').forEach(function(pair) {\n 'use strict';\n var indexOfEquals = pair.indexOf('=');\n var name = indexOfEquals >= 0 ? pair.slice(0, indexOfEquals) : pair;\n if (!params.hasOwnProperty(name)) {\n buffer.push(pair);\n }\n });\n }\n parts[1] = goog.uri.utils.appendQueryData_(\n buffer.join('&'), goog.uri.utils.buildQueryDataFromMap(params));\n return goog.uri.utils.joinQueryData_(parts);\n};\n\n\n/**\n * Generates a URI path using a given URI and a path with checks to\n * prevent consecutive \"//\". The baseUri passed in must not contain\n * query or fragment identifiers. The path to append may not contain query or\n * fragment identifiers.\n *\n * @param {string} baseUri URI to use as the base.\n * @param {string} path Path to append.\n * @return {string} Updated URI.\n */\ngoog.uri.utils.appendPath = function(baseUri, path) {\n 'use strict';\n goog.uri.utils.assertNoFragmentsOrQueries_(baseUri);\n\n // Remove any trailing '/'\n if (goog.string.endsWith(baseUri, '/')) {\n baseUri = baseUri.slice(0, -1);\n }\n // Remove any leading '/'\n if (goog.string.startsWith(path, '/')) {\n path = path.slice(1);\n }\n return '' + baseUri + '/' + path;\n};\n\n\n/**\n * Replaces the path.\n * @param {string} uri URI to use as the base.\n * @param {string} path New path.\n * @return {string} Updated URI.\n */\ngoog.uri.utils.setPath = function(uri, path) {\n 'use strict';\n // Add any missing '/'.\n if (!goog.string.startsWith(path, '/')) {\n path = '/' + path;\n }\n var parts = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n parts[goog.uri.utils.ComponentIndex.SCHEME],\n parts[goog.uri.utils.ComponentIndex.USER_INFO],\n parts[goog.uri.utils.ComponentIndex.DOMAIN],\n parts[goog.uri.utils.ComponentIndex.PORT], path,\n parts[goog.uri.utils.ComponentIndex.QUERY_DATA],\n parts[goog.uri.utils.ComponentIndex.FRAGMENT]);\n};\n\n\n/**\n * Standard supported query parameters.\n * @enum {string}\n */\ngoog.uri.utils.StandardQueryParam = {\n\n /** Unused parameter for unique-ifying. */\n RANDOM: 'zx'\n};\n\n\n/**\n * Sets the zx parameter of a URI to a random value.\n * @param {string} uri Any URI.\n * @return {string} That URI with the \"zx\" parameter added or replaced to\n * contain a random string.\n */\ngoog.uri.utils.makeUnique = function(uri) {\n 'use strict';\n return goog.uri.utils.setParam(\n uri, goog.uri.utils.StandardQueryParam.RANDOM,\n goog.string.getRandomString());\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Interface and shared data structures for implementing\n * different wire protocol versions.\n */\ngoog.provide('goog.labs.net.webChannel.Wire');\ngoog.provide('goog.labs.net.webChannel.Wire.QueuedMap');\n\n\n\ngoog.require('goog.collections.maps');\n\n\n\n/**\n * The interface class.\n * @interface\n */\ngoog.labs.net.webChannel.Wire = class {\n constructor() {}\n};\n\n\n/**\n * The latest protocol version that this class supports. We request this version\n * from the server when opening the connection. Should match\n * LATEST_CHANNEL_VERSION on the server code.\n * @type {number}\n */\ngoog.labs.net.webChannel.Wire.LATEST_CHANNEL_VERSION = 8;\n\n\n/**\n * The JSON field key for the raw data wrapper object.\n * @type {string}\n */\ngoog.labs.net.webChannel.Wire.RAW_DATA_KEY = '__data__';\n\n\n\n/**\n * Simple container class for a (mapId, map) pair.\n */\ngoog.labs.net.webChannel.Wire.QueuedMap = class {\n /**\n * @param {number} mapId The id for this map.\n * @param {!Object|!goog.collections.maps.MapLike} map The map itself.\n * @param {!Object=} opt_context The context associated with the map.\n */\n constructor(mapId, map, opt_context) {\n 'use strict';\n /**\n * The id for this map.\n * @type {number}\n */\n this.mapId = mapId;\n\n /**\n * The map itself.\n * @type {!Object|!goog.collections.maps.MapLike}\n */\n this.map = map;\n\n /**\n * The context for the map.\n * @type {Object}\n */\n this.context = opt_context || null;\n }\n\n /**\n * @return {number|undefined} the size of the raw JSON message or\n * undefined if the message is not encoded as a raw JSON message\n */\n getRawDataSize() {\n 'use strict';\n if (goog.labs.net.webChannel.Wire.RAW_DATA_KEY in this.map) {\n const data = this.map[goog.labs.net.webChannel.Wire.RAW_DATA_KEY];\n if (typeof data === 'string') {\n return data.length;\n }\n }\n\n return undefined;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n\n/**\n * @fileoverview Defines a class for parsing JSON using the browser's built in\n * JSON library.\n */\n\ngoog.module('goog.json.NativeJsonProcessor');\ngoog.module.declareLegacyNamespace();\n\nconst Parser = goog.require('goog.string.Parser');\nconst Stringifier = goog.require('goog.string.Stringifier');\nconst asserts = goog.require('goog.asserts');\nconst {Replacer, Reviver} = goog.require('goog.json.types');\n\n\n\n/**\n * A class that parses and stringifies JSON using the browser's built-in JSON\n * library.\n *\n\n * @implements {Parser}\n * @implements {Stringifier}\n * @final\n */\nexports = class {\n /**\n * @param {?Replacer=} opt_replacer An optional replacer to use during\n * serialization.\n * @param {?=} opt_reviver An optional reviver to use during\n * parsing.\n */\n constructor(opt_replacer, opt_reviver) {\n asserts.assert(goog.global['JSON'] !== undefined, 'JSON not defined');\n\n /**\n * @type {!Replacer|null|undefined}\n * @private\n */\n this.replacer_ = opt_replacer;\n\n /**\n * @type {!Reviver|null|undefined}\n * @private\n */\n this.reviver_ = opt_reviver;\n };\n\n /**\n * Serializes an object or a value to a string.\n * Agnostic to the particular format of object and string.\n *\n * @param {*} object The object to stringify.\n * @return {string} A string representation of the input.\n * @override\n */\n stringify(object) {\n return goog.global['JSON'].stringify(object, this.replacer_);\n }\n\n /**\n * Parses a string into an object and returns the result.\n * Agnostic to the format of string and object.\n *\n * @param {string} s The string to parse.\n * @return {*} The object generated from the string.\n * @override\n */\n parse(s) {\n return goog.global['JSON'].parse(s, this.reviver_);\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for creating functions. Loosely inspired by these\n * java classes from the Guava library:\n * com.google.common.base.Functions\n * https://google.github.io/guava/releases/snapshot-jre/api/docs/index.html?com/google/common/base/Functions.html\n *\n * com.google.common.base.Predicates\n * https://google.github.io/guava/releases/snapshot-jre/api/docs/index.html?com/google/common/base/Predicates.html\n *\n * More about these can be found at\n * https://github.com/google/guava/wiki/FunctionalExplained\n */\n\n\ngoog.provide('goog.functions');\n\n\n/**\n * Creates a function that always returns the same value.\n * @param {T} retValue The value to return.\n * @return {function():T} The new function.\n * @template T\n */\ngoog.functions.constant = function(retValue) {\n 'use strict';\n return function() {\n 'use strict';\n return retValue;\n };\n};\n\n\n/**\n * Always returns false.\n * @type {function(...): boolean}\n */\ngoog.functions.FALSE = function() {\n 'use strict';\n return false;\n};\n\n\n/**\n * Always returns true.\n * @type {function(...): boolean}\n */\ngoog.functions.TRUE = function() {\n 'use strict';\n return true;\n};\n\n\n/**\n * Always returns `null`.\n * @type {function(...): null}\n */\ngoog.functions.NULL = function() {\n 'use strict';\n return null;\n};\n\n\n/**\n * Always returns `undefined`.\n * @type {function(...): undefined}\n */\ngoog.functions.UNDEFINED = function() {\n return undefined;\n};\n\n/**\n * Always returns `undefined` (loosely-typed version).\n * @type {!Function}\n */\ngoog.functions.EMPTY = /** @type {?} */ (goog.functions.UNDEFINED);\n\n\n/**\n * A simple function that returns the first argument of whatever is passed\n * into it.\n * @param {T=} opt_returnValue The single value that will be returned.\n * @param {...*} var_args Optional trailing arguments. These are ignored.\n * @return {T} The first argument passed in, or undefined if nothing was passed.\n * @template T\n */\ngoog.functions.identity = function(opt_returnValue, var_args) {\n 'use strict';\n return opt_returnValue;\n};\n\n\n/**\n * Creates a function that always throws an error with the given message.\n * @param {string} message The error message.\n * @return {!Function} The error-throwing function.\n */\ngoog.functions.error = function(message) {\n 'use strict';\n return function() {\n 'use strict';\n throw new Error(message);\n };\n};\n\n\n/**\n * Creates a function that throws the given object.\n * @param {*} err An object to be thrown.\n * @return {!Function} The error-throwing function.\n */\ngoog.functions.fail = function(err) {\n 'use strict';\n return function() {\n 'use strict';\n throw err;\n };\n};\n\n\n/**\n * Given a function, create a function that keeps opt_numArgs arguments and\n * silently discards all additional arguments.\n * @param {Function} f The original function.\n * @param {number=} opt_numArgs The number of arguments to keep. Defaults to 0.\n * @return {!Function} A version of f that only keeps the first opt_numArgs\n * arguments.\n */\ngoog.functions.lock = function(f, opt_numArgs) {\n 'use strict';\n opt_numArgs = opt_numArgs || 0;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n return f.apply(self, Array.prototype.slice.call(arguments, 0, opt_numArgs));\n };\n};\n\n\n/**\n * Creates a function that returns its nth argument.\n * @param {number} n The position of the return argument.\n * @return {!Function} A new function.\n */\ngoog.functions.nth = function(n) {\n 'use strict';\n return function() {\n 'use strict';\n return arguments[n];\n };\n};\n\n\n/**\n * Like goog.partial(), except that arguments are added after arguments to the\n * returned function.\n *\n * Usage:\n * function f(arg1, arg2, arg3, arg4) { ... }\n * var g = goog.functions.partialRight(f, arg3, arg4);\n * g(arg1, arg2);\n *\n * @param {!Function} fn A function to partially apply.\n * @param {...*} var_args Additional arguments that are partially applied to fn\n * at the end.\n * @return {!Function} A partially-applied form of the function goog.partial()\n * was invoked as a method of.\n */\ngoog.functions.partialRight = function(fn, var_args) {\n 'use strict';\n const rightArgs = Array.prototype.slice.call(arguments, 1);\n return function() {\n 'use strict';\n // Even in strict mode, IE10/11 and Edge (non-Chromium) use global context\n // when free-calling functions. To catch cases where people were using this\n // erroneously, we explicitly change the context to undefined to match\n // strict mode specifications.\n let self = /** @type {*} */ (this);\n if (self === goog.global) {\n self = undefined;\n }\n const newArgs = Array.prototype.slice.call(arguments);\n newArgs.push.apply(newArgs, rightArgs);\n return fn.apply(self, newArgs);\n };\n};\n\n\n/**\n * Given a function, create a new function that swallows its return value\n * and replaces it with a new one.\n * @param {Function} f A function.\n * @param {T} retValue A new return value.\n * @return {function(...?):T} A new function.\n * @template T\n */\ngoog.functions.withReturnValue = function(f, retValue) {\n 'use strict';\n return goog.functions.sequence(f, goog.functions.constant(retValue));\n};\n\n\n/**\n * Creates a function that returns whether its argument equals the given value.\n *\n * Example:\n * var key = goog.object.findKey(obj, goog.functions.equalTo('needle'));\n *\n * @param {*} value The value to compare to.\n * @param {boolean=} opt_useLooseComparison Whether to use a loose (==)\n * comparison rather than a strict (===) one. Defaults to false.\n * @return {function(*):boolean} The new function.\n */\ngoog.functions.equalTo = function(value, opt_useLooseComparison) {\n 'use strict';\n return function(other) {\n 'use strict';\n return opt_useLooseComparison ? (value == other) : (value === other);\n };\n};\n\n\n/**\n * Creates the composition of the functions passed in.\n * For example, (goog.functions.compose(f, g))(a) is equivalent to f(g(a)).\n * @param {function(...?):T} fn The final function.\n * @param {...Function} var_args A list of functions.\n * @return {function(...?):T} The composition of all inputs.\n * @template T\n */\ngoog.functions.compose = function(fn, var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n let result;\n if (length) {\n result = functions[length - 1].apply(self, arguments);\n }\n\n for (let i = length - 2; i >= 0; i--) {\n result = functions[i].call(self, result);\n }\n return result;\n };\n};\n\n\n/**\n * Creates a function that calls the functions passed in in sequence, and\n * returns the value of the last function. For example,\n * (goog.functions.sequence(f, g))(x) is equivalent to f(x),g(x).\n * @param {...Function} var_args A list of functions.\n * @return {!Function} A function that calls all inputs in sequence.\n */\ngoog.functions.sequence = function(var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n let result;\n for (let i = 0; i < length; i++) {\n result = functions[i].apply(self, arguments);\n }\n return result;\n };\n};\n\n\n/**\n * Creates a function that returns true if each of its components evaluates\n * to true. The components are evaluated in order, and the evaluation will be\n * short-circuited as soon as a function returns false.\n * For example, (goog.functions.and(f, g))(x) is equivalent to f(x) && g(x).\n * @param {...Function} var_args A list of functions.\n * @return {function(...?):boolean} A function that ANDs its component\n * functions.\n */\ngoog.functions.and = function(var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n for (let i = 0; i < length; i++) {\n if (!functions[i].apply(self, arguments)) {\n return false;\n }\n }\n return true;\n };\n};\n\n\n/**\n * Creates a function that returns true if any of its components evaluates\n * to true. The components are evaluated in order, and the evaluation will be\n * short-circuited as soon as a function returns true.\n * For example, (goog.functions.or(f, g))(x) is equivalent to f(x) || g(x).\n * @param {...Function} var_args A list of functions.\n * @return {function(...?):boolean} A function that ORs its component\n * functions.\n */\ngoog.functions.or = function(var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n for (let i = 0; i < length; i++) {\n if (functions[i].apply(self, arguments)) {\n return true;\n }\n }\n return false;\n };\n};\n\n\n/**\n * Creates a function that returns the Boolean opposite of a provided function.\n * For example, (goog.functions.not(f))(x) is equivalent to !f(x).\n * @param {!Function} f The original function.\n * @return {function(...?):boolean} A function that delegates to f and returns\n * opposite.\n */\ngoog.functions.not = function(f) {\n 'use strict';\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n return !f.apply(self, arguments);\n };\n};\n\n\n/**\n * Generic factory function to construct an object given the constructor\n * and the arguments. Intended to be bound to create object factories.\n *\n * Example:\n *\n * var factory = goog.partial(goog.functions.create, Class);\n *\n * @param {function(new:T, ...)} constructor The constructor for the Object.\n * @param {...*} var_args The arguments to be passed to the constructor.\n * @return {T} A new instance of the class given in `constructor`.\n * @template T\n * @deprecated This function does not work with ES6 class constructors. Use\n * arrow functions + spread args instead.\n */\ngoog.functions.create = function(constructor, var_args) {\n 'use strict';\n /**\n * @constructor\n * @final\n */\n const temp = function() {};\n temp.prototype = constructor.prototype;\n\n // obj will have constructor's prototype in its chain and\n // 'obj instanceof constructor' will be true.\n const obj = new temp();\n\n // obj is initialized by constructor.\n // arguments is only array-like so lacks shift(), but can be used with\n // the Array prototype function.\n constructor.apply(obj, Array.prototype.slice.call(arguments, 1));\n return obj;\n};\n\n\n/**\n * @define {boolean} Whether the return value cache should be used.\n * This should only be used to disable caches when testing.\n */\ngoog.functions.CACHE_RETURN_VALUE =\n goog.define('goog.functions.CACHE_RETURN_VALUE', true);\n\n\n/**\n * Gives a wrapper function that caches the return value of a parameterless\n * function when first called.\n *\n * When called for the first time, the given function is called and its\n * return value is cached (thus this is only appropriate for idempotent\n * functions). Subsequent calls will return the cached return value. This\n * allows the evaluation of expensive functions to be delayed until first used.\n *\n * To cache the return values of functions with parameters, see goog.memoize.\n *\n * @param {function():T} fn A function to lazily evaluate.\n * @return {function():T} A wrapped version the function.\n * @template T\n */\ngoog.functions.cacheReturnValue = function(fn) {\n 'use strict';\n let called = false;\n let value;\n\n return function() {\n 'use strict';\n if (!goog.functions.CACHE_RETURN_VALUE) {\n return fn();\n }\n\n if (!called) {\n value = fn();\n called = true;\n }\n\n return value;\n };\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once. All\n * additional calls are no-ops.\n *\n * This is particularly useful for initialization functions\n * that should be called, at most, once.\n *\n * @param {function():*} f Function to call.\n * @return {function():undefined} Wrapped function.\n */\ngoog.functions.once = function(f) {\n 'use strict';\n // Keep a reference to the function that we null out when we're done with\n // it -- that way, the function can be GC'd when we're done with it.\n let inner = f;\n return function() {\n 'use strict';\n if (inner) {\n const tmp = inner;\n inner = null;\n tmp();\n }\n };\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once per interval\n * (specified in milliseconds). If the wrapper function is called N times within\n * that interval, only the Nth call will go through.\n *\n * This is particularly useful for batching up repeated actions where the\n * last action should win. This can be used, for example, for refreshing an\n * autocomplete pop-up every so often rather than updating with every keystroke,\n * since the final text typed by the user is the one that should produce the\n * final autocomplete results. For more stateful debouncing with support for\n * pausing, resuming, and canceling debounced actions, use\n * `goog.async.Debouncer`.\n *\n * @param {function(this:SCOPE, ...?)} f Function to call.\n * @param {number} interval Interval over which to debounce. The function will\n * only be called after the full interval has elapsed since the last call.\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\n * @return {function(...?): undefined} Wrapped function.\n * @template SCOPE\n */\ngoog.functions.debounce = function(f, interval, opt_scope) {\n 'use strict';\n let timeout = 0;\n return /** @type {function(...?)} */ (function(var_args) {\n 'use strict';\n goog.global.clearTimeout(timeout);\n const args = arguments;\n timeout = goog.global.setTimeout(function() {\n 'use strict';\n f.apply(opt_scope, args);\n }, interval);\n });\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once per interval\n * (specified in milliseconds). If the wrapper function is called N times in\n * that interval, both the 1st and the Nth calls will go through.\n *\n * This is particularly useful for limiting repeated user requests where the\n * the last action should win, but you also don't want to wait until the end of\n * the interval before sending a request out, as it leads to a perception of\n * slowness for the user.\n *\n * @param {function(this:SCOPE, ...?)} f Function to call.\n * @param {number} interval Interval over which to throttle. The function can\n * only be called once per interval.\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\n * @return {function(...?): undefined} Wrapped function.\n * @template SCOPE\n */\ngoog.functions.throttle = function(f, interval, opt_scope) {\n 'use strict';\n let timeout = 0;\n let shouldFire = false;\n let storedArgs = [];\n\n const handleTimeout = function() {\n 'use strict';\n timeout = 0;\n if (shouldFire) {\n shouldFire = false;\n fire();\n }\n };\n\n const fire = function() {\n 'use strict';\n timeout = goog.global.setTimeout(handleTimeout, interval);\n let args = storedArgs;\n storedArgs = []; // Avoid a space leak by clearing stored arguments.\n f.apply(opt_scope, args);\n };\n\n return /** @type {function(...?)} */ (function(var_args) {\n 'use strict';\n storedArgs = arguments;\n if (!timeout) {\n fire();\n } else {\n shouldFire = true;\n }\n });\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once per interval\n * (specified in milliseconds). If the wrapper function is called N times within\n * that interval, only the 1st call will go through.\n *\n * This is particularly useful for limiting repeated user requests where the\n * first request is guaranteed to have all the data required to perform the\n * final action, so there's no need to wait until the end of the interval before\n * sending the request out.\n *\n * @param {function(this:SCOPE, ...?)} f Function to call.\n * @param {number} interval Interval over which to rate-limit. The function will\n * only be called once per interval, and ignored for the remainer of the\n * interval.\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\n * @return {function(...?): undefined} Wrapped function.\n * @template SCOPE\n */\ngoog.functions.rateLimit = function(f, interval, opt_scope) {\n 'use strict';\n let timeout = 0;\n\n const handleTimeout = function() {\n 'use strict';\n timeout = 0;\n };\n\n return /** @type {function(...?)} */ (function(var_args) {\n 'use strict';\n if (!timeout) {\n timeout = goog.global.setTimeout(handleTimeout, interval);\n f.apply(opt_scope, arguments);\n }\n });\n};\n\n/**\n * Returns true if the specified value is a function.\n * @param {*} val Variable to test.\n * @return {boolean} Whether variable is a function.\n */\ngoog.functions.isFunction = (val) => {\n return typeof val === 'function';\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utility functions for managing networking, such as\n * testing network connectivity.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.netUtils');\n\ngoog.require('goog.Uri');\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\n\ngoog.scope(function() {\n'use strict';\nconst netUtils = goog.labs.net.webChannel.netUtils;\nconst WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\n\n\n/**\n * Default timeout to allow for URI pings.\n * @type {number}\n */\nnetUtils.NETWORK_TIMEOUT = 10000;\n\n\n/**\n * Pings the network with an image URI to check if an error is a server error\n * or user's network error.\n *\n * The caller needs to add a 'rand' parameter to make sure the response is\n * not fulfilled by browser cache.\n *\n * @param {function(boolean)} callback The function to call back with results.\n * @param {goog.Uri=} opt_imageUri The URI (of an image) to use for the network\n * test.\n */\nnetUtils.testNetwork = function(callback, opt_imageUri) {\n 'use strict';\n let uri = opt_imageUri;\n if (!uri) {\n // default google.com image\n uri = new goog.Uri('//www.google.com/images/cleardot.gif');\n\n if (!(goog.global.location && goog.global.location.protocol == 'http')) {\n uri.setScheme('https'); // e.g. chrome-extension\n }\n uri.makeUnique();\n }\n\n netUtils.testLoadImage(uri.toString(), netUtils.NETWORK_TIMEOUT, callback);\n};\n\n\n/**\n * Test loading the given image, retrying if necessary.\n * @param {string} url URL to the image.\n * @param {number} timeout Milliseconds before giving up.\n * @param {function(boolean)} callback Function to call with results.\n * @param {number} retries The number of times to retry.\n * @param {!WebChannelDebug} channelDebug The debug object\n * @param {number=} opt_pauseBetweenRetriesMS Optional number of milliseconds\n * between retries - defaults to 0.\n */\nnetUtils.testLoadImageWithRetries = function(\n url, timeout, callback, retries, channelDebug, opt_pauseBetweenRetriesMS) {\n 'use strict';\n channelDebug.debug('TestLoadImageWithRetries: ' + opt_pauseBetweenRetriesMS);\n if (retries == 0) {\n // no more retries, give up\n callback(false);\n return;\n }\n\n const pauseBetweenRetries = opt_pauseBetweenRetriesMS || 0;\n retries--;\n netUtils.testLoadImage(url, timeout, function(succeeded) {\n 'use strict';\n if (succeeded) {\n callback(true);\n } else {\n // try again\n goog.global.setTimeout(function() {\n 'use strict';\n netUtils.testLoadImageWithRetries(\n url, timeout, callback, retries, channelDebug, pauseBetweenRetries);\n }, pauseBetweenRetries);\n }\n });\n};\n\n\n/**\n * Test loading the given image.\n * @param {string} url URL to the image.\n * @param {number} timeout Milliseconds before giving up.\n * @param {function(boolean)} callback Function to call with results.\n * @suppress {strictMissingProperties} Part of the go/strict_warnings_migration\n */\nnetUtils.testLoadImage = function(url, timeout, callback) {\n 'use strict';\n const channelDebug = new WebChannelDebug();\n channelDebug.debug('TestLoadImage: loading ' + url);\n if (goog.global.Image) {\n const img = new Image();\n img.onload = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: loaded',\n true, callback);\n img.onerror = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: error',\n false, callback);\n img.onabort = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: abort',\n false, callback);\n img.ontimeout = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: timeout',\n false, callback);\n\n goog.global.setTimeout(function() {\n 'use strict';\n if (img.ontimeout) {\n img.ontimeout();\n }\n }, timeout);\n img.src = url;\n } else {\n // log ERROR_OTHER from environements where Image is not supported\n callback(false);\n }\n};\n\n\n/**\n * Wrap the image callback with debug and cleanup logic.\n * @param {!WebChannelDebug} channelDebug The WebChannelDebug object.\n * @param {!Image} img The image element.\n * @param {string} debugText The debug text.\n * @param {boolean} result The result of image loading.\n * @param {function(boolean)} callback The image callback.\n * @private\n */\nnetUtils.imageCallback_ = function(\n channelDebug, img, debugText, result, callback) {\n 'use strict';\n try {\n channelDebug.debug(debugText);\n netUtils.clearImageCallbacks_(img);\n callback(result);\n } catch (e) {\n channelDebug.dumpException(e);\n }\n};\n\n\n/**\n * Clears handlers to avoid memory leaks.\n * @param {Image} img The image to clear handlers from.\n * @private\n * @suppress {strictMissingProperties} Part of the go/strict_warnings_migration\n */\nnetUtils.clearImageCallbacks_ = function(img) {\n 'use strict';\n img.onload = null;\n img.onerror = null;\n img.onabort = null;\n img.ontimeout = null;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.provide('goog.net.FetchXmlHttp');\ngoog.provide('goog.net.FetchXmlHttpFactory');\n\ngoog.require('goog.asserts');\ngoog.require('goog.events.EventTarget');\ngoog.require('goog.functions');\ngoog.require('goog.log');\ngoog.require('goog.net.XhrLike');\ngoog.require('goog.net.XmlHttpFactory');\n\n\n\n/**\n * @record\n */\ngoog.net.FetchXmlHttpFactoryOptions = function() {\n /**\n * @type {!WorkerGlobalScope|undefined} The Service Worker global scope.\n */\n this.worker;\n\n /**\n * @type {boolean|undefined} Whether to store the FetchXmlHttp response as an\n * array of Uint8Arrays. If this is true then the 'responseType' attribute\n * must be empty.\n */\n this.streamBinaryChunks;\n};\n\n\n\n/**\n * Factory for creating Xhr objects that uses the native fetch() method.\n * https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\n * @param {!goog.net.FetchXmlHttpFactoryOptions} opts\n * @extends {goog.net.XmlHttpFactory}\n * @struct\n * @constructor\n */\ngoog.net.FetchXmlHttpFactory = function(opts) {\n 'use strict';\n goog.net.FetchXmlHttpFactory.base(this, 'constructor');\n\n /** @private @final {?WorkerGlobalScope} */\n this.worker_ = opts.worker || null;\n\n /** @private @final {boolean} */\n this.streamBinaryChunks_ = opts.streamBinaryChunks || false;\n\n /** @private {!RequestCredentials|undefined} */\n this.credentialsMode_ = undefined;\n\n /** @private {!RequestCache|undefined} */\n this.cacheMode_ = undefined;\n};\ngoog.inherits(goog.net.FetchXmlHttpFactory, goog.net.XmlHttpFactory);\n\n\n/** @override */\ngoog.net.FetchXmlHttpFactory.prototype.createInstance = function() {\n 'use strict';\n const instance =\n new goog.net.FetchXmlHttp(this.worker_, this.streamBinaryChunks_);\n if (this.credentialsMode_) {\n instance.setCredentialsMode(this.credentialsMode_);\n }\n if (this.cacheMode_) {\n instance.setCacheMode(this.cacheMode_);\n }\n return instance;\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttpFactory.prototype.internalGetOptions =\n goog.functions.constant({});\n\n\n/**\n * @param {!RequestCredentials} credentialsMode The credentials mode of the\n * Service Worker fetch.\n */\ngoog.net.FetchXmlHttpFactory.prototype.setCredentialsMode = function(\n credentialsMode) {\n 'use strict';\n this.credentialsMode_ = credentialsMode;\n};\n\n\n/**\n * @param {!RequestCache} cacheMode The cache mode of the Service Worker fetch.\n */\ngoog.net.FetchXmlHttpFactory.prototype.setCacheMode = function(cacheMode) {\n 'use strict';\n this.cacheMode_ = cacheMode;\n};\n\n\n\n/**\n * FetchXmlHttp object constructor.\n * @param {?WorkerGlobalScope} worker\n * @param {boolean} streamBinaryChunks\n * @extends {goog.events.EventTarget}\n * @implements {goog.net.XhrLike}\n * @constructor\n * @struct\n */\ngoog.net.FetchXmlHttp = function(worker, streamBinaryChunks) {\n 'use strict';\n goog.net.FetchXmlHttp.base(this, 'constructor');\n\n /** @private @final {?WorkerGlobalScope} */\n this.worker_ = worker;\n\n /** @private @final {boolean} */\n this.streamBinaryChunks_ = streamBinaryChunks;\n\n /** @private {RequestCredentials|undefined} */\n this.credentialsMode_ = undefined;\n\n /** @private {RequestCache|undefined} */\n this.cacheMode_ = undefined;\n\n /**\n * Request state.\n * @type {goog.net.FetchXmlHttp.RequestState}\n */\n this.readyState = goog.net.FetchXmlHttp.RequestState.UNSENT;\n\n /**\n * HTTP status.\n * @type {number}\n */\n this.status = 0;\n\n /**\n * HTTP status string.\n * @type {string}\n */\n this.statusText = '';\n\n /**\n * Content of the response.\n * @type {string|!ArrayBuffer|!Array<!Uint8Array>}\n */\n this.response = '';\n\n /**\n * Content of the response.\n * @type {string}\n */\n this.responseText = '';\n\n /**\n * The type of the response. If this is set to 'arraybuffer' the request will\n * be discrete, streaming is only supported for text encoded requests.\n * @type {string}\n */\n this.responseType = '';\n\n /**\n * Document response entity body.\n * NOTE: This is always null and not supported by this class.\n * @final {null}\n */\n this.responseXML = null;\n\n /**\n * Method to call when the state changes.\n * @type {?function()}\n */\n this.onreadystatechange = null;\n\n /** @private {!Headers} */\n this.requestHeaders_ = new Headers();\n\n /** @private {?Headers} */\n this.responseHeaders_ = null;\n\n /**\n * Request method (GET or POST).\n * @private {string}\n */\n this.method_ = 'GET';\n\n /**\n * Request URL.\n * @private {string}\n */\n this.url_ = '';\n\n /**\n * Whether the request is in progress.\n * @private {boolean}\n */\n this.inProgress_ = false;\n\n /** @private @final {?goog.log.Logger} */\n this.logger_ = goog.log.getLogger('goog.net.FetchXmlHttp');\n\n /** @private {?Response} */\n this.fetchResponse_ = null;\n\n /** @private {!ReadableStreamDefaultReader|null} */\n this.currentReader_ = null;\n\n /** @private {?TextDecoder} */\n this.textDecoder_ = null;\n};\ngoog.inherits(goog.net.FetchXmlHttp, goog.events.EventTarget);\n\n\n/**\n * State of the requests.\n * @enum {number}\n */\ngoog.net.FetchXmlHttp.RequestState = {\n UNSENT: 0,\n OPENED: 1,\n HEADER_RECEIVED: 2,\n LOADING: 3,\n DONE: 4,\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.open = function(method, url, opt_async) {\n 'use strict';\n goog.asserts.assert(!!opt_async, 'Only async requests are supported.');\n if (this.readyState != goog.net.FetchXmlHttp.RequestState.UNSENT) {\n this.abort();\n throw new Error('Error reopening a connection');\n }\n\n this.method_ = method;\n this.url_ = url;\n\n this.readyState = goog.net.FetchXmlHttp.RequestState.OPENED;\n this.dispatchCallback_();\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.send = function(opt_data) {\n 'use strict';\n if (this.readyState != goog.net.FetchXmlHttp.RequestState.OPENED) {\n this.abort();\n throw new Error('need to call open() first. ');\n }\n\n this.inProgress_ = true;\n const requestInit = {\n headers: this.requestHeaders_,\n method: this.method_,\n credentials: this.credentialsMode_,\n cache: this.cacheMode_,\n };\n if (opt_data) {\n requestInit['body'] = opt_data;\n }\n\n (this.worker_ || goog.global)\n .fetch(new Request(this.url_, /** @type {!RequestInit} */ (requestInit)))\n .then(\n this.handleResponse_.bind(this), this.handleSendFailure_.bind(this));\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.abort = function() {\n 'use strict';\n this.response = this.responseText = '';\n this.requestHeaders_ = new Headers();\n this.status = 0;\n\n if (!!this.currentReader_) {\n this.currentReader_.cancel('Request was aborted.')\n .catch(\n e => goog.log.warning(\n this.logger_, 'Fetch reader cancellation error.', e));\n }\n\n if (((this.readyState >= goog.net.FetchXmlHttp.RequestState.OPENED) &&\n this.inProgress_) &&\n (this.readyState != goog.net.FetchXmlHttp.RequestState.DONE)) {\n this.inProgress_ = false;\n this.requestDone_();\n }\n\n this.readyState = goog.net.FetchXmlHttp.RequestState.UNSENT;\n};\n\n\n/**\n * Handles the fetch response.\n * @param {!Response} response\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleResponse_ = function(response) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n this.fetchResponse_ = response;\n\n if (!this.responseHeaders_) {\n this.status = this.fetchResponse_.status;\n this.statusText = this.fetchResponse_.statusText;\n this.responseHeaders_ = response.headers;\n this.readyState = goog.net.FetchXmlHttp.RequestState.HEADER_RECEIVED;\n this.dispatchCallback_();\n }\n // A callback may abort the request.\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n this.readyState = goog.net.FetchXmlHttp.RequestState.LOADING;\n this.dispatchCallback_();\n // A callback may abort the request.\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n if (this.responseType === 'arraybuffer') {\n response.arrayBuffer().then(\n this.handleResponseArrayBuffer_.bind(this),\n this.handleSendFailure_.bind(this));\n } else if (\n typeof (goog.global.ReadableStream) !== 'undefined' &&\n 'body' in response) {\n this.currentReader_ =\n /** @type {!ReadableStreamDefaultReader} */ (response.body.getReader());\n if (this.streamBinaryChunks_) {\n if (this.responseType) {\n throw new Error(\n 'responseType must be empty for \"streamBinaryChunks\" mode responses.');\n }\n this.response = [];\n } else {\n this.response = this.responseText = '';\n this.textDecoder_ = new TextDecoder();\n }\n this.readInputFromFetch_();\n } else {\n response.text().then(\n this.handleResponseText_.bind(this),\n this.handleSendFailure_.bind(this));\n }\n};\n\n\n/**\n * Reads the next chunk of data from the fetch response.\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.readInputFromFetch_ = function() {\n 'use strict';\n this.currentReader_.read()\n .then(this.handleDataFromStream_.bind(this))\n .catch(this.handleSendFailure_.bind(this));\n};\n\n\n/**\n * Handles a chunk of data from the fetch response stream reader.\n * @param {!IIterableResult} result\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleDataFromStream_ = function(result) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n if (this.streamBinaryChunks_ && result.value) {\n // When streamBinaryChunks_ is enabled, \"response\" is an array\n /** @type {!Array} */ (this.response)\n .push(/** @type {!Uint8Array} */ (result.value));\n } else if (!this.streamBinaryChunks_) {\n const dataPacket = result.value ?\n /** @type {!Uint8Array} */ (result.value) :\n new Uint8Array(0);\n const newText =\n this.textDecoder_.decode(dataPacket, {stream: !result.done});\n if (newText) {\n this.responseText += newText;\n this.response = this.responseText;\n }\n }\n if (result.done) {\n this.requestDone_();\n } else {\n this.dispatchCallback_();\n }\n\n if (this.readyState == goog.net.FetchXmlHttp.RequestState.LOADING) {\n this.readInputFromFetch_();\n }\n};\n\n/**\n * Handles the response text.\n * @param {string} responseText\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleResponseText_ = function(responseText) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n this.response = this.responseText = responseText;\n this.requestDone_();\n};\n\n\n/**\n * Handles the response text.\n * @param {!ArrayBuffer} responseArrayBuffer\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleResponseArrayBuffer_ = function(\n responseArrayBuffer) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n this.response = responseArrayBuffer;\n this.requestDone_();\n};\n\n\n/**\n * Handles the send failure.\n * @param {*} error\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleSendFailure_ = function(error) {\n 'use strict';\n const e = error instanceof Error ? error : Error(error);\n goog.log.warning(this.logger_, 'Failed to fetch url ' + this.url_, e);\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n this.requestDone_();\n};\n\n\n/**\n * Sets the request state to DONE and performs cleanup.\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.requestDone_ = function() {\n 'use strict';\n this.readyState = goog.net.FetchXmlHttp.RequestState.DONE;\n\n this.fetchResponse_ = null;\n this.currentReader_ = null;\n this.textDecoder_ = null;\n\n this.dispatchCallback_();\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.setRequestHeader = function(header, value) {\n 'use strict';\n this.requestHeaders_.append(header, value);\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.getResponseHeader = function(header) {\n 'use strict';\n // TODO(user): This method should return null when the headers are not\n // present or the specified header is missing. The externs need to be fixed.\n if (!this.responseHeaders_) {\n goog.log.warning(\n this.logger_,\n 'Attempting to get response header but no headers have been received ' +\n 'for url: ' + this.url_);\n return '';\n }\n return this.responseHeaders_.get(header.toLowerCase()) || '';\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.getAllResponseHeaders = function() {\n 'use strict';\n if (!this.responseHeaders_) {\n goog.log.warning(\n this.logger_,\n 'Attempting to get all response headers but no headers have been ' +\n 'received for url: ' + this.url_);\n return '';\n }\n const lines = [];\n const iter = this.responseHeaders_.entries();\n let entry = iter.next();\n while (!entry.done) {\n const pair = entry.value;\n lines.push(pair[0] + ': ' + pair[1]);\n entry = iter.next();\n }\n return lines.join('\\r\\n');\n};\n\n\n/**\n * @param {!RequestCredentials} credentialsMode The credentials mode of the\n * Service Worker fetch.\n */\ngoog.net.FetchXmlHttp.prototype.setCredentialsMode = function(credentialsMode) {\n 'use strict';\n this.credentialsMode_ = credentialsMode;\n};\n\n/**\n * @return {!RequestCredentials|undefined} The credentials mode of the\n * Service Worker fetch.\n */\ngoog.net.FetchXmlHttp.prototype.getCredentialsMode = function() {\n 'use strict';\n return this.credentialsMode_;\n};\n\n/**\n * @param {!RequestCache} cacheMode The cache mode of the Service Worker fetch.\n */\ngoog.net.FetchXmlHttp.prototype.setCacheMode = function(cacheMode) {\n 'use strict';\n this.cacheMode_ = cacheMode;\n};\n\n\n/**\n * Dispatches the callback, if the callback attribute is defined.\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.dispatchCallback_ = function() {\n 'use strict';\n if (this.onreadystatechange) {\n this.onreadystatechange.call(this);\n }\n};\n\n// Polyfill XmlHttpRequest's withCredentials property for specifying whether to\n// include credentials on cross domain requests.\nObject.defineProperty(goog.net.FetchXmlHttp.prototype, 'withCredentials', {\n get:\n /**\n * @this {goog.net.FetchXmlHttp}\n * @return {boolean} Whether to include credentials in cross domain\n * requests.\n */\n function() {\n 'use strict';\n return this.getCredentialsMode() === 'include';\n },\n\n set:\n /**\n * @param {boolean} value Whether to include credentials in cross domain\n * requests.\n * @this {goog.net.FetchXmlHttp}\n **/\n function(value) {\n 'use strict';\n this.setCredentialsMode(value ? 'include' : 'same-origin');\n }\n});\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n\n/**\n * @fileoverview Utility to attempt native JSON processing, falling back to\n * goog.json if not available.\n *\n * This is intended as a drop-in for current users of goog.json who want\n * to take advantage of native JSON if present.\n */\n\ngoog.provide('goog.json.hybrid');\n\ngoog.require('goog.asserts');\ngoog.require('goog.json');\n\n\n/**\n * Attempts to serialize the JSON string natively, falling back to\n * `goog.json.serialize` if unsuccessful.\n * @param {!Object} obj JavaScript object to serialize to JSON.\n * @return {string} Resulting JSON string.\n */\ngoog.json.hybrid.stringify = goog.json.USE_NATIVE_JSON ?\n goog.global['JSON']['stringify'] :\n function(obj) {\n 'use strict';\n if (goog.global.JSON) {\n try {\n return goog.global.JSON.stringify(obj);\n } catch (e) {\n // Native serialization failed. Fall through to retry with\n // goog.json.serialize.\n }\n }\n\n return goog.json.serialize(obj);\n };\n\n\n/**\n * Attempts to parse the JSON string natively, falling back to\n * the supplied `fallbackParser` if unsuccessful.\n * @param {string} jsonString JSON string to parse.\n * @param {function(string):Object} fallbackParser Fallback JSON parser used\n * if native\n * @return {?Object} Resulting JSON object.\n * @private\n */\ngoog.json.hybrid.parse_ = function(jsonString, fallbackParser) {\n 'use strict';\n if (goog.global.JSON) {\n try {\n var obj = goog.global.JSON.parse(jsonString);\n goog.asserts.assert(typeof obj == 'object');\n return /** @type {?Object} */ (obj);\n } catch (e) {\n // Native parse failed. Fall through to retry with goog.json.parse.\n }\n }\n\n return fallbackParser(jsonString);\n};\n\n\n/**\n * Attempts to parse the JSON string natively, falling back to\n * `goog.json.parse` if unsuccessful.\n * @param {string} jsonString JSON string to parse.\n * @return {?Object} Resulting JSON object.\n */\ngoog.json.hybrid.parse = goog.json.USE_NATIVE_JSON ?\n goog.global['JSON']['parse'] :\n function(jsonString) {\n 'use strict';\n return goog.json.hybrid.parse_(jsonString, goog.json.parse);\n };\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Constants for HTTP status codes.\n */\n\ngoog.provide('goog.net.HttpStatus');\n\n\n/**\n * HTTP Status Codes defined in RFC 2616, RFC 6585, RFC 4918 and RFC 7538.\n * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html\n * @see http://tools.ietf.org/html/rfc6585\n * @see https://tools.ietf.org/html/rfc4918\n * @see https://tools.ietf.org/html/rfc7538\n * @enum {number}\n */\ngoog.net.HttpStatus = {\n // Informational 1xx\n CONTINUE: 100,\n SWITCHING_PROTOCOLS: 101,\n\n // Successful 2xx\n OK: 200,\n CREATED: 201,\n ACCEPTED: 202,\n NON_AUTHORITATIVE_INFORMATION: 203,\n NO_CONTENT: 204,\n RESET_CONTENT: 205,\n PARTIAL_CONTENT: 206,\n MULTI_STATUS: 207,\n\n // Redirection 3xx\n MULTIPLE_CHOICES: 300,\n MOVED_PERMANENTLY: 301,\n FOUND: 302,\n SEE_OTHER: 303,\n NOT_MODIFIED: 304,\n USE_PROXY: 305,\n TEMPORARY_REDIRECT: 307,\n PERMANENT_REDIRECT: 308,\n\n // Client Error 4xx\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n NOT_ACCEPTABLE: 406,\n PROXY_AUTHENTICATION_REQUIRED: 407,\n REQUEST_TIMEOUT: 408,\n CONFLICT: 409,\n GONE: 410,\n LENGTH_REQUIRED: 411,\n PRECONDITION_FAILED: 412,\n REQUEST_ENTITY_TOO_LARGE: 413,\n REQUEST_URI_TOO_LONG: 414,\n UNSUPPORTED_MEDIA_TYPE: 415,\n REQUEST_RANGE_NOT_SATISFIABLE: 416,\n EXPECTATION_FAILED: 417,\n UNPROCESSABLE_ENTITY: 422,\n LOCKED: 423,\n FAILED_DEPENDENCY: 424,\n PRECONDITION_REQUIRED: 428,\n TOO_MANY_REQUESTS: 429,\n REQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n CLIENT_CLOSED_REQUEST: 499, // Nonstandard, used by GRPC\n\n // Server Error 5xx\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n HTTP_VERSION_NOT_SUPPORTED: 505,\n INSUFFICIENT_STORAGE: 507,\n NETWORK_AUTHENTICATION_REQUIRED: 511,\n\n /*\n * IE returns this code for 204 due to its use of URLMon, which returns this\n * code for 'Operation Aborted'. The status text is 'Unknown', the response\n * headers are ''. Known to occur on IE 6 on XP through IE9 on Win7.\n */\n QUIRK_IE_NO_CONTENT: 1223,\n};\n\n\n/**\n * Returns whether the given status should be considered successful.\n *\n * Successful codes are OK (200), CREATED (201), ACCEPTED (202),\n * NO CONTENT (204), PARTIAL CONTENT (206), NOT MODIFIED (304),\n * and IE's no content code (1223).\n *\n * @param {number} status The status code to test.\n * @return {boolean} Whether the status code should be considered successful.\n */\ngoog.net.HttpStatus.isSuccess = function(status) {\n 'use strict';\n switch (status) {\n case goog.net.HttpStatus.OK:\n case goog.net.HttpStatus.CREATED:\n case goog.net.HttpStatus.ACCEPTED:\n case goog.net.HttpStatus.NO_CONTENT:\n case goog.net.HttpStatus.PARTIAL_CONTENT:\n case goog.net.HttpStatus.NOT_MODIFIED:\n case goog.net.HttpStatus.QUIRK_IE_NO_CONTENT:\n return true;\n\n default:\n return false;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Provides CORS support for HTTP based RPC requests.\n *\n * As part of net.rpc package, CORS features provided by this class\n * depend on the server support. Please check related specs to decide how\n * to enable any of the features provided by this class.\n */\n\ngoog.module('goog.net.rpc.HttpCors');\n\nconst GoogUri = goog.require('goog.Uri');\nconst googObject = goog.require('goog.object');\nconst googString = goog.require('goog.string');\nconst googUriUtils = goog.require('goog.uri.utils');\n\n\n/**\n * The default URL parameter name to overwrite http headers with a URL param\n * to avoid CORS preflight.\n *\n * See https://github.com/whatwg/fetch/issues/210#issue-129531743 for the spec.\n *\n * @type {string}\n */\nexports.HTTP_HEADERS_PARAM_NAME = '$httpHeaders';\n\n\n/**\n * The default URL parameter name to overwrite http method with a URL param\n * to avoid CORS preflight.\n *\n * See https://github.com/whatwg/fetch/issues/210#issue-129531743 for the spec.\n *\n * @type {string}\n */\nexports.HTTP_METHOD_PARAM_NAME = '$httpMethod';\n\n\n/**\n * Generates the URL parameter value with custom headers encoded as\n * HTTP/1.1 headers block.\n *\n * @param {!Object<string, string>} headers The custom headers.\n * @return {string} The URL param to overwrite custom HTTP headers.\n */\nexports.generateHttpHeadersOverwriteParam = function(headers) {\n let result = '';\n googObject.forEach(headers, function(value, key) {\n result += key;\n result += ':';\n result += value;\n result += '\\r\\n';\n });\n return result;\n};\n\n\n/**\n * Generates the URL-encoded URL parameter value with custom headers encoded as\n * HTTP/1.1 headers block.\n *\n * @param {!Object<string, string>} headers The custom headers.\n * @return {string} The URL param to overwrite custom HTTP headers.\n */\nexports.generateEncodedHttpHeadersOverwriteParam = function(headers) {\n return googString.urlEncode(\n exports.generateHttpHeadersOverwriteParam(headers));\n};\n\n\n/**\n * Sets custom HTTP headers via an overwrite URL param.\n *\n * @param {!GoogUri|string} url The URI object or a string path.\n * @param {string} urlParam The URL param name.\n * @param {!Object<string, string>} extraHeaders The HTTP headers.\n * @return {!GoogUri|string} The URI object or a string path with headers\n * encoded as a url param.\n */\nexports.setHttpHeadersWithOverwriteParam = function(\n url, urlParam, extraHeaders) {\n if (googObject.isEmpty(extraHeaders)) {\n return url;\n }\n const httpHeaders = exports.generateHttpHeadersOverwriteParam(extraHeaders);\n if (typeof url === 'string') {\n return googUriUtils.appendParam(\n url, googString.urlEncode(urlParam), httpHeaders);\n } else {\n url.setParameterValue(urlParam, httpHeaders); // duplicate removed!\n return url;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Implementation of a WebChannel transport using WebChannelBase.\n *\n * When WebChannelBase is used as the underlying transport, the capabilities\n * of the WebChannel are limited to what's supported by the implementation.\n * Particularly, multiplexing is not possible, and only strings are\n * supported as message types.\n */\n\ngoog.provide('goog.labs.net.webChannel.WebChannelBaseTransport');\n\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.events.EventTarget');\ngoog.require('goog.json');\ngoog.require('goog.labs.net.webChannel.ChannelRequest');\ngoog.require('goog.labs.net.webChannel.WebChannelBase');\ngoog.require('goog.labs.net.webChannel.Wire');\ngoog.require('goog.log');\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.net.WebChannelTransport');\ngoog.require('goog.object');\ngoog.require('goog.string');\n\n\n\n/**\n * Implementation of {@link goog.net.WebChannelTransport} with\n * {@link goog.labs.net.webChannel.WebChannelBase} as the underlying channel\n * implementation.\n *\n * @constructor\n * @struct\n * @implements {goog.net.WebChannelTransport}\n * @final\n */\ngoog.labs.net.webChannel.WebChannelBaseTransport = function() {\n 'use strict';\n if (!goog.labs.net.webChannel.ChannelRequest.supportsXhrStreaming()) {\n throw new Error('Environmental error: no available transport.');\n }\n};\n\n\ngoog.scope(function() {\n'use strict';\nconst WebChannelBaseTransport =\n goog.labs.net.webChannel.WebChannelBaseTransport;\nconst WebChannelBase = goog.labs.net.webChannel.WebChannelBase;\nconst Wire = goog.labs.net.webChannel.Wire;\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.prototype.createWebChannel = function(\n url, opt_options) {\n 'use strict';\n return new WebChannelBaseTransport.Channel(url, opt_options);\n};\n\n\n\n/**\n * Implementation of the {@link goog.net.WebChannel} interface.\n *\n * @param {string} url The URL path for the new WebChannel instance.\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\n * new WebChannel instance.\n *\n * @constructor\n * @implements {goog.net.WebChannel}\n * @extends {goog.events.EventTarget}\n * @final\n */\nWebChannelBaseTransport.Channel = function(url, opt_options) {\n 'use strict';\n WebChannelBaseTransport.Channel.base(this, 'constructor');\n\n /**\n * @private {!WebChannelBase} The underlying channel object.\n */\n this.channel_ = new WebChannelBase(\n opt_options, goog.net.WebChannelTransport.CLIENT_VERSION);\n\n /**\n * @private {string} The URL of the target server end-point.\n */\n this.url_ = url;\n\n /**\n * @private {goog.log.Logger} The logger for this class.\n */\n this.logger_ =\n goog.log.getLogger('goog.labs.net.webChannel.WebChannelBaseTransport');\n\n /**\n * @private {Object<string, string>} Extra URL parameters\n * to be added to each HTTP request.\n */\n this.messageUrlParams_ =\n (opt_options && opt_options.messageUrlParams) || null;\n\n let messageHeaders = (opt_options && opt_options.messageHeaders) || null;\n\n // default is false\n if (opt_options && opt_options.clientProtocolHeaderRequired) {\n if (messageHeaders) {\n goog.object.set(\n messageHeaders, goog.net.WebChannel.X_CLIENT_PROTOCOL,\n goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL);\n } else {\n messageHeaders = goog.object.create(\n goog.net.WebChannel.X_CLIENT_PROTOCOL,\n goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL);\n }\n }\n\n this.channel_.setExtraHeaders(messageHeaders);\n\n let initHeaders = (opt_options && opt_options.initMessageHeaders) || null;\n\n if (opt_options && opt_options.messageContentType) {\n if (initHeaders) {\n goog.object.set(\n initHeaders, goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE,\n opt_options.messageContentType);\n } else {\n initHeaders = goog.object.create(\n goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE,\n opt_options.messageContentType);\n }\n }\n\n if (opt_options && opt_options.clientProfile) {\n if (initHeaders) {\n goog.object.set(\n initHeaders, goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE,\n opt_options.clientProfile);\n } else {\n initHeaders = goog.object.create(\n goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE,\n opt_options.clientProfile);\n }\n }\n\n this.channel_.setInitHeaders(initHeaders);\n\n const httpHeadersOverwriteParam =\n opt_options && opt_options.httpHeadersOverwriteParam;\n if (httpHeadersOverwriteParam &&\n !goog.string.isEmptyOrWhitespace(httpHeadersOverwriteParam)) {\n this.channel_.setHttpHeadersOverwriteParam(httpHeadersOverwriteParam);\n }\n\n /**\n * @private {boolean} Whether to enable CORS.\n */\n this.supportsCrossDomainXhr_ =\n (opt_options && opt_options.supportsCrossDomainXhr) || false;\n\n /**\n * @private {boolean} Whether to send raw Json and bypass v8 wire format.\n */\n this.sendRawJson_ = (opt_options && opt_options.sendRawJson) || false;\n\n // Note that httpSessionIdParam will be ignored if the same parameter name\n // has already been specified with messageUrlParams\n const httpSessionIdParam = opt_options && opt_options.httpSessionIdParam;\n if (httpSessionIdParam &&\n !goog.string.isEmptyOrWhitespace(httpSessionIdParam)) {\n this.channel_.setHttpSessionIdParam(httpSessionIdParam);\n if (goog.object.containsKey(this.messageUrlParams_, httpSessionIdParam)) {\n goog.object.remove(this.messageUrlParams_, httpSessionIdParam);\n goog.log.warning(\n this.logger_,\n 'Ignore httpSessionIdParam also specified with messageUrlParams: ' +\n httpSessionIdParam);\n }\n }\n\n /**\n * The channel handler.\n *\n * @private {!WebChannelBaseTransport.Channel.Handler_}\n */\n this.channelHandler_ = new WebChannelBaseTransport.Channel.Handler_(this);\n};\ngoog.inherits(WebChannelBaseTransport.Channel, goog.events.EventTarget);\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.open = function() {\n 'use strict';\n this.channel_.setHandler(this.channelHandler_);\n if (this.supportsCrossDomainXhr_) {\n this.channel_.setSupportsCrossDomainXhrs(true);\n }\n this.channel_.connect(this.url_, (this.messageUrlParams_ || undefined));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.close = function() {\n 'use strict';\n this.channel_.disconnect();\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.halfClose = function() {\n 'use strict';\n // to be implemented\n throw new Error('Not implemented');\n};\n\n\n/**\n * The WebChannelBase only supports object types.\n *\n * @param {!goog.net.WebChannel.MessageData} message The message to send.\n *\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.send = function(message) {\n 'use strict';\n this.channel_.sendMap(this.messageToMapObject_(message));\n};\n\n\n/**\n * Converts a message to the map used by the underlying channel.\n *\n * @param {!goog.net.WebChannel.MessageData} message\n * @return {!Object|!goog.collections.maps.MapLike}\n */\nWebChannelBaseTransport.Channel.prototype.messageToMapObject_ = function(\n message) {\n 'use strict';\n goog.asserts.assert(\n goog.isObject(message) || typeof message === 'string',\n 'only object type or raw string is supported');\n\n if (typeof message === 'string') {\n const rawJson = {};\n rawJson[Wire.RAW_DATA_KEY] = message;\n return rawJson;\n }\n\n if (this.sendRawJson_) {\n const rawJson = {};\n rawJson[Wire.RAW_DATA_KEY] = goog.json.serialize(message);\n return rawJson;\n }\n\n return message;\n};\n\n\n/**\n * Converts the map used by the underlying channel to a message.\n *\n * NOTE: In the case of the message being JS Object or string, the exact same\n * object passed during `messageToMapObject_()` is returned. In the case of raw\n * JSON, an equal (but not the same) object is returned (due to serialization).\n *\n * @param {!Object|!goog.collections.maps.MapLike} map\n * @return {!goog.net.WebChannel.MessageData}\n */\nWebChannelBaseTransport.Channel.prototype.mapObjectToMessage_ = function(map) {\n 'use strict';\n if (Wire.RAW_DATA_KEY in map) {\n const rawMessage = map[Wire.RAW_DATA_KEY];\n\n if (this.sendRawJson_) {\n return /** @type {!goog.net.WebChannel.MessageData} */ (\n goog.json.parse(rawMessage));\n } else { // string message\n return rawMessage;\n }\n }\n\n return map;\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.disposeInternal = function() {\n 'use strict';\n this.channel_.setHandler(null);\n delete this.channelHandler_;\n this.channel_.disconnect();\n delete this.channel_;\n\n WebChannelBaseTransport.Channel.base(this, 'disposeInternal');\n};\n\n\n\n/**\n * The message event.\n *\n * @param {!Array<?>|!Object} array The data array from the underlying channel.\n * @constructor\n * @extends {goog.net.WebChannel.MessageEvent}\n * @final\n */\nWebChannelBaseTransport.Channel.MessageEvent = function(array) {\n 'use strict';\n WebChannelBaseTransport.Channel.MessageEvent.base(this, 'constructor');\n\n // Metadata as HTTP headers and status code (always come in a pair).\n if (array['__headers__']) {\n this.headers = array['__headers__'];\n this.statusCode = array['__status__'];\n delete array['__headers__'];\n delete array['__status__'];\n }\n\n // single-metadata only\n const metadata = array['__sm__'];\n if (metadata) {\n this.metadataKey = goog.object.getAnyKey(metadata);\n if (this.metadataKey) {\n this.data = goog.object.get(metadata, this.metadataKey);\n } else {\n this.data = metadata; // empty\n }\n } else {\n this.data = array;\n }\n};\ngoog.inherits(\n WebChannelBaseTransport.Channel.MessageEvent,\n goog.net.WebChannel.MessageEvent);\n\n\n\n/**\n * The error event.\n *\n * @param {WebChannelBase.Error} error The error code.\n * @constructor\n * @extends {goog.net.WebChannel.ErrorEvent}\n * @final\n */\nWebChannelBaseTransport.Channel.ErrorEvent = function(error) {\n 'use strict';\n WebChannelBaseTransport.Channel.ErrorEvent.base(this, 'constructor');\n\n /**\n * High-level status code.\n */\n this.status = goog.net.WebChannel.ErrorStatus.NETWORK_ERROR;\n\n /**\n * @const {WebChannelBase.Error} Internal error code, for debugging use only.\n */\n this.errorCode = error;\n};\ngoog.inherits(\n WebChannelBaseTransport.Channel.ErrorEvent, goog.net.WebChannel.ErrorEvent);\n\n\n\n/**\n * Implementation of {@link WebChannelBase.Handler} interface.\n *\n * @param {!WebChannelBaseTransport.Channel} channel The enclosing WebChannel.\n *\n * @constructor\n * @extends {WebChannelBase.Handler}\n * @private\n */\nWebChannelBaseTransport.Channel.Handler_ = function(channel) {\n 'use strict';\n WebChannelBaseTransport.Channel.Handler_.base(this, 'constructor');\n\n /**\n * @type {!WebChannelBaseTransport.Channel}\n * @private\n */\n this.channel_ = channel;\n};\ngoog.inherits(WebChannelBaseTransport.Channel.Handler_, WebChannelBase.Handler);\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelOpened = function(\n channel) {\n 'use strict';\n goog.log.info(\n this.channel_.logger_, 'WebChannel opened on ' + this.channel_.url_);\n this.channel_.dispatchEvent(goog.net.WebChannel.EventType.OPEN);\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelHandleArray =\n function(channel, array) {\n 'use strict';\n goog.asserts.assert(array, 'array expected to be defined');\n this.channel_.dispatchEvent(\n new WebChannelBaseTransport.Channel.MessageEvent(array));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelError = function(\n channel, error) {\n 'use strict';\n goog.log.info(\n this.channel_.logger_,\n 'WebChannel aborted on ' + this.channel_.url_ +\n ' due to channel error: ' + error);\n this.channel_.dispatchEvent(\n new WebChannelBaseTransport.Channel.ErrorEvent(error));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelClosed = function(\n channel, opt_pendingMaps, opt_undeliveredMaps) {\n 'use strict';\n goog.log.info(\n this.channel_.logger_, 'WebChannel closed on ' + this.channel_.url_);\n this.channel_.dispatchEvent(goog.net.WebChannel.EventType.CLOSE);\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.getRuntimeProperties = function() {\n 'use strict';\n return new WebChannelBaseTransport.ChannelProperties(this, this.channel_);\n};\n\n\n\n/**\n * Implementation of the {@link goog.net.WebChannel.RuntimeProperties}.\n *\n * @param {!WebChannelBaseTransport.Channel} transportChannel The transport\n * channel object.\n * @param {!WebChannelBase} channel The underlying channel object.\n *\n * @constructor\n * @implements {goog.net.WebChannel.RuntimeProperties}\n * @final\n */\nWebChannelBaseTransport.ChannelProperties = function(\n transportChannel, channel) {\n 'use strict';\n /**\n * The transport channel object.\n *\n * @private @const {!WebChannelBaseTransport.Channel}\n */\n this.transportChannel_ = transportChannel;\n\n /**\n * The underlying channel object.\n *\n * @private @const {!WebChannelBase}\n */\n this.channel_ = channel;\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getConcurrentRequestLimit =\n function() {\n 'use strict';\n return this.channel_.getForwardChannelRequestPool().getMaxSize();\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.isSpdyEnabled = function() {\n 'use strict';\n return this.getConcurrentRequestLimit() > 1;\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getPendingRequestCount =\n function() {\n 'use strict';\n return this.channel_.getForwardChannelRequestPool().getRequestCount();\n};\n\n\n/**\n * @override\n * @return {!Array<!goog.net.WebChannel.MessageData>}\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getNonAckedMessages =\n function() {\n 'use strict';\n return this.channel_.getNonAckedMaps().map(\n queued_map => this.transportChannel_.mapObjectToMessage_(queued_map.map));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getHttpSessionId =\n function() {\n 'use strict';\n return this.channel_.getHttpSessionId();\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.commit = function(\n callback) {\n 'use strict';\n this.channel_.setForwardChannelFlushCallback(callback);\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.notifyNonAckedMessageCount =\n goog.abstractMethod;\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.onCommit =\n goog.abstractMethod;\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.ackCommit =\n goog.abstractMethod;\n\n\n/**\n * @override\n * @return {!Object<string, string>|undefined}\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getLastResponseHeaders =\n function() {\n 'use strict';\n return this.channel_.getLastResponseHeaders();\n};\n\n/** @override */\nWebChannelBaseTransport.ChannelProperties.prototype.getLastStatusCode =\n function() {\n 'use strict';\n return this.channel_.getLastStatusCode();\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview MD5 cryptographic hash.\n * Implementation of http://tools.ietf.org/html/rfc1321 with common\n * optimizations and tweaks (see http://en.wikipedia.org/wiki/MD5).\n *\n * Usage:\n * var md5 = new goog.crypt.Md5();\n * md5.update(bytes);\n * var hash = md5.digest();\n *\n * Performance:\n * Chrome 23 ~680 Mbit/s\n * Chrome 13 (in a VM) ~250 Mbit/s\n * Firefox 6.0 (in a VM) ~100 Mbit/s\n * IE9 (in a VM) ~27 Mbit/s\n * Firefox 3.6 ~15 Mbit/s\n * IE8 (in a VM) ~13 Mbit/s\n */\n\ngoog.provide('goog.crypt.Md5');\n\ngoog.require('goog.crypt.Hash');\n\n\n\n/**\n * MD5 cryptographic hash constructor.\n * @constructor\n * @extends {goog.crypt.Hash}\n * @final\n * @struct\n */\ngoog.crypt.Md5 = function() {\n 'use strict';\n goog.crypt.Md5.base(this, 'constructor');\n\n this.blockSize = 512 / 8;\n\n /**\n * Holds the current values of accumulated A-D variables (MD buffer).\n * @type {!Array<number>}\n * @private\n */\n this.chain_ = new Array(4);\n\n /**\n * A buffer holding the data until the whole block can be processed.\n * @type {!Array<number>}\n * @private\n */\n this.block_ = new Array(this.blockSize);\n\n /**\n * The length of yet-unprocessed data as collected in the block.\n * @type {number}\n * @private\n */\n this.blockLength_ = 0;\n\n /**\n * The total length of the message so far.\n * @type {number}\n * @private\n */\n this.totalLength_ = 0;\n\n this.reset();\n};\ngoog.inherits(goog.crypt.Md5, goog.crypt.Hash);\n\n\n/**\n * Integer rotation constants used by the abbreviated implementation.\n * They are hardcoded in the unrolled implementation, so it is left\n * here commented out.\n * @type {Array<number>}\n * @private\n *\ngoog.crypt.Md5.S_ = [\n 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,\n 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21\n];\n */\n\n/**\n * Sine function constants used by the abbreviated implementation.\n * They are hardcoded in the unrolled implementation, so it is left\n * here commented out.\n * @type {Array<number>}\n * @private\n *\ngoog.crypt.Md5.T_ = [\n 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,\n 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,\n 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,\n 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,\n 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,\n 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,\n 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,\n 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,\n 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,\n 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,\n 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,\n 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,\n 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,\n 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,\n 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,\n 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391\n];\n */\n\n\n/** @override */\ngoog.crypt.Md5.prototype.reset = function() {\n 'use strict';\n this.chain_[0] = 0x67452301;\n this.chain_[1] = 0xefcdab89;\n this.chain_[2] = 0x98badcfe;\n this.chain_[3] = 0x10325476;\n\n this.blockLength_ = 0;\n this.totalLength_ = 0;\n};\n\n\n/**\n * Internal compress helper function. It takes a block of data (64 bytes)\n * and updates the accumulator.\n * @param {Array<number>|Uint8Array|string} buf The block to compress.\n * @param {number=} opt_offset Offset of the block in the buffer.\n * @private\n */\ngoog.crypt.Md5.prototype.compress_ = function(buf, opt_offset) {\n 'use strict';\n if (!opt_offset) {\n opt_offset = 0;\n }\n\n // We allocate the array every time, but it's cheap in practice.\n var X = new Array(16);\n\n // Get 16 little endian words. It is not worth unrolling this for Chrome 11.\n if (typeof buf === 'string') {\n for (var i = 0; i < 16; ++i) {\n X[i] = (buf.charCodeAt(opt_offset++)) |\n (buf.charCodeAt(opt_offset++) << 8) |\n (buf.charCodeAt(opt_offset++) << 16) |\n (buf.charCodeAt(opt_offset++) << 24);\n }\n } else {\n for (var i = 0; i < 16; ++i) {\n X[i] = (buf[opt_offset++]) | (buf[opt_offset++] << 8) |\n (buf[opt_offset++] << 16) | (buf[opt_offset++] << 24);\n }\n }\n\n var A = this.chain_[0];\n var B = this.chain_[1];\n var C = this.chain_[2];\n var D = this.chain_[3];\n var sum = 0;\n\n /*\n * This is an abbreviated implementation, it is left here commented out for\n * reference purposes. See below for an unrolled version in use.\n *\n var f, n, tmp;\n for (var i = 0; i < 64; ++i) {\n\n if (i < 16) {\n f = (D ^ (B & (C ^ D)));\n n = i;\n } else if (i < 32) {\n f = (C ^ (D & (B ^ C)));\n n = (5 * i + 1) % 16;\n } else if (i < 48) {\n f = (B ^ C ^ D);\n n = (3 * i + 5) % 16;\n } else {\n f = (C ^ (B | (~D)));\n n = (7 * i) % 16;\n }\n\n tmp = D;\n D = C;\n C = B;\n sum = (A + f + goog.crypt.Md5.T_[i] + X[n]) & 0xffffffff;\n B += ((sum << goog.crypt.Md5.S_[i]) & 0xffffffff) |\n (sum >>> (32 - goog.crypt.Md5.S_[i]));\n A = tmp;\n }\n */\n\n /*\n * This is an unrolled MD5 implementation, which gives ~30% speedup compared\n * to the abbreviated implementation above, as measured on Chrome 11. It is\n * important to keep 32-bit croppings to minimum and inline the integer\n * rotation.\n */\n sum = (A + (D ^ (B & (C ^ D))) + X[0] + 0xd76aa478) & 0xffffffff;\n A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25));\n sum = (D + (C ^ (A & (B ^ C))) + X[1] + 0xe8c7b756) & 0xffffffff;\n D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20));\n sum = (C + (B ^ (D & (A ^ B))) + X[2] + 0x242070db) & 0xffffffff;\n C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15));\n sum = (B + (A ^ (C & (D ^ A))) + X[3] + 0xc1bdceee) & 0xffffffff;\n B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10));\n sum = (A + (D ^ (B & (C ^ D))) + X[4] + 0xf57c0faf) & 0xffffffff;\n A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25));\n sum = (D + (C ^ (A & (B ^ C))) + X[5] + 0x4787c62a) & 0xffffffff;\n D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20));\n sum = (C + (B ^ (D & (A ^ B))) + X[6] + 0xa8304613) & 0xffffffff;\n C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15));\n sum = (B + (A ^ (C & (D ^ A))) + X[7] + 0xfd469501) & 0xffffffff;\n B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10));\n sum = (A + (D ^ (B & (C ^ D))) + X[8] + 0x698098d8) & 0xffffffff;\n A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25));\n sum = (D + (C ^ (A & (B ^ C))) + X[9] + 0x8b44f7af) & 0xffffffff;\n D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20));\n sum = (C + (B ^ (D & (A ^ B))) + X[10] + 0xffff5bb1) & 0xffffffff;\n C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15));\n sum = (B + (A ^ (C & (D ^ A))) + X[11] + 0x895cd7be) & 0xffffffff;\n B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10));\n sum = (A + (D ^ (B & (C ^ D))) + X[12] + 0x6b901122) & 0xffffffff;\n A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25));\n sum = (D + (C ^ (A & (B ^ C))) + X[13] + 0xfd987193) & 0xffffffff;\n D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20));\n sum = (C + (B ^ (D & (A ^ B))) + X[14] + 0xa679438e) & 0xffffffff;\n C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15));\n sum = (B + (A ^ (C & (D ^ A))) + X[15] + 0x49b40821) & 0xffffffff;\n B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10));\n sum = (A + (C ^ (D & (B ^ C))) + X[1] + 0xf61e2562) & 0xffffffff;\n A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27));\n sum = (D + (B ^ (C & (A ^ B))) + X[6] + 0xc040b340) & 0xffffffff;\n D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23));\n sum = (C + (A ^ (B & (D ^ A))) + X[11] + 0x265e5a51) & 0xffffffff;\n C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18));\n sum = (B + (D ^ (A & (C ^ D))) + X[0] + 0xe9b6c7aa) & 0xffffffff;\n B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12));\n sum = (A + (C ^ (D & (B ^ C))) + X[5] + 0xd62f105d) & 0xffffffff;\n A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27));\n sum = (D + (B ^ (C & (A ^ B))) + X[10] + 0x02441453) & 0xffffffff;\n D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23));\n sum = (C + (A ^ (B & (D ^ A))) + X[15] + 0xd8a1e681) & 0xffffffff;\n C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18));\n sum = (B + (D ^ (A & (C ^ D))) + X[4] + 0xe7d3fbc8) & 0xffffffff;\n B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12));\n sum = (A + (C ^ (D & (B ^ C))) + X[9] + 0x21e1cde6) & 0xffffffff;\n A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27));\n sum = (D + (B ^ (C & (A ^ B))) + X[14] + 0xc33707d6) & 0xffffffff;\n D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23));\n sum = (C + (A ^ (B & (D ^ A))) + X[3] + 0xf4d50d87) & 0xffffffff;\n C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18));\n sum = (B + (D ^ (A & (C ^ D))) + X[8] + 0x455a14ed) & 0xffffffff;\n B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12));\n sum = (A + (C ^ (D & (B ^ C))) + X[13] + 0xa9e3e905) & 0xffffffff;\n A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27));\n sum = (D + (B ^ (C & (A ^ B))) + X[2] + 0xfcefa3f8) & 0xffffffff;\n D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23));\n sum = (C + (A ^ (B & (D ^ A))) + X[7] + 0x676f02d9) & 0xffffffff;\n C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18));\n sum = (B + (D ^ (A & (C ^ D))) + X[12] + 0x8d2a4c8a) & 0xffffffff;\n B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12));\n sum = (A + (B ^ C ^ D) + X[5] + 0xfffa3942) & 0xffffffff;\n A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28));\n sum = (D + (A ^ B ^ C) + X[8] + 0x8771f681) & 0xffffffff;\n D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21));\n sum = (C + (D ^ A ^ B) + X[11] + 0x6d9d6122) & 0xffffffff;\n C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16));\n sum = (B + (C ^ D ^ A) + X[14] + 0xfde5380c) & 0xffffffff;\n B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9));\n sum = (A + (B ^ C ^ D) + X[1] + 0xa4beea44) & 0xffffffff;\n A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28));\n sum = (D + (A ^ B ^ C) + X[4] + 0x4bdecfa9) & 0xffffffff;\n D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21));\n sum = (C + (D ^ A ^ B) + X[7] + 0xf6bb4b60) & 0xffffffff;\n C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16));\n sum = (B + (C ^ D ^ A) + X[10] + 0xbebfbc70) & 0xffffffff;\n B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9));\n sum = (A + (B ^ C ^ D) + X[13] + 0x289b7ec6) & 0xffffffff;\n A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28));\n sum = (D + (A ^ B ^ C) + X[0] + 0xeaa127fa) & 0xffffffff;\n D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21));\n sum = (C + (D ^ A ^ B) + X[3] + 0xd4ef3085) & 0xffffffff;\n C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16));\n sum = (B + (C ^ D ^ A) + X[6] + 0x04881d05) & 0xffffffff;\n B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9));\n sum = (A + (B ^ C ^ D) + X[9] + 0xd9d4d039) & 0xffffffff;\n A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28));\n sum = (D + (A ^ B ^ C) + X[12] + 0xe6db99e5) & 0xffffffff;\n D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21));\n sum = (C + (D ^ A ^ B) + X[15] + 0x1fa27cf8) & 0xffffffff;\n C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16));\n sum = (B + (C ^ D ^ A) + X[2] + 0xc4ac5665) & 0xffffffff;\n B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9));\n sum = (A + (C ^ (B | (~D))) + X[0] + 0xf4292244) & 0xffffffff;\n A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26));\n sum = (D + (B ^ (A | (~C))) + X[7] + 0x432aff97) & 0xffffffff;\n D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22));\n sum = (C + (A ^ (D | (~B))) + X[14] + 0xab9423a7) & 0xffffffff;\n C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17));\n sum = (B + (D ^ (C | (~A))) + X[5] + 0xfc93a039) & 0xffffffff;\n B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11));\n sum = (A + (C ^ (B | (~D))) + X[12] + 0x655b59c3) & 0xffffffff;\n A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26));\n sum = (D + (B ^ (A | (~C))) + X[3] + 0x8f0ccc92) & 0xffffffff;\n D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22));\n sum = (C + (A ^ (D | (~B))) + X[10] + 0xffeff47d) & 0xffffffff;\n C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17));\n sum = (B + (D ^ (C | (~A))) + X[1] + 0x85845dd1) & 0xffffffff;\n B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11));\n sum = (A + (C ^ (B | (~D))) + X[8] + 0x6fa87e4f) & 0xffffffff;\n A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26));\n sum = (D + (B ^ (A | (~C))) + X[15] + 0xfe2ce6e0) & 0xffffffff;\n D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22));\n sum = (C + (A ^ (D | (~B))) + X[6] + 0xa3014314) & 0xffffffff;\n C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17));\n sum = (B + (D ^ (C | (~A))) + X[13] + 0x4e0811a1) & 0xffffffff;\n B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11));\n sum = (A + (C ^ (B | (~D))) + X[4] + 0xf7537e82) & 0xffffffff;\n A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26));\n sum = (D + (B ^ (A | (~C))) + X[11] + 0xbd3af235) & 0xffffffff;\n D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22));\n sum = (C + (A ^ (D | (~B))) + X[2] + 0x2ad7d2bb) & 0xffffffff;\n C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17));\n sum = (B + (D ^ (C | (~A))) + X[9] + 0xeb86d391) & 0xffffffff;\n B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11));\n\n this.chain_[0] = (this.chain_[0] + A) & 0xffffffff;\n this.chain_[1] = (this.chain_[1] + B) & 0xffffffff;\n this.chain_[2] = (this.chain_[2] + C) & 0xffffffff;\n this.chain_[3] = (this.chain_[3] + D) & 0xffffffff;\n};\n\n\n/** @override */\ngoog.crypt.Md5.prototype.update = function(bytes, opt_length) {\n 'use strict';\n if (opt_length === undefined) {\n opt_length = bytes.length;\n }\n var lengthMinusBlock = opt_length - this.blockSize;\n\n // Copy some object properties to local variables in order to save on access\n // time from inside the loop (~10% speedup was observed on Chrome 11).\n var block = this.block_;\n var blockLength = this.blockLength_;\n var i = 0;\n\n // The outer while loop should execute at most twice.\n while (i < opt_length) {\n // When we have no data in the block to top up, we can directly process the\n // input buffer (assuming it contains sufficient data). This gives ~30%\n // speedup on Chrome 14 and ~70% speedup on Firefox 6.0, but requires that\n // the data is provided in large chunks (or in multiples of 64 bytes).\n if (blockLength == 0) {\n while (i <= lengthMinusBlock) {\n this.compress_(bytes, i);\n i += this.blockSize;\n }\n }\n\n if (typeof bytes === 'string') {\n while (i < opt_length) {\n block[blockLength++] = bytes.charCodeAt(i++);\n if (blockLength == this.blockSize) {\n this.compress_(block);\n blockLength = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n } else {\n while (i < opt_length) {\n block[blockLength++] = bytes[i++];\n if (blockLength == this.blockSize) {\n this.compress_(block);\n blockLength = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n }\n }\n\n this.blockLength_ = blockLength;\n this.totalLength_ += opt_length;\n};\n\n\n/** @override */\ngoog.crypt.Md5.prototype.digest = function() {\n 'use strict';\n // This must accommodate at least 1 padding byte (0x80), 8 bytes of\n // total bitlength, and must end at a 64-byte boundary.\n var pad = new Array(\n (this.blockLength_ < 56 ? this.blockSize : this.blockSize * 2) -\n this.blockLength_);\n\n // Add padding: 0x80 0x00*\n pad[0] = 0x80;\n for (var i = 1; i < pad.length - 8; ++i) {\n pad[i] = 0;\n }\n // Add the total number of bits, little endian 64-bit integer.\n var totalBits = this.totalLength_ * 8;\n for (var i = pad.length - 8; i < pad.length; ++i) {\n pad[i] = totalBits & 0xff;\n totalBits /= 0x100; // Don't use bit-shifting here!\n }\n this.update(pad);\n\n var digest = new Array(16);\n var n = 0;\n for (var i = 0; i < 4; ++i) {\n for (var j = 0; j < 32; j += 8) {\n digest[n++] = (this.chain_[i] >>> j) & 0xff;\n }\n }\n return digest;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Abstract cryptographic hash interface.\n *\n * See goog.crypt.Sha1 and goog.crypt.Md5 for sample implementations.\n */\n\ngoog.provide('goog.crypt.Hash');\n\n\n\n/**\n * Create a cryptographic hash instance.\n *\n * @constructor\n * @struct\n */\ngoog.crypt.Hash = function() {\n 'use strict';\n /**\n * The block size for the hasher.\n * @type {number}\n */\n this.blockSize = -1;\n};\n\n\n/**\n * Resets the internal accumulator.\n */\ngoog.crypt.Hash.prototype.reset = goog.abstractMethod;\n\n\n/**\n * Adds a byte array (array with values in [0-255] range) or a string (must\n * only contain 8-bit, i.e., Latin1 characters) to the internal accumulator.\n *\n * Many hash functions operate on blocks of data and implement optimizations\n * when a full chunk of data is readily available. Hence it is often preferable\n * to provide large chunks of data (a kilobyte or more) than to repeatedly\n * call the update method with few tens of bytes. If this is not possible, or\n * not feasible, it might be good to provide data in multiplies of hash block\n * size (often 64 bytes). Please see the implementation and performance tests\n * of your favourite hash.\n *\n * @param {Array<number>|Uint8Array|string} bytes Data used for the update.\n * @param {number=} opt_length Number of bytes to use.\n */\ngoog.crypt.Hash.prototype.update = goog.abstractMethod;\n\n\n/**\n * @return {!Array<number>} The finalized hash computed\n * from the internal accumulator.\n */\ngoog.crypt.Hash.prototype.digest = goog.abstractMethod;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Defines an Integer class for representing (potentially)\n * infinite length two's-complement integer values.\n *\n * For the specific case of 64-bit integers, use goog.math.Long, which is more\n * efficient.\n */\n\ngoog.provide('goog.math.Integer');\n\ngoog.require('goog.reflect');\n\n/**\n * Constructs a two's-complement integer an array containing bits of the\n * integer in 32-bit (signed) pieces, given in little-endian order (i.e.,\n * lowest-order bits in the first piece), and the sign of -1 or 0.\n *\n * See the from* functions below for other convenient ways of constructing\n * Integers.\n *\n * The internal representation of an integer is an array of 32-bit signed\n * pieces, along with a sign (0 or -1) that indicates the contents of all the\n * other 32-bit pieces out to infinity. We use 32-bit pieces because these are\n * the size of integers on which JavaScript performs bit-operations. For\n * operations like addition and multiplication, we split each number into 16-bit\n * pieces, which can easily be multiplied within JavaScript's floating-point\n * representation without overflow or change in sign.\n *\n * @struct\n * @constructor\n * @param {Array<number>} bits Array containing the bits of the number.\n * @param {number} sign The sign of the number: -1 for negative and 0 positive.\n * @final\n */\ngoog.math.Integer = function(bits, sign) {\n 'use strict';\n /**\n * @type {number}\n * @private\n */\n this.sign_ = sign;\n\n // Note: using a local variable while initializing the array helps the\n // compiler understand that assigning to the array is local side-effect and\n // that enables the entire constructor to be seen as side-effect free.\n var localBits = [];\n\n // Copy the 32-bit signed integer values passed in. We prune out those at the\n // top that equal the sign since they are redundant.\n var top = true;\n\n for (var i = bits.length - 1; i >= 0; i--) {\n var val = bits[i] | 0;\n if (!top || val != sign) {\n localBits[i] = val;\n top = false;\n }\n }\n\n /**\n * @type {!Array<number>}\n * @private\n * @const\n */\n this.bits_ = localBits;\n};\n\n\n// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the\n// from* methods on which they depend.\n\n\n/**\n * A cache of the Integer representations of small integer values.\n * @type {!Object<number, !goog.math.Integer>}\n * @private\n */\ngoog.math.Integer.IntCache_ = {};\n\n\n/**\n * Returns an Integer representing the given (32-bit) integer value.\n * @param {number} value A 32-bit integer value.\n * @return {!goog.math.Integer} The corresponding Integer value.\n */\ngoog.math.Integer.fromInt = function(value) {\n 'use strict';\n if (-128 <= value && value < 128) {\n return goog.reflect.cache(\n goog.math.Integer.IntCache_, value, function(val) {\n 'use strict';\n return new goog.math.Integer([val | 0], val < 0 ? -1 : 0);\n });\n }\n return new goog.math.Integer([value | 0], value < 0 ? -1 : 0);\n};\n\n\n/**\n * Returns an Integer representing the given value, provided that it is a finite\n * number. Otherwise, zero is returned.\n * @param {number} value The value in question.\n * @return {!goog.math.Integer} The corresponding Integer value.\n */\ngoog.math.Integer.fromNumber = function(value) {\n 'use strict';\n if (isNaN(value) || !isFinite(value)) {\n return goog.math.Integer.ZERO;\n } else if (value < 0) {\n return goog.math.Integer.fromNumber(-value).negate();\n } else {\n var bits = [];\n var pow = 1;\n for (var i = 0; value >= pow; i++) {\n bits[i] = (value / pow) | 0;\n pow *= goog.math.Integer.TWO_PWR_32_DBL_;\n }\n return new goog.math.Integer(bits, 0);\n }\n};\n\n\n/**\n * Returns a Integer representing the value that comes by concatenating the\n * given entries, each is assumed to be 32 signed bits, given in little-endian\n * order (lowest order bits in the lowest index), and sign-extending the highest\n * order 32-bit value.\n * @param {Array<number>} bits The bits of the number, in 32-bit signed pieces,\n * in little-endian order.\n * @return {!goog.math.Integer} The corresponding Integer value.\n */\ngoog.math.Integer.fromBits = function(bits) {\n 'use strict';\n var high = bits[bits.length - 1];\n return new goog.math.Integer(bits, high & (1 << 31) ? -1 : 0);\n};\n\n\n/**\n * Returns an Integer representation of the given string, written using the\n * given radix.\n * @param {string} str The textual representation of the Integer.\n * @param {number=} opt_radix The radix in which the text is written.\n * @return {!goog.math.Integer} The corresponding Integer value.\n */\ngoog.math.Integer.fromString = function(str, opt_radix) {\n 'use strict';\n if (str.length == 0) {\n throw new Error('number format error: empty string');\n }\n\n var radix = opt_radix || 10;\n if (radix < 2 || 36 < radix) {\n throw new Error('radix out of range: ' + radix);\n }\n\n if (str.charAt(0) == '-') {\n return goog.math.Integer.fromString(str.substring(1), radix).negate();\n } else if (str.indexOf('-') >= 0) {\n throw new Error('number format error: interior \"-\" character');\n }\n\n // Do several (8) digits each time through the loop, so as to\n // minimize the calls to the very expensive emulated div.\n var radixToPower = goog.math.Integer.fromNumber(Math.pow(radix, 8));\n\n var result = goog.math.Integer.ZERO;\n for (var i = 0; i < str.length; i += 8) {\n var size = Math.min(8, str.length - i);\n var value = parseInt(str.substring(i, i + size), radix);\n if (size < 8) {\n var power = goog.math.Integer.fromNumber(Math.pow(radix, size));\n result = result.multiply(power).add(goog.math.Integer.fromNumber(value));\n } else {\n result = result.multiply(radixToPower);\n result = result.add(goog.math.Integer.fromNumber(value));\n }\n }\n return result;\n};\n\n\n/**\n * A number used repeatedly in calculations. This must appear before the first\n * call to the from* functions below.\n * @type {number}\n * @private\n */\ngoog.math.Integer.TWO_PWR_32_DBL_ = (1 << 16) * (1 << 16);\n\n\n/** @type {!goog.math.Integer} */\ngoog.math.Integer.ZERO = goog.math.Integer.fromInt(0);\n\n/** @type {!goog.math.Integer} */\ngoog.math.Integer.ONE = goog.math.Integer.fromInt(1);\n\n\n/**\n * @const\n * @type {!goog.math.Integer}\n * @private\n */\ngoog.math.Integer.TWO_PWR_24_ = goog.math.Integer.fromInt(1 << 24);\n\n/**\n * Returns the value, assuming it is a 32-bit integer.\n * @return {number} The corresponding int value.\n */\ngoog.math.Integer.prototype.toInt = function() {\n 'use strict';\n return this.bits_.length > 0 ? this.bits_[0] : this.sign_;\n};\n\n\n/** @return {number} The closest floating-point representation to this value. */\ngoog.math.Integer.prototype.toNumber = function() {\n 'use strict';\n if (this.isNegative()) {\n return -this.negate().toNumber();\n } else {\n var val = 0;\n var pow = 1;\n for (var i = 0; i < this.bits_.length; i++) {\n val += this.getBitsUnsigned(i) * pow;\n pow *= goog.math.Integer.TWO_PWR_32_DBL_;\n }\n return val;\n }\n};\n\n\n/**\n * @param {number=} opt_radix The radix in which the text should be written.\n * @return {string} The textual representation of this value.\n * @override\n */\ngoog.math.Integer.prototype.toString = function(opt_radix) {\n 'use strict';\n var radix = opt_radix || 10;\n if (radix < 2 || 36 < radix) {\n throw new Error('radix out of range: ' + radix);\n }\n\n if (this.isZero()) {\n return '0';\n } else if (this.isNegative()) {\n return '-' + this.negate().toString(radix);\n }\n\n // Do several (6) digits each time through the loop, so as to\n // minimize the calls to the very expensive emulated div.\n var radixToPower = goog.math.Integer.fromNumber(Math.pow(radix, 6));\n\n var rem = this;\n var result = '';\n while (true) {\n var remDiv = rem.divide(radixToPower);\n // The right shifting fixes negative values in the case when\n // intval >= 2^31; for more details see\n // https://github.com/google/closure-library/pull/498\n var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt() >>> 0;\n var digits = intval.toString(radix);\n\n rem = remDiv;\n if (rem.isZero()) {\n return digits + result;\n } else {\n while (digits.length < 6) {\n digits = '0' + digits;\n }\n result = '' + digits + result;\n }\n }\n};\n\n\n/**\n * Returns the index-th 32-bit (signed) piece of the Integer according to\n * little-endian order (i.e., index 0 contains the smallest bits).\n * @param {number} index The index in question.\n * @return {number} The requested 32-bits as a signed number.\n */\ngoog.math.Integer.prototype.getBits = function(index) {\n 'use strict';\n if (index < 0) {\n return 0; // Allowing this simplifies bit shifting operations below...\n } else if (index < this.bits_.length) {\n return this.bits_[index];\n } else {\n return this.sign_;\n }\n};\n\n\n/**\n * Returns the index-th 32-bit piece as an unsigned number.\n * @param {number} index The index in question.\n * @return {number} The requested 32-bits as an unsigned number.\n */\ngoog.math.Integer.prototype.getBitsUnsigned = function(index) {\n 'use strict';\n var val = this.getBits(index);\n return val >= 0 ? val : goog.math.Integer.TWO_PWR_32_DBL_ + val;\n};\n\n\n/** @return {number} The sign bit of this number, -1 or 0. */\ngoog.math.Integer.prototype.getSign = function() {\n 'use strict';\n return this.sign_;\n};\n\n\n/** @return {boolean} Whether this value is zero. */\ngoog.math.Integer.prototype.isZero = function() {\n 'use strict';\n if (this.sign_ != 0) {\n return false;\n }\n for (var i = 0; i < this.bits_.length; i++) {\n if (this.bits_[i] != 0) {\n return false;\n }\n }\n return true;\n};\n\n\n/** @return {boolean} Whether this value is negative. */\ngoog.math.Integer.prototype.isNegative = function() {\n 'use strict';\n return this.sign_ == -1;\n};\n\n\n/** @return {boolean} Whether this value is odd. */\ngoog.math.Integer.prototype.isOdd = function() {\n 'use strict';\n return (this.bits_.length == 0) && (this.sign_ == -1) ||\n (this.bits_.length > 0) && ((this.bits_[0] & 1) != 0);\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer equals the other.\n */\ngoog.math.Integer.prototype.equals = function(other) {\n 'use strict';\n if (this.sign_ != other.sign_) {\n return false;\n }\n var len = Math.max(this.bits_.length, other.bits_.length);\n for (var i = 0; i < len; i++) {\n if (this.getBits(i) != other.getBits(i)) {\n return false;\n }\n }\n return true;\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer does not equal the other.\n */\ngoog.math.Integer.prototype.notEquals = function(other) {\n 'use strict';\n return !this.equals(other);\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer is greater than the other.\n */\ngoog.math.Integer.prototype.greaterThan = function(other) {\n 'use strict';\n return this.compare(other) > 0;\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer is greater than or equal to the other.\n */\ngoog.math.Integer.prototype.greaterThanOrEqual = function(other) {\n 'use strict';\n return this.compare(other) >= 0;\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer is less than the other.\n */\ngoog.math.Integer.prototype.lessThan = function(other) {\n 'use strict';\n return this.compare(other) < 0;\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer is less than or equal to the other.\n */\ngoog.math.Integer.prototype.lessThanOrEqual = function(other) {\n 'use strict';\n return this.compare(other) <= 0;\n};\n\n\n/**\n * Compares this Integer with the given one.\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {number} 0 if they are the same, 1 if the this is greater, and -1\n * if the given one is greater.\n */\ngoog.math.Integer.prototype.compare = function(other) {\n 'use strict';\n var diff = this.subtract(other);\n if (diff.isNegative()) {\n return -1;\n } else if (diff.isZero()) {\n return 0;\n } else {\n return +1;\n }\n};\n\n\n/**\n * Returns an integer with only the first numBits bits of this value, sign\n * extended from the final bit.\n * @param {number} numBits The number of bits by which to shift.\n * @return {!goog.math.Integer} The shorted integer value.\n */\ngoog.math.Integer.prototype.shorten = function(numBits) {\n 'use strict';\n var arr_index = (numBits - 1) >> 5;\n var bit_index = (numBits - 1) % 32;\n var bits = [];\n for (var i = 0; i < arr_index; i++) {\n bits[i] = this.getBits(i);\n }\n var sigBits = bit_index == 31 ? 0xFFFFFFFF : (1 << (bit_index + 1)) - 1;\n var val = this.getBits(arr_index) & sigBits;\n if (val & (1 << bit_index)) {\n val |= 0xFFFFFFFF - sigBits;\n bits[arr_index] = val;\n return new goog.math.Integer(bits, -1);\n } else {\n bits[arr_index] = val;\n return new goog.math.Integer(bits, 0);\n }\n};\n\n\n/** @return {!goog.math.Integer} The negation of this value. */\ngoog.math.Integer.prototype.negate = function() {\n 'use strict';\n return this.not().add(goog.math.Integer.ONE);\n};\n\n\n/** @return {!goog.math.Integer} The absolute value of this value. */\ngoog.math.Integer.prototype.abs = function() {\n 'use strict';\n return this.isNegative() ? this.negate() : this;\n};\n\n\n/**\n * Returns the sum of this and the given Integer.\n * @param {goog.math.Integer} other The Integer to add to this.\n * @return {!goog.math.Integer} The Integer result.\n */\ngoog.math.Integer.prototype.add = function(other) {\n 'use strict';\n var len = Math.max(this.bits_.length, other.bits_.length);\n var arr = [];\n var carry = 0;\n\n for (var i = 0; i <= len; i++) {\n var a1 = this.getBits(i) >>> 16;\n var a0 = this.getBits(i) & 0xFFFF;\n\n var b1 = other.getBits(i) >>> 16;\n var b0 = other.getBits(i) & 0xFFFF;\n\n var c0 = carry + a0 + b0;\n var c1 = (c0 >>> 16) + a1 + b1;\n carry = c1 >>> 16;\n c0 &= 0xFFFF;\n c1 &= 0xFFFF;\n arr[i] = (c1 << 16) | c0;\n }\n return goog.math.Integer.fromBits(arr);\n};\n\n\n/**\n * Returns the difference of this and the given Integer.\n * @param {goog.math.Integer} other The Integer to subtract from this.\n * @return {!goog.math.Integer} The Integer result.\n */\ngoog.math.Integer.prototype.subtract = function(other) {\n 'use strict';\n return this.add(other.negate());\n};\n\n\n/**\n * Returns the product of this and the given Integer.\n * @param {goog.math.Integer} other The Integer to multiply against this.\n * @return {!goog.math.Integer} The product of this and the other.\n */\ngoog.math.Integer.prototype.multiply = function(other) {\n 'use strict';\n if (this.isZero()) {\n return goog.math.Integer.ZERO;\n } else if (other.isZero()) {\n return goog.math.Integer.ZERO;\n }\n\n if (this.isNegative()) {\n if (other.isNegative()) {\n return this.negate().multiply(other.negate());\n } else {\n return this.negate().multiply(other).negate();\n }\n } else if (other.isNegative()) {\n return this.multiply(other.negate()).negate();\n }\n\n // If both numbers are small, use float multiplication\n if (this.lessThan(goog.math.Integer.TWO_PWR_24_) &&\n other.lessThan(goog.math.Integer.TWO_PWR_24_)) {\n return goog.math.Integer.fromNumber(this.toNumber() * other.toNumber());\n }\n\n // Fill in an array of 16-bit products.\n var len = this.bits_.length + other.bits_.length;\n var arr = [];\n for (var i = 0; i < 2 * len; i++) {\n arr[i] = 0;\n }\n for (var i = 0; i < this.bits_.length; i++) {\n for (var j = 0; j < other.bits_.length; j++) {\n var a1 = this.getBits(i) >>> 16;\n var a0 = this.getBits(i) & 0xFFFF;\n\n var b1 = other.getBits(j) >>> 16;\n var b0 = other.getBits(j) & 0xFFFF;\n\n arr[2 * i + 2 * j] += a0 * b0;\n goog.math.Integer.carry16_(arr, 2 * i + 2 * j);\n arr[2 * i + 2 * j + 1] += a1 * b0;\n goog.math.Integer.carry16_(arr, 2 * i + 2 * j + 1);\n arr[2 * i + 2 * j + 1] += a0 * b1;\n goog.math.Integer.carry16_(arr, 2 * i + 2 * j + 1);\n arr[2 * i + 2 * j + 2] += a1 * b1;\n goog.math.Integer.carry16_(arr, 2 * i + 2 * j + 2);\n }\n }\n\n // Combine the 16-bit values into 32-bit values.\n for (var i = 0; i < len; i++) {\n arr[i] = (arr[2 * i + 1] << 16) | arr[2 * i];\n }\n for (var i = len; i < 2 * len; i++) {\n arr[i] = 0;\n }\n return new goog.math.Integer(arr, 0);\n};\n\n\n/**\n * Carries any overflow from the given index into later entries.\n * @param {Array<number>} bits Array of 16-bit values in little-endian order.\n * @param {number} index The index in question.\n * @private\n */\ngoog.math.Integer.carry16_ = function(bits, index) {\n 'use strict';\n while ((bits[index] & 0xFFFF) != bits[index]) {\n bits[index + 1] += bits[index] >>> 16;\n bits[index] &= 0xFFFF;\n index++;\n }\n};\n\n\n/**\n * Returns \"this\" Integer divided by the given one. Both \"this\" and the given\n * Integer MUST be positive.\n *\n * This method is only needed for very large numbers (>10^308),\n * for which the original division algorithm gets into an infinite\n * loop (see https://github.com/google/closure-library/issues/500).\n *\n * The algorithm has some possible performance enhancements (or\n * could be rewritten entirely), it's just an initial solution for\n * the issue linked above.\n *\n * @param {!goog.math.Integer} other The Integer to divide \"this\" by.\n * @return {!goog.math.Integer.DivisionResult}\n * @private\n */\ngoog.math.Integer.prototype.slowDivide_ = function(other) {\n 'use strict';\n if (this.isNegative() || other.isNegative()) {\n throw new Error('slowDivide_ only works with positive integers.');\n }\n\n var twoPower = goog.math.Integer.ONE;\n var multiple = other;\n\n // First we have to figure out what the highest bit of the result\n // is, so we increase \"twoPower\" and \"multiple\" until \"multiple\"\n // exceeds \"this\".\n while (multiple.lessThanOrEqual(this)) {\n twoPower = twoPower.shiftLeft(1);\n multiple = multiple.shiftLeft(1);\n }\n\n // Rewind by one power of two, giving us the highest bit of the\n // result.\n var res = twoPower.shiftRight(1);\n var total = multiple.shiftRight(1);\n\n // Now we starting decreasing \"multiple\" and \"twoPower\" to find the\n // rest of the bits of the result.\n var total2;\n multiple = multiple.shiftRight(2);\n twoPower = twoPower.shiftRight(2);\n while (!multiple.isZero()) {\n // whenever we can add \"multiple\" to the total and not exceed\n // \"this\", that means we've found a 1 bit. Else we've found a 0\n // and don't need to add to the result.\n total2 = total.add(multiple);\n if (total2.lessThanOrEqual(this)) {\n res = res.add(twoPower);\n total = total2;\n }\n multiple = multiple.shiftRight(1);\n twoPower = twoPower.shiftRight(1);\n }\n\n\n // TODO(user): Calculate this more efficiently during the division.\n // This is kind of a waste since it isn't always needed, but it keeps the\n // API smooth. Since this is already a slow path it probably isn't a big deal.\n var remainder = this.subtract(res.multiply(other));\n return new goog.math.Integer.DivisionResult(res, remainder);\n};\n\n\n/**\n * Returns this Integer divided by the given one.\n * @param {!goog.math.Integer} other The Integer to divide this by.\n * @return {!goog.math.Integer} This value divided by the given one.\n */\ngoog.math.Integer.prototype.divide = function(other) {\n 'use strict';\n return this.divideAndRemainder(other).quotient;\n};\n\n\n/**\n * A struct for holding the quotient and remainder of a division.\n *\n * @constructor\n * @final\n * @struct\n *\n * @param {!goog.math.Integer} quotient\n * @param {!goog.math.Integer} remainder\n */\ngoog.math.Integer.DivisionResult = function(quotient, remainder) {\n 'use strict';\n /** @const */\n this.quotient = quotient;\n\n /** @const */\n this.remainder = remainder;\n};\n\n\n/**\n * Returns this Integer divided by the given one, as well as the remainder of\n * that division.\n *\n * @param {!goog.math.Integer} other The Integer to divide this by.\n * @return {!goog.math.Integer.DivisionResult}\n */\ngoog.math.Integer.prototype.divideAndRemainder = function(other) {\n 'use strict';\n if (other.isZero()) {\n throw new Error('division by zero');\n } else if (this.isZero()) {\n return new goog.math.Integer.DivisionResult(\n goog.math.Integer.ZERO, goog.math.Integer.ZERO);\n }\n\n if (this.isNegative()) {\n // Do the division on the negative of the numerator...\n var result = this.negate().divideAndRemainder(other);\n return new goog.math.Integer.DivisionResult(\n // ...and flip the sign back after.\n result.quotient.negate(),\n // The remainder must always have the same sign as the numerator.\n result.remainder.negate());\n } else if (other.isNegative()) {\n // Do the division on the negative of the denominator...\n var result = this.divideAndRemainder(other.negate());\n return new goog.math.Integer.DivisionResult(\n // ...and flip the sign back after.\n result.quotient.negate(),\n // The remainder must always have the same sign as the numerator.\n result.remainder);\n }\n\n // Have to degrade to slowDivide for Very Large Numbers, because\n // they're out of range for the floating-point approximation\n // technique used below.\n if (this.bits_.length > 30) {\n return this.slowDivide_(other);\n }\n\n // Repeat the following until the remainder is less than other: find a\n // floating-point that approximates remainder / other *from below*, add this\n // into the result, and subtract it from the remainder. It is critical that\n // the approximate value is less than or equal to the real value so that the\n // remainder never becomes negative.\n var res = goog.math.Integer.ZERO;\n var rem = this;\n while (rem.greaterThanOrEqual(other)) {\n // Approximate the result of division. This may be a little greater or\n // smaller than the actual value.\n var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));\n\n // We will tweak the approximate result by changing it in the 48-th digit or\n // the smallest non-fractional digit, whichever is larger.\n var log2 = Math.ceil(Math.log(approx) / Math.LN2);\n var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48);\n\n // Decrease the approximation until it is smaller than the remainder. Note\n // that if it is too large, the product overflows and is negative.\n var approxRes = goog.math.Integer.fromNumber(approx);\n var approxRem = approxRes.multiply(other);\n while (approxRem.isNegative() || approxRem.greaterThan(rem)) {\n approx -= delta;\n approxRes = goog.math.Integer.fromNumber(approx);\n approxRem = approxRes.multiply(other);\n }\n\n // We know the answer can't be zero... and actually, zero would cause\n // infinite recursion since we would make no progress.\n if (approxRes.isZero()) {\n approxRes = goog.math.Integer.ONE;\n }\n\n res = res.add(approxRes);\n rem = rem.subtract(approxRem);\n }\n return new goog.math.Integer.DivisionResult(res, rem);\n};\n\n\n/**\n * Returns this Integer modulo the given one.\n * @param {!goog.math.Integer} other The Integer by which to mod.\n * @return {!goog.math.Integer} This value modulo the given one.\n */\ngoog.math.Integer.prototype.modulo = function(other) {\n 'use strict';\n return this.divideAndRemainder(other).remainder;\n};\n\n\n/** @return {!goog.math.Integer} The bitwise-NOT of this value. */\ngoog.math.Integer.prototype.not = function() {\n 'use strict';\n var len = this.bits_.length;\n var arr = [];\n for (var i = 0; i < len; i++) {\n arr[i] = ~this.bits_[i];\n }\n return new goog.math.Integer(arr, ~this.sign_);\n};\n\n\n/**\n * Returns the bitwise-AND of this Integer and the given one.\n * @param {goog.math.Integer} other The Integer to AND with this.\n * @return {!goog.math.Integer} The bitwise-AND of this and the other.\n */\ngoog.math.Integer.prototype.and = function(other) {\n 'use strict';\n var len = Math.max(this.bits_.length, other.bits_.length);\n var arr = [];\n for (var i = 0; i < len; i++) {\n arr[i] = this.getBits(i) & other.getBits(i);\n }\n return new goog.math.Integer(arr, this.sign_ & other.sign_);\n};\n\n\n/**\n * Returns the bitwise-OR of this Integer and the given one.\n * @param {goog.math.Integer} other The Integer to OR with this.\n * @return {!goog.math.Integer} The bitwise-OR of this and the other.\n */\ngoog.math.Integer.prototype.or = function(other) {\n 'use strict';\n var len = Math.max(this.bits_.length, other.bits_.length);\n var arr = [];\n for (var i = 0; i < len; i++) {\n arr[i] = this.getBits(i) | other.getBits(i);\n }\n return new goog.math.Integer(arr, this.sign_ | other.sign_);\n};\n\n\n/**\n * Returns the bitwise-XOR of this Integer and the given one.\n * @param {goog.math.Integer} other The Integer to XOR with this.\n * @return {!goog.math.Integer} The bitwise-XOR of this and the other.\n */\ngoog.math.Integer.prototype.xor = function(other) {\n 'use strict';\n var len = Math.max(this.bits_.length, other.bits_.length);\n var arr = [];\n for (var i = 0; i < len; i++) {\n arr[i] = this.getBits(i) ^ other.getBits(i);\n }\n return new goog.math.Integer(arr, this.sign_ ^ other.sign_);\n};\n\n\n/**\n * Returns this value with bits shifted to the left by the given amount.\n * @param {number} numBits The number of bits by which to shift.\n * @return {!goog.math.Integer} This shifted to the left by the given amount.\n */\ngoog.math.Integer.prototype.shiftLeft = function(numBits) {\n 'use strict';\n var arr_delta = numBits >> 5;\n var bit_delta = numBits % 32;\n var len = this.bits_.length + arr_delta + (bit_delta > 0 ? 1 : 0);\n var arr = [];\n for (var i = 0; i < len; i++) {\n if (bit_delta > 0) {\n arr[i] = (this.getBits(i - arr_delta) << bit_delta) |\n (this.getBits(i - arr_delta - 1) >>> (32 - bit_delta));\n } else {\n arr[i] = this.getBits(i - arr_delta);\n }\n }\n return new goog.math.Integer(arr, this.sign_);\n};\n\n\n/**\n * Returns this value with bits shifted to the right by the given amount.\n * @param {number} numBits The number of bits by which to shift.\n * @return {!goog.math.Integer} This shifted to the right by the given amount.\n */\ngoog.math.Integer.prototype.shiftRight = function(numBits) {\n 'use strict';\n var arr_delta = numBits >> 5;\n var bit_delta = numBits % 32;\n var len = this.bits_.length - arr_delta;\n var arr = [];\n for (var i = 0; i < len; i++) {\n if (bit_delta > 0) {\n arr[i] = (this.getBits(i + arr_delta) >>> bit_delta) |\n (this.getBits(i + arr_delta + 1) << (32 - bit_delta));\n } else {\n arr[i] = this.getBits(i + arr_delta);\n }\n }\n return new goog.math.Integer(arr, this.sign_);\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Transport support for WebChannel.\n *\n * The <code>WebChannelTransport</code> implementation serves as the factory\n * for <code>WebChannel</code>, which offers an abstraction for\n * point-to-point socket-like communication similar to what BrowserChannel\n * or HTML5 WebSocket offers.\n */\n\ngoog.provide('goog.net.WebChannelTransport');\n\ngoog.requireType('goog.net.WebChannel');\ngoog.requireType('goog.net.WebChannel.Options');\n\n\n\n/**\n * A WebChannelTransport instance represents a shared context of logical\n * connectivity between a browser client and a remote origin.\n *\n * Over a single WebChannelTransport instance, multiple WebChannels may be\n * created against different URLs, which may all share the same\n * underlying connectivity (i.e. TCP connection) whenever possible.\n *\n * When multi-domains are supported, such as CORS, multiple origins may be\n * supported over a single WebChannelTransport instance at the same time.\n *\n * Sharing between different window contexts such as tabs is not addressed\n * by WebChannelTransport. Applications may choose HTML5 shared workers\n * or other techniques to access the same transport instance\n * across different window contexts.\n *\n * @interface\n */\ngoog.net.WebChannelTransport = function() {};\n\n\n/**\n * The client version. This integer value will be passed to the server\n * when a channel is opened to inform the server the client \"capabilities\".\n *\n * Wire protocol version is a different concept and is internal to the\n * transport implementation.\n *\n * @const\n * @type {number}\n */\ngoog.net.WebChannelTransport.CLIENT_VERSION = 22;\n\n\n/**\n * Create a new WebChannel instance.\n *\n * The new WebChannel is to be opened against the server-side resource\n * as specified by the given URL. See {@link goog.net.WebChannel} for detailed\n * semantics.\n *\n * @param {string} url The URL path for the new WebChannel instance.\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\n * new WebChannel instance. The configuration object is reusable after\n * the new channel instance is created.\n * @return {!goog.net.WebChannel} the newly created WebChannel instance.\n */\ngoog.net.WebChannelTransport.prototype.createWebChannel = goog.abstractMethod;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Bring in closure-library dependencies\n */\n\ngoog.provide('firebase.webchannel.wrapper');\n\n// goog.net.WebChannelTransport\ngoog.require('goog.net.createWebChannelTransport');\ngoog.require('goog.net.FetchXmlHttpFactory');\ngoog.require('goog.labs.net.webChannel.requestStats');\ngoog.require('goog.labs.net.webChannel.WebChannelBaseTransport');\n\n/**\n * NOTE: The `createWebChannel` function takes an options object as a second param\n * whose properties are typically mangled. We override these in externs/overrides.js\n * Without those externs, this does not function properly.\n */\ngoog.labs.net.webChannel.WebChannelBaseTransport.prototype['createWebChannel'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.prototype.createWebChannel;\ngoog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype['send'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.send;\ngoog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype['open'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.open;\ngoog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype['close'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.close;\n\n// goog.net.ErrorCode\ngoog.require('goog.net.ErrorCode');\ngoog.net.ErrorCode['NO_ERROR'] = goog.net.ErrorCode.NO_ERROR;\ngoog.net.ErrorCode['TIMEOUT'] = goog.net.ErrorCode.TIMEOUT;\ngoog.net.ErrorCode['HTTP_ERROR'] = goog.net.ErrorCode.HTTP_ERROR;\n\n// goog.net.ErrorType\ngoog.require('goog.net.EventType');\ngoog.net.EventType['COMPLETE'] = goog.net.EventType.COMPLETE;\n\n// goog.net.WebChannel\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.events.EventTarget');\ngoog.net.WebChannel['EventType'] = goog.net.WebChannel.EventType;\ngoog.net.WebChannel.EventType['OPEN'] = goog.net.WebChannel.EventType.OPEN;\ngoog.net.WebChannel.EventType['CLOSE'] = goog.net.WebChannel.EventType.CLOSE;\ngoog.net.WebChannel.EventType['ERROR'] = goog.net.WebChannel.EventType.ERROR;\ngoog.net.WebChannel.EventType['MESSAGE'] =\n goog.net.WebChannel.EventType.MESSAGE;\ngoog.events.EventTarget.prototype['listen'] =\n goog.events.EventTarget.prototype.listen;\n\ngoog.require('goog.net.XhrIo');\ngoog.net.XhrIo.prototype['listenOnce'] = goog.net.XhrIo.prototype.listenOnce;\ngoog.net.XhrIo.prototype['getLastError'] =\n goog.net.XhrIo.prototype.getLastError;\ngoog.net.XhrIo.prototype['getLastErrorCode'] =\n goog.net.XhrIo.prototype.getLastErrorCode;\ngoog.net.XhrIo.prototype['getStatus'] = goog.net.XhrIo.prototype.getStatus;\ngoog.net.XhrIo.prototype['getResponseJson'] =\n goog.net.XhrIo.prototype.getResponseJson;\ngoog.net.XhrIo.prototype['getResponseText'] =\n goog.net.XhrIo.prototype.getResponseText;\ngoog.net.XhrIo.prototype['send'] = goog.net.XhrIo.prototype.send;\ngoog.net.XhrIo.prototype['setWithCredentials'] =\n goog.net.XhrIo.prototype.setWithCredentials;\n\ngoog.require('goog.crypt.Md5');\ngoog.crypt.Md5.prototype['digest'] = goog.crypt.Md5.prototype.digest;\ngoog.crypt.Md5.prototype['reset'] = goog.crypt.Md5.prototype.reset;\ngoog.crypt.Md5.prototype['update'] = goog.crypt.Md5.prototype.update;\n\ngoog.require('goog.math.Integer');\ngoog.math.Integer.prototype['add'] = goog.math.Integer.prototype.add;\ngoog.math.Integer.prototype['multiply'] = goog.math.Integer.prototype.multiply;\ngoog.math.Integer.prototype['modulo'] = goog.math.Integer.prototype.modulo;\ngoog.math.Integer.prototype['compare'] = goog.math.Integer.prototype.compare;\ngoog.math.Integer.prototype['toNumber'] = goog.math.Integer.prototype.toNumber;\ngoog.math.Integer.prototype['toString'] = goog.math.Integer.prototype.toString;\ngoog.math.Integer.prototype['getBits'] = goog.math.Integer.prototype.getBits;\ngoog.math.Integer['fromNumber'] = goog.math.Integer.fromNumber;\ngoog.math.Integer['fromString'] = goog.math.Integer.fromString;\n\nmodule['exports']['createWebChannelTransport'] =\n goog.net.createWebChannelTransport;\nmodule['exports']['getStatEventTarget'] =\n goog.labs.net.webChannel.requestStats.getStatEventTarget;\nmodule['exports']['ErrorCode'] = goog.net.ErrorCode;\nmodule['exports']['EventType'] = goog.net.EventType;\nmodule['exports']['Event'] = goog.labs.net.webChannel.requestStats.Event;\nmodule['exports']['Stat'] = goog.labs.net.webChannel.requestStats.Stat;\nmodule['exports']['FetchXmlHttpFactory'] = goog.net.FetchXmlHttpFactory;\nmodule['exports']['WebChannel'] = goog.net.WebChannel;\nmodule['exports']['XhrIo'] = goog.net.XhrIo;\nmodule['exports']['Md5'] = goog.crypt.Md5;\nmodule['exports']['Integer'] = goog.math.Integer;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Default factory for <code>WebChannelTransport</code> to\n * avoid exposing concrete classes to clients.\n */\n\ngoog.provide('goog.net.createWebChannelTransport');\n\ngoog.require('goog.labs.net.webChannel.WebChannelBaseTransport');\ngoog.requireType('goog.net.WebChannelTransport');\n\n\n/**\n * Create a new WebChannelTransport instance using the default implementation.\n * Throws an error message if no default transport available in the current\n * environment.\n *\n * @return {!goog.net.WebChannelTransport} the newly created transport instance.\n */\ngoog.net.createWebChannelTransport = function() {\n 'use strict';\n return new goog.labs.net.webChannel.WebChannelBaseTransport();\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n * <ul>\n * <li>`debug` for the most verbose logging level, primarily for\n * debugging.</li>\n * <li>`error` to log errors only.</li>\n * <li><code>`silent` to turn off logging.</li>\n * </ul>\n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n logClient.setLogLevel(logLevel);\n}\n\nexport function logDebug(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n const args = obj.map(argToString);\n logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function logError(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n const args = obj.map(argToString);\n logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * @internal\n */\nexport function logWarn(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n const args = obj.map(argToString);\n logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj: unknown): string | unknown {\n if (typeof obj === 'string') {\n return obj;\n } else {\n try {\n return formatJSON(obj);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Formats an object as a JSON string, suitable for logging. */\nexport function formatJSON(value: unknown): string {\n return JSON.stringify(value);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../core/version';\n\nimport { logError } from './log';\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */\nexport function fail(failure: string = 'Unexpected state'): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const message =\n `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ` + failure;\n logError(message);\n\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n */\nexport function hardAssert(\n assertion: boolean,\n message?: string\n): asserts assertion {\n if (!assertion) {\n fail(message);\n }\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */\nexport function debugAssert(\n assertion: boolean,\n message: string\n): asserts assertion {\n if (!assertion) {\n fail(message);\n }\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */\nexport function debugCast<T>(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n debugAssert(\n obj instanceof constructor,\n `Expected type '${constructor.name}', but was '${obj.constructor.name}'`\n );\n return obj as T;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * The set of Firestore status codes. The codes are the same at the ones\n * exposed by gRPC here:\n * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md\n *\n * Possible values:\n * - 'cancelled': The operation was cancelled (typically by the caller).\n * - 'unknown': Unknown error or an error from a different error domain.\n * - 'invalid-argument': Client specified an invalid argument. Note that this\n * differs from 'failed-precondition'. 'invalid-argument' indicates\n * arguments that are problematic regardless of the state of the system\n * (e.g. an invalid field name).\n * - 'deadline-exceeded': Deadline expired before operation could complete.\n * For operations that change the state of the system, this error may be\n * returned even if the operation has completed successfully. For example,\n * a successful response from a server could have been delayed long enough\n * for the deadline to expire.\n * - 'not-found': Some requested document was not found.\n * - 'already-exists': Some document that we attempted to create already\n * exists.\n * - 'permission-denied': The caller does not have permission to execute the\n * specified operation.\n * - 'resource-exhausted': Some resource has been exhausted, perhaps a\n * per-user quota, or perhaps the entire file system is out of space.\n * - 'failed-precondition': Operation was rejected because the system is not\n * in a state required for the operation's execution.\n * - 'aborted': The operation was aborted, typically due to a concurrency\n * issue like transaction aborts, etc.\n * - 'out-of-range': Operation was attempted past the valid range.\n * - 'unimplemented': Operation is not implemented or not supported/enabled.\n * - 'internal': Internal errors. Means some invariants expected by\n * underlying system has been broken. If you see one of these errors,\n * something is very broken.\n * - 'unavailable': The service is currently unavailable. This is most likely\n * a transient condition and may be corrected by retrying with a backoff.\n * - 'data-loss': Unrecoverable data loss or corruption.\n * - 'unauthenticated': The request does not have valid authentication\n * credentials for the operation.\n */\nexport type FirestoreErrorCode =\n | 'cancelled'\n | 'unknown'\n | 'invalid-argument'\n | 'deadline-exceeded'\n | 'not-found'\n | 'already-exists'\n | 'permission-denied'\n | 'resource-exhausted'\n | 'failed-precondition'\n | 'aborted'\n | 'out-of-range'\n | 'unimplemented'\n | 'internal'\n | 'unavailable'\n | 'data-loss'\n | 'unauthenticated';\n\n/**\n * Error Codes describing the different ways Firestore can fail. These come\n * directly from GRPC.\n */\nexport type Code = FirestoreErrorCode;\n\nexport const Code = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: 'ok' as FirestoreErrorCode,\n\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: 'cancelled' as FirestoreErrorCode,\n\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: 'unknown' as FirestoreErrorCode,\n\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: 'invalid-argument' as FirestoreErrorCode,\n\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: 'deadline-exceeded' as FirestoreErrorCode,\n\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: 'not-found' as FirestoreErrorCode,\n\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: 'already-exists' as FirestoreErrorCode,\n\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller can not be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: 'permission-denied' as FirestoreErrorCode,\n\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: 'unauthenticated' as FirestoreErrorCode,\n\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: 'resource-exhausted' as FirestoreErrorCode,\n\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: 'failed-precondition' as FirestoreErrorCode,\n\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: 'aborted' as FirestoreErrorCode,\n\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: 'out-of-range' as FirestoreErrorCode,\n\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: 'unimplemented' as FirestoreErrorCode,\n\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: 'internal' as FirestoreErrorCode,\n\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: 'unavailable' as FirestoreErrorCode,\n\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: 'data-loss' as FirestoreErrorCode\n};\n\n/** An error returned by a Firestore operation. */\nexport class FirestoreError extends FirebaseError {\n /** The stack of the error. */\n readonly stack?: string;\n\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n readonly code: FirestoreErrorCode,\n /**\n * A custom error description.\n */\n readonly message: string\n ) {\n super(code, message);\n\n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Resolver<R> {\n (value: R | Promise<R>): void;\n}\n\nexport interface Rejecter {\n (reason?: Error): void;\n}\n\nexport class Deferred<R = void> {\n promise: Promise<R>;\n // Assigned synchronously in constructor by Promise constructor callback.\n resolve!: Resolver<R>;\n reject!: Rejecter;\n\n constructor() {\n this.promise = new Promise((resolve: Resolver<R>, reject: Rejecter) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\n\n/**\n * Takes an array of values and a function from a value to a Promise. The function is run on each\n * value sequentially, waiting for the previous promise to resolve before starting the next one.\n * The returned promise resolves once the function has been run on all values.\n */\nexport function sequence<T>(\n values: T[],\n fn: (value: T) => Promise<void>\n): Promise<void> {\n let p = Promise.resolve();\n for (const value of values) {\n p = p.then(() => fn(value));\n }\n return p;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { User } from '../auth/user';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { Deferred } from '../util/promise';\n\n// TODO(mikelehen): This should be split into multiple files and probably\n// moved to an auth/ folder to match other platforms.\n\n/**\n * @internal\n */\nexport type AuthTokenFactory = () => string;\n\n/**\n * @internal\n */\nexport interface FirstPartyCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'firstParty';\n ['sessionIndex']: string;\n ['iamToken']: string | null;\n ['authTokenFactory']: AuthTokenFactory | null;\n}\n\nexport interface ProviderCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'provider';\n ['client']: CredentialsProvider<User>;\n}\n\n/** Settings for private credentials */\nexport type CredentialsSettings =\n | FirstPartyCredentialsSettings\n | ProviderCredentialsSettings;\n\nexport type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';\nexport interface Token {\n /** Type of token. */\n type: TokenType;\n\n /**\n * The user with which the token is associated (used for persisting user\n * state on disk, etc.).\n * This will be null for Tokens of the type 'AppCheck'.\n */\n user?: User;\n\n /** Header values to set for this token */\n headers: Map<string, string>;\n}\n\nexport class OAuthToken implements Token {\n type = 'OAuth' as TokenType;\n headers = new Map();\n\n constructor(value: string, public user: User) {\n this.headers.set('Authorization', `Bearer ${value}`);\n }\n}\n\n/**\n * A Listener for credential change events. The listener should fetch a new\n * token and may need to invalidate other state if the current user has also\n * changed.\n */\nexport type CredentialChangeListener<T> = (credential: T) => Promise<void>;\n\n/**\n * Provides methods for getting the uid and token for the current user and\n * listening for changes.\n */\nexport interface CredentialsProvider<T> {\n /**\n * Starts the credentials provider and specifies a listener to be notified of\n * credential changes (sign-in / sign-out, token changes). It is immediately\n * called once with the initial user.\n *\n * The change listener is invoked on the provided AsyncQueue.\n */\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<T>\n ): void;\n\n /** Requests a token for the current user. */\n getToken(): Promise<Token | null>;\n\n /**\n * Marks the last retrieved token as invalid, making the next GetToken request\n * force-refresh the token.\n */\n invalidateToken(): void;\n\n shutdown(): void;\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */\nexport class EmptyAuthCredentialsProvider implements CredentialsProvider<User> {\n getToken(): Promise<Token | null> {\n return Promise.resolve<Token | null>(null);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED));\n }\n\n shutdown(): void {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */\nexport class EmulatorAuthCredentialsProvider\n implements CredentialsProvider<User>\n{\n constructor(private token: Token) {}\n\n /**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n private changeListener: CredentialChangeListener<User> | null = null;\n\n getToken(): Promise<Token | null> {\n return Promise.resolve(this.token);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {\n debugAssert(\n !this.changeListener,\n 'Can only call setChangeListener() once.'\n );\n this.changeListener = changeListener;\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(this.token.user!));\n }\n\n shutdown(): void {\n this.changeListener = null;\n }\n}\n\n/** Credential provider for the Lite SDK. */\nexport class LiteAuthCredentialsProvider implements CredentialsProvider<User> {\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(authProvider: Provider<FirebaseAuthInternalName>) {\n authProvider.onInit(auth => {\n this.auth = auth;\n });\n }\n\n getToken(): Promise<Token | null> {\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken().then(tokenData => {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 'Invalid tokenData returned from getToken():' + tokenData\n );\n return new OAuthToken(\n tokenData.accessToken,\n new User(this.auth!.getUid())\n );\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {}\n\n shutdown(): void {}\n}\n\nexport class FirebaseAuthCredentialsProvider\n implements CredentialsProvider<User>\n{\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n private tokenListener!: () => void;\n\n /** Tracks the current User. */\n private currentUser: User = User.UNAUTHENTICATED;\n\n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n private tokenCounter = 0;\n\n private forceRefresh = false;\n\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(private authProvider: Provider<FirebaseAuthInternalName>) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {\n let lastTokenId = this.tokenCounter;\n\n // A change listener that prevents double-firing for the same token change.\n const guardedChangeListener: (user: User) => Promise<void> = user => {\n if (this.tokenCounter !== lastTokenId) {\n lastTokenId = this.tokenCounter;\n return changeListener(user);\n } else {\n return Promise.resolve();\n }\n };\n\n // A promise that can be waited on to block on the next token change.\n // This promise is re-created after each change.\n let nextToken = new Deferred<void>();\n\n this.tokenListener = () => {\n this.tokenCounter++;\n this.currentUser = this.getUser();\n nextToken.resolve();\n nextToken = new Deferred<void>();\n asyncQueue.enqueueRetryable(() =>\n guardedChangeListener(this.currentUser)\n );\n };\n\n const awaitNextToken: () => void = () => {\n const currentTokenAttempt = nextToken;\n asyncQueue.enqueueRetryable(async () => {\n await currentTokenAttempt.promise;\n await guardedChangeListener(this.currentUser);\n });\n };\n\n const registerAuth = (auth: FirebaseAuthInternal): void => {\n logDebug('FirebaseAuthCredentialsProvider', 'Auth detected');\n this.auth = auth;\n this.auth.addAuthTokenListener(this.tokenListener);\n awaitNextToken();\n };\n\n this.authProvider.onInit(auth => registerAuth(auth));\n\n // Our users can initialize Auth right after Firestore, so we give it\n // a chance to register itself with the component framework before we\n // determine whether to start up in unauthenticated mode.\n setTimeout(() => {\n if (!this.auth) {\n const auth = this.authProvider.getImmediate({ optional: true });\n if (auth) {\n registerAuth(auth);\n } else {\n // If auth is still not available, proceed with `null` user\n logDebug('FirebaseAuthCredentialsProvider', 'Auth not yet detected');\n nextToken.resolve();\n nextToken = new Deferred<void>();\n }\n }\n }, 0);\n\n awaitNextToken();\n }\n\n getToken(): Promise<Token | null> {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAuthCredentialsProvider not started.'\n );\n\n // Take note of the current value of the tokenCounter so that this method\n // can fail (with an ABORTED error) if there is a token change while the\n // request is outstanding.\n const initialTokenCounter = this.tokenCounter;\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken(forceRefresh).then(tokenData => {\n // Cancel the request since the token changed while the request was\n // outstanding so the response is potentially for a previous user (which\n // user, we can't be sure).\n if (this.tokenCounter !== initialTokenCounter) {\n logDebug(\n 'FirebaseAuthCredentialsProvider',\n 'getToken aborted due to token change.'\n );\n return this.getToken();\n } else {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 'Invalid tokenData returned from getToken():' + tokenData\n );\n return new OAuthToken(tokenData.accessToken, this.currentUser);\n } else {\n return null;\n }\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.auth) {\n this.auth.removeAuthTokenListener(this.tokenListener!);\n }\n }\n\n // Auth.getUid() can return null even with a user logged in. It is because\n // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n // This method should only be called in the AuthTokenListener callback\n // to guarantee to get the actual user.\n private getUser(): User {\n const currentUid = this.auth && this.auth.getUid();\n hardAssert(\n currentUid === null || typeof currentUid === 'string',\n 'Received invalid UID: ' + currentUid\n );\n return new User(currentUid);\n }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */\nexport class FirstPartyToken implements Token {\n type = 'FirstParty' as TokenType;\n user = User.FIRST_PARTY;\n private _headers = new Map();\n\n constructor(\n private readonly sessionIndex: string,\n private readonly iamToken: string | null,\n private readonly authTokenFactory: AuthTokenFactory | null\n ) {}\n\n /**\n * Gets an authorization token, using a provided factory function, or return\n * null.\n */\n private getAuthToken(): string | null {\n if (this.authTokenFactory) {\n return this.authTokenFactory();\n } else {\n return null;\n }\n }\n\n get headers(): Map<string, string> {\n this._headers.set('X-Goog-AuthUser', this.sessionIndex);\n // Use array notation to prevent minification\n const authHeaderTokenValue = this.getAuthToken();\n if (authHeaderTokenValue) {\n this._headers.set('Authorization', authHeaderTokenValue);\n }\n if (this.iamToken) {\n this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken);\n }\n\n return this._headers;\n }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */\nexport class FirstPartyAuthCredentialsProvider\n implements CredentialsProvider<User>\n{\n constructor(\n private sessionIndex: string,\n private iamToken: string | null,\n private authTokenFactory: AuthTokenFactory | null\n ) {}\n\n getToken(): Promise<Token | null> {\n return Promise.resolve(\n new FirstPartyToken(\n this.sessionIndex,\n this.iamToken,\n this.authTokenFactory\n )\n );\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {\n // Fire with initial uid.\n asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY));\n }\n\n shutdown(): void {}\n\n invalidateToken(): void {}\n}\n\nexport class AppCheckToken implements Token {\n type = 'AppCheck' as TokenType;\n headers = new Map();\n\n constructor(private value: string) {\n if (value && value.length > 0) {\n this.headers.set('x-firebase-appcheck', this.value);\n }\n }\n}\n\nexport class FirebaseAppCheckTokenProvider\n implements CredentialsProvider<string>\n{\n /**\n * The AppCheck token listener registered with FirebaseApp, retained here so\n * we can unregister it.\n */\n private tokenListener!: AppCheckTokenListener;\n private forceRefresh = false;\n private appCheck: FirebaseAppCheckInternal | null = null;\n private latestAppCheckToken: string | null = null;\n\n constructor(\n private appCheckProvider: Provider<AppCheckInternalComponentName>\n ) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<string>\n ): void {\n const onTokenChanged: (\n tokenResult: AppCheckTokenResult\n ) => Promise<void> = tokenResult => {\n if (tokenResult.error != null) {\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Error getting App Check token; using placeholder token instead. Error: ${tokenResult.error.message}`\n );\n }\n const tokenUpdated = tokenResult.token !== this.latestAppCheckToken;\n this.latestAppCheckToken = tokenResult.token;\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Received ${tokenUpdated ? 'new' : 'existing'} token.`\n );\n return tokenUpdated\n ? changeListener(tokenResult.token)\n : Promise.resolve();\n };\n\n this.tokenListener = (tokenResult: AppCheckTokenResult) => {\n asyncQueue.enqueueRetryable(() => onTokenChanged(tokenResult));\n };\n\n const registerAppCheck = (appCheck: FirebaseAppCheckInternal): void => {\n logDebug('FirebaseAppCheckTokenProvider', 'AppCheck detected');\n this.appCheck = appCheck;\n this.appCheck.addTokenListener(this.tokenListener);\n };\n\n this.appCheckProvider.onInit(appCheck => registerAppCheck(appCheck));\n\n // Our users can initialize AppCheck after Firestore, so we give it\n // a chance to register itself with the component framework.\n setTimeout(() => {\n if (!this.appCheck) {\n const appCheck = this.appCheckProvider.getImmediate({ optional: true });\n if (appCheck) {\n registerAppCheck(appCheck);\n } else {\n // If AppCheck is still not available, proceed without it.\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n 'AppCheck not yet detected'\n );\n }\n }\n }, 0);\n }\n\n getToken(): Promise<Token | null> {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAppCheckTokenProvider not started.'\n );\n\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken(forceRefresh).then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 'Invalid tokenResult returned from getToken():' + tokenResult\n );\n this.latestAppCheckToken = tokenResult.token;\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.appCheck) {\n this.appCheck.removeTokenListener(this.tokenListener!);\n }\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */\nexport class EmptyAppCheckTokenProvider implements CredentialsProvider<string> {\n getToken(): Promise<Token | null> {\n return Promise.resolve<Token | null>(new AppCheckToken(''));\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<string>\n ): void {}\n\n shutdown(): void {}\n}\n\n/** AppCheck token provider for the Lite SDK. */\nexport class LiteAppCheckTokenProvider implements CredentialsProvider<string> {\n private appCheck: FirebaseAppCheckInternal | null = null;\n\n constructor(\n private appCheckProvider: Provider<AppCheckInternalComponentName>\n ) {\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise<Token | null> {\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken().then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 'Invalid tokenResult returned from getToken():' + tokenResult\n );\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<string>\n ): void {}\n\n shutdown(): void {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeAuthCredentialsProvider(\n credentials?: CredentialsSettings\n): CredentialsProvider<User> {\n if (!credentials) {\n return new EmptyAuthCredentialsProvider();\n }\n switch (credentials['type']) {\n case 'firstParty':\n return new FirstPartyAuthCredentialsProvider(\n credentials['sessionIndex'] || '0',\n credentials['iamToken'] || null,\n credentials['authTokenFactory'] || null\n );\n\n case 'provider':\n return credentials['client'];\n\n default:\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'makeAuthCredentialsProvider failed due to invalid credential type'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../../util/assert';\n\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nexport function randomBytes(nBytes: number): Uint8Array {\n debugAssert(nBytes >= 0, `Expecting non-negative nBytes, got: ${nBytes}`);\n\n // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n const crypto =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof self !== 'undefined' && (self.crypto || (self as any)['msCrypto']);\n const bytes = new Uint8Array(nBytes);\n if (crypto && typeof crypto.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n // Falls back to Math.random\n for (let i = 0; i < nBytes; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n return bytes;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { randomBytes } from '../platform/random_bytes';\n\nimport { debugAssert } from './assert';\n\nexport type EventHandler<E> = (value: E) => void;\nexport interface Indexable {\n [k: string]: unknown;\n}\n\n/**\n * A utility class for generating unique alphanumeric IDs of a specified length.\n *\n * @internal\n * Exported internally for testing purposes.\n */\nexport class AutoId {\n static newId(): string {\n // Alphanumeric characters\n const chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n // The largest byte value that is a multiple of `char.length`.\n const maxMultiple = Math.floor(256 / chars.length) * chars.length;\n debugAssert(\n 0 < maxMultiple && maxMultiple < 256,\n `Expect maxMultiple to be (0, 256), but got ${maxMultiple}`\n );\n\n let autoId = '';\n const targetLength = 20;\n while (autoId.length < targetLength) {\n const bytes = randomBytes(40);\n for (let i = 0; i < bytes.length; ++i) {\n // Only accept values that are [0, maxMultiple), this ensures they can\n // be evenly mapped to indices of `chars` via a modulo operation.\n if (autoId.length < targetLength && bytes[i] < maxMultiple) {\n autoId += chars.charAt(bytes[i] % chars.length);\n }\n }\n }\n debugAssert(autoId.length === targetLength, 'Invalid auto ID: ' + autoId);\n\n return autoId;\n }\n}\n\nexport function primitiveComparator<T>(left: T, right: T): number {\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n return 0;\n}\n\nexport interface Equatable<T> {\n isEqual(other: T): boolean;\n}\n\nexport interface Iterable<V> {\n forEach: (cb: (v: V) => void) => void;\n}\n\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals<T>(\n left: T[],\n right: T[],\n comparator: (l: T, r: T) => boolean\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => comparator(value, right[index]));\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nexport function immediateSuccessor(s: string): string {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\nimport { primitiveComparator } from '../util/misc';\n\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\nconst MIN_SECONDS = -62135596800;\n\n// Number of nanoseconds in a millisecond.\nconst MS_TO_NANOS = 1e6;\n\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nexport class Timestamp {\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */\n static now(): Timestamp {\n return Timestamp.fromMillis(Date.now());\n }\n\n /**\n * Creates a new timestamp from the given date.\n *\n * @param date - The date to initialize the `Timestamp` from.\n * @returns A new `Timestamp` representing the same point in time as the given\n * date.\n */\n static fromDate(date: Date): Timestamp {\n return Timestamp.fromMillis(date.getTime());\n }\n\n /**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds - Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @returns A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */\n static fromMillis(milliseconds: number): Timestamp {\n const seconds = Math.floor(milliseconds / 1000);\n const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS);\n return new Timestamp(seconds, nanos);\n }\n\n /**\n * Creates a new timestamp.\n *\n * @param seconds - The number of seconds of UTC time since Unix epoch\n * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59Z inclusive.\n * @param nanoseconds - The non-negative fractions of a second at nanosecond\n * resolution. Negative second values with fractions must still have\n * non-negative nanoseconds values that count forward in time. Must be\n * from 0 to 999,999,999 inclusive.\n */\n constructor(\n /**\n * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n */\n readonly seconds: number,\n /**\n * The fractions of a second at nanosecond resolution.*\n */\n readonly nanoseconds: number\n ) {\n if (nanoseconds < 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (nanoseconds >= 1e9) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (seconds < MIN_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n // This will break in the year 10,000.\n if (seconds >= 253402300800) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n }\n\n /**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n * causes a loss of precision since `Date` objects only support millisecond\n * precision.\n *\n * @returns JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */\n toDate(): Date {\n return new Date(this.toMillis());\n }\n\n /**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @returns The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */\n toMillis(): number {\n return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS;\n }\n\n _compareTo(other: Timestamp): number {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanoseconds, other.nanoseconds);\n }\n return primitiveComparator(this.seconds, other.seconds);\n }\n\n /**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other - The `Timestamp` to compare against.\n * @returns true if this `Timestamp` is equal to the provided one.\n */\n isEqual(other: Timestamp): boolean {\n return (\n other.seconds === this.seconds && other.nanoseconds === this.nanoseconds\n );\n }\n\n /** Returns a textual representation of this `Timestamp`. */\n toString(): string {\n return (\n 'Timestamp(seconds=' +\n this.seconds +\n ', nanoseconds=' +\n this.nanoseconds +\n ')'\n );\n }\n\n /** Returns a JSON-serializable representation of this `Timestamp`. */\n toJSON(): { seconds: number; nanoseconds: number } {\n return { seconds: this.seconds, nanoseconds: this.nanoseconds };\n }\n\n /**\n * Converts this object to a primitive string, which allows `Timestamp` objects\n * to be compared using the `>`, `<=`, `>=` and `>` operators.\n */\n valueOf(): string {\n // This method returns a string of the form <seconds>.<nanoseconds> where\n // <seconds> is translated to have a non-negative value and both <seconds>\n // and <nanoseconds> are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexiographical ordering that matches\n // the expected ordering. The <seconds> translation is done to avoid having\n // a leading negative sign (i.e. a leading '-' character) in its string\n // representation, which would affect its lexiographical ordering.\n const adjustedSeconds = this.seconds - MIN_SECONDS;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n const formattedSeconds = String(adjustedSeconds).padStart(12, '0');\n const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');\n return formattedSeconds + '.' + formattedNanoseconds;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\n\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nexport class SnapshotVersion {\n static fromTimestamp(value: Timestamp): SnapshotVersion {\n return new SnapshotVersion(value);\n }\n\n static min(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(0, 0));\n }\n\n static max(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1));\n }\n\n private constructor(private timestamp: Timestamp) {}\n\n compareTo(other: SnapshotVersion): number {\n return this.timestamp._compareTo(other.timestamp);\n }\n\n isEqual(other: SnapshotVersion): boolean {\n return this.timestamp.isEqual(other.timestamp);\n }\n\n /** Returns a number representation of the version for use in spec tests. */\n toMicroseconds(): number {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;\n }\n\n toString(): string {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n }\n\n toTimestamp(): Timestamp {\n return this.timestamp;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DOCUMENT_KEY_NAME = '__name__';\n\n/**\n * Path represents an ordered sequence of string segments.\n */\nabstract class BasePath<B extends BasePath<B>> {\n private segments: string[];\n private offset: number;\n private len: number;\n\n constructor(segments: string[], offset?: number, length?: number) {\n if (offset === undefined) {\n offset = 0;\n } else if (offset > segments.length) {\n fail('offset ' + offset + ' out of range ' + segments.length);\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail('length ' + length + ' out of range ' + (segments.length - offset));\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n }\n\n /**\n * Abstract constructor method to construct an instance of B with the given\n * parameters.\n */\n protected abstract construct(\n segments: string[],\n offset?: number,\n length?: number\n ): B;\n\n /**\n * Returns a String representation.\n *\n * Implementing classes are required to provide deterministic implementations as\n * the String representation is used to obtain canonical Query IDs.\n */\n abstract toString(): string;\n\n get length(): number {\n return this.len;\n }\n\n isEqual(other: B): boolean {\n return BasePath.comparator(this, other) === 0;\n }\n\n child(nameOrPath: string | B): B {\n const segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof BasePath) {\n nameOrPath.forEach(segment => {\n segments.push(segment);\n });\n } else {\n segments.push(nameOrPath);\n }\n return this.construct(segments);\n }\n\n /** The index of one past the last segment of the path. */\n private limit(): number {\n return this.offset + this.length;\n }\n\n popFirst(size?: number): B {\n size = size === undefined ? 1 : size;\n debugAssert(\n this.length >= size,\n \"Can't call popFirst() with less segments\"\n );\n return this.construct(\n this.segments,\n this.offset + size,\n this.length - size\n );\n }\n\n popLast(): B {\n debugAssert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n\n firstSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n }\n\n lastSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.get(this.length - 1);\n }\n\n get(index: number): string {\n debugAssert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n }\n\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n isPrefixOf(other: this): boolean {\n if (other.length < this.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n isImmediateParentOf(potentialChild: this): boolean {\n if (this.length + 1 !== potentialChild.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== potentialChild.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n forEach(fn: (segment: string) => void): void {\n for (let i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n }\n\n toArray(): string[] {\n return this.segments.slice(this.offset, this.limit());\n }\n\n static comparator<T extends BasePath<T>>(\n p1: BasePath<T>,\n p2: BasePath<T>\n ): number {\n const len = Math.min(p1.length, p2.length);\n for (let i = 0; i < len; i++) {\n const left = p1.get(i);\n const right = p2.get(i);\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n }\n if (p1.length < p2.length) {\n return -1;\n }\n if (p1.length > p2.length) {\n return 1;\n }\n return 0;\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */\nexport class ResourcePath extends BasePath<ResourcePath> {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): ResourcePath {\n return new ResourcePath(segments, offset, length);\n }\n\n canonicalString(): string {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n return this.toArray().join('/');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */\n static fromString(...pathComponents: string[]): ResourcePath {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n const segments: string[] = [];\n for (const path of pathComponents) {\n if (path.indexOf('//') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid segment (${path}). Paths must not contain // in them.`\n );\n }\n // Strip leading and traling slashed.\n segments.push(...path.split('/').filter(segment => segment.length > 0));\n }\n\n return new ResourcePath(segments);\n }\n\n static emptyPath(): ResourcePath {\n return new ResourcePath([]);\n }\n}\n\nconst identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */\nexport class FieldPath extends BasePath<FieldPath> {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): FieldPath {\n return new FieldPath(segments, offset, length);\n }\n\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n private static isValidIdentifier(segment: string): boolean {\n return identifierRegExp.test(segment);\n }\n\n canonicalString(): string {\n return this.toArray()\n .map(str => {\n str = str.replace(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns true if this field references the key of a document.\n */\n isKeyField(): boolean {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n }\n\n /**\n * The field designating the key of a document.\n */\n static keyField(): FieldPath {\n return new FieldPath([DOCUMENT_KEY_NAME]);\n }\n\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */\n static fromServerFormat(path: string): FieldPath {\n const segments: string[] = [];\n let current = '';\n let i = 0;\n\n const addCurrentSegment = (): void => {\n if (current.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field path (${path}). Paths must not be empty, begin ` +\n `with '.', end with '.', or contain '..'`\n );\n }\n segments.push(current);\n current = '';\n };\n\n let inBackticks = false;\n\n while (i < path.length) {\n const c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has trailing escape character: ' + path\n );\n }\n const next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has invalid escape sequence: ' + path\n );\n }\n current += next;\n i += 2;\n } else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n } else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n } else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n\n if (inBackticks) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unterminated ` in path: ' + path\n );\n }\n\n return new FieldPath(segments);\n }\n\n static emptyPath(): FieldPath {\n return new FieldPath([]);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\n\nimport { ResourcePath } from './path';\n\n/**\n * @internal\n */\nexport class DocumentKey {\n constructor(readonly path: ResourcePath) {\n debugAssert(\n DocumentKey.isDocumentKey(path),\n 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/')\n );\n }\n\n static fromPath(path: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(path));\n }\n\n static fromName(name: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(name).popFirst(5));\n }\n\n static empty(): DocumentKey {\n return new DocumentKey(ResourcePath.emptyPath());\n }\n\n get collectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.popLast().lastSegment();\n }\n\n /** Returns true if the document is in the specified collectionId. */\n hasCollectionId(collectionId: string): boolean {\n return (\n this.path.length >= 2 &&\n this.path.get(this.path.length - 2) === collectionId\n );\n }\n\n /** Returns the collection group (i.e. the name of the parent collection) for this key. */\n getCollectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.get(this.path.length - 2);\n }\n\n /** Returns the fully qualified path to the parent collection. */\n getCollectionPath(): ResourcePath {\n return this.path.popLast();\n }\n\n isEqual(other: DocumentKey | null): boolean {\n return (\n other !== null && ResourcePath.comparator(this.path, other.path) === 0\n );\n }\n\n toString(): string {\n return this.path.toString();\n }\n\n static comparator(k1: DocumentKey, k2: DocumentKey): number {\n return ResourcePath.comparator(k1.path, k2.path);\n }\n\n static isDocumentKey(path: ResourcePath): boolean {\n return path.length % 2 === 0;\n }\n\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param segments - The segments of the path to the document\n * @returns A new instance of DocumentKey\n */\n static fromSegments(segments: string[]): DocumentKey {\n return new DocumentKey(new ResourcePath(segments.slice()));\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { primitiveComparator } from '../util/misc';\n\nimport { Document } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldPath } from './path';\n\n/**\n * The initial mutation batch id for each index. Gets updated during index\n * backfill.\n */\nexport const INITIAL_LARGEST_BATCH_ID = -1;\n\n/**\n * The initial sequence number for each index. Gets updated during index\n * backfill.\n */\nexport const INITIAL_SEQUENCE_NUMBER = 0;\n\n/**\n * An index definition for field indexes in Firestore.\n *\n * Every index is associated with a collection. The definition contains a list\n * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or\n * `CONTAINS` for ArrayContains/ArrayContainsAny queries).\n *\n * Unlike the backend, the SDK does not differentiate between collection or\n * collection group-scoped indices. Every index can be used for both single\n * collection and collection group queries.\n */\nexport class FieldIndex {\n /** An ID for an index that has not yet been added to persistence. */\n static UNKNOWN_ID = -1;\n\n constructor(\n /**\n * The index ID. Returns -1 if the index ID is not available (e.g. the index\n * has not yet been persisted).\n */\n readonly indexId: number,\n /** The collection ID this index applies to. */\n readonly collectionGroup: string,\n /** The field segments for this index. */\n readonly fields: IndexSegment[],\n /** Shows how up-to-date the index is for the current user. */\n readonly indexState: IndexState\n ) {}\n}\n\n/** Returns the ArrayContains/ArrayContainsAny segment for this index. */\nexport function fieldIndexGetArraySegment(\n fieldIndex: FieldIndex\n): IndexSegment | undefined {\n return fieldIndex.fields.find(s => s.kind === IndexKind.CONTAINS);\n}\n\n/** Returns all directional (ascending/descending) segments for this index. */\nexport function fieldIndexGetDirectionalSegments(\n fieldIndex: FieldIndex\n): IndexSegment[] {\n return fieldIndex.fields.filter(s => s.kind !== IndexKind.CONTAINS);\n}\n\n/**\n * Returns the order of the document key component for the given index.\n *\n * PORTING NOTE: This is only used in the Web IndexedDb implementation.\n */\nexport function fieldIndexGetKeyOrder(fieldIndex: FieldIndex): IndexKind {\n const directionalSegments = fieldIndexGetDirectionalSegments(fieldIndex);\n return directionalSegments.length === 0\n ? IndexKind.ASCENDING\n : directionalSegments[directionalSegments.length - 1].kind;\n}\n\n/**\n * Compares indexes by collection group and segments. Ignores update time and\n * index ID.\n */\nexport function fieldIndexSemanticComparator(\n left: FieldIndex,\n right: FieldIndex\n): number {\n let cmp = primitiveComparator(left.collectionGroup, right.collectionGroup);\n if (cmp !== 0) {\n return cmp;\n }\n\n for (let i = 0; i < Math.min(left.fields.length, right.fields.length); ++i) {\n cmp = indexSegmentComparator(left.fields[i], right.fields[i]);\n if (cmp !== 0) {\n return cmp;\n }\n }\n return primitiveComparator(left.fields.length, right.fields.length);\n}\n\n/** Returns a debug representation of the field index */\nexport function fieldIndexToString(fieldIndex: FieldIndex): string {\n return `id=${fieldIndex.indexId}|cg=${\n fieldIndex.collectionGroup\n }|f=${fieldIndex.fields.map(f => `${f.fieldPath}:${f.kind}`).join(',')}`;\n}\n\n/** The type of the index, e.g. for which type of query it can be used. */\nexport const enum IndexKind {\n // Note: The order of these values cannot be changed as the enum values are\n // stored in IndexedDb.\n /**\n * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries.\n */\n ASCENDING,\n /**\n * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries.\n */\n DESCENDING,\n /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */\n CONTAINS\n}\n\n/** An index component consisting of field path and index type. */\nexport class IndexSegment {\n constructor(\n /** The field path of the component. */\n readonly fieldPath: FieldPath,\n /** The fields sorting order. */\n readonly kind: IndexKind\n ) {}\n}\n\nfunction indexSegmentComparator(\n left: IndexSegment,\n right: IndexSegment\n): number {\n const cmp = FieldPath.comparator(left.fieldPath, right.fieldPath);\n if (cmp !== 0) {\n return cmp;\n }\n return primitiveComparator(left.kind, right.kind);\n}\n\n/**\n * Stores the \"high water mark\" that indicates how updated the Index is for the\n * current user.\n */\nexport class IndexState {\n constructor(\n /**\n * Indicates when the index was last updated (relative to other indexes).\n */\n readonly sequenceNumber: number,\n /** The the latest indexed read time, document and batch id. */\n readonly offset: IndexOffset\n ) {}\n\n /** The state of an index that has not yet been backfilled. */\n static empty(): IndexState {\n return new IndexState(INITIAL_SEQUENCE_NUMBER, IndexOffset.min());\n }\n}\n\n/**\n * Creates an offset that matches all documents with a read time higher than\n * `readTime`.\n */\nexport function newIndexOffsetSuccessorFromReadTime(\n readTime: SnapshotVersion,\n largestBatchId: number\n): IndexOffset {\n // We want to create an offset that matches all documents with a read time\n // greater than the provided read time. To do so, we technically need to\n // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use\n // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use\n // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches\n // all valid document IDs.\n const successorSeconds = readTime.toTimestamp().seconds;\n const successorNanos = readTime.toTimestamp().nanoseconds + 1;\n const successor = SnapshotVersion.fromTimestamp(\n successorNanos === 1e9\n ? new Timestamp(successorSeconds + 1, 0)\n : new Timestamp(successorSeconds, successorNanos)\n );\n return new IndexOffset(successor, DocumentKey.empty(), largestBatchId);\n}\n\n/** Creates a new offset based on the provided document. */\nexport function newIndexOffsetFromDocument(document: Document): IndexOffset {\n return new IndexOffset(\n document.readTime,\n document.key,\n INITIAL_LARGEST_BATCH_ID\n );\n}\n\n/**\n * Stores the latest read time, document and batch ID that were processed for an\n * index.\n */\nexport class IndexOffset {\n constructor(\n /**\n * The latest read time version that has been indexed by Firestore for this\n * field index.\n */\n readonly readTime: SnapshotVersion,\n\n /**\n * The key of the last document that was indexed for this query. Use\n * `DocumentKey.empty()` if no document has been indexed.\n */\n readonly documentKey: DocumentKey,\n\n /*\n * The largest mutation batch id that's been processed by Firestore.\n */\n readonly largestBatchId: number\n ) {}\n\n /** Returns an offset that sorts before all regular offsets. */\n static min(): IndexOffset {\n return new IndexOffset(\n SnapshotVersion.min(),\n DocumentKey.empty(),\n INITIAL_LARGEST_BATCH_ID\n );\n }\n\n /** Returns an offset that sorts after all regular offsets. */\n static max(): IndexOffset {\n return new IndexOffset(\n SnapshotVersion.max(),\n DocumentKey.empty(),\n INITIAL_LARGEST_BATCH_ID\n );\n }\n}\n\nexport function indexOffsetComparator(\n left: IndexOffset,\n right: IndexOffset\n): number {\n let cmp = left.readTime.compareTo(right.readTime);\n if (cmp !== 0) {\n return cmp;\n }\n cmp = DocumentKey.comparator(left.documentKey, right.documentKey);\n if (cmp !== 0) {\n return cmp;\n }\n return primitiveComparator(left.largestBatchId, right.largestBatchId);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber } from '../core/types';\nexport const PRIMARY_LEASE_LOST_ERROR_MSG =\n 'The current tab is not in the required state to perform this operation. ' +\n 'It might be necessary to refresh the browser tab.';\n\n/** The different modes supported by `Persistence.runTransaction()`. */\nexport type PersistenceTransactionMode =\n | 'readonly'\n | 'readwrite'\n | 'readwrite-primary';\n\n/**\n * A base class representing a persistence transaction, encapsulating both the\n * transaction's sequence numbers as well as a list of onCommitted listeners.\n *\n * When you call Persistence.runTransaction(), it will create a transaction and\n * pass it to your callback. You then pass it to any method that operates\n * on persistence.\n */\nexport abstract class PersistenceTransaction {\n private readonly onCommittedListeners: Array<() => void> = [];\n\n abstract readonly currentSequenceNumber: ListenSequenceNumber;\n\n addOnCommittedListener(listener: () => void): void {\n this.onCommittedListeners.push(listener);\n }\n\n raiseOnCommittedEvent(): void {\n this.onCommittedListeners.forEach(listener => listener());\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { IndexManager } from './index_manager';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { LruGarbageCollector, LruResults } from './lru_garbage_collector';\nimport { PRIMARY_LEASE_LOST_ERROR_MSG } from './persistence_transaction';\n\nexport interface LocalStore {\n collectGarbage(garbageCollector: LruGarbageCollector): Promise<LruResults>;\n\n /** Manages the list of active field and collection indices. */\n indexManager: IndexManager;\n\n /**\n * The \"local\" view of all documents (layering mutationQueue on top of\n * remoteDocumentCache).\n */\n localDocuments: LocalDocumentsView;\n}\n\n/**\n * Verifies the error thrown by a LocalStore operation. If a LocalStore\n * operation fails because the primary lease has been taken by another client,\n * we ignore the error (the persistence layer will immediately call\n * `applyPrimaryLease` to propagate the primary state change). All other errors\n * are re-thrown.\n *\n * @param err - An error returned by a LocalStore operation.\n * @returns A Promise that resolves after we recovered, or the original error.\n */\nexport async function ignoreIfPrimaryLeaseLoss(\n err: FirestoreError\n): Promise<void> {\n if (\n err.code === Code.FAILED_PRECONDITION &&\n err.message === PRIMARY_LEASE_LOST_ERROR_MSG\n ) {\n logDebug('LocalStore', 'Unexpectedly lost primary lease');\n } else {\n throw err;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\n\nexport type FulfilledHandler<T, R> =\n | ((result: T) => R | PersistencePromise<R>)\n | null;\nexport type RejectedHandler<R> =\n | ((reason: Error) => R | PersistencePromise<R>)\n | null;\nexport type Resolver<T> = (value?: T) => void;\nexport type Rejector = (error: Error) => void;\n\n/**\n * PersistencePromise is essentially a re-implementation of Promise except\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\n * are executed synchronously when a PersistencePromise resolves rather than\n * asynchronously (Promise implementations use setImmediate() or similar).\n *\n * This is necessary to interoperate with IndexedDB which will automatically\n * commit transactions if control is returned to the event loop without\n * synchronously initiating another operation on the transaction.\n *\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\n * Promises.\n */\nexport class PersistencePromise<T> {\n // NOTE: next/catchCallback will always point to our own wrapper functions,\n // not the user's raw next() or catch() callbacks.\n private nextCallback: FulfilledHandler<T, unknown> = null;\n private catchCallback: RejectedHandler<unknown> = null;\n\n // When the operation resolves, we'll set result or error and mark isDone.\n private result: T | undefined = undefined;\n private error: Error | undefined = undefined;\n private isDone = false;\n\n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n private callbackAttached = false;\n\n constructor(callback: (resolve: Resolver<T>, reject: Rejector) => void) {\n callback(\n value => {\n this.isDone = true;\n this.result = value;\n if (this.nextCallback) {\n // value should be defined unless T is Void, but we can't express\n // that in the type system.\n this.nextCallback(value!);\n }\n },\n error => {\n this.isDone = true;\n this.error = error;\n if (this.catchCallback) {\n this.catchCallback(error);\n }\n }\n );\n }\n\n catch<R>(\n fn: (error: Error) => R | PersistencePromise<R>\n ): PersistencePromise<R> {\n return this.next(undefined, fn);\n }\n\n next<R>(\n nextFn?: FulfilledHandler<T, R>,\n catchFn?: RejectedHandler<R>\n ): PersistencePromise<R> {\n if (this.callbackAttached) {\n fail('Called next() or catch() twice for PersistencePromise');\n }\n this.callbackAttached = true;\n if (this.isDone) {\n if (!this.error) {\n return this.wrapSuccess(nextFn, this.result!);\n } else {\n return this.wrapFailure(catchFn, this.error);\n }\n } else {\n return new PersistencePromise<R>((resolve, reject) => {\n this.nextCallback = (value: T) => {\n this.wrapSuccess(nextFn, value).next(resolve, reject);\n };\n this.catchCallback = (error: Error) => {\n this.wrapFailure(catchFn, error).next(resolve, reject);\n };\n });\n }\n }\n\n toPromise(): Promise<T> {\n return new Promise((resolve, reject) => {\n this.next(resolve, reject);\n });\n }\n\n private wrapUserFunction<R>(\n fn: () => R | PersistencePromise<R>\n ): PersistencePromise<R> {\n try {\n const result = fn();\n if (result instanceof PersistencePromise) {\n return result;\n } else {\n return PersistencePromise.resolve(result);\n }\n } catch (e) {\n return PersistencePromise.reject<R>(e as Error);\n }\n }\n\n private wrapSuccess<R>(\n nextFn: FulfilledHandler<T, R> | undefined,\n value: T\n ): PersistencePromise<R> {\n if (nextFn) {\n return this.wrapUserFunction(() => nextFn(value));\n } else {\n // If there's no nextFn, then R must be the same as T\n return PersistencePromise.resolve<R>(value as unknown as R);\n }\n }\n\n private wrapFailure<R>(\n catchFn: RejectedHandler<R> | undefined,\n error: Error\n ): PersistencePromise<R> {\n if (catchFn) {\n return this.wrapUserFunction(() => catchFn(error));\n } else {\n return PersistencePromise.reject<R>(error);\n }\n }\n\n static resolve(): PersistencePromise<void>;\n static resolve<R>(result: R): PersistencePromise<R>;\n static resolve<R>(result?: R): PersistencePromise<R | void> {\n return new PersistencePromise<R | void>((resolve, reject) => {\n resolve(result);\n });\n }\n\n static reject<R>(error: Error): PersistencePromise<R> {\n return new PersistencePromise<R>((resolve, reject) => {\n reject(error);\n });\n }\n\n static waitFor(\n // Accept all Promise types in waitFor().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n all: { forEach: (cb: (el: PersistencePromise<any>) => void) => void }\n ): PersistencePromise<void> {\n return new PersistencePromise<void>((resolve, reject) => {\n let expectedCount = 0;\n let resolvedCount = 0;\n let done = false;\n\n all.forEach(element => {\n ++expectedCount;\n element.next(\n () => {\n ++resolvedCount;\n if (done && resolvedCount === expectedCount) {\n resolve();\n }\n },\n err => reject(err)\n );\n });\n\n done = true;\n if (resolvedCount === expectedCount) {\n resolve();\n }\n });\n }\n\n /**\n * Given an array of predicate functions that asynchronously evaluate to a\n * boolean, implements a short-circuiting `or` between the results. Predicates\n * will be evaluated until one of them returns `true`, then stop. The final\n * result will be whether any of them returned `true`.\n */\n static or(\n predicates: Array<() => PersistencePromise<boolean>>\n ): PersistencePromise<boolean> {\n let p: PersistencePromise<boolean> =\n PersistencePromise.resolve<boolean>(false);\n for (const predicate of predicates) {\n p = p.next(isTrue => {\n if (isTrue) {\n return PersistencePromise.resolve<boolean>(isTrue);\n } else {\n return predicate();\n }\n });\n }\n return p;\n }\n\n /**\n * Given an iterable, call the given function on each element in the\n * collection and wait for all of the resulting concurrent PersistencePromises\n * to resolve.\n */\n static forEach<R, S>(\n collection: { forEach: (cb: (r: R, s: S) => void) => void },\n f:\n | ((r: R, s: S) => PersistencePromise<void>)\n | ((r: R) => PersistencePromise<void>)\n ): PersistencePromise<void>;\n static forEach<R>(\n collection: { forEach: (cb: (r: R) => void) => void },\n f: (r: R) => PersistencePromise<void>\n ): PersistencePromise<void>;\n static forEach<R, S>(\n collection: { forEach: (cb: (r: R, s?: S) => void) => void },\n f: (r: R, s?: S) => PersistencePromise<void>\n ): PersistencePromise<void> {\n const promises: Array<PersistencePromise<void>> = [];\n collection.forEach((r, s) => {\n promises.push(f.call(this, r, s));\n });\n return this.waitFor(promises);\n }\n\n /**\n * Concurrently map all array elements through asynchronous function.\n */\n static mapArray<T, U>(\n array: T[],\n f: (t: T) => PersistencePromise<U>\n ): PersistencePromise<U[]> {\n return new PersistencePromise<U[]>((resolve, reject) => {\n const expectedCount = array.length;\n const results: U[] = new Array(expectedCount);\n let resolvedCount = 0;\n for (let i = 0; i < expectedCount; i++) {\n const current = i;\n f(array[current]).next(\n result => {\n results[current] = result;\n ++resolvedCount;\n if (resolvedCount === expectedCount) {\n resolve(results);\n }\n },\n err => reject(err)\n );\n }\n });\n }\n\n /**\n * An alternative to recursive PersistencePromise calls, that avoids\n * potential memory problems from unbounded chains of promises.\n *\n * The `action` will be called repeatedly while `condition` is true.\n */\n static doWhile(\n condition: () => boolean,\n action: () => PersistencePromise<void>\n ): PersistencePromise<void> {\n return new PersistencePromise<void>((resolve, reject) => {\n const process = (): void => {\n if (condition() === true) {\n action().next(() => {\n process();\n }, reject);\n } else {\n resolve();\n }\n };\n process();\n });\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getUA, isIndexedDBAvailable } from '@firebase/util';\n\nimport { debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { Deferred } from '../util/promise';\n\nimport { PersistencePromise } from './persistence_promise';\n\n// References to `window` are guarded by SimpleDb.isAvailable()\n/* eslint-disable no-restricted-globals */\n\nconst LOG_TAG = 'SimpleDb';\n\n/**\n * The maximum number of retry attempts for an IndexedDb transaction that fails\n * with a DOMException.\n */\nconst TRANSACTION_RETRY_COUNT = 3;\n\n// The different modes supported by `SimpleDb.runTransaction()`\ntype SimpleDbTransactionMode = 'readonly' | 'readwrite';\n\nexport interface SimpleDbSchemaConverter {\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise<void>;\n}\n\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nexport class SimpleDbTransaction {\n private aborted = false;\n\n /**\n * A `Promise` that resolves with the result of the IndexedDb transaction.\n */\n private readonly completionDeferred = new Deferred<void>();\n\n static open(\n db: IDBDatabase,\n action: string,\n mode: IDBTransactionMode,\n objectStoreNames: string[]\n ): SimpleDbTransaction {\n try {\n return new SimpleDbTransaction(\n action,\n db.transaction(objectStoreNames, mode)\n );\n } catch (e) {\n throw new IndexedDbTransactionError(action, e as Error);\n }\n }\n\n constructor(\n private readonly action: string,\n private readonly transaction: IDBTransaction\n ) {\n this.transaction.oncomplete = () => {\n this.completionDeferred.resolve();\n };\n this.transaction.onabort = () => {\n if (transaction.error) {\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, transaction.error)\n );\n } else {\n this.completionDeferred.resolve();\n }\n };\n this.transaction.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, error)\n );\n };\n }\n\n get completionPromise(): Promise<void> {\n return this.completionDeferred.promise;\n }\n\n abort(error?: Error): void {\n if (error) {\n this.completionDeferred.reject(error);\n }\n\n if (!this.aborted) {\n logDebug(\n LOG_TAG,\n 'Aborting transaction:',\n error ? error.message : 'Client-initiated abort'\n );\n this.aborted = true;\n this.transaction.abort();\n }\n }\n\n maybeCommit(): void {\n // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n // speed up index DB processing if the event loop remains blocks.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const maybeV3IndexedDb = this.transaction as any;\n if (!this.aborted && typeof maybeV3IndexedDb.commit === 'function') {\n maybeV3IndexedDb.commit();\n }\n }\n\n /**\n * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */\n store<KeyType extends IDBValidKey, ValueType extends unknown>(\n storeName: string\n ): SimpleDbStore<KeyType, ValueType> {\n const store = this.transaction.objectStore(storeName);\n debugAssert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore<KeyType, ValueType>(store);\n }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */\nexport class SimpleDb {\n private db?: IDBDatabase;\n private versionchangelistener?: (event: IDBVersionChangeEvent) => void;\n\n /** Deletes the specified database. */\n static delete(name: string): Promise<void> {\n logDebug(LOG_TAG, 'Removing database:', name);\n return wrapRequest<void>(window.indexedDB.deleteDatabase(name)).toPromise();\n }\n\n /** Returns true if IndexedDB is available in the current environment. */\n static isAvailable(): boolean {\n if (!isIndexedDBAvailable()) {\n return false;\n }\n\n if (SimpleDb.isMockPersistence()) {\n return true;\n }\n\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n\n // Check the UA string to find out the browser.\n const ua = getUA();\n\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n\n // iOS Safari: Disable for users running iOS version < 10.\n const iOSVersion = SimpleDb.getIOSVersion(ua);\n const isUnsupportedIOS = 0 < iOSVersion && iOSVersion < 10;\n\n // Android browser: Disable for userse running version < 4.5.\n const androidVersion = SimpleDb.getAndroidVersion(ua);\n const isUnsupportedAndroid = 0 < androidVersion && androidVersion < 4.5;\n\n if (\n ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0 ||\n isUnsupportedIOS ||\n isUnsupportedAndroid\n ) {\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */\n static isMockPersistence(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.env?.USE_MOCK_PERSISTENCE === 'YES'\n );\n }\n\n /** Helper to get a typed SimpleDbStore from a transaction. */\n static getStore<KeyType extends IDBValidKey, ValueType extends unknown>(\n txn: SimpleDbTransaction,\n store: string\n ): SimpleDbStore<KeyType, ValueType> {\n return txn.store<KeyType, ValueType>(store);\n }\n\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static getIOSVersion(ua: string): number {\n const iOSVersionRegex = ua.match(/i(?:phone|pad|pod) os ([\\d_]+)/i);\n const version = iOSVersionRegex\n ? iOSVersionRegex[1].split('_').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n }\n\n // visible for testing\n /** Parse User Agent to determine Android version. Returns -1 if not found. */\n static getAndroidVersion(ua: string): number {\n const androidVersionRegex = ua.match(/Android ([\\d.]+)/i);\n const version = androidVersionRegex\n ? androidVersionRegex[1].split('.').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n }\n\n /*\n * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support\n * downgrading the schema version. We currently do not support any way to do\n * versioning outside of IndexedDB's versioning mechanism, as only\n * version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n constructor(\n private readonly name: string,\n private readonly version: number,\n private readonly schemaConverter: SimpleDbSchemaConverter\n ) {\n debugAssert(\n SimpleDb.isAvailable(),\n 'IndexedDB not supported in current environment.'\n );\n\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n // whatever reason it's much harder to hit after 12.2 so we only proactively\n // log on 12.2.\n if (iOSVersion === 12.2) {\n logError(\n 'Firestore persistence suffers from a bug in iOS 12.2 ' +\n 'Safari that may cause your app to stop working. See ' +\n 'https://stackoverflow.com/q/56496296/110915 for details ' +\n 'and a potential workaround.'\n );\n }\n }\n\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n */\n async ensureDb(action: string): Promise<IDBDatabase> {\n if (!this.db) {\n logDebug(LOG_TAG, 'Opening database:', this.name);\n this.db = await new Promise<IDBDatabase>((resolve, reject) => {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently. They expect setVersion, as described here:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n const request = indexedDB.open(this.name, this.version);\n\n request.onsuccess = (event: Event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n resolve(db);\n };\n\n request.onblocked = () => {\n reject(\n new IndexedDbTransactionError(\n action,\n 'Cannot upgrade IndexedDB schema while another tab is open. ' +\n 'Close all tabs that access Firestore and reload this page to proceed.'\n )\n );\n };\n\n request.onerror = (event: Event) => {\n const error: DOMException = (event.target as IDBOpenDBRequest).error!;\n if (error.name === 'VersionError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A newer version of the Firestore SDK was previously used and so the persisted ' +\n 'data is not compatible with the version of the SDK you are now using. The SDK ' +\n 'will operate with persistence disabled. If you need persistence, please ' +\n 're-upgrade to a newer version of the SDK or else clear the persisted IndexedDB ' +\n 'data for your app to start fresh.'\n )\n );\n } else if (error.name === 'InvalidStateError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Unable to open an IndexedDB connection. This could be due to running in a ' +\n 'private browsing session on a browser whose private browsing sessions do not ' +\n 'support IndexedDB: ' +\n error\n )\n );\n } else {\n reject(new IndexedDbTransactionError(action, error));\n }\n };\n\n request.onupgradeneeded = (event: IDBVersionChangeEvent) => {\n logDebug(\n LOG_TAG,\n 'Database \"' + this.name + '\" requires upgrade from version:',\n event.oldVersion\n );\n const db = (event.target as IDBOpenDBRequest).result;\n this.schemaConverter\n .createOrUpgrade(\n db,\n request.transaction!,\n event.oldVersion,\n this.version\n )\n .next(() => {\n logDebug(\n LOG_TAG,\n 'Database upgrade to version ' + this.version + ' complete'\n );\n });\n };\n });\n }\n\n if (this.versionchangelistener) {\n this.db.onversionchange = event => this.versionchangelistener!(event);\n }\n return this.db;\n }\n\n setVersionChangeListener(\n versionChangeListener: (event: IDBVersionChangeEvent) => void\n ): void {\n this.versionchangelistener = versionChangeListener;\n if (this.db) {\n this.db.onversionchange = (event: IDBVersionChangeEvent) => {\n return versionChangeListener(event);\n };\n }\n }\n\n async runTransaction<T>(\n action: string,\n mode: SimpleDbTransactionMode,\n objectStores: string[],\n transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise<T>\n ): Promise<T> {\n const readonly = mode === 'readonly';\n let attemptNumber = 0;\n\n while (true) {\n ++attemptNumber;\n\n try {\n this.db = await this.ensureDb(action);\n\n const transaction = SimpleDbTransaction.open(\n this.db,\n action,\n readonly ? 'readonly' : 'readwrite',\n objectStores\n );\n const transactionFnResult = transactionFn(transaction)\n .next(result => {\n transaction.maybeCommit();\n return result;\n })\n .catch(error => {\n // Abort the transaction if there was an error.\n transaction.abort(error);\n // We cannot actually recover, and calling `abort()` will cause the transaction's\n // completion promise to be rejected. This in turn means that we won't use\n // `transactionFnResult` below. We return a rejection here so that we don't add the\n // possibility of returning `void` to the type of `transactionFnResult`.\n return PersistencePromise.reject<T>(error);\n })\n .toPromise();\n\n // As noted above, errors are propagated by aborting the transaction. So\n // we swallow any error here to avoid the browser logging it as unhandled.\n transactionFnResult.catch(() => {});\n\n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n await transaction.completionPromise;\n return transactionFnResult;\n } catch (e) {\n const error = e as Error;\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n const retryable =\n error.name !== 'FirebaseError' &&\n attemptNumber < TRANSACTION_RETRY_COUNT;\n logDebug(\n LOG_TAG,\n 'Transaction failed with error:',\n error.message,\n 'Retrying:',\n retryable\n );\n\n this.close();\n\n if (!retryable) {\n return Promise.reject(error);\n }\n }\n }\n }\n\n close(): void {\n if (this.db) {\n this.db.close();\n }\n this.db = undefined;\n }\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */\nexport class IterationController {\n private shouldStop = false;\n private nextKey: IDBValidKey | null = null;\n\n constructor(private dbCursor: IDBCursorWithValue) {}\n\n get isDone(): boolean {\n return this.shouldStop;\n }\n\n get skipToKey(): IDBValidKey | null {\n return this.nextKey;\n }\n\n set cursor(value: IDBCursorWithValue) {\n this.dbCursor = value;\n }\n\n /**\n * This function can be called to stop iteration at any point.\n */\n done(): void {\n this.shouldStop = true;\n }\n\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */\n skip(key: IDBValidKey): void {\n this.nextKey = key;\n }\n\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n delete(): PersistencePromise<void> {\n return wrapRequest<void>(this.dbCursor.delete());\n }\n}\n\n/**\n * Callback used with iterate() method.\n */\nexport type IterateCallback<KeyType, ValueType> = (\n key: KeyType,\n value: ValueType,\n control: IterationController\n) => void | PersistencePromise<void>;\n\n/** Options available to the iterate() method. */\nexport interface IterateOptions {\n /** Index to iterate over (else primary keys will be iterated) */\n index?: string;\n\n /** IndxedDB Range to iterate over (else entire store will be iterated) */\n range?: IDBKeyRange;\n\n /** If true, values aren't read while iterating. */\n keysOnly?: boolean;\n\n /** If true, iterate over the store in reverse. */\n reverse?: boolean;\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */\nexport class IndexedDbTransactionError extends FirestoreError {\n name = 'IndexedDbTransactionError';\n\n constructor(actionName: string, cause: Error | string) {\n super(\n Code.UNAVAILABLE,\n `IndexedDB transaction '${actionName}' failed: ${cause}`\n );\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */\nexport function isIndexedDbTransactionError(e: Error): boolean {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return e.name === 'IndexedDbTransactionError';\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */\nexport class SimpleDbStore<\n KeyType extends IDBValidKey,\n ValueType extends unknown\n> {\n constructor(private store: IDBObjectStore) {}\n\n /**\n * Writes a value into the Object Store.\n *\n * @param key - Optional explicit key to use when writing the object, else the\n * key will be auto-assigned (e.g. via the defined keyPath for the store).\n * @param value - The object to write.\n */\n put(value: ValueType): PersistencePromise<void>;\n put(key: KeyType, value: ValueType): PersistencePromise<void>;\n put(\n keyOrValue: KeyType | ValueType,\n value?: ValueType\n ): PersistencePromise<void> {\n let request;\n if (value !== undefined) {\n logDebug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue as KeyType);\n } else {\n logDebug(LOG_TAG, 'PUT', this.store.name, '<auto-key>', keyOrValue);\n request = this.store.put(keyOrValue as ValueType);\n }\n return wrapRequest<void>(request);\n }\n\n /**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value - The object to write.\n * @returns The key of the value to add.\n */\n add(value: ValueType): PersistencePromise<KeyType> {\n logDebug(LOG_TAG, 'ADD', this.store.name, value, value);\n const request = this.store.add(value as ValueType);\n return wrapRequest<KeyType>(request);\n }\n\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @returns The object with the specified key or null if no object exists.\n */\n get(key: KeyType): PersistencePromise<ValueType | null> {\n const request = this.store.get(key);\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return wrapRequest<any>(request).next(result => {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n logDebug(LOG_TAG, 'GET', this.store.name, key, result);\n return result;\n });\n }\n\n delete(key: KeyType | IDBKeyRange): PersistencePromise<void> {\n logDebug(LOG_TAG, 'DELETE', this.store.name, key);\n const request = this.store.delete(key);\n return wrapRequest<void>(request);\n }\n\n /**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */\n count(): PersistencePromise<number> {\n logDebug(LOG_TAG, 'COUNT', this.store.name);\n const request = this.store.count();\n return wrapRequest<number>(request);\n }\n\n /** Loads all elements from the object store. */\n loadAll(): PersistencePromise<ValueType[]>;\n /** Loads all elements for the index range from the object store. */\n loadAll(range: IDBKeyRange): PersistencePromise<ValueType[]>;\n /** Loads all elements ordered by the given index. */\n loadAll(index: string): PersistencePromise<ValueType[]>;\n /**\n * Loads all elements from the object store that fall into the provided in the\n * index range for the given index.\n */\n loadAll(index: string, range: IDBKeyRange): PersistencePromise<ValueType[]>;\n loadAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise<ValueType[]> {\n const iterateOptions = this.options(indexOrRange, range);\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster. Unfortunately, getAll() does not support custom indices.\n if (!iterateOptions.index && typeof this.store.getAll === 'function') {\n const request = this.store.getAll(iterateOptions.range);\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n } else {\n const cursor = this.cursor(iterateOptions);\n const results: ValueType[] = [];\n return this.iterateCursor(cursor, (key, value) => {\n results.push(value);\n }).next(() => {\n return results;\n });\n }\n }\n\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */\n loadFirst(\n range: IDBKeyRange,\n count: number | null\n ): PersistencePromise<ValueType[]> {\n const request = this.store.getAll(\n range,\n count === null ? undefined : count\n );\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n }\n\n deleteAll(): PersistencePromise<void>;\n deleteAll(range: IDBKeyRange): PersistencePromise<void>;\n deleteAll(index: string, range: IDBKeyRange): PersistencePromise<void>;\n deleteAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise<void> {\n logDebug(LOG_TAG, 'DELETE ALL', this.store.name);\n const options = this.options(indexOrRange, range);\n options.keysOnly = false;\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, (key, value, control) => {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n }\n\n /**\n * Iterates over keys and values in an object store.\n *\n * @param options - Options specifying how to iterate the objects in the\n * store.\n * @param callback - will be called for each iterated object. Iteration can be\n * canceled at any point by calling the doneFn passed to the callback.\n * The callback can return a PersistencePromise if it performs async\n * operations but note that iteration will continue without waiting for them\n * to complete.\n * @returns A PersistencePromise that resolves once all PersistencePromises\n * returned by callbacks resolve.\n */\n iterate(\n callback: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void>;\n iterate(\n options: IterateOptions,\n callback: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void>;\n iterate(\n optionsOrCallback: IterateOptions | IterateCallback<KeyType, ValueType>,\n callback?: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void> {\n let options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback as IterateCallback<KeyType, ValueType>;\n } else {\n options = optionsOrCallback as IterateOptions;\n }\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n }\n\n /**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */\n iterateSerial(\n callback: (k: KeyType, v: ValueType) => PersistencePromise<boolean>\n ): PersistencePromise<void> {\n const cursorRequest = this.cursor({});\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n\n callback(cursor.primaryKey as KeyType, cursor.value).next(\n shouldContinue => {\n if (shouldContinue) {\n cursor.continue();\n } else {\n resolve();\n }\n }\n );\n };\n });\n }\n\n private iterateCursor(\n cursorRequest: IDBRequest,\n fn: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void> {\n const results: Array<PersistencePromise<void>> = [];\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n const controller = new IterationController(cursor);\n const userResult = fn(\n cursor.primaryKey as KeyType,\n cursor.value,\n controller\n );\n if (userResult instanceof PersistencePromise) {\n const userPromise: PersistencePromise<void> = userResult.catch(\n err => {\n controller.done();\n return PersistencePromise.reject(err);\n }\n );\n results.push(userPromise);\n }\n if (controller.isDone) {\n resolve();\n } else if (controller.skipToKey === null) {\n cursor.continue();\n } else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(() => PersistencePromise.waitFor(results));\n }\n\n private options(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): IterateOptions {\n let indexName: string | undefined = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n } else {\n debugAssert(\n range === undefined,\n '3rd argument must not be defined if 2nd is a range.'\n );\n range = indexOrRange;\n }\n }\n return { index: indexName, range };\n }\n\n private cursor(options: IterateOptions): IDBRequest {\n let direction: IDBCursorDirection = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n const index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n } else {\n return index.openCursor(options.range, direction);\n }\n } else {\n return this.store.openCursor(options.range, direction);\n }\n }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest<R>(request: IDBRequest): PersistencePromise<R> {\n return new PersistencePromise<R>((resolve, reject) => {\n request.onsuccess = (event: Event) => {\n const result = (event.target as IDBRequest).result;\n resolve(result);\n };\n\n request.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n });\n}\n\n// Guard so we only report the error once.\nlet reportedIOSError = false;\nfunction checkForAndReportiOSError(error: DOMException): Error {\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n if (iOSVersion >= 12.2 && iOSVersion < 13) {\n const IOS_ERROR =\n 'An internal error was encountered in the Indexed Database server';\n if (error.message.indexOf(IOS_ERROR) >= 0) {\n // Wrap error in a more descriptive one.\n const newError = new FirestoreError(\n 'internal',\n `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${IOS_ERROR}'. This is likely ` +\n `due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 ` +\n `for details and a potential workaround.`\n );\n if (!reportedIOSError) {\n reportedIOSError = true;\n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout(() => {\n throw newError;\n }, 0);\n }\n return newError;\n }\n }\n return error;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber } from './types';\n\n/**\n * `SequenceNumberSyncer` defines the methods required to keep multiple instances of a\n * `ListenSequence` in sync.\n */\nexport interface SequenceNumberSyncer {\n // Notify the syncer that a new sequence number has been used.\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n // Setting this property allows the syncer to notify when a sequence number has been used, and\n // and lets the ListenSequence adjust its internal previous value accordingly.\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n}\n\n/**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */\nexport class ListenSequence {\n static readonly INVALID: ListenSequenceNumber = -1;\n\n private writeNewSequenceNumber?: (\n newSequenceNumber: ListenSequenceNumber\n ) => void;\n\n constructor(\n private previousValue: ListenSequenceNumber,\n sequenceNumberSyncer?: SequenceNumberSyncer\n ) {\n if (sequenceNumberSyncer) {\n sequenceNumberSyncer.sequenceNumberHandler = sequenceNumber =>\n this.setPreviousValue(sequenceNumber);\n this.writeNewSequenceNumber = sequenceNumber =>\n sequenceNumberSyncer.writeSequenceNumber(sequenceNumber);\n }\n }\n\n private setPreviousValue(\n externalPreviousValue: ListenSequenceNumber\n ): ListenSequenceNumber {\n this.previousValue = Math.max(externalPreviousValue, this.previousValue);\n return this.previousValue;\n }\n\n next(): ListenSequenceNumber {\n const nextValue = ++this.previousValue;\n if (this.writeNewSequenceNumber) {\n this.writeNewSequenceNumber(nextValue);\n }\n return nextValue;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Sentinel value that sorts before any Mutation Batch ID. */\nexport const BATCHID_UNKNOWN = -1;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/** Returns whether the value represents -0. */\nexport function isNegativeZero(value: number): boolean {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return value === 0 && 1 / value === 1 / -0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */\nexport function isSafeInteger(value: unknown): boolean {\n return (\n typeof value === 'number' &&\n Number.isInteger(value) &&\n !isNegativeZero(value) &&\n value <= Number.MAX_SAFE_INTEGER &&\n value >= Number.MIN_SAFE_INTEGER\n );\n}\n\n/** The subset of the browser's Window interface used by the SDK. */\nexport interface WindowLike {\n readonly localStorage: Storage;\n readonly indexedDB: IDBFactory | null;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n\n/** The subset of the browser's Document interface used by the SDK. */\nexport interface DocumentLike {\n readonly visibilityState: DocumentVisibilityState;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchId, TargetId } from '../core/types';\nimport { ResourcePath } from '../model/path';\nimport { fail } from '../util/assert';\n\nimport {\n EncodedResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { DbDocumentMutation } from './indexeddb_schema';\nimport { DbRemoteDocumentStore as DbRemoteDocumentStoreLegacy } from './indexeddb_schema_legacy';\n\n// This file contains static constants and helper functions for IndexedDB.\n// It is split from indexeddb_schema to allow for minification.\n\n/** A timestamp type that can be used in IndexedDb keys. */\nexport type DbTimestampKey = [/* seconds */ number, /* nanos */ number];\n\n// The key for the singleton object in the DbPrimaryClient is a single string.\nexport type DbPrimaryClientKey = typeof DbPrimaryClientKey;\n\n/**\n * Name of the IndexedDb object store.\n *\n * Note that the name 'owner' is chosen to ensure backwards compatibility with\n * older clients that only supported single locked access to the persistence\n * layer.\n */\nexport const DbPrimaryClientStore = 'owner';\n\n/**\n * The key string used for the single object that exists in the\n * DbPrimaryClient store.\n */\n\nexport const DbPrimaryClientKey = 'owner';\n\n/** Object keys in the 'mutationQueues' store are userId strings. */\nexport type DbMutationQueueKey = string;\n\n/** Name of the IndexedDb object store. */\nexport const DbMutationQueueStore = 'mutationQueues';\n\n/** Keys are automatically assigned via the userId property. */\nexport const DbMutationQueueKeyPath = 'userId';\n\n/** The 'mutations' store is keyed by batch ID. */\nexport type DbMutationBatchKey = BatchId;\n\n/** Name of the IndexedDb object store. */\nexport const DbMutationBatchStore = 'mutations';\n\n/** Keys are automatically assigned via the userId, batchId properties. */\nexport const DbMutationBatchKeyPath = 'batchId';\n\n/** The index name for lookup of mutations by user. */\n\nexport const DbMutationBatchUserMutationsIndex = 'userMutationsIndex';\n\n/** The user mutations index is keyed by [userId, batchId] pairs. */\nexport const DbMutationBatchUserMutationsKeyPath = ['userId', 'batchId'];\n\n/**\n * The key for a db document mutation, which is made up of a userID, path, and\n * batchId. Note that the path must be serialized into a form that indexedDB can\n * sort.\n */\nexport type DbDocumentMutationKey = [string, EncodedResourcePath, BatchId];\n\n/**\n * Creates a [userId] key for use in the DbDocumentMutations index to iterate\n * over all of a user's document mutations.\n */\nexport function newDbDocumentMutationPrefixForUser(userId: string): [string] {\n return [userId];\n}\n\n/**\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\n * index to iterate over all at document mutations for a given path or lower.\n */\nexport function newDbDocumentMutationPrefixForPath(\n userId: string,\n path: ResourcePath\n): [string, EncodedResourcePath] {\n return [userId, encodeResourcePath(path)];\n}\n\n/**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */\nexport function newDbDocumentMutationKey(\n userId: string,\n path: ResourcePath,\n batchId: BatchId\n): DbDocumentMutationKey {\n return [userId, encodeResourcePath(path), batchId];\n}\n\n/**\n * Because we store all the useful information for this store in the key,\n * there is no useful information to store as the value. The raw (unencoded)\n * path cannot be stored because IndexedDb doesn't store prototype\n * information.\n */\nexport const DbDocumentMutationPlaceholder: DbDocumentMutation = {};\n\nexport const DbDocumentMutationStore = 'documentMutations';\n\nexport const DbRemoteDocumentStore = 'remoteDocumentsV14';\n\n/**\n * A key in the 'remoteDocumentsV14' object store is an array containing the\n * collection path, the collection group, the read time and the document id.\n */\nexport type DbRemoteDocumentKey = [\n /** path to collection */ string[],\n /** collection group */ string,\n /** read time */ DbTimestampKey,\n /** document ID */ string\n];\n\n/**\n * The primary key of the remote documents store, which allows for efficient\n * access by collection path and read time.\n */\nexport const DbRemoteDocumentKeyPath = [\n 'prefixPath',\n 'collectionGroup',\n 'readTime',\n 'documentId'\n];\n\n/** An index that provides access to documents by key. */\nexport const DbRemoteDocumentDocumentKeyIndex = 'documentKeyIndex';\n\nexport const DbRemoteDocumentDocumentKeyIndexPath = [\n 'prefixPath',\n 'collectionGroup',\n 'documentId'\n];\n\n/**\n * An index that provides access to documents by collection group and read\n * time.\n *\n * This index is used by the index backfiller.\n */\nexport const DbRemoteDocumentCollectionGroupIndex = 'collectionGroupIndex';\n\nexport const DbRemoteDocumentCollectionGroupIndexPath = [\n 'collectionGroup',\n 'readTime',\n 'prefixPath',\n 'documentId'\n];\n\nexport const DbRemoteDocumentGlobalStore = 'remoteDocumentGlobal';\n\nexport const DbRemoteDocumentGlobalKey = 'remoteDocumentGlobalKey';\n\nexport type DbRemoteDocumentGlobalKey = typeof DbRemoteDocumentGlobalKey;\n\n/**\n * A key in the 'targets' object store is a targetId of the query.\n */\nexport type DbTargetKey = TargetId;\n\nexport const DbTargetStore = 'targets';\n\n/** Keys are automatically assigned via the targetId property. */\nexport const DbTargetKeyPath = 'targetId';\n\n/** The name of the queryTargets index. */\nexport const DbTargetQueryTargetsIndexName = 'queryTargetsIndex';\n\n/**\n * The index of all canonicalIds to the targets that they match. This is not\n * a unique mapping because canonicalId does not promise a unique name for all\n * possible queries, so we append the targetId to make the mapping unique.\n */\nexport const DbTargetQueryTargetsKeyPath = ['canonicalId', 'targetId'];\n\n/**\n * The key for a DbTargetDocument, containing a targetId and an encoded resource\n * path.\n */\nexport type DbTargetDocumentKey = [TargetId, EncodedResourcePath];\n\n/** Name of the IndexedDb object store. */\nexport const DbTargetDocumentStore = 'targetDocuments';\n\n/** Keys are automatically assigned via the targetId, path properties. */\nexport const DbTargetDocumentKeyPath = ['targetId', 'path'];\n\n/** The index name for the reverse index. */\nexport const DbTargetDocumentDocumentTargetsIndex = 'documentTargetsIndex';\n\n/** We also need to create the reverse index for these properties. */\nexport const DbTargetDocumentDocumentTargetsKeyPath = ['path', 'targetId'];\n\n/**\n * The type to represent the single allowed key for the DbTargetGlobal store.\n */\nexport type DbTargetGlobalKey = typeof DbTargetGlobalKey;\n/**\n * The key string used for the single object that exists in the\n * DbTargetGlobal store.\n */\nexport const DbTargetGlobalKey = 'targetGlobalKey';\n\nexport const DbTargetGlobalStore = 'targetGlobal';\n\n/**\n * The key for a DbCollectionParent entry, containing the collection ID\n * and the parent path that contains it. Note that the parent path will be an\n * empty path in the case of root-level collections.\n */\nexport type DbCollectionParentKey = [string, EncodedResourcePath];\n\n/** Name of the IndexedDb object store. */\nexport const DbCollectionParentStore = 'collectionParents';\n\n/** Keys are automatically assigned via the collectionId, parent properties. */\nexport const DbCollectionParentKeyPath = ['collectionId', 'parent'];\n\n/** Name of the IndexedDb object store. */\nexport const DbClientMetadataStore = 'clientMetadata';\n\n/** Keys are automatically assigned via the clientId properties. */\nexport const DbClientMetadataKeyPath = 'clientId';\n\n/** Object keys in the 'clientMetadata' store are clientId strings. */\nexport type DbClientMetadataKey = string;\n\nexport type DbBundlesKey = string;\n\n/** Name of the IndexedDb object store. */\nexport const DbBundleStore = 'bundles';\n\nexport const DbBundleKeyPath = 'bundleId';\n\nexport type DbNamedQueriesKey = string;\n\n/** Name of the IndexedDb object store. */\nexport const DbNamedQueryStore = 'namedQueries';\n\nexport const DbNamedQueryKeyPath = 'name';\n\n/** The key for each index consisting of just the index id. */\nexport type DbIndexConfigurationKey = number;\n\n/** Name of the IndexedDb object store. */\nexport const DbIndexConfigurationStore = 'indexConfiguration';\n\nexport const DbIndexConfigurationKeyPath = 'indexId';\n\n/**\n * An index that provides access to the index configurations by collection\n * group.\n *\n * PORTING NOTE: iOS and Android maintain this index in-memory, but this is\n * not possible here as the Web client supports concurrent access to\n * persistence via multi-tab.\n */\nexport const DbIndexConfigurationCollectionGroupIndex = 'collectionGroupIndex';\n\nexport const DbIndexConfigurationCollectionGroupIndexPath = 'collectionGroup';\n\n/** The key for each index state consisting of the index id and its user id. */\nexport type DbIndexStateKey = [number, string];\n\n/** Name of the IndexedDb object store. */\nexport const DbIndexStateStore = 'indexState';\n\nexport const DbIndexStateKeyPath = ['indexId', 'uid'];\n\n/**\n * An index that provides access to documents in a collection sorted by last\n * update time. Used by the backfiller.\n *\n * PORTING NOTE: iOS and Android maintain this index in-memory, but this is\n * not possible here as the Web client supports concurrent access to\n * persistence via multi-tab.\n */\nexport const DbIndexStateSequenceNumberIndex = 'sequenceNumberIndex';\n\nexport const DbIndexStateSequenceNumberIndexPath = ['uid', 'sequenceNumber'];\n\n/**\n * The key for each index entry consists of the index id and its user id,\n * the encoded array and directional value for the indexed fields as well as\n * an ordered and an encoded document path for the indexed document.\n */\nexport type DbIndexEntryKey = [\n number,\n string,\n Uint8Array,\n Uint8Array,\n Uint8Array,\n string[]\n];\n\n/** Name of the IndexedDb object store. */\nexport const DbIndexEntryStore = 'indexEntries';\n\nexport const DbIndexEntryKeyPath = [\n 'indexId',\n 'uid',\n 'arrayValue',\n 'directionalValue',\n 'orderedDocumentKey',\n 'documentKey'\n];\n\nexport const DbIndexEntryDocumentKeyIndex = 'documentKeyIndex';\n\nexport const DbIndexEntryDocumentKeyIndexPath = [\n 'indexId',\n 'uid',\n 'orderedDocumentKey'\n];\n\nexport type DbDocumentOverlayKey = [\n /* userId */ string,\n /* collectionPath */ string,\n /* documentId */ string\n];\n\n/** Name of the IndexedDb object store. */\nexport const DbDocumentOverlayStore = 'documentOverlays';\n\nexport const DbDocumentOverlayKeyPath = [\n 'userId',\n 'collectionPath',\n 'documentId'\n];\n\nexport const DbDocumentOverlayCollectionPathOverlayIndex =\n 'collectionPathOverlayIndex';\n\nexport const DbDocumentOverlayCollectionPathOverlayIndexPath = [\n 'userId',\n 'collectionPath',\n 'largestBatchId'\n];\n\nexport const DbDocumentOverlayCollectionGroupOverlayIndex =\n 'collectionGroupOverlayIndex';\n\nexport const DbDocumentOverlayCollectionGroupOverlayIndexPath = [\n 'userId',\n 'collectionGroup',\n 'largestBatchId'\n];\n\n// Visible for testing\nexport const V1_STORES = [\n DbMutationQueueStore,\n DbMutationBatchStore,\n DbDocumentMutationStore,\n DbRemoteDocumentStoreLegacy,\n DbTargetStore,\n DbPrimaryClientStore,\n DbTargetGlobalStore,\n DbTargetDocumentStore\n];\n\n// Visible for testing\nexport const V3_STORES = V1_STORES;\n// Note: DbRemoteDocumentChanges is no longer used and dropped with v9.\nexport const V4_STORES = [...V3_STORES, DbClientMetadataStore];\nexport const V6_STORES = [...V4_STORES, DbRemoteDocumentGlobalStore];\nexport const V8_STORES = [...V6_STORES, DbCollectionParentStore];\nexport const V11_STORES = [...V8_STORES, DbBundleStore, DbNamedQueryStore];\nexport const V12_STORES = [...V11_STORES, DbDocumentOverlayStore];\nexport const V13_STORES = [\n DbMutationQueueStore,\n DbMutationBatchStore,\n DbDocumentMutationStore,\n DbRemoteDocumentStore,\n DbTargetStore,\n DbPrimaryClientStore,\n DbTargetGlobalStore,\n DbTargetDocumentStore,\n DbClientMetadataStore,\n DbRemoteDocumentGlobalStore,\n DbCollectionParentStore,\n DbBundleStore,\n DbNamedQueryStore,\n DbDocumentOverlayStore\n];\nexport const V14_STORES = V13_STORES;\nexport const V15_STORES = [\n ...V14_STORES,\n DbIndexConfigurationStore,\n DbIndexStateStore,\n DbIndexEntryStore\n];\n\n/**\n * The list of all default IndexedDB stores used throughout the SDK. This is\n * used when creating transactions so that access across all stores is done\n * atomically.\n */\nexport const ALL_STORES = V12_STORES;\n\n/** Returns the object stores for the provided schema. */\nexport function getObjectStores(schemaVersion: number): string[] {\n if (schemaVersion === 15) {\n return V15_STORES;\n } else if (schemaVersion === 14) {\n return V14_STORES;\n } else if (schemaVersion === 13) {\n return V13_STORES;\n } else if (schemaVersion === 12) {\n return V12_STORES;\n } else if (schemaVersion === 11) {\n return V11_STORES;\n } else {\n fail('Only schema version 11 and 12 and 13 are supported');\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document as ProtoDocument } from '../protos/firestore_proto_api';\n\nimport { DbNoDocument, DbUnknownDocument } from './indexeddb_schema';\nimport { DbTimestampKey } from './indexeddb_sentinels';\n\n// This file contains older schema definitions for object stores that were\n// migrated to newer schema versions. These object stores should only be used\n// during schema migrations.\n\nexport interface DbRemoteDocument {\n unknownDocument?: DbUnknownDocument;\n noDocument?: DbNoDocument;\n document?: ProtoDocument;\n hasCommittedMutations?: boolean;\n readTime?: DbTimestampKey;\n parentPath?: string[];\n}\n\nexport type DbRemoteDocumentKey = string[];\nexport const DbRemoteDocumentStore = 'remoteDocuments';\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict<V> {\n [stringKey: string]: V;\n}\n\nexport function objectSize(obj: object): number {\n let count = 0;\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n\nexport function forEach<V>(\n obj: Dict<V> | undefined,\n fn: (key: string, val: V) => void\n): void {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\n\nexport function mapToArray<V, R>(\n obj: Dict<V>,\n fn: (element: V, key: string, obj: Dict<V>) => R\n): R[] {\n const result: R[] = [];\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result.push(fn(obj[key], key, obj));\n }\n }\n return result;\n}\n\nexport function isEmpty<V>(obj: Dict<V>): boolean {\n debugAssert(\n obj != null && typeof obj === 'object',\n 'isEmpty() expects object parameter.'\n );\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, fail } from './assert';\n\n/*\n * Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\nexport type Comparator<K> = (key1: K, key2: K) => number;\n\nexport interface Entry<K, V> {\n key: K;\n value: V;\n}\n\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nexport class SortedMap<K, V> {\n // visible for testing\n root: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n\n constructor(\n public comparator: Comparator<K>,\n root?: LLRBNode<K, V> | LLRBEmptyNode<K, V>\n ) {\n this.root = root ? root : LLRBNode.EMPTY;\n }\n\n // Returns a copy of the map, with the specified key/value added or replaced.\n insert(key: K, value: V): SortedMap<K, V> {\n return new SortedMap<K, V>(\n this.comparator,\n this.root\n .insert(key, value, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns a copy of the map, with the specified key removed.\n remove(key: K): SortedMap<K, V> {\n return new SortedMap<K, V>(\n this.comparator,\n this.root\n .remove(key, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns the value of the node with the given key, or null.\n get(key: K): V | null {\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return node.value;\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\n\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(key: K): number {\n // Number of nodes that were pruned when descending right\n let prunedNodes = 0;\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n } else if (cmp < 0) {\n node = node.left;\n } else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n }\n\n isEmpty(): boolean {\n return this.root.isEmpty();\n }\n\n // Returns the total number of nodes in the map.\n get size(): number {\n return this.root.size;\n }\n\n // Returns the minimum key in the map.\n minKey(): K | null {\n return this.root.minKey();\n }\n\n // Returns the maximum key in the map.\n maxKey(): K | null {\n return this.root.maxKey();\n }\n\n // Traverses the map in key order and calls the specified action function\n // for each key/value pair. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal<T>(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode<K, V>).inorderTraversal(action);\n }\n\n forEach(fn: (k: K, v: V) => void): void {\n this.inorderTraversal((k, v) => {\n fn(k, v);\n return false;\n });\n }\n\n toString(): string {\n const descriptions: string[] = [];\n this.inorderTraversal((k, v) => {\n descriptions.push(`${k}:${v}`);\n return false;\n });\n return `{${descriptions.join(', ')}}`;\n }\n\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal<T>(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode<K, V>).reverseTraversal(action);\n }\n\n // Returns an iterator over the SortedMap.\n getIterator(): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, null, this.comparator, false);\n }\n\n getIteratorFrom(key: K): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, key, this.comparator, false);\n }\n\n getReverseIterator(): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, null, this.comparator, true);\n }\n\n getReverseIteratorFrom(key: K): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, key, this.comparator, true);\n }\n} // end SortedMap\n\n// An iterator over an LLRBNode.\nexport class SortedMapIterator<K, V> {\n private isReverse: boolean;\n private nodeStack: Array<LLRBNode<K, V> | LLRBEmptyNode<K, V>>;\n\n constructor(\n node: LLRBNode<K, V> | LLRBEmptyNode<K, V>,\n startKey: K | null,\n comparator: Comparator<K>,\n isReverse: boolean\n ) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n\n let cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (startKey && isReverse) {\n cmp *= -1;\n }\n\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse) {\n node = node.left;\n } else {\n node = node.right;\n }\n } else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(node);\n break;\n } else {\n // This node is greater than our start key, add it to the stack and move\n // to the next one\n this.nodeStack.push(node);\n if (this.isReverse) {\n node = node.right;\n } else {\n node = node.left;\n }\n }\n }\n }\n\n getNext(): Entry<K, V> {\n debugAssert(\n this.nodeStack.length > 0,\n 'getNext() called on iterator when hasNext() is false.'\n );\n\n let node = this.nodeStack.pop()!;\n const result = { key: node.key, value: node.value };\n\n if (this.isReverse) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.left;\n }\n }\n\n return result;\n }\n\n hasNext(): boolean {\n return this.nodeStack.length > 0;\n }\n\n peek(): Entry<K, V> | null {\n if (this.nodeStack.length === 0) {\n return null;\n }\n\n const node = this.nodeStack[this.nodeStack.length - 1];\n return { key: node.key, value: node.value };\n }\n} // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nexport class LLRBNode<K, V> {\n readonly color: boolean;\n readonly left: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n readonly right: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n readonly size: number;\n\n // Empty node is shared between all LLRB trees.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static EMPTY: LLRBEmptyNode<any, any> = null as any;\n\n static RED = true;\n static BLACK = false;\n\n constructor(\n public key: K,\n public value: V,\n color?: boolean,\n left?: LLRBNode<K, V> | LLRBEmptyNode<K, V>,\n right?: LLRBNode<K, V> | LLRBEmptyNode<K, V>\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n\n // Returns a copy of the current node, optionally replacing pieces of it.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n ): LLRBNode<K, V> {\n return new LLRBNode<K, V>(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n isEmpty(): boolean {\n return false;\n }\n\n // Traverses the tree in key order and calls the specified action function\n // for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal<T>(action: (k: K, v: V) => T): T {\n return (\n (this.left as LLRBNode<K, V>).inorderTraversal(action) ||\n action(this.key, this.value) ||\n (this.right as LLRBNode<K, V>).inorderTraversal(action)\n );\n }\n\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal<T>(action: (k: K, v: V) => T): T {\n return (\n (this.right as LLRBNode<K, V>).reverseTraversal(action) ||\n action(this.key, this.value) ||\n (this.left as LLRBNode<K, V>).reverseTraversal(action)\n );\n }\n\n // Returns the minimum node in the tree.\n private min(): LLRBNode<K, V> {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode<K, V>).min();\n }\n }\n\n // Returns the maximum key in the tree.\n minKey(): K | null {\n return this.min().key;\n }\n\n // Returns the maximum key in the tree.\n maxKey(): K | null {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n // Returns new tree, with the key/value added.\n insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {\n let n: LLRBNode<K, V> = this;\n const cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n } else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n } else {\n n = n.copy(\n null,\n null,\n null,\n null,\n n.right.insert(key, value, comparator)\n );\n }\n return n.fixUp();\n }\n\n private removeMin(): LLRBNode<K, V> | LLRBEmptyNode<K, V> {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n let n: LLRBNode<K, V> = this;\n if (!n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode<K, V>).removeMin(), null);\n return n.fixUp();\n }\n\n // Returns new tree, with the specified item removed.\n remove(\n key: K,\n comparator: Comparator<K>\n ): LLRBNode<K, V> | LLRBEmptyNode<K, V> {\n let smallest: LLRBNode<K, V>;\n let n: LLRBNode<K, V> = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n } else {\n if (n.left.isRed()) {\n n = n.rotateRight();\n }\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n n = n.moveRedRight();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return LLRBNode.EMPTY;\n } else {\n smallest = (n.right as LLRBNode<K, V>).min();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode<K, V>).removeMin()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp();\n }\n\n isRed(): boolean {\n return this.color;\n }\n\n // Returns new tree after performing any needed rotations.\n private fixUp(): LLRBNode<K, V> {\n let n: LLRBNode<K, V> = this;\n if (n.right.isRed() && !n.left.isRed()) {\n n = n.rotateLeft();\n }\n if (n.left.isRed() && n.left.left.isRed()) {\n n = n.rotateRight();\n }\n if (n.left.isRed() && n.right.isRed()) {\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedLeft(): LLRBNode<K, V> {\n let n = this.colorFlip();\n if (n.right.left.isRed()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode<K, V>).rotateRight()\n );\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedRight(): LLRBNode<K, V> {\n let n = this.colorFlip();\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n return n;\n }\n\n private rotateLeft(): LLRBNode<K, V> {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return (this.right as LLRBNode<K, V>).copy(\n null,\n null,\n this.color,\n nl,\n null\n );\n }\n\n private rotateRight(): LLRBNode<K, V> {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return (this.left as LLRBNode<K, V>).copy(null, null, this.color, null, nr);\n }\n\n private colorFlip(): LLRBNode<K, V> {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n const blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n } else {\n return false;\n }\n }\n\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n protected check(): number {\n if (this.isRed() && this.left.isRed()) {\n throw fail('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed()) {\n throw fail('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n const blackDepth = (this.left as LLRBNode<K, V>).check();\n if (blackDepth !== (this.right as LLRBNode<K, V>).check()) {\n throw fail('Black depths differ');\n } else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n }\n} // end LLRBNode\n\n// Represents an empty node (a leaf node in the Red-Black Tree).\nexport class LLRBEmptyNode<K, V> {\n get key(): never {\n throw fail('LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail('LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail('LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail('LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail('LLRBEmptyNode has no right child.');\n }\n size = 0;\n\n // Returns a copy of the current node.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n ): LLRBEmptyNode<K, V> {\n return this;\n }\n\n // Returns a copy of the tree, with the specified key/value added.\n insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {\n return new LLRBNode<K, V>(key, value);\n }\n\n // Returns a copy of the tree, with the specified key removed.\n remove(key: K, comparator: Comparator<K>): LLRBEmptyNode<K, V> {\n return this;\n }\n\n isEmpty(): boolean {\n return true;\n }\n\n inorderTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n reverseTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n minKey(): K | null {\n return null;\n }\n\n maxKey(): K | null {\n return null;\n }\n\n isRed(): boolean {\n return false;\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n return true;\n }\n\n protected check(): 0 {\n return 0;\n }\n} // end LLRBEmptyNode\n\nLLRBNode.EMPTY = new LLRBEmptyNode<unknown, unknown>();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap, SortedMapIterator } from './sorted_map';\n\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nexport class SortedSet<T> {\n private data: SortedMap<T, boolean>;\n\n constructor(private comparator: (left: T, right: T) => number) {\n this.data = new SortedMap<T, boolean>(this.comparator);\n }\n\n has(elem: T): boolean {\n return this.data.get(elem) !== null;\n }\n\n first(): T | null {\n return this.data.minKey();\n }\n\n last(): T | null {\n return this.data.maxKey();\n }\n\n get size(): number {\n return this.data.size;\n }\n\n indexOf(elem: T): number {\n return this.data.indexOf(elem);\n }\n\n /** Iterates elements in order defined by \"comparator\" */\n forEach(cb: (elem: T) => void): void {\n this.data.inorderTraversal((k: T, v: boolean) => {\n cb(k);\n return false;\n });\n }\n\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n forEachInRange(range: [T, T], cb: (elem: T) => void): void {\n const iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n const elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0) {\n return;\n }\n cb(elem.key);\n }\n }\n\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n forEachWhile(cb: (elem: T) => boolean, start?: T): void {\n let iter: SortedMapIterator<T, boolean>;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n } else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n const elem = iter.getNext();\n const result = cb(elem.key);\n if (!result) {\n return;\n }\n }\n }\n\n /** Finds the least element greater than or equal to `elem`. */\n firstAfterOrEqual(elem: T): T | null {\n const iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n }\n\n getIterator(): SortedSetIterator<T> {\n return new SortedSetIterator<T>(this.data.getIterator());\n }\n\n getIteratorFrom(key: T): SortedSetIterator<T> {\n return new SortedSetIterator<T>(this.data.getIteratorFrom(key));\n }\n\n /** Inserts or updates an element */\n add(elem: T): SortedSet<T> {\n return this.copy(this.data.remove(elem).insert(elem, true));\n }\n\n /** Deletes an element */\n delete(elem: T): SortedSet<T> {\n if (!this.has(elem)) {\n return this;\n }\n return this.copy(this.data.remove(elem));\n }\n\n isEmpty(): boolean {\n return this.data.isEmpty();\n }\n\n unionWith(other: SortedSet<T>): SortedSet<T> {\n let result: SortedSet<T> = this;\n\n // Make sure `result` always refers to the larger one of the two sets.\n if (result.size < other.size) {\n result = other;\n other = this;\n }\n\n other.forEach(elem => {\n result = result.add(elem);\n });\n return result;\n }\n\n isEqual(other: SortedSet<T>): boolean {\n if (!(other instanceof SortedSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.data.getIterator();\n const otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n const thisElem = thisIt.getNext().key;\n const otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0) {\n return false;\n }\n }\n return true;\n }\n\n toArray(): T[] {\n const res: T[] = [];\n this.forEach(targetId => {\n res.push(targetId);\n });\n return res;\n }\n\n toString(): string {\n const result: T[] = [];\n this.forEach(elem => result.push(elem));\n return 'SortedSet(' + result.toString() + ')';\n }\n\n private copy(data: SortedMap<T, boolean>): SortedSet<T> {\n const result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n }\n}\n\nexport class SortedSetIterator<T> {\n constructor(private iter: SortedMapIterator<T, boolean>) {}\n\n getNext(): T {\n return this.iter.getNext().key;\n }\n\n hasNext(): boolean {\n return this.iter.hasNext();\n }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffSortedSets<T>(\n before: SortedSet<T>,\n after: SortedSet<T>,\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n const beforeIt = before.getIterator();\n const afterIt = after.getIterator();\n\n let beforeValue = advanceIterator(beforeIt);\n let afterValue = advanceIterator(afterIt);\n\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n while (beforeValue || afterValue) {\n let added = false;\n let removed = false;\n\n if (beforeValue && afterValue) {\n const cmp = comparator(beforeValue, afterValue);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n removed = true;\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n added = true;\n }\n } else if (beforeValue != null) {\n removed = true;\n } else {\n added = true;\n }\n\n if (added) {\n onAdd(afterValue!);\n afterValue = advanceIterator(afterIt);\n } else if (removed) {\n onRemove(beforeValue!);\n beforeValue = advanceIterator(beforeIt);\n } else {\n beforeValue = advanceIterator(beforeIt);\n afterValue = advanceIterator(afterIt);\n }\n }\n}\n\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction advanceIterator<T>(it: SortedSetIterator<T>): T | undefined {\n return it.hasNext() ? it.getNext() : undefined;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { FieldPath } from './path';\n\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */\nexport class FieldMask {\n constructor(readonly fields: FieldPath[]) {\n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n fields.sort(FieldPath.comparator);\n debugAssert(\n !fields.some((v, i) => i !== 0 && v.isEqual(fields[i - 1])),\n 'FieldMask contains field that is not unique: ' +\n fields.find((v, i) => i !== 0 && v.isEqual(fields[i - 1]))!\n );\n }\n\n static empty(): FieldMask {\n return new FieldMask([]);\n }\n\n /**\n * Returns a new FieldMask object that is the result of adding all the given\n * fields paths to this field mask.\n */\n unionWith(extraFields: FieldPath[]): FieldMask {\n let mergedMaskSet = new SortedSet<FieldPath>(FieldPath.comparator);\n for (const fieldPath of this.fields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n for (const fieldPath of extraFields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n return new FieldMask(mergedMaskSet.toArray());\n }\n\n /**\n * Verifies that `fieldPath` is included by at least one field in this field\n * mask.\n *\n * This is an O(n) operation, where `n` is the size of the field mask.\n */\n covers(fieldPath: FieldPath): boolean {\n for (const fieldMaskPath of this.fields) {\n if (fieldMaskPath.isPrefixOf(fieldPath)) {\n return true;\n }\n }\n return false;\n }\n\n isEqual(other: FieldMask): boolean {\n return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r));\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class Base64DecodeError extends Error {\n readonly name = 'Base64DecodeError';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { decodeBase64, encodeBase64 } from '../platform/base64';\n\nimport { primitiveComparator } from './misc';\n\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */\nexport class ByteString {\n static readonly EMPTY_BYTE_STRING = new ByteString('');\n\n private constructor(private readonly binaryString: string) {}\n\n static fromBase64String(base64: string): ByteString {\n const binaryString = decodeBase64(base64);\n return new ByteString(binaryString);\n }\n\n static fromUint8Array(array: Uint8Array): ByteString {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const binaryString = binaryStringFromUint8Array(array);\n return new ByteString(binaryString);\n }\n\n [Symbol.iterator](): Iterator<number> {\n let i = 0;\n return {\n next: () => {\n if (i < this.binaryString.length) {\n return { value: this.binaryString.charCodeAt(i++), done: false };\n } else {\n return { value: undefined, done: true };\n }\n }\n };\n }\n\n toBase64(): string {\n return encodeBase64(this.binaryString);\n }\n\n toUint8Array(): Uint8Array {\n return uint8ArrayFromBinaryString(this.binaryString);\n }\n\n approximateByteSize(): number {\n return this.binaryString.length * 2;\n }\n\n compareTo(other: ByteString): number {\n return primitiveComparator(this.binaryString, other.binaryString);\n }\n\n isEqual(other: ByteString): boolean {\n return this.binaryString === other.binaryString;\n }\n}\n\n/**\n * Helper function to convert an Uint8array to a binary string.\n */\nexport function binaryStringFromUint8Array(array: Uint8Array): string {\n let binaryString = '';\n for (let i = 0; i < array.length; ++i) {\n binaryString += String.fromCharCode(array[i]);\n }\n return binaryString;\n}\n\n/**\n * Helper function to convert a binary string to an Uint8Array.\n */\nexport function uint8ArrayFromBinaryString(binaryString: string): Uint8Array {\n const buffer = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n buffer[i] = binaryString.charCodeAt(i);\n }\n return buffer;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Base64DecodeError } from '../../util/base64_decode_error';\n\n/** Converts a Base64 encoded string to a binary string. */\nexport function decodeBase64(encoded: string): string {\n try {\n return atob(encoded);\n } catch (e) {\n // Check that `DOMException` is defined before using it to avoid\n // \"ReferenceError: Property 'DOMException' doesn't exist\" in react-native.\n // (https://github.com/firebase/firebase-js-sdk/issues/7115)\n if (typeof DOMException !== 'undefined' && e instanceof DOMException) {\n throw new Base64DecodeError('Invalid base64 string: ' + e);\n } else {\n throw e;\n }\n }\n}\n\n/** Converts a binary string to a Base64 encoded string. */\nexport function encodeBase64(raw: string): string {\n return btoa(raw);\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return typeof atob !== 'undefined';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../protos/firestore_proto_api';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nconst ISO_TIMESTAMP_REG_EXP = new RegExp(\n /^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/\n);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */\nexport function normalizeTimestamp(date: Timestamp): {\n seconds: number;\n nanos: number;\n} {\n hardAssert(!!date, 'Cannot normalize null or undefined timestamp.');\n\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (typeof date === 'string') {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n\n // Parse the nanos right out of the string.\n let nanos = 0;\n const fraction = ISO_TIMESTAMP_REG_EXP.exec(date);\n hardAssert(!!fraction, 'invalid timestamp: ' + date);\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n }\n\n // Parse the date to get the seconds.\n const parsedDate = new Date(date);\n const seconds = Math.floor(parsedDate.getTime() / 1000);\n\n return { seconds, nanos };\n } else {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n const seconds = normalizeNumber(date.seconds);\n const nanos = normalizeNumber(date.nanos);\n return { seconds, nanos };\n }\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */\nexport function normalizeNumber(value: number | string | undefined): number {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n } else if (typeof value === 'string') {\n return Number(value);\n } else {\n return 0;\n }\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */\nexport function normalizeByteString(blob: string | Uint8Array): ByteString {\n if (typeof blob === 'string') {\n return ByteString.fromBase64String(blob);\n } else {\n return ByteString.fromUint8Array(blob);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n Value as ProtoValue,\n MapValue as ProtoMapValue\n} from '../protos/firestore_proto_api';\n\nimport { normalizeTimestamp } from './normalize';\n\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * transform. They can only exist in the local view of a document. Therefore\n * they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */\n\nconst SERVER_TIMESTAMP_SENTINEL = 'server_timestamp';\nconst TYPE_KEY = '__type__';\nconst PREVIOUS_VALUE_KEY = '__previous_value__';\nconst LOCAL_WRITE_TIME_KEY = '__local_write_time__';\n\nexport function isServerTimestamp(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === SERVER_TIMESTAMP_SENTINEL;\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\nexport function serverTimestamp(\n localWriteTime: Timestamp,\n previousValue: ProtoValue | null\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: SERVER_TIMESTAMP_SENTINEL\n },\n [LOCAL_WRITE_TIME_KEY]: {\n timestampValue: {\n seconds: localWriteTime.seconds,\n nanos: localWriteTime.nanoseconds\n }\n }\n }\n };\n\n // We should avoid storing deeply nested server timestamp map values\n // because we never use the intermediate \"previous values\".\n // For example:\n // previous: 42L, add: t1, result: t1 -> 42L\n // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)\n // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)\n // `getPreviousValue` recursively traverses server timestamps to find the\n // least recent Value.\n if (previousValue && isServerTimestamp(previousValue)) {\n previousValue = getPreviousValue(previousValue);\n }\n if (previousValue) {\n mapValue.fields![PREVIOUS_VALUE_KEY] = previousValue;\n }\n\n return { mapValue };\n}\n\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nexport function getPreviousValue(value: ProtoValue): ProtoValue | null {\n const previousValue = value.mapValue!.fields![PREVIOUS_VALUE_KEY];\n\n if (isServerTimestamp(previousValue)) {\n return getPreviousValue(previousValue);\n }\n return previousValue;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */\nexport function getLocalWriteTime(value: ProtoValue): Timestamp {\n const localWriteTime = normalizeTimestamp(\n value.mapValue!.fields![LOCAL_WRITE_TIME_KEY].timestampValue!\n );\n return new Timestamp(localWriteTime.seconds, localWriteTime.nanos);\n}\n","import { FirebaseApp } from '@firebase/app';\n\nimport { ExperimentalLongPollingOptions } from '../api/long_polling_options';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class DatabaseInfo {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId - The database to use.\n * @param appId - The Firebase App Id.\n * @param persistenceKey - A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host - The Firestore backend host to connect to.\n * @param ssl - Whether to use SSL when connecting.\n * @param forceLongPolling - Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n * option when using WebChannel as the network transport.\n * @param longPollingOptions Options that configure long-polling.\n * @param useFetchStreams Whether to use the Fetch API instead of\n * XMLHTTPRequest\n */\n constructor(\n readonly databaseId: DatabaseId,\n readonly appId: string,\n readonly persistenceKey: string,\n readonly host: string,\n readonly ssl: boolean,\n readonly forceLongPolling: boolean,\n readonly autoDetectLongPolling: boolean,\n readonly longPollingOptions: ExperimentalLongPollingOptions,\n readonly useFetchStreams: boolean\n ) {}\n}\n\n/** The default database name for a project. */\nexport const DEFAULT_DATABASE_NAME = '(default)';\n\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nexport class DatabaseId {\n readonly database: string;\n constructor(readonly projectId: string, database?: string) {\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n\n static empty(): DatabaseId {\n return new DatabaseId('', '');\n }\n\n get isDefaultDatabase(): boolean {\n return this.database === DEFAULT_DATABASE_NAME;\n }\n\n isEqual(other: {}): boolean {\n return (\n other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database\n );\n }\n}\n\nexport function databaseIdFromApp(\n app: FirebaseApp,\n database?: string\n): DatabaseId {\n if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n '\"projectId\" not provided in firebase.initializeApp.'\n );\n }\n\n return new DatabaseId(app.options.projectId!, database);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseId } from '../core/database_info';\nimport {\n ArrayValue,\n LatLng,\n MapValue,\n Timestamp,\n Value\n} from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport { arrayEquals, primitiveComparator } from '../util/misc';\nimport { forEach, objectSize } from '../util/obj';\nimport { isNegativeZero } from '../util/types';\n\nimport { DocumentKey } from './document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from './normalize';\nimport {\n getLocalWriteTime,\n getPreviousValue,\n isServerTimestamp\n} from './server_timestamps';\nimport { TypeOrder } from './type_order';\n\nconst MAX_VALUE_TYPE = '__max__';\nexport const MAX_VALUE: Value = {\n mapValue: {\n fields: {\n '__type__': { stringValue: MAX_VALUE_TYPE }\n }\n }\n};\n\nexport const MIN_VALUE: Value = {\n nullValue: 'NULL_VALUE'\n};\n\n/** Extracts the backend's type order for the provided value. */\nexport function typeOrder(value: Value): TypeOrder {\n if ('nullValue' in value) {\n return TypeOrder.NullValue;\n } else if ('booleanValue' in value) {\n return TypeOrder.BooleanValue;\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return TypeOrder.NumberValue;\n } else if ('timestampValue' in value) {\n return TypeOrder.TimestampValue;\n } else if ('stringValue' in value) {\n return TypeOrder.StringValue;\n } else if ('bytesValue' in value) {\n return TypeOrder.BlobValue;\n } else if ('referenceValue' in value) {\n return TypeOrder.RefValue;\n } else if ('geoPointValue' in value) {\n return TypeOrder.GeoPointValue;\n } else if ('arrayValue' in value) {\n return TypeOrder.ArrayValue;\n } else if ('mapValue' in value) {\n if (isServerTimestamp(value)) {\n return TypeOrder.ServerTimestampValue;\n } else if (isMaxValue(value)) {\n return TypeOrder.MaxValue;\n }\n return TypeOrder.ObjectValue;\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */\nexport function valueEquals(left: Value, right: Value): boolean {\n if (left === right) {\n return true;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n if (leftType !== rightType) {\n return false;\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n return true;\n case TypeOrder.BooleanValue:\n return left.booleanValue === right.booleanValue;\n case TypeOrder.ServerTimestampValue:\n return getLocalWriteTime(left).isEqual(getLocalWriteTime(right));\n case TypeOrder.TimestampValue:\n return timestampEquals(left, right);\n case TypeOrder.StringValue:\n return left.stringValue === right.stringValue;\n case TypeOrder.BlobValue:\n return blobEquals(left, right);\n case TypeOrder.RefValue:\n return left.referenceValue === right.referenceValue;\n case TypeOrder.GeoPointValue:\n return geoPointEquals(left, right);\n case TypeOrder.NumberValue:\n return numberEquals(left, right);\n case TypeOrder.ArrayValue:\n return arrayEquals(\n left.arrayValue!.values || [],\n right.arrayValue!.values || [],\n valueEquals\n );\n case TypeOrder.ObjectValue:\n return objectEquals(left, right);\n case TypeOrder.MaxValue:\n return true;\n default:\n return fail('Unexpected value type: ' + JSON.stringify(left));\n }\n}\n\nfunction timestampEquals(left: Value, right: Value): boolean {\n if (\n typeof left.timestampValue === 'string' &&\n typeof right.timestampValue === 'string' &&\n left.timestampValue.length === right.timestampValue.length\n ) {\n // Use string equality for ISO 8601 timestamps\n return left.timestampValue === right.timestampValue;\n }\n\n const leftTimestamp = normalizeTimestamp(left.timestampValue!);\n const rightTimestamp = normalizeTimestamp(right.timestampValue!);\n return (\n leftTimestamp.seconds === rightTimestamp.seconds &&\n leftTimestamp.nanos === rightTimestamp.nanos\n );\n}\n\nfunction geoPointEquals(left: Value, right: Value): boolean {\n return (\n normalizeNumber(left.geoPointValue!.latitude) ===\n normalizeNumber(right.geoPointValue!.latitude) &&\n normalizeNumber(left.geoPointValue!.longitude) ===\n normalizeNumber(right.geoPointValue!.longitude)\n );\n}\n\nfunction blobEquals(left: Value, right: Value): boolean {\n return normalizeByteString(left.bytesValue!).isEqual(\n normalizeByteString(right.bytesValue!)\n );\n}\n\nexport function numberEquals(left: Value, right: Value): boolean {\n if ('integerValue' in left && 'integerValue' in right) {\n return (\n normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)\n );\n } else if ('doubleValue' in left && 'doubleValue' in right) {\n const n1 = normalizeNumber(left.doubleValue!);\n const n2 = normalizeNumber(right.doubleValue!);\n\n if (n1 === n2) {\n return isNegativeZero(n1) === isNegativeZero(n2);\n } else {\n return isNaN(n1) && isNaN(n2);\n }\n }\n\n return false;\n}\n\nfunction objectEquals(left: Value, right: Value): boolean {\n const leftMap = left.mapValue!.fields || {};\n const rightMap = right.mapValue!.fields || {};\n\n if (objectSize(leftMap) !== objectSize(rightMap)) {\n return false;\n }\n\n for (const key in leftMap) {\n if (leftMap.hasOwnProperty(key)) {\n if (\n rightMap[key] === undefined ||\n !valueEquals(leftMap[key], rightMap[key])\n ) {\n return false;\n }\n }\n }\n return true;\n}\n\n/** Returns true if the ArrayValue contains the specified element. */\nexport function arrayValueContains(\n haystack: ArrayValue,\n needle: Value\n): boolean {\n return (\n (haystack.values || []).find(v => valueEquals(v, needle)) !== undefined\n );\n}\n\nexport function valueCompare(left: Value, right: Value): number {\n if (left === right) {\n return 0;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n\n if (leftType !== rightType) {\n return primitiveComparator(leftType, rightType);\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n case TypeOrder.MaxValue:\n return 0;\n case TypeOrder.BooleanValue:\n return primitiveComparator(left.booleanValue!, right.booleanValue!);\n case TypeOrder.NumberValue:\n return compareNumbers(left, right);\n case TypeOrder.TimestampValue:\n return compareTimestamps(left.timestampValue!, right.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return compareTimestamps(\n getLocalWriteTime(left),\n getLocalWriteTime(right)\n );\n case TypeOrder.StringValue:\n return primitiveComparator(left.stringValue!, right.stringValue!);\n case TypeOrder.BlobValue:\n return compareBlobs(left.bytesValue!, right.bytesValue!);\n case TypeOrder.RefValue:\n return compareReferences(left.referenceValue!, right.referenceValue!);\n case TypeOrder.GeoPointValue:\n return compareGeoPoints(left.geoPointValue!, right.geoPointValue!);\n case TypeOrder.ArrayValue:\n return compareArrays(left.arrayValue!, right.arrayValue!);\n case TypeOrder.ObjectValue:\n return compareMaps(left.mapValue!, right.mapValue!);\n default:\n throw fail('Invalid value type: ' + leftType);\n }\n}\n\nfunction compareNumbers(left: Value, right: Value): number {\n const leftNumber = normalizeNumber(left.integerValue || left.doubleValue);\n const rightNumber = normalizeNumber(right.integerValue || right.doubleValue);\n\n if (leftNumber < rightNumber) {\n return -1;\n } else if (leftNumber > rightNumber) {\n return 1;\n } else if (leftNumber === rightNumber) {\n return 0;\n } else {\n // one or both are NaN.\n if (isNaN(leftNumber)) {\n return isNaN(rightNumber) ? 0 : -1;\n } else {\n return 1;\n }\n }\n}\n\nfunction compareTimestamps(left: Timestamp, right: Timestamp): number {\n if (\n typeof left === 'string' &&\n typeof right === 'string' &&\n left.length === right.length\n ) {\n return primitiveComparator(left, right);\n }\n\n const leftTimestamp = normalizeTimestamp(left);\n const rightTimestamp = normalizeTimestamp(right);\n\n const comparison = primitiveComparator(\n leftTimestamp.seconds,\n rightTimestamp.seconds\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos);\n}\n\nfunction compareReferences(leftPath: string, rightPath: string): number {\n const leftSegments = leftPath.split('/');\n const rightSegments = rightPath.split('/');\n for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) {\n const comparison = primitiveComparator(leftSegments[i], rightSegments[i]);\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(leftSegments.length, rightSegments.length);\n}\n\nfunction compareGeoPoints(left: LatLng, right: LatLng): number {\n const comparison = primitiveComparator(\n normalizeNumber(left.latitude),\n normalizeNumber(right.latitude)\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(\n normalizeNumber(left.longitude),\n normalizeNumber(right.longitude)\n );\n}\n\nfunction compareBlobs(\n left: string | Uint8Array,\n right: string | Uint8Array\n): number {\n const leftBytes = normalizeByteString(left);\n const rightBytes = normalizeByteString(right);\n return leftBytes.compareTo(rightBytes);\n}\n\nfunction compareArrays(left: ArrayValue, right: ArrayValue): number {\n const leftArray = left.values || [];\n const rightArray = right.values || [];\n\n for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) {\n const compare = valueCompare(leftArray[i], rightArray[i]);\n if (compare) {\n return compare;\n }\n }\n return primitiveComparator(leftArray.length, rightArray.length);\n}\n\nfunction compareMaps(left: MapValue, right: MapValue): number {\n if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {\n return 0;\n } else if (left === MAX_VALUE.mapValue) {\n return 1;\n } else if (right === MAX_VALUE.mapValue) {\n return -1;\n }\n\n const leftMap = left.fields || {};\n const leftKeys = Object.keys(leftMap);\n const rightMap = right.fields || {};\n const rightKeys = Object.keys(rightMap);\n\n // Even though MapValues are likely sorted correctly based on their insertion\n // order (e.g. when received from the backend), local modifications can bring\n // elements out of order. We need to re-sort the elements to ensure that\n // canonical IDs are independent of insertion order.\n leftKeys.sort();\n rightKeys.sort();\n\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) {\n const keyCompare = primitiveComparator(leftKeys[i], rightKeys[i]);\n if (keyCompare !== 0) {\n return keyCompare;\n }\n const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]);\n if (compare !== 0) {\n return compare;\n }\n }\n\n return primitiveComparator(leftKeys.length, rightKeys.length);\n}\n\n/**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */\nexport function canonicalId(value: Value): string {\n return canonifyValue(value);\n}\n\nfunction canonifyValue(value: Value): string {\n if ('nullValue' in value) {\n return 'null';\n } else if ('booleanValue' in value) {\n return '' + value.booleanValue!;\n } else if ('integerValue' in value) {\n return '' + value.integerValue!;\n } else if ('doubleValue' in value) {\n return '' + value.doubleValue!;\n } else if ('timestampValue' in value) {\n return canonifyTimestamp(value.timestampValue!);\n } else if ('stringValue' in value) {\n return value.stringValue!;\n } else if ('bytesValue' in value) {\n return canonifyByteString(value.bytesValue!);\n } else if ('referenceValue' in value) {\n return canonifyReference(value.referenceValue!);\n } else if ('geoPointValue' in value) {\n return canonifyGeoPoint(value.geoPointValue!);\n } else if ('arrayValue' in value) {\n return canonifyArray(value.arrayValue!);\n } else if ('mapValue' in value) {\n return canonifyMap(value.mapValue!);\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nfunction canonifyByteString(byteString: string | Uint8Array): string {\n return normalizeByteString(byteString).toBase64();\n}\n\nfunction canonifyTimestamp(timestamp: Timestamp): string {\n const normalizedTimestamp = normalizeTimestamp(timestamp);\n return `time(${normalizedTimestamp.seconds},${normalizedTimestamp.nanos})`;\n}\n\nfunction canonifyGeoPoint(geoPoint: LatLng): string {\n return `geo(${geoPoint.latitude},${geoPoint.longitude})`;\n}\n\nfunction canonifyReference(referenceValue: string): string {\n return DocumentKey.fromName(referenceValue).toString();\n}\n\nfunction canonifyMap(mapValue: MapValue): string {\n // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n // matching canonical IDs for identical maps, we need to sort the keys.\n const sortedKeys = Object.keys(mapValue.fields || {}).sort();\n\n let result = '{';\n let first = true;\n for (const key of sortedKeys) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += `${key}:${canonifyValue(mapValue.fields![key])}`;\n }\n return result + '}';\n}\n\nfunction canonifyArray(arrayValue: ArrayValue): string {\n let result = '[';\n let first = true;\n for (const value of arrayValue.values || []) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += canonifyValue(value);\n }\n return result + ']';\n}\n\n/**\n * Returns an approximate (and wildly inaccurate) in-memory size for the field\n * value.\n *\n * The memory size takes into account only the actual user data as it resides\n * in memory and ignores object overhead.\n */\nexport function estimateByteSize(value: Value): number {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return 4;\n case TypeOrder.BooleanValue:\n return 4;\n case TypeOrder.NumberValue:\n return 8;\n case TypeOrder.TimestampValue:\n // Timestamps are made up of two distinct numbers (seconds + nanoseconds)\n return 16;\n case TypeOrder.ServerTimestampValue:\n const previousValue = getPreviousValue(value);\n return previousValue ? 16 + estimateByteSize(previousValue) : 16;\n case TypeOrder.StringValue:\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:\n // \"JavaScript's String type is [...] a set of elements of 16-bit unsigned\n // integer values\"\n return value.stringValue!.length * 2;\n case TypeOrder.BlobValue:\n return normalizeByteString(value.bytesValue!).approximateByteSize();\n case TypeOrder.RefValue:\n return value.referenceValue!.length;\n case TypeOrder.GeoPointValue:\n // GeoPoints are made up of two distinct numbers (latitude + longitude)\n return 16;\n case TypeOrder.ArrayValue:\n return estimateArrayByteSize(value.arrayValue!);\n case TypeOrder.ObjectValue:\n return estimateMapByteSize(value.mapValue!);\n default:\n throw fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nfunction estimateMapByteSize(mapValue: MapValue): number {\n let size = 0;\n forEach(mapValue.fields, (key, val) => {\n size += key.length + estimateByteSize(val);\n });\n return size;\n}\n\nfunction estimateArrayByteSize(arrayValue: ArrayValue): number {\n return (arrayValue.values || []).reduce(\n (previousSize, value) => previousSize + estimateByteSize(value),\n 0\n );\n}\n\n/** Returns a reference value for the provided database and key. */\nexport function refValue(databaseId: DatabaseId, key: DocumentKey): Value {\n return {\n referenceValue: `projects/${databaseId.projectId}/databases/${\n databaseId.database\n }/documents/${key.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */\nexport function isInteger(\n value?: Value | null\n): value is { integerValue: string | number } {\n return !!value && 'integerValue' in value;\n}\n\n/** Returns true if `value` is a DoubleValue. */\nexport function isDouble(\n value?: Value | null\n): value is { doubleValue: string | number } {\n return !!value && 'doubleValue' in value;\n}\n\n/** Returns true if `value` is either an IntegerValue or a DoubleValue. */\nexport function isNumber(value?: Value | null): boolean {\n return isInteger(value) || isDouble(value);\n}\n\n/** Returns true if `value` is an ArrayValue. */\nexport function isArray(\n value?: Value | null\n): value is { arrayValue: ArrayValue } {\n return !!value && 'arrayValue' in value;\n}\n\n/** Returns true if `value` is a ReferenceValue. */\nexport function isReferenceValue(\n value?: Value | null\n): value is { referenceValue: string } {\n return !!value && 'referenceValue' in value;\n}\n\n/** Returns true if `value` is a NullValue. */\nexport function isNullValue(\n value?: Value | null\n): value is { nullValue: 'NULL_VALUE' } {\n return !!value && 'nullValue' in value;\n}\n\n/** Returns true if `value` is NaN. */\nexport function isNanValue(\n value?: Value | null\n): value is { doubleValue: 'NaN' | number } {\n return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */\nexport function isMapValue(\n value?: Value | null\n): value is { mapValue: MapValue } {\n return !!value && 'mapValue' in value;\n}\n\n/** Creates a deep copy of `source`. */\nexport function deepClone(source: Value): Value {\n if (source.geoPointValue) {\n return { geoPointValue: { ...source.geoPointValue } };\n } else if (\n source.timestampValue &&\n typeof source.timestampValue === 'object'\n ) {\n return { timestampValue: { ...source.timestampValue } };\n } else if (source.mapValue) {\n const target: Value = { mapValue: { fields: {} } };\n forEach(\n source.mapValue.fields,\n (key, val) => (target.mapValue!.fields![key] = deepClone(val))\n );\n return target;\n } else if (source.arrayValue) {\n const target: Value = { arrayValue: { values: [] } };\n for (let i = 0; i < (source.arrayValue.values || []).length; ++i) {\n target.arrayValue!.values![i] = deepClone(source.arrayValue.values![i]);\n }\n return target;\n } else {\n return { ...source };\n }\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */\nexport function isMaxValue(value: Value): boolean {\n return (\n (((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue ===\n MAX_VALUE_TYPE\n );\n}\n\n/** Returns the lowest value for the given value type (inclusive). */\nexport function valuesGetLowerBound(value: Value): Value {\n if ('nullValue' in value) {\n return MIN_VALUE;\n } else if ('booleanValue' in value) {\n return { booleanValue: false };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { doubleValue: NaN };\n } else if ('timestampValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('stringValue' in value) {\n return { stringValue: '' };\n } else if ('bytesValue' in value) {\n return { bytesValue: '' };\n } else if ('referenceValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('geoPointValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('arrayValue' in value) {\n return { arrayValue: {} };\n } else if ('mapValue' in value) {\n return { mapValue: {} };\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\n/** Returns the largest value for the given value type (exclusive). */\nexport function valuesGetUpperBound(value: Value): Value {\n if ('nullValue' in value) {\n return { booleanValue: false };\n } else if ('booleanValue' in value) {\n return { doubleValue: NaN };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('timestampValue' in value) {\n return { stringValue: '' };\n } else if ('stringValue' in value) {\n return { bytesValue: '' };\n } else if ('bytesValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('referenceValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('geoPointValue' in value) {\n return { arrayValue: {} };\n } else if ('arrayValue' in value) {\n return { mapValue: {} };\n } else if ('mapValue' in value) {\n return MAX_VALUE;\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nexport function lowerBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return -1;\n } else if (!left.inclusive && right.inclusive) {\n return 1;\n }\n\n return 0;\n}\n\nexport function upperBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return 1;\n } else if (!left.inclusive && right.inclusive) {\n return -1;\n }\n\n return 0;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\nimport { forEach } from '../util/obj';\n\nimport { FieldMask } from './field_mask';\nimport { FieldPath } from './path';\nimport { isServerTimestamp } from './server_timestamps';\nimport { deepClone, isMapValue, valueEquals } from './values';\n\nexport interface JsonObject<T> {\n [name: string]: T;\n}\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */\nexport class ObjectValue {\n constructor(readonly value: { mapValue: ProtoMapValue }) {\n debugAssert(\n !isServerTimestamp(value),\n 'ServerTimestamps should be converted to ServerTimestampValue'\n );\n }\n\n static empty(): ObjectValue {\n return new ObjectValue({ mapValue: {} });\n }\n\n /**\n * Returns the value at the given path or null.\n *\n * @param path - the path to search\n * @returns The value at the path or null if the path is not set.\n */\n field(path: FieldPath): ProtoValue | null {\n if (path.isEmpty()) {\n return this.value;\n } else {\n let currentLevel: ProtoValue = this.value;\n for (let i = 0; i < path.length - 1; ++i) {\n currentLevel = (currentLevel.mapValue!.fields || {})[path.get(i)];\n if (!isMapValue(currentLevel)) {\n return null;\n }\n }\n currentLevel = (currentLevel.mapValue!.fields! || {})[path.lastSegment()];\n return currentLevel || null;\n }\n }\n\n /**\n * Sets the field to the provided value.\n *\n * @param path - The field path to set.\n * @param value - The value to set.\n */\n set(path: FieldPath, value: ProtoValue): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot set field for empty path on ObjectValue'\n );\n const fieldsMap = this.getFieldsMap(path.popLast());\n fieldsMap[path.lastSegment()] = deepClone(value);\n }\n\n /**\n * Sets the provided fields to the provided values.\n *\n * @param data - A map of fields to values (or null for deletes).\n */\n setAll(data: Map<FieldPath, ProtoValue | null>): void {\n let parent = FieldPath.emptyPath();\n\n let upserts: { [key: string]: ProtoValue } = {};\n let deletes: string[] = [];\n\n data.forEach((value, path) => {\n if (!parent.isImmediateParentOf(path)) {\n // Insert the accumulated changes at this parent location\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n upserts = {};\n deletes = [];\n parent = path.popLast();\n }\n\n if (value) {\n upserts[path.lastSegment()] = deepClone(value);\n } else {\n deletes.push(path.lastSegment());\n }\n });\n\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n }\n\n /**\n * Removes the field at the specified path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path - The field path to remove.\n */\n delete(path: FieldPath): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot delete field for empty path on ObjectValue'\n );\n const nestedValue = this.field(path.popLast());\n if (isMapValue(nestedValue) && nestedValue.mapValue.fields) {\n delete nestedValue.mapValue.fields[path.lastSegment()];\n }\n }\n\n isEqual(other: ObjectValue): boolean {\n return valueEquals(this.value, other.value);\n }\n\n /**\n * Returns the map that contains the leaf element of `path`. If the parent\n * entry does not yet exist, or if it is not a map, a new map will be created.\n */\n private getFieldsMap(path: FieldPath): Record<string, ProtoValue> {\n let current = this.value;\n\n if (!current.mapValue!.fields) {\n current.mapValue = { fields: {} };\n }\n\n for (let i = 0; i < path.length; ++i) {\n let next = current.mapValue!.fields![path.get(i)];\n if (!isMapValue(next) || !next.mapValue.fields) {\n next = { mapValue: { fields: {} } };\n current.mapValue!.fields![path.get(i)] = next;\n }\n current = next as { mapValue: ProtoMapValue };\n }\n\n return current.mapValue!.fields!;\n }\n\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */\n private applyChanges(\n fieldsMap: Record<string, ProtoValue>,\n inserts: { [key: string]: ProtoValue },\n deletes: string[]\n ): void {\n forEach(inserts, (key, val) => (fieldsMap[key] = val));\n for (const field of deletes) {\n delete fieldsMap[field];\n }\n }\n\n clone(): ObjectValue {\n return new ObjectValue(\n deepClone(this.value) as { mapValue: ProtoMapValue }\n );\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */\nexport function extractFieldMask(value: ProtoMapValue): FieldMask {\n const fields: FieldPath[] = [];\n forEach(value!.fields, (key, value) => {\n const currentPath = new FieldPath([key]);\n if (isMapValue(value)) {\n const nestedMask = extractFieldMask(value.mapValue!);\n const nestedFields = nestedMask.fields;\n if (nestedFields.length === 0) {\n // Preserve the empty map by adding it to the FieldMask.\n fields.push(currentPath);\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const nestedPath of nestedFields) {\n fields.push(currentPath.child(nestedPath));\n }\n }\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n fields.push(currentPath);\n }\n });\n return new FieldMask(fields);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { DocumentKey } from './document_key';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport { valueCompare } from './values';\n\n/**\n * Whether the document represents an existing document, a document that is\n * known to exist or a document whose state or existence is unknown.\n */\nconst enum DocumentType {\n /**\n * Represents the initial state of a MutableDocument when only the document\n * key is known. Invalid documents transition to other states as mutations are\n * applied. If a document remains invalid after applying mutations, it should\n * be discarded.\n *\n * Invalid documents can have neither local nor committed mutations.\n */\n INVALID,\n /**\n * Represents a document in Firestore with a key, version, data and whether\n * the data has local mutations applied to it.\n *\n * Found documents can be sycned or have or committed mutations applied.\n */\n FOUND_DOCUMENT,\n /**\n * Represents that no documents exists for the key at the given version.\n *\n * Documents that are deleted based on a local mutation do not raise snapshots\n * with `hasPendingWrites`. As such, deleted documents never have\n * `HAS_LOCAL_MUTATIONS` set. Once a delete is committed, we store them with\n * `HAS_COMMITTED_MUTATIONS` until we received the delete from the Watch\n * stream.\n */\n NO_DOCUMENT,\n /**\n * Represents an existing document whose data is unknown (e.g. a document that\n * was updated without a known base document).\n *\n * An unknown document always has `HAS_COMMITTED_MUTATIONS` set, since unknown\n * documents can only be generated by applying a patch mutation from a write\n * acknowledgement.\n */\n UNKNOWN_DOCUMENT\n}\n\n/** Describes whether a document has latency-compensated edits applied. */\nconst enum DocumentState {\n /** No mutations applied. Document was sent to us by Watch. */\n SYNCED,\n /**\n * Local mutations applied via the mutation queue. Document is potentially\n * inconsistent.\n */\n HAS_LOCAL_MUTATIONS,\n /**\n * Mutations applied based on a write acknowledgment. Document is potentially\n * inconsistent.\n */\n HAS_COMMITTED_MUTATIONS\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether the\n * data has local mutations applied to it.\n */\nexport interface Document {\n /** The key for this document */\n readonly key: DocumentKey;\n\n /**\n * The version of this document if it exists or a version at which this\n * document was guaranteed to not exist.\n */\n readonly version: SnapshotVersion;\n\n /**\n * The timestamp at which this document was read from the remote server. Uses\n * `SnapshotVersion.min()` for documents created by the user.\n */\n readonly readTime: SnapshotVersion;\n\n /**\n * The timestamp at which the document was created. This value increases\n * monotonically when a document is deleted then recreated. It can also be\n * compared to `createTime` of other documents and the `readTime` of a query.\n */\n readonly createTime: SnapshotVersion;\n\n /** The underlying data of this document or an empty value if no data exists. */\n readonly data: ObjectValue;\n\n /** Returns whether local mutations were applied via the mutation queue. */\n readonly hasLocalMutations: boolean;\n\n /** Returns whether mutations were applied based on a write acknowledgment. */\n readonly hasCommittedMutations: boolean;\n\n /**\n * Whether this document had a local mutation applied that has not yet been\n * acknowledged by Watch.\n */\n readonly hasPendingWrites: boolean;\n\n /**\n * Returns whether this document is valid (i.e. it is an entry in the\n * RemoteDocumentCache, was created by a mutation or read from the backend).\n */\n isValidDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is known at the current\n * version.\n */\n isFoundDocument(): boolean;\n\n /**\n * Returns whether the document is known to not exist at the current version.\n */\n isNoDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is unknown at the current\n * version.\n */\n isUnknownDocument(): boolean;\n\n isEqual(other: Document | null | undefined): boolean;\n\n /** Creates a mutable copy of this document. */\n mutableCopy(): MutableDocument;\n\n toString(): string;\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */\nexport class MutableDocument implements Document {\n private constructor(\n readonly key: DocumentKey,\n private documentType: DocumentType,\n public version: SnapshotVersion,\n public readTime: SnapshotVersion,\n public createTime: SnapshotVersion,\n public data: ObjectValue,\n private documentState: DocumentState\n ) {}\n\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */\n static newInvalidDocument(documentKey: DocumentKey): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.INVALID,\n /* version */ SnapshotVersion.min(),\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */\n static newFoundDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion,\n createTime: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.FOUND_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ createTime,\n value,\n DocumentState.SYNCED\n );\n }\n\n /** Creates a new document that is known to not exist at the given version. */\n static newNoDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.NO_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist at the given version but\n * whose data is not known (e.g. a document that was updated without a known\n * base document).\n */\n static newUnknownDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.UNKNOWN_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.HAS_COMMITTED_MUTATIONS\n );\n }\n\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */\n convertToFoundDocument(\n version: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n // If a document is switching state from being an invalid or deleted\n // document to a valid (FOUND_DOCUMENT) document, either due to receiving an\n // update from Watch or due to applying a local set mutation on top\n // of a deleted document, our best guess about its createTime would be the\n // version at which the document transitioned to a FOUND_DOCUMENT.\n if (\n this.createTime.isEqual(SnapshotVersion.min()) &&\n (this.documentType === DocumentType.NO_DOCUMENT ||\n this.documentType === DocumentType.INVALID)\n ) {\n this.createTime = version;\n }\n this.version = version;\n this.documentType = DocumentType.FOUND_DOCUMENT;\n this.data = value;\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */\n convertToNoDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.NO_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it exists at a given version but\n * that its data is not known (e.g. a document that was updated without a known\n * base document).\n */\n convertToUnknownDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.UNKNOWN_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasCommittedMutations(): MutableDocument {\n debugAssert(\n this.isValidDocument(),\n 'Invalid documents cannot have committed mutations'\n );\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasLocalMutations(): MutableDocument {\n this.documentState = DocumentState.HAS_LOCAL_MUTATIONS;\n this.version = SnapshotVersion.min();\n return this;\n }\n\n setReadTime(readTime: SnapshotVersion): MutableDocument {\n this.readTime = readTime;\n return this;\n }\n\n get hasLocalMutations(): boolean {\n return this.documentState === DocumentState.HAS_LOCAL_MUTATIONS;\n }\n\n get hasCommittedMutations(): boolean {\n return this.documentState === DocumentState.HAS_COMMITTED_MUTATIONS;\n }\n\n get hasPendingWrites(): boolean {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n\n isValidDocument(): boolean {\n return this.documentType !== DocumentType.INVALID;\n }\n\n isFoundDocument(): boolean {\n return this.documentType === DocumentType.FOUND_DOCUMENT;\n }\n\n isNoDocument(): boolean {\n return this.documentType === DocumentType.NO_DOCUMENT;\n }\n\n isUnknownDocument(): boolean {\n return this.documentType === DocumentType.UNKNOWN_DOCUMENT;\n }\n\n isEqual(other: Document | null | undefined): boolean {\n return (\n other instanceof MutableDocument &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.documentType === other.documentType &&\n this.documentState === other.documentState &&\n this.data.isEqual(other.data)\n );\n }\n\n mutableCopy(): MutableDocument {\n return new MutableDocument(\n this.key,\n this.documentType,\n this.version,\n this.readTime,\n this.createTime,\n this.data.clone(),\n this.documentState\n );\n }\n\n toString(): string {\n return (\n `Document(${this.key}, ${this.version}, ${JSON.stringify(\n this.data.value\n )}, ` +\n `{createTime: ${this.createTime}}), ` +\n `{documentType: ${this.documentType}}), ` +\n `{documentState: ${this.documentState}})`\n );\n }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\nexport function compareDocumentsByField(\n field: FieldPath,\n d1: Document,\n d2: Document\n): number {\n const v1 = d1.data.field(field);\n const v2 = d2.data.field(field);\n if (v1 !== null && v2 !== null) {\n return valueCompare(v1, v2);\n } else {\n return fail(\"Trying to compare documents on fields that don't exist\");\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { isReferenceValue, valueCompare, valueEquals } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\n\nimport { Direction, OrderBy } from './order_by';\n\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */\nexport class Bound {\n constructor(readonly position: ProtoValue[], readonly inclusive: boolean) {}\n}\n\nfunction boundCompareToDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): number {\n debugAssert(\n bound.position.length <= orderBy.length,\n \"Bound has more components than query's orderBy\"\n );\n let comparison = 0;\n for (let i = 0; i < bound.position.length; i++) {\n const orderByComponent = orderBy[i];\n const component = bound.position[i];\n if (orderByComponent.field.isKeyField()) {\n debugAssert(\n isReferenceValue(component),\n 'Bound has a non-key value where the key path is being used.'\n );\n comparison = DocumentKey.comparator(\n DocumentKey.fromName(component.referenceValue),\n doc.key\n );\n } else {\n const docValue = doc.data.field(orderByComponent.field);\n debugAssert(\n docValue !== null,\n 'Field should exist since document matched the orderBy already.'\n );\n comparison = valueCompare(component, docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return comparison;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */\nexport function boundSortsAfterDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison >= 0 : comparison > 0;\n}\n\n/**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\nexport function boundSortsBeforeDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison <= 0 : comparison < 0;\n}\n\nexport function boundEquals(left: Bound | null, right: Bound | null): boolean {\n if (left === null) {\n return right === null;\n } else if (right === null) {\n return false;\n }\n\n if (\n left.inclusive !== right.inclusive ||\n left.position.length !== right.position.length\n ) {\n return false;\n }\n for (let i = 0; i < left.position.length; i++) {\n const leftPosition = left.position[i];\n const rightPosition = right.position[i];\n if (!valueEquals(leftPosition, rightPosition)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from '../model/path';\n\n/**\n * The direction of sorting in an order by.\n */\nexport const enum Direction {\n ASCENDING = 'asc',\n DESCENDING = 'desc'\n}\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nexport class OrderBy {\n constructor(\n readonly field: FieldPath,\n readonly dir: Direction = Direction.ASCENDING\n ) {}\n}\n\nexport function canonifyOrderBy(orderBy: OrderBy): string {\n // TODO(b/29183165): Make this collision robust.\n return orderBy.field.canonicalString() + orderBy.dir;\n}\n\nexport function stringifyOrderBy(orderBy: OrderBy): string {\n return `${orderBy.field.canonicalString()} (${orderBy.dir})`;\n}\n\nexport function orderByEquals(left: OrderBy, right: OrderBy): boolean {\n return left.dir === right.dir && left.field.isEqual(right.field);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath } from '../model/path';\nimport {\n arrayValueContains,\n canonicalId,\n isArray,\n isReferenceValue,\n typeOrder,\n valueCompare,\n valueEquals\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail } from '../util/assert';\n\n// The operator of a FieldFilter\nexport const enum Operator {\n LESS_THAN = '<',\n LESS_THAN_OR_EQUAL = '<=',\n EQUAL = '==',\n NOT_EQUAL = '!=',\n GREATER_THAN = '>',\n GREATER_THAN_OR_EQUAL = '>=',\n ARRAY_CONTAINS = 'array-contains',\n IN = 'in',\n NOT_IN = 'not-in',\n ARRAY_CONTAINS_ANY = 'array-contains-any'\n}\n\n// The operator of a CompositeFilter\nexport const enum CompositeOperator {\n OR = 'or',\n AND = 'and'\n}\n\nexport abstract class Filter {\n abstract matches(doc: Document): boolean;\n\n abstract getFlattenedFilters(): readonly FieldFilter[];\n\n abstract getFilters(): Filter[];\n}\n\nexport class FieldFilter extends Filter {\n protected constructor(\n public readonly field: FieldPath,\n public readonly op: Operator,\n public readonly value: ProtoValue\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(\n field: FieldPath,\n op: Operator,\n value: ProtoValue\n ): FieldFilter {\n if (field.isKeyField()) {\n if (op === Operator.IN || op === Operator.NOT_IN) {\n return this.createKeyFieldInFilter(field, op, value);\n } else {\n debugAssert(\n isReferenceValue(value),\n 'Comparing on key, but filter value not a RefValue'\n );\n debugAssert(\n op !== Operator.ARRAY_CONTAINS && op !== Operator.ARRAY_CONTAINS_ANY,\n `'${op.toString()}' queries don't make sense on document keys.`\n );\n return new KeyFieldFilter(field, op, value);\n }\n } else if (op === Operator.ARRAY_CONTAINS) {\n return new ArrayContainsFilter(field, value);\n } else if (op === Operator.IN) {\n debugAssert(\n isArray(value),\n 'IN filter has invalid value: ' + value.toString()\n );\n return new InFilter(field, value);\n } else if (op === Operator.NOT_IN) {\n debugAssert(\n isArray(value),\n 'NOT_IN filter has invalid value: ' + value.toString()\n );\n return new NotInFilter(field, value);\n } else if (op === Operator.ARRAY_CONTAINS_ANY) {\n debugAssert(\n isArray(value),\n 'ARRAY_CONTAINS_ANY filter has invalid value: ' + value.toString()\n );\n return new ArrayContainsAnyFilter(field, value);\n } else {\n return new FieldFilter(field, op, value);\n }\n }\n\n private static createKeyFieldInFilter(\n field: FieldPath,\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n ): FieldFilter {\n debugAssert(\n isArray(value),\n `Comparing on key with ${op.toString()}` +\n ', but filter value not an ArrayValue'\n );\n debugAssert(\n (value.arrayValue.values || []).every(elem => isReferenceValue(elem)),\n `Comparing on key with ${op.toString()}` +\n ', but an array value was not a RefValue'\n );\n\n return op === Operator.IN\n ? new KeyFieldInFilter(field, value)\n : new KeyFieldNotInFilter(field, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n if (this.op === Operator.NOT_EQUAL) {\n return (\n other !== null &&\n this.matchesComparison(valueCompare(other!, this.value))\n );\n }\n\n // Only compare types with matching backend order (such as double and int).\n return (\n other !== null &&\n typeOrder(this.value) === typeOrder(other) &&\n this.matchesComparison(valueCompare(other, this.value))\n );\n }\n\n protected matchesComparison(comparison: number): boolean {\n switch (this.op) {\n case Operator.LESS_THAN:\n return comparison < 0;\n case Operator.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case Operator.EQUAL:\n return comparison === 0;\n case Operator.NOT_EQUAL:\n return comparison !== 0;\n case Operator.GREATER_THAN:\n return comparison > 0;\n case Operator.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail('Unknown FieldFilter operator: ' + this.op);\n }\n }\n\n isInequality(): boolean {\n return (\n [\n Operator.LESS_THAN,\n Operator.LESS_THAN_OR_EQUAL,\n Operator.GREATER_THAN,\n Operator.GREATER_THAN_OR_EQUAL,\n Operator.NOT_EQUAL,\n Operator.NOT_IN\n ].indexOf(this.op) >= 0\n );\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n return [this];\n }\n\n getFilters(): Filter[] {\n return [this];\n }\n}\n\nexport class CompositeFilter extends Filter {\n private memoizedFlattenedFilters: FieldFilter[] | null = null;\n\n protected constructor(\n public readonly filters: readonly Filter[],\n public readonly op: CompositeOperator\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(filters: Filter[], op: CompositeOperator): CompositeFilter {\n return new CompositeFilter(filters, op);\n }\n\n matches(doc: Document): boolean {\n if (compositeFilterIsConjunction(this)) {\n // For conjunctions, all filters must match, so return false if any filter doesn't match.\n return this.filters.find(filter => !filter.matches(doc)) === undefined;\n } else {\n // For disjunctions, at least one filter should match.\n return this.filters.find(filter => filter.matches(doc)) !== undefined;\n }\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n if (this.memoizedFlattenedFilters !== null) {\n return this.memoizedFlattenedFilters;\n }\n\n this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => {\n return result.concat(subfilter.getFlattenedFilters());\n }, [] as FieldFilter[]);\n\n return this.memoizedFlattenedFilters;\n }\n\n // Returns a mutable copy of `this.filters`\n getFilters(): Filter[] {\n return Object.assign([], this.filters);\n }\n}\n\nexport function compositeFilterIsConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.AND;\n}\n\nexport function compositeFilterIsDisjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.OR;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */\nexport function compositeFilterIsFlatConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return (\n compositeFilterIsFlat(compositeFilter) &&\n compositeFilterIsConjunction(compositeFilter)\n );\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */\nexport function compositeFilterIsFlat(\n compositeFilter: CompositeFilter\n): boolean {\n for (const filter of compositeFilter.filters) {\n if (filter instanceof CompositeFilter) {\n return false;\n }\n }\n return true;\n}\n\nexport function canonifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'canonifyFilter() only supports FieldFilters and CompositeFilters'\n );\n\n if (filter instanceof FieldFilter) {\n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return (\n filter.field.canonicalString() +\n filter.op.toString() +\n canonicalId(filter.value)\n );\n } else if (compositeFilterIsFlatConjunction(filter)) {\n // Older SDK versions use an implicit AND operation between their filters.\n // In the new SDK versions, the developer may use an explicit AND filter.\n // To stay consistent with the old usages, we add a special case to ensure\n // the canonical ID for these two are the same. For example:\n // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n return filter.filters.map(filter => canonifyFilter(filter)).join(',');\n } else {\n // filter instanceof CompositeFilter\n const canonicalIdsString = filter.filters\n .map(filter => canonifyFilter(filter))\n .join(',');\n return `${filter.op}(${canonicalIdsString})`;\n }\n}\n\nexport function filterEquals(f1: Filter, f2: Filter): boolean {\n if (f1 instanceof FieldFilter) {\n return fieldFilterEquals(f1, f2);\n } else if (f1 instanceof CompositeFilter) {\n return compositeFilterEquals(f1, f2);\n } else {\n fail('Only FieldFilters and CompositeFilters can be compared');\n }\n}\n\nexport function fieldFilterEquals(f1: FieldFilter, f2: Filter): boolean {\n return (\n f2 instanceof FieldFilter &&\n f1.op === f2.op &&\n f1.field.isEqual(f2.field) &&\n valueEquals(f1.value, f2.value)\n );\n}\n\nexport function compositeFilterEquals(\n f1: CompositeFilter,\n f2: Filter\n): boolean {\n if (\n f2 instanceof CompositeFilter &&\n f1.op === f2.op &&\n f1.filters.length === f2.filters.length\n ) {\n const subFiltersMatch: boolean = f1.filters.reduce(\n (result: boolean, f1Filter: Filter, index: number): boolean =>\n result && filterEquals(f1Filter, f2.filters[index]),\n true\n );\n\n return subFiltersMatch;\n }\n\n return false;\n}\n\n/**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */\nexport function compositeFilterWithAddedFilters(\n compositeFilter: CompositeFilter,\n otherFilters: Filter[]\n): CompositeFilter {\n const mergedFilters = compositeFilter.filters.concat(otherFilters);\n return CompositeFilter.create(mergedFilters, compositeFilter.op);\n}\n\n/** Returns a debug description for `filter`. */\nexport function stringifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'stringifyFilter() only supports FieldFilters and CompositeFilters'\n );\n if (filter instanceof FieldFilter) {\n return stringifyFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return stringifyCompositeFilter(filter);\n } else {\n return 'Filter';\n }\n}\n\nexport function stringifyCompositeFilter(filter: CompositeFilter): string {\n return (\n filter.op.toString() +\n ` {` +\n filter.getFilters().map(stringifyFilter).join(' ,') +\n '}'\n );\n}\n\nexport function stringifyFieldFilter(filter: FieldFilter): string {\n return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(\n filter.value\n )}`;\n}\n\n/** Filter that matches on key fields (i.e. '__name__'). */\nexport class KeyFieldFilter extends FieldFilter {\n private readonly key: DocumentKey;\n\n constructor(field: FieldPath, op: Operator, value: ProtoValue) {\n super(field, op, value);\n debugAssert(\n isReferenceValue(value),\n 'KeyFieldFilter expects a ReferenceValue'\n );\n this.key = DocumentKey.fromName(value.referenceValue);\n }\n\n matches(doc: Document): boolean {\n const comparison = DocumentKey.comparator(doc.key, this.key);\n return this.matchesComparison(comparison);\n }\n}\n\n/** Filter that matches on key fields within an array. */\nexport class KeyFieldInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.IN, value);\n }\n\n matches(doc: Document): boolean {\n return this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */\nexport class KeyFieldNotInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.NOT_IN, value);\n }\n\n matches(doc: Document): boolean {\n return !this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\nfunction extractDocumentKeysFromArrayValue(\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n): DocumentKey[] {\n debugAssert(\n isArray(value),\n 'KeyFieldInFilter/KeyFieldNotInFilter expects an ArrayValue'\n );\n return (value.arrayValue?.values || []).map(v => {\n debugAssert(\n isReferenceValue(v),\n `Comparing on key with ${op.toString()}, but an array value was not ` +\n `a ReferenceValue`\n );\n return DocumentKey.fromName(v.referenceValue);\n });\n}\n\n/** A Filter that implements the array-contains operator. */\nexport class ArrayContainsFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return isArray(other) && arrayValueContains(other.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */\nexport class InFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n debugAssert(isArray(value), 'InFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return other !== null && arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the not-in operator. */\nexport class NotInFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n debugAssert(isArray(value), 'NotInFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n if (\n arrayValueContains(this.value.arrayValue!, { nullValue: 'NULL_VALUE' })\n ) {\n return false;\n }\n const other = doc.data.field(this.field);\n return other !== null && !arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */\nexport class ArrayContainsAnyFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS_ANY, value);\n debugAssert(isArray(value), 'ArrayContainsAnyFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n if (!isArray(other) || !other.arrayValue.values) {\n return false;\n }\n return other.arrayValue.values.some(val =>\n arrayValueContains(this.value.arrayValue!, val)\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind\n} from '../model/field_index';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n canonicalId,\n MAX_VALUE,\n MIN_VALUE,\n lowerBoundCompare,\n upperBoundCompare,\n valuesGetLowerBound,\n valuesGetUpperBound\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugCast } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Bound, boundEquals } from './bound';\nimport {\n Filter,\n FieldFilter,\n canonifyFilter,\n stringifyFilter,\n filterEquals,\n Operator\n} from './filter';\nimport {\n canonifyOrderBy,\n OrderBy,\n orderByEquals,\n stringifyOrderBy\n} from './order_by';\n\n/**\n * A Target represents the WatchTarget representation of a Query, which is used\n * by the LocalStore and the RemoteStore to keep track of and to execute\n * backend queries. While a Query can represent multiple Targets, each Targets\n * maps to a single WatchTarget in RemoteStore and a single TargetData entry\n * in persistence.\n */\nexport interface Target {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly orderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n// Visible for testing\nexport class TargetImpl implements Target {\n memoizedCanonicalId: string | null = null;\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly orderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {}\n}\n\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */\nexport function newTarget(\n path: ResourcePath,\n collectionGroup: string | null = null,\n orderBy: OrderBy[] = [],\n filters: Filter[] = [],\n limit: number | null = null,\n startAt: Bound | null = null,\n endAt: Bound | null = null\n): Target {\n return new TargetImpl(\n path,\n collectionGroup,\n orderBy,\n filters,\n limit,\n startAt,\n endAt\n );\n}\n\nexport function canonifyTarget(target: Target): string {\n const targetImpl = debugCast(target, TargetImpl);\n\n if (targetImpl.memoizedCanonicalId === null) {\n let str = targetImpl.path.canonicalString();\n if (targetImpl.collectionGroup !== null) {\n str += '|cg:' + targetImpl.collectionGroup;\n }\n str += '|f:';\n str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');\n str += '|ob:';\n str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');\n\n if (!isNullOrUndefined(targetImpl.limit)) {\n str += '|l:';\n str += targetImpl.limit!;\n }\n if (targetImpl.startAt) {\n str += '|lb:';\n str += targetImpl.startAt.inclusive ? 'b:' : 'a:';\n str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (targetImpl.endAt) {\n str += '|ub:';\n str += targetImpl.endAt.inclusive ? 'a:' : 'b:';\n str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');\n }\n targetImpl.memoizedCanonicalId = str;\n }\n return targetImpl.memoizedCanonicalId;\n}\n\nexport function stringifyTarget(target: Target): string {\n let str = target.path.canonicalString();\n if (target.collectionGroup !== null) {\n str += ' collectionGroup=' + target.collectionGroup;\n }\n if (target.filters.length > 0) {\n str += `, filters: [${target.filters\n .map(f => stringifyFilter(f))\n .join(', ')}]`;\n }\n if (!isNullOrUndefined(target.limit)) {\n str += ', limit: ' + target.limit;\n }\n if (target.orderBy.length > 0) {\n str += `, orderBy: [${target.orderBy\n .map(o => stringifyOrderBy(o))\n .join(', ')}]`;\n }\n if (target.startAt) {\n str += ', startAt: ';\n str += target.startAt.inclusive ? 'b:' : 'a:';\n str += target.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (target.endAt) {\n str += ', endAt: ';\n str += target.endAt.inclusive ? 'a:' : 'b:';\n str += target.endAt.position.map(p => canonicalId(p)).join(',');\n }\n return `Target(${str})`;\n}\n\nexport function targetEquals(left: Target, right: Target): boolean {\n if (left.limit !== right.limit) {\n return false;\n }\n\n if (left.orderBy.length !== right.orderBy.length) {\n return false;\n }\n\n for (let i = 0; i < left.orderBy.length; i++) {\n if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {\n return false;\n }\n }\n\n if (left.filters.length !== right.filters.length) {\n return false;\n }\n\n for (let i = 0; i < left.filters.length; i++) {\n if (!filterEquals(left.filters[i], right.filters[i])) {\n return false;\n }\n }\n\n if (left.collectionGroup !== right.collectionGroup) {\n return false;\n }\n\n if (!left.path.isEqual(right.path)) {\n return false;\n }\n\n if (!boundEquals(left.startAt, right.startAt)) {\n return false;\n }\n\n return boundEquals(left.endAt, right.endAt);\n}\n\nexport function targetIsDocumentTarget(target: Target): boolean {\n return (\n DocumentKey.isDocumentKey(target.path) &&\n target.collectionGroup === null &&\n target.filters.length === 0\n );\n}\n\n/** Returns the field filters that target the given field path. */\nexport function targetGetFieldFiltersForPath(\n target: Target,\n path: FieldPath\n): FieldFilter[] {\n return target.filters.filter(\n f => f instanceof FieldFilter && f.field.isEqual(path)\n ) as FieldFilter[];\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\nexport function targetGetArrayValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const segment = fieldIndexGetArraySegment(fieldIndex);\n if (segment === undefined) {\n return null;\n }\n\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.ARRAY_CONTAINS_ANY:\n return fieldFilter.value.arrayValue!.values || [];\n case Operator.ARRAY_CONTAINS:\n return [fieldFilter.value];\n default:\n // Remaining filters are not array filters.\n }\n }\n return null;\n}\n\n/**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */\nexport function targetGetNotInValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const values = new Map</* fieldPath = */ string, ProtoValue>();\n\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.EQUAL:\n case Operator.IN:\n // Encode equality prefix, which is encoded in the index value before\n // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n // `value != 'ab'`).\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n break;\n case Operator.NOT_IN:\n case Operator.NOT_EQUAL:\n // NotIn/NotEqual is always a suffix. There cannot be any remaining\n // segments and hence we can return early here.\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n return Array.from(values.values());\n default:\n // Remaining filters cannot be used as notIn bounds.\n }\n }\n }\n\n return null;\n}\n\n/**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */\nexport function targetGetLowerBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)\n : targetGetDescendingBound(target, segment.fieldPath, target.startAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */\nexport function targetGetUpperBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)\n : targetGetAscendingBound(target, segment.fieldPath, target.endAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction targetGetAscendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MIN_VALUE;\n\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MIN_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.LESS_THAN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = valuesGetLowerBound(fieldFilter.value);\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.GREATER_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.GREATER_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MIN_VALUE;\n break;\n default:\n // Remaining filters cannot be used as lower bounds.\n }\n\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) < 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) < 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */\nfunction targetGetDescendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MAX_VALUE;\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MAX_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.GREATER_THAN_OR_EQUAL:\n case Operator.GREATER_THAN:\n filterValue = valuesGetUpperBound(fieldFilter.value);\n filterInclusive = false;\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.LESS_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MAX_VALUE;\n break;\n default:\n // Remaining filters cannot be used as upper bounds.\n }\n\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) > 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) > 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\nexport function targetGetSegmentCount(target: Target): number {\n let fields = new SortedSet<FieldPath>(FieldPath.comparator);\n let hasArraySegment = false;\n\n for (const filter of target.filters) {\n for (const subFilter of filter.getFlattenedFilters()) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (subFilter.field.isKeyField()) {\n continue;\n }\n\n // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n // though these are on the same field, they should be counted as two\n // separate segments in an index.\n if (\n subFilter.op === Operator.ARRAY_CONTAINS ||\n subFilter.op === Operator.ARRAY_CONTAINS_ANY\n ) {\n hasArraySegment = true;\n } else {\n fields = fields.add(subFilter.field);\n }\n }\n }\n\n for (const orderBy of target.orderBy) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (!orderBy.field.isKeyField()) {\n fields = fields.add(orderBy.field);\n }\n }\n\n return fields.size + (hasArraySegment ? 1 : 0);\n}\n\nexport function targetHasLimit(target: Target): boolean {\n return target.limit !== null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { compareDocumentsByField, Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { debugAssert, debugCast, fail } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n Bound,\n boundSortsAfterDocument,\n boundSortsBeforeDocument\n} from './bound';\nimport { FieldFilter, Filter } from './filter';\nimport { Direction, OrderBy } from './order_by';\nimport {\n canonifyTarget,\n newTarget,\n stringifyTarget,\n Target,\n targetEquals\n} from './target';\n\nexport const enum LimitType {\n First = 'F',\n Last = 'L'\n}\n\n/**\n * The Query interface defines all external properties of a query.\n *\n * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy`\n * and `queryToTarget`.\n */\nexport interface Query {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly explicitOrderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly limitType: LimitType;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nexport class QueryImpl implements Query {\n memoizedNormalizedOrderBy: OrderBy[] | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // non-aggregate queries.\n memoizedTarget: Target | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // aggregate queries. Unlike targets for non-aggregate queries,\n // aggregate query targets do not contain normalized order-bys, they only\n // contain explicit order-bys.\n memoizedAggregateTarget: Target | null = null;\n\n /**\n * Initializes a Query with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n */\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly explicitOrderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly limitType: LimitType = LimitType.First,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {\n if (this.startAt) {\n debugAssert(\n this.startAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n if (this.endAt) {\n debugAssert(\n this.endAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n }\n}\n\n/** Creates a new Query instance with the options provided. */\nexport function newQuery(\n path: ResourcePath,\n collectionGroup: string | null,\n explicitOrderBy: OrderBy[],\n filters: Filter[],\n limit: number | null,\n limitType: LimitType,\n startAt: Bound | null,\n endAt: Bound | null\n): Query {\n return new QueryImpl(\n path,\n collectionGroup,\n explicitOrderBy,\n filters,\n limit,\n limitType,\n startAt,\n endAt\n );\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */\nexport function newQueryForPath(path: ResourcePath): Query {\n return new QueryImpl(path);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\nexport function asCollectionQueryAtPath(\n query: Query,\n path: ResourcePath\n): Query {\n return new QueryImpl(\n path,\n /*collectionGroup=*/ null,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nexport function queryMatchesAllDocuments(query: Query): boolean {\n return (\n query.filters.length === 0 &&\n query.limit === null &&\n query.startAt == null &&\n query.endAt == null &&\n (query.explicitOrderBy.length === 0 ||\n (query.explicitOrderBy.length === 1 &&\n query.explicitOrderBy[0].field.isKeyField()))\n );\n}\n\n// Returns the sorted set of inequality filter fields used in this query.\nexport function getInequalityFilterFields(query: Query): SortedSet<FieldPath> {\n let result = new SortedSet<FieldPath>(FieldPath.comparator);\n query.filters.forEach((filter: Filter) => {\n const subFilters = filter.getFlattenedFilters();\n subFilters.forEach((filter: FieldFilter) => {\n if (filter.isInequality()) {\n result = result.add(filter.field);\n }\n });\n });\n return result;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\nexport function newQueryForCollectionGroup(collectionId: string): Query {\n return new QueryImpl(ResourcePath.emptyPath(), collectionId);\n}\n\n/**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\nexport function isDocumentQuery(query: Query): boolean {\n return (\n DocumentKey.isDocumentKey(query.path) &&\n query.collectionGroup === null &&\n query.filters.length === 0\n );\n}\n\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nexport function isCollectionGroupQuery(query: Query): boolean {\n return query.collectionGroup !== null;\n}\n\n/**\n * Returns the normalized order-by constraint that is used to execute the Query,\n * which can be different from the order-by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`). The normalized order-by\n * includes implicit order-bys in addition to the explicit user provided\n * order-bys.\n */\nexport function queryNormalizedOrderBy(query: Query): OrderBy[] {\n const queryImpl = debugCast(query, QueryImpl);\n if (queryImpl.memoizedNormalizedOrderBy === null) {\n queryImpl.memoizedNormalizedOrderBy = [];\n const fieldsNormalized = new Set<string>();\n\n // Any explicit order by fields should be added as is.\n for (const orderBy of queryImpl.explicitOrderBy) {\n queryImpl.memoizedNormalizedOrderBy.push(orderBy);\n fieldsNormalized.add(orderBy.field.canonicalString());\n }\n\n // The order of the implicit ordering always matches the last explicit order by.\n const lastDirection =\n queryImpl.explicitOrderBy.length > 0\n ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n\n // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical\n // order. When there are multiple inequality filters on the same field, the field should be added\n // only once.\n // Note: `SortedSet<FieldPath>` sorts the key field before other fields. However, we want the key\n // field to be sorted last.\n const inequalityFields: SortedSet<FieldPath> =\n getInequalityFilterFields(queryImpl);\n inequalityFields.forEach(field => {\n if (\n !fieldsNormalized.has(field.canonicalString()) &&\n !field.isKeyField()\n ) {\n queryImpl.memoizedNormalizedOrderBy!.push(\n new OrderBy(field, lastDirection)\n );\n }\n });\n\n // Add the document key field to the last if it is not explicitly ordered.\n if (!fieldsNormalized.has(FieldPath.keyField().canonicalString())) {\n queryImpl.memoizedNormalizedOrderBy.push(\n new OrderBy(FieldPath.keyField(), lastDirection)\n );\n }\n }\n return queryImpl.memoizedNormalizedOrderBy;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation.\n */\nexport function queryToTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n if (!queryImpl.memoizedTarget) {\n queryImpl.memoizedTarget = _queryToTarget(\n queryImpl,\n queryNormalizedOrderBy(query)\n );\n }\n\n return queryImpl.memoizedTarget;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation,\n * for use within an aggregate query. Unlike targets for non-aggregate queries,\n * aggregate query targets do not contain normalized order-bys, they only\n * contain explicit order-bys.\n */\nexport function queryToAggregateTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n\n if (!queryImpl.memoizedAggregateTarget) {\n // Do not include implicit order-bys for aggregate queries.\n queryImpl.memoizedAggregateTarget = _queryToTarget(\n queryImpl,\n query.explicitOrderBy\n );\n }\n\n return queryImpl.memoizedAggregateTarget;\n}\n\nfunction _queryToTarget(queryImpl: QueryImpl, orderBys: OrderBy[]): Target {\n if (queryImpl.limitType === LimitType.First) {\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n queryImpl.startAt,\n queryImpl.endAt\n );\n } else {\n // Flip the orderBy directions since we want the last results\n orderBys = orderBys.map(orderBy => {\n const dir =\n orderBy.dir === Direction.DESCENDING\n ? Direction.ASCENDING\n : Direction.DESCENDING;\n return new OrderBy(orderBy.field, dir);\n });\n\n // We need to swap the cursors to match the now-flipped query ordering.\n const startAt = queryImpl.endAt\n ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)\n : null;\n const endAt = queryImpl.startAt\n ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)\n : null;\n\n // Now return as a LimitType.First query.\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n startAt,\n endAt\n );\n }\n}\n\nexport function queryWithAddedFilter(query: Query, filter: Filter): Query {\n debugAssert(\n !isDocumentQuery(query),\n 'No filtering allowed for document query'\n );\n\n const newFilters = query.filters.concat([filter]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n newFilters,\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithAddedOrderBy(query: Query, orderBy: OrderBy): Query {\n debugAssert(\n !query.startAt && !query.endAt,\n 'Bounds must be set after orderBy'\n );\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const newOrderBy = query.explicitOrderBy.concat([orderBy]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n newOrderBy,\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithLimit(\n query: Query,\n limit: number | null,\n limitType: LimitType\n): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n limit,\n limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithStartAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n bound,\n query.endAt\n );\n}\n\nexport function queryWithEndAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n bound\n );\n}\n\nexport function queryEquals(left: Query, right: Query): boolean {\n return (\n targetEquals(queryToTarget(left), queryToTarget(right)) &&\n left.limitType === right.limitType\n );\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nexport function canonifyQuery(query: Query): string {\n return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;\n}\n\nexport function stringifyQuery(query: Query): string {\n return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${\n query.limitType\n })`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */\nexport function queryMatches(query: Query, doc: Document): boolean {\n return (\n doc.isFoundDocument() &&\n queryMatchesPathAndCollectionGroup(query, doc) &&\n queryMatchesOrderBy(query, doc) &&\n queryMatchesFilters(query, doc) &&\n queryMatchesBounds(query, doc)\n );\n}\n\nfunction queryMatchesPathAndCollectionGroup(\n query: Query,\n doc: Document\n): boolean {\n const docPath = doc.key.path;\n if (query.collectionGroup !== null) {\n // NOTE: this.path is currently always empty since we don't expose Collection\n // Group queries rooted at a document path yet.\n return (\n doc.key.hasCollectionId(query.collectionGroup) &&\n query.path.isPrefixOf(docPath)\n );\n } else if (DocumentKey.isDocumentKey(query.path)) {\n // exact match for document queries\n return query.path.isEqual(docPath);\n } else {\n // shallow ancestor queries by default\n return query.path.isImmediateParentOf(docPath);\n }\n}\n\n/**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\nfunction queryMatchesOrderBy(query: Query, doc: Document): boolean {\n // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit).\n // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n // A document with content of {b:1} matches the filters, but does not match the orderBy because\n // it's missing the field 'a'.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n // order-by key always matches\n if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {\n return false;\n }\n }\n return true;\n}\n\nfunction queryMatchesFilters(query: Query, doc: Document): boolean {\n for (const filter of query.filters) {\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n}\n\n/** Makes sure a document is within the bounds, if provided. */\nfunction queryMatchesBounds(query: Query, doc: Document): boolean {\n if (\n query.startAt &&\n !boundSortsBeforeDocument(query.startAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n if (\n query.endAt &&\n !boundSortsAfterDocument(query.endAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n return true;\n}\n\n/**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */\nexport function queryCollectionGroup(query: Query): string {\n return (\n query.collectionGroup ||\n (query.path.length % 2 === 1\n ? query.path.lastSegment()\n : query.path.get(query.path.length - 2))\n );\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */\nexport function newQueryComparator(\n query: Query\n): (d1: Document, d2: Document) => number {\n return (d1: Document, d2: Document): number => {\n let comparedOnKeyField = false;\n for (const orderBy of queryNormalizedOrderBy(query)) {\n const comp = compareDocs(orderBy, d1, d2);\n if (comp !== 0) {\n return comp;\n }\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n debugAssert(\n comparedOnKeyField,\n \"orderBy used that doesn't compare on key field\"\n );\n return 0;\n };\n}\n\nexport function compareDocs(\n orderBy: OrderBy,\n d1: Document,\n d2: Document\n): number {\n const comparison = orderBy.field.isKeyField()\n ? DocumentKey.comparator(d1.key, d2.key)\n : compareDocumentsByField(orderBy.field, d1, d2);\n switch (orderBy.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail('Unknown direction: ' + orderBy.dir);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { forEach, isEmpty } from './obj';\n\ntype Entry<K, V> = [K, V];\n\n/**\n * A map implementation that uses objects as keys. Objects must have an\n * associated equals function and must be immutable. Entries in the map are\n * stored together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */\nexport class ObjectMap<KeyType, ValueType> {\n /**\n * The inner map for a key/value pair. Due to the possibility of collisions we\n * keep a list of entries that we do a linear search through to find an actual\n * match. Note that collisions should be rare, so we still expect near\n * constant time lookups in practice.\n */\n private inner: {\n [canonicalId: string]: Array<Entry<KeyType, ValueType>>;\n } = {};\n\n /** The number of entries stored in the map */\n private innerSize = 0;\n\n constructor(\n private mapKeyFn: (key: KeyType) => string,\n private equalsFn: (l: KeyType, r: KeyType) => boolean\n ) {}\n\n /** Get a value for this key, or undefined if it does not exist. */\n get(key: KeyType): ValueType | undefined {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n return undefined;\n }\n for (const [otherKey, value] of matches) {\n if (this.equalsFn(otherKey, key)) {\n return value;\n }\n }\n return undefined;\n }\n\n has(key: KeyType): boolean {\n return this.get(key) !== undefined;\n }\n\n /** Put this key and value in the map. */\n set(key: KeyType, value: ValueType): void {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n this.inner[id] = [[key, value]];\n this.innerSize++;\n return;\n }\n for (let i = 0; i < matches.length; i++) {\n if (this.equalsFn(matches[i][0], key)) {\n // This is updating an existing entry and does not increase `innerSize`.\n matches[i] = [key, value];\n return;\n }\n }\n matches.push([key, value]);\n this.innerSize++;\n }\n\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */\n delete(key: KeyType): boolean {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n return false;\n }\n for (let i = 0; i < matches.length; i++) {\n if (this.equalsFn(matches[i][0], key)) {\n if (matches.length === 1) {\n delete this.inner[id];\n } else {\n matches.splice(i, 1);\n }\n this.innerSize--;\n return true;\n }\n }\n return false;\n }\n\n forEach(fn: (key: KeyType, val: ValueType) => void): void {\n forEach(this.inner, (_, entries) => {\n for (const [k, v] of entries) {\n fn(k, v);\n }\n });\n }\n\n isEmpty(): boolean {\n return isEmpty(this.inner);\n }\n\n size(): number {\n return this.innerSize;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { OverlayedDocument } from '../local/overlayed_document';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { Mutation } from './mutation';\nimport { Overlay } from './overlay';\n\n/** Miscellaneous collection types / constants. */\n\nexport type MutableDocumentMap = SortedMap<DocumentKey, MutableDocument>;\nconst EMPTY_MUTABLE_DOCUMENT_MAP = new SortedMap<DocumentKey, MutableDocument>(\n DocumentKey.comparator\n);\nexport function mutableDocumentMap(): MutableDocumentMap {\n return EMPTY_MUTABLE_DOCUMENT_MAP;\n}\n\nexport interface DocumentSizeEntries {\n documents: MutableDocumentMap;\n sizeMap: SortedMap<DocumentKey, number>;\n}\n\nexport type DocumentMap = SortedMap<DocumentKey, Document>;\nconst EMPTY_DOCUMENT_MAP = new SortedMap<DocumentKey, Document>(\n DocumentKey.comparator\n);\nexport function documentMap(...docs: Document[]): DocumentMap {\n let map = EMPTY_DOCUMENT_MAP;\n for (const doc of docs) {\n map = map.insert(doc.key, doc);\n }\n return map;\n}\n\nexport type OverlayedDocumentMap = DocumentKeyMap<OverlayedDocument>;\nexport function newOverlayedDocumentMap(): OverlayedDocumentMap {\n return newDocumentKeyMap<OverlayedDocument>();\n}\n\nexport function convertOverlayedDocumentMapToDocumentMap(\n collection: OverlayedDocumentMap\n): DocumentMap {\n let documents = EMPTY_DOCUMENT_MAP;\n collection.forEach(\n (k, v) => (documents = documents.insert(k, v.overlayedDocument))\n );\n return documents;\n}\n\nexport type OverlayMap = DocumentKeyMap<Overlay>;\nexport function newOverlayMap(): OverlayMap {\n return newDocumentKeyMap<Overlay>();\n}\n\nexport type MutationMap = DocumentKeyMap<Mutation>;\nexport function newMutationMap(): MutationMap {\n return newDocumentKeyMap<Mutation>();\n}\n\nexport type DocumentKeyMap<T> = ObjectMap<DocumentKey, T>;\nexport function newDocumentKeyMap<T>(): DocumentKeyMap<T> {\n return new ObjectMap<DocumentKey, T>(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\n}\n\nexport type DocumentVersionMap = SortedMap<DocumentKey, SnapshotVersion>;\nconst EMPTY_DOCUMENT_VERSION_MAP = new SortedMap<DocumentKey, SnapshotVersion>(\n DocumentKey.comparator\n);\nexport function documentVersionMap(): DocumentVersionMap {\n return EMPTY_DOCUMENT_VERSION_MAP;\n}\n\nexport type DocumentKeySet = SortedSet<DocumentKey>;\nconst EMPTY_DOCUMENT_KEY_SET = new SortedSet(DocumentKey.comparator);\nexport function documentKeySet(...keys: DocumentKey[]): DocumentKeySet {\n let set = EMPTY_DOCUMENT_KEY_SET;\n for (const key of keys) {\n set = set.add(key);\n }\n return set;\n}\n\nexport type TargetIdSet = SortedSet<TargetId>;\nconst EMPTY_TARGET_ID_SET = new SortedSet<TargetId>(primitiveComparator);\nexport function targetIdSet(): SortedSet<TargetId> {\n return EMPTY_TARGET_ID_SET;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { isNegativeZero, isSafeInteger } from '../util/types';\n\n/** Base interface for the Serializer implementation. */\nexport interface Serializer {\n readonly useProto3Json: boolean;\n}\n\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */\nexport function toDouble(serializer: Serializer, value: number): ProtoValue {\n if (serializer.useProto3Json) {\n if (isNaN(value)) {\n return { doubleValue: 'NaN' };\n } else if (value === Infinity) {\n return { doubleValue: 'Infinity' };\n } else if (value === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: isNegativeZero(value) ? '-0' : value };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */\nexport function toInteger(value: number): ProtoValue {\n return { integerValue: '' + value };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */\nexport function toNumber(serializer: Serializer, value: number): ProtoValue {\n return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Serializer, toDouble, toInteger } from '../remote/number_serializer';\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport { normalizeNumber } from './normalize';\nimport { serverTimestamp } from './server_timestamps';\nimport { isArray, isInteger, isNumber, valueEquals } from './values';\n\n/** Used to represent a field transform on a mutation. */\nexport class TransformOperation {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n private _ = undefined;\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */\nexport function applyTransformOperationToLocalView(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n localWriteTime: Timestamp\n): ProtoValue {\n if (transform instanceof ServerTimestampTransform) {\n return serverTimestamp(localWriteTime, previousValue);\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n } else {\n debugAssert(\n transform instanceof NumericIncrementTransformOperation,\n 'Expected NumericIncrementTransformOperation but was: ' + transform\n );\n return applyNumericIncrementTransformOperationToLocalView(\n transform,\n previousValue\n );\n }\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */\nexport function applyTransformOperationToRemoteDocument(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n transformResult: ProtoValue | null\n): ProtoValue {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n }\n\n debugAssert(\n transformResult !== null,\n \"Didn't receive transformResult for non-array transform\"\n );\n return transformResult;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */\nexport function computeTransformOperationBaseValue(\n transform: TransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue | null {\n if (transform instanceof NumericIncrementTransformOperation) {\n return isNumber(previousValue) ? previousValue! : { integerValue: 0 };\n }\n return null;\n}\n\nexport function transformOperationEquals(\n left: TransformOperation,\n right: TransformOperation\n): boolean {\n if (\n left instanceof ArrayUnionTransformOperation &&\n right instanceof ArrayUnionTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof ArrayRemoveTransformOperation &&\n right instanceof ArrayRemoveTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof NumericIncrementTransformOperation &&\n right instanceof NumericIncrementTransformOperation\n ) {\n return valueEquals(left.operand, right.operand);\n }\n\n return (\n left instanceof ServerTimestampTransform &&\n right instanceof ServerTimestampTransform\n );\n}\n\n/** Transforms a value into a server-generated timestamp. */\nexport class ServerTimestampTransform extends TransformOperation {}\n\n/** Transforms an array value via a union operation. */\nexport class ArrayUnionTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayUnionTransformOperation(\n transform: ArrayUnionTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n const values = coercedFieldValuesArray(previousValue);\n for (const toUnion of transform.elements) {\n if (!values.some(element => valueEquals(element, toUnion))) {\n values.push(toUnion);\n }\n }\n return { arrayValue: { values } };\n}\n\n/** Transforms an array value via a remove operation. */\nexport class ArrayRemoveTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayRemoveTransformOperation(\n transform: ArrayRemoveTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n let values = coercedFieldValuesArray(previousValue);\n for (const toRemove of transform.elements) {\n values = values.filter(element => !valueEquals(element, toRemove));\n }\n return { arrayValue: { values } };\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */\nexport class NumericIncrementTransformOperation extends TransformOperation {\n constructor(readonly serializer: Serializer, readonly operand: ProtoValue) {\n super();\n debugAssert(\n isNumber(operand),\n 'NumericIncrementTransform transform requires a NumberValue'\n );\n }\n}\n\nexport function applyNumericIncrementTransformOperationToLocalView(\n transform: NumericIncrementTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n const baseValue = computeTransformOperationBaseValue(\n transform,\n previousValue\n )!;\n const sum = asNumber(baseValue) + asNumber(transform.operand);\n if (isInteger(baseValue) && isInteger(transform.operand)) {\n return toInteger(sum);\n } else {\n return toDouble(transform.serializer, sum);\n }\n}\n\nfunction asNumber(value: ProtoValue): number {\n return normalizeNumber(value.integerValue || value.doubleValue);\n}\n\nfunction coercedFieldValuesArray(value: ProtoValue | null): ProtoValue[] {\n return isArray(value) && value.arrayValue.values\n ? value.arrayValue.values.slice()\n : [];\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldMask } from './field_mask';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport {\n applyTransformOperationToLocalView,\n applyTransformOperationToRemoteDocument,\n computeTransformOperationBaseValue,\n TransformOperation,\n transformOperationEquals\n} from './transform_operation';\n\n/** A field path and the TransformOperation to perform upon it. */\nexport class FieldTransform {\n constructor(\n readonly field: FieldPath,\n readonly transform: TransformOperation\n ) {}\n}\n\nexport function fieldTransformEquals(\n left: FieldTransform,\n right: FieldTransform\n): boolean {\n return (\n left.field.isEqual(right.field) &&\n transformOperationEquals(left.transform, right.transform)\n );\n}\n\nexport function fieldTransformsAreEqual(\n left?: FieldTransform[],\n right?: FieldTransform[]\n): boolean {\n if (left === undefined && right === undefined) {\n return true;\n }\n\n if (left && right) {\n return arrayEquals(left, right, (l, r) => fieldTransformEquals(l, r));\n }\n\n return false;\n}\n\n/** The result of successfully applying a mutation to the backend. */\nexport class MutationResult {\n constructor(\n /**\n * The version at which the mutation was committed:\n *\n * - For most operations, this is the updateTime in the WriteResult.\n * - For deletes, the commitTime of the WriteResponse (because deletes are\n * not stored and have no updateTime).\n *\n * Note that these versions can be different: No-op writes will not change\n * the updateTime even though the commitTime advances.\n */\n readonly version: SnapshotVersion,\n /**\n * The resulting fields returned from the backend after a mutation\n * containing field transforms has been committed. Contains one FieldValue\n * for each FieldTransform that was in the mutation.\n *\n * Will be empty if the mutation did not contain any field transforms.\n */\n readonly transformResults: Array<ProtoValue | null>\n ) {}\n}\n\nexport const enum MutationType {\n Set,\n Patch,\n Delete,\n Verify\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */\nexport class Precondition {\n private constructor(\n readonly updateTime?: SnapshotVersion,\n readonly exists?: boolean\n ) {\n debugAssert(\n updateTime === undefined || exists === undefined,\n 'Precondition can specify \"exists\" or \"updateTime\" but not both'\n );\n }\n\n /** Creates a new empty Precondition. */\n static none(): Precondition {\n return new Precondition();\n }\n\n /** Creates a new Precondition with an exists flag. */\n static exists(exists: boolean): Precondition {\n return new Precondition(undefined, exists);\n }\n\n /** Creates a new Precondition based on a version a document exists at. */\n static updateTime(version: SnapshotVersion): Precondition {\n return new Precondition(version);\n }\n\n /** Returns whether this Precondition is empty. */\n get isNone(): boolean {\n return this.updateTime === undefined && this.exists === undefined;\n }\n\n isEqual(other: Precondition): boolean {\n return (\n this.exists === other.exists &&\n (this.updateTime\n ? !!other.updateTime && this.updateTime.isEqual(other.updateTime)\n : !other.updateTime)\n );\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */\nexport function preconditionIsValidForDocument(\n precondition: Precondition,\n document: MutableDocument\n): boolean {\n if (precondition.updateTime !== undefined) {\n return (\n document.isFoundDocument() &&\n document.version.isEqual(precondition.updateTime)\n );\n } else if (precondition.exists !== undefined) {\n return precondition.exists === document.isFoundDocument();\n } else {\n debugAssert(precondition.isNone, 'Precondition should be empty');\n return true;\n }\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation InvalidDocument(v0) Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation InvalidDocument(v0) UnknownDocument(v3)\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation InvalidDocument(v0) NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */\nexport abstract class Mutation {\n abstract readonly type: MutationType;\n abstract readonly key: DocumentKey;\n abstract readonly precondition: Precondition;\n abstract readonly fieldTransforms: FieldTransform[];\n /**\n * Returns a `FieldMask` representing the fields that will be changed by\n * applying this mutation. Returns `null` if the mutation will overwrite the\n * entire document.\n */\n abstract getFieldMask(): FieldMask | null;\n}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */\nexport function calculateOverlayMutation(\n doc: MutableDocument,\n mask: FieldMask | null\n): Mutation | null {\n if (!doc.hasLocalMutations || (mask && mask!.fields.length === 0)) {\n return null;\n }\n\n // mask is null when sets or deletes are applied to the current document.\n if (mask === null) {\n if (doc.isNoDocument()) {\n return new DeleteMutation(doc.key, Precondition.none());\n } else {\n return new SetMutation(doc.key, doc.data, Precondition.none());\n }\n } else {\n const docValue = doc.data;\n const patchValue = ObjectValue.empty();\n let maskSet = new SortedSet<FieldPath>(FieldPath.comparator);\n for (let path of mask.fields) {\n if (!maskSet.has(path)) {\n let value = docValue.field(path);\n // If we are deleting a nested field, we take the immediate parent as\n // the mask used to construct the resulting mutation.\n // Justification: Nested fields can create parent fields implicitly. If\n // only a leaf entry is deleted in later mutations, the parent field\n // should still remain, but we may have lost this information.\n // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n // This leaves the final result (foo, {}). Despite the fact that `doc`\n // has the correct result, `foo` is not in `mask`, and the resulting\n // mutation would miss `foo`.\n if (value === null && path.length > 1) {\n path = path.popLast();\n value = docValue.field(path);\n }\n if (value === null) {\n patchValue.delete(path);\n } else {\n patchValue.set(path, value);\n }\n maskSet = maskSet.add(path);\n }\n }\n return new PatchMutation(\n doc.key,\n patchValue,\n new FieldMask(maskSet.toArray()),\n Precondition.none()\n );\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */\nexport function mutationApplyToRemoteDocument(\n mutation: Mutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n mutationVerifyKeyMatches(mutation, document);\n if (mutation instanceof SetMutation) {\n setMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else if (mutation instanceof PatchMutation) {\n patchMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n deleteMutationApplyToRemoteDocument(mutation, document, mutationResult);\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */\nexport function mutationApplyToLocalView(\n mutation: Mutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n mutationVerifyKeyMatches(mutation, document);\n\n if (mutation instanceof SetMutation) {\n return setMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else if (mutation instanceof PatchMutation) {\n return patchMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n return deleteMutationApplyToLocalView(mutation, document, previousMask);\n }\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */\nexport function mutationExtractBaseValue(\n mutation: Mutation,\n document: Document\n): ObjectValue | null {\n let baseObject: ObjectValue | null = null;\n for (const fieldTransform of mutation.fieldTransforms) {\n const existingValue = document.data.field(fieldTransform.field);\n const coercedValue = computeTransformOperationBaseValue(\n fieldTransform.transform,\n existingValue || null\n );\n\n if (coercedValue != null) {\n if (baseObject === null) {\n baseObject = ObjectValue.empty();\n }\n baseObject.set(fieldTransform.field, coercedValue);\n }\n }\n return baseObject ? baseObject : null;\n}\n\nexport function mutationEquals(left: Mutation, right: Mutation): boolean {\n if (left.type !== right.type) {\n return false;\n }\n\n if (!left.key.isEqual(right.key)) {\n return false;\n }\n\n if (!left.precondition.isEqual(right.precondition)) {\n return false;\n }\n\n if (!fieldTransformsAreEqual(left.fieldTransforms, right.fieldTransforms)) {\n return false;\n }\n\n if (left.type === MutationType.Set) {\n return (left as SetMutation).value.isEqual((right as SetMutation).value);\n }\n\n if (left.type === MutationType.Patch) {\n return (\n (left as PatchMutation).data.isEqual((right as PatchMutation).data) &&\n (left as PatchMutation).fieldMask.isEqual(\n (right as PatchMutation).fieldMask\n )\n );\n }\n\n return true;\n}\n\nfunction mutationVerifyKeyMatches(\n mutation: Mutation,\n document: MutableDocument\n): void {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply a mutation to a document with the same key'\n );\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nexport class SetMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly value: ObjectValue,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Set;\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction setMutationApplyToRemoteDocument(\n mutation: SetMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n // remote document the server has accepted the mutation so the precondition\n // must have held.\n const newData = mutation.value.clone();\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction setMutationApplyToLocalView(\n mutation: SetMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return previousMask;\n }\n\n const newData = mutation.value.clone();\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n return null; // SetMutation overwrites all fields.\n}\n\n/**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */\nexport class PatchMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Patch;\n\n getFieldMask(): FieldMask | null {\n return this.fieldMask;\n }\n}\n\nfunction patchMutationApplyToRemoteDocument(\n mutation: PatchMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and convert to an UnknownDocument with a\n // known updateTime.\n document.convertToUnknownDocument(mutationResult.version);\n return;\n }\n\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction patchMutationApplyToLocalView(\n mutation: PatchMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n return previousMask;\n }\n\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n\n if (previousMask === null) {\n return null;\n }\n\n return previousMask\n .unionWith(mutation.fieldMask.fields)\n .unionWith(mutation.fieldTransforms.map(transform => transform.field));\n}\n\n/**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */\nfunction getPatch(mutation: PatchMutation): Map<FieldPath, ProtoValue | null> {\n const result = new Map<FieldPath, ProtoValue | null>();\n mutation.fieldMask.fields.forEach(fieldPath => {\n if (!fieldPath.isEmpty()) {\n const newValue = mutation.data.field(fieldPath);\n result.set(fieldPath, newValue);\n }\n });\n return result;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */\nfunction serverTransformResults(\n fieldTransforms: FieldTransform[],\n mutableDocument: MutableDocument,\n serverTransformResults: Array<ProtoValue | null>\n): Map<FieldPath, ProtoValue> {\n const transformResults = new Map<FieldPath, ProtoValue>();\n hardAssert(\n fieldTransforms.length === serverTransformResults.length,\n `server transform result count (${serverTransformResults.length}) ` +\n `should match field transform count (${fieldTransforms.length})`\n );\n\n for (let i = 0; i < serverTransformResults.length; i++) {\n const fieldTransform = fieldTransforms[i];\n const transform = fieldTransform.transform;\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToRemoteDocument(\n transform,\n previousValue,\n serverTransformResults[i]\n )\n );\n }\n return transformResults;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n * generate ServerTimestampValues).\n * @param mutableDocument - The document to apply transforms on.\n * @returns The transform results list.\n */\nfunction localTransformResults(\n fieldTransforms: FieldTransform[],\n localWriteTime: Timestamp,\n mutableDocument: MutableDocument\n): Map<FieldPath, ProtoValue> {\n const transformResults = new Map<FieldPath, ProtoValue>();\n for (const fieldTransform of fieldTransforms) {\n const transform = fieldTransform.transform;\n\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToLocalView(\n transform,\n previousValue,\n localWriteTime\n )\n );\n }\n return transformResults;\n}\n\n/** A mutation that deletes the document at the given key. */\nexport class DeleteMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Delete;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction deleteMutationApplyToRemoteDocument(\n mutation: DeleteMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n debugAssert(\n mutationResult.transformResults.length === 0,\n 'Transform results received by DeleteMutation.'\n );\n\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n document\n .convertToNoDocument(mutationResult.version)\n .setHasCommittedMutations();\n}\n\nfunction deleteMutationApplyToLocalView(\n mutation: DeleteMutation,\n document: MutableDocument,\n previousMask: FieldMask | null\n): FieldMask | null {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply mutation to document with same key'\n );\n if (preconditionIsValidForDocument(mutation.precondition, document)) {\n document.convertToNoDocument(document.version).setHasLocalMutations();\n return null;\n }\n return previousMask;\n}\n\n/**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */\nexport class VerifyMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Verify;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport {\n documentKeySet,\n DocumentKeySet,\n MutationMap,\n DocumentVersionMap,\n documentVersionMap,\n newMutationMap,\n OverlayedDocumentMap\n} from './collections';\nimport { MutableDocument } from './document';\nimport { FieldMask } from './field_mask';\nimport {\n calculateOverlayMutation,\n Mutation,\n mutationApplyToLocalView,\n mutationApplyToRemoteDocument,\n mutationEquals,\n MutationResult\n} from './mutation';\n\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */\nexport class MutationBatch {\n /**\n * @param batchId - The unique ID of this mutation batch.\n * @param localWriteTime - The original write time of this mutation.\n * @param baseMutations - Mutations that are used to populate the base\n * values when this mutation is applied locally. This can be used to locally\n * overwrite values that are persisted in the remote document cache. Base\n * mutations are never sent to the backend.\n * @param mutations - The user-provided mutations in this mutation batch.\n * User-provided mutations are applied both locally and remotely on the\n * backend.\n */\n constructor(\n public batchId: BatchId,\n public localWriteTime: Timestamp,\n public baseMutations: Mutation[],\n public mutations: Mutation[]\n ) {\n debugAssert(mutations.length > 0, 'Cannot create an empty mutation batch');\n }\n\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to compute the state of the remote document\n *\n * @param document - The document to apply mutations to.\n * @param batchResult - The result of applying the MutationBatch to the\n * backend.\n */\n applyToRemoteDocument(\n document: MutableDocument,\n batchResult: MutationBatchResult\n ): void {\n const mutationResults = batchResult.mutationResults;\n debugAssert(\n mutationResults.length === this.mutations.length,\n `Mismatch between mutations length\n (${this.mutations.length}) and mutation results length\n (${mutationResults.length}).`\n );\n\n for (let i = 0; i < this.mutations.length; i++) {\n const mutation = this.mutations[i];\n if (mutation.key.isEqual(document.key)) {\n const mutationResult = mutationResults[i];\n mutationApplyToRemoteDocument(mutation, document, mutationResult);\n }\n }\n }\n\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param document - The document to apply mutations to.\n * @param mutatedFields - Fields that have been updated before applying this mutation batch.\n * @returns A `FieldMask` representing all the fields that are mutated.\n */\n applyToLocalView(\n document: MutableDocument,\n mutatedFields: FieldMask | null\n ): FieldMask | null {\n // First, apply the base state. This allows us to apply non-idempotent\n // transform against a consistent set of values.\n for (const mutation of this.baseMutations) {\n if (mutation.key.isEqual(document.key)) {\n mutatedFields = mutationApplyToLocalView(\n mutation,\n document,\n mutatedFields,\n this.localWriteTime\n );\n }\n }\n\n // Second, apply all user-provided mutations.\n for (const mutation of this.mutations) {\n if (mutation.key.isEqual(document.key)) {\n mutatedFields = mutationApplyToLocalView(\n mutation,\n document,\n mutatedFields,\n this.localWriteTime\n );\n }\n }\n return mutatedFields;\n }\n\n /**\n * Computes the local view for all provided documents given the mutations in\n * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to\n * replace all the mutation applications.\n */\n applyToLocalDocumentSet(\n documentMap: OverlayedDocumentMap,\n documentsWithoutRemoteVersion: DocumentKeySet\n ): MutationMap {\n // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations\n // directly (as done in `applyToLocalView()`), we can reduce the complexity\n // to O(n).\n const overlays = newMutationMap();\n this.mutations.forEach(m => {\n const overlayedDocument = documentMap.get(m.key)!;\n // TODO(mutabledocuments): This method should take a MutableDocumentMap\n // and we should remove this cast.\n const mutableDocument =\n overlayedDocument.overlayedDocument as MutableDocument;\n let mutatedFields = this.applyToLocalView(\n mutableDocument,\n overlayedDocument.mutatedFields\n );\n // Set mutatedFields to null if the document is only from local mutations.\n // This creates a Set or Delete mutation, instead of trying to create a\n // patch mutation as the overlay.\n mutatedFields = documentsWithoutRemoteVersion.has(m.key)\n ? null\n : mutatedFields;\n const overlay = calculateOverlayMutation(mutableDocument, mutatedFields);\n if (overlay !== null) {\n overlays.set(m.key, overlay);\n }\n\n if (!mutableDocument.isValidDocument()) {\n mutableDocument.convertToNoDocument(SnapshotVersion.min());\n }\n });\n return overlays;\n }\n\n keys(): DocumentKeySet {\n return this.mutations.reduce(\n (keys, m) => keys.add(m.key),\n documentKeySet()\n );\n }\n\n isEqual(other: MutationBatch): boolean {\n return (\n this.batchId === other.batchId &&\n arrayEquals(this.mutations, other.mutations, (l, r) =>\n mutationEquals(l, r)\n ) &&\n arrayEquals(this.baseMutations, other.baseMutations, (l, r) =>\n mutationEquals(l, r)\n )\n );\n }\n}\n\n/** The result of applying a mutation batch to the backend. */\nexport class MutationBatchResult {\n private constructor(\n readonly batch: MutationBatch,\n readonly commitVersion: SnapshotVersion,\n readonly mutationResults: MutationResult[],\n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n readonly docVersions: DocumentVersionMap\n ) {}\n\n /**\n * Creates a new MutationBatchResult for the given batch and results. There\n * must be one result for each mutation in the batch. This static factory\n * caches a document=>version mapping (docVersions).\n */\n static from(\n batch: MutationBatch,\n commitVersion: SnapshotVersion,\n results: MutationResult[]\n ): MutationBatchResult {\n hardAssert(\n batch.mutations.length === results.length,\n 'Mutations sent ' +\n batch.mutations.length +\n ' must equal results received ' +\n results.length\n );\n\n let versionMap = documentVersionMap();\n const mutations = batch.mutations;\n for (let i = 0; i < mutations.length; i++) {\n versionMap = versionMap.insert(mutations[i].key, results[i].version);\n }\n\n return new MutationBatchResult(batch, commitVersion, results, versionMap);\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from './document_key';\nimport { Mutation } from './mutation';\n\n/**\n * Representation of an overlay computed by Firestore.\n *\n * Holds information about a mutation and the largest batch id in Firestore when\n * the mutation was created.\n */\nexport class Overlay {\n constructor(readonly largestBatchId: number, readonly mutation: Mutation) {}\n\n getKey(): DocumentKey {\n return this.mutation.key;\n }\n\n isEqual(other: Overlay | null): boolean {\n return other !== null && this.mutation === other.mutation;\n }\n\n toString(): string {\n return `Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BloomFilter as ProtoBloomFilter } from '../protos/firestore_proto_api';\n\nexport class ExistenceFilter {\n constructor(public count: number, public unchangedNames?: ProtoBloomFilter) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\nimport { Code } from '../util/error';\nimport { logError } from '../util/log';\n\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */\nenum RpcCode {\n OK = 0,\n CANCELLED = 1,\n UNKNOWN = 2,\n INVALID_ARGUMENT = 3,\n DEADLINE_EXCEEDED = 4,\n NOT_FOUND = 5,\n ALREADY_EXISTS = 6,\n PERMISSION_DENIED = 7,\n UNAUTHENTICATED = 16,\n RESOURCE_EXHAUSTED = 8,\n FAILED_PRECONDITION = 9,\n ABORTED = 10,\n OUT_OF_RANGE = 11,\n UNIMPLEMENTED = 12,\n INTERNAL = 13,\n UNAVAILABLE = 14,\n DATA_LOSS = 15\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nexport function isPermanentError(code: Code): boolean {\n switch (code) {\n case Code.OK:\n return fail('Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependant on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\nexport function isPermanentWriteError(code: Code): boolean {\n return isPermanentError(code) && code !== Code.ABORTED;\n}\n\n/**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\nexport function mapCodeFromRpcStatus(status: string): Code | undefined {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const code: RpcCode = RpcCode[status as any] as any;\n if (code === undefined) {\n return undefined;\n }\n\n return mapCodeFromRpcCode(code);\n}\n\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nexport function mapCodeFromRpcCode(code: number | undefined): Code {\n if (code === undefined) {\n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n logError('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nexport function mapRpcCodeFromCode(code: Code | undefined): number {\n if (code === undefined) {\n return RpcCode.OK;\n }\n\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status - An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpStatus(status?: number): Code {\n if (status === undefined) {\n logError('RPC_ERROR', 'HTTP error has no status');\n return Code.UNKNOWN;\n }\n\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200: // OK\n return Code.OK;\n\n case 400: // Bad Request\n return Code.FAILED_PRECONDITION;\n // Other possibilities based on the forward mapping\n // return Code.INVALID_ARGUMENT;\n // return Code.OUT_OF_RANGE;\n\n case 401: // Unauthorized\n return Code.UNAUTHENTICATED;\n\n case 403: // Forbidden\n return Code.PERMISSION_DENIED;\n\n case 404: // Not Found\n return Code.NOT_FOUND;\n\n case 409: // Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n\n case 416: // Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n\n case 429: // Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n\n case 499: // Client Closed Request\n return Code.CANCELLED;\n\n case 500: // Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n\n case 501: // Unimplemented\n return Code.UNIMPLEMENTED;\n\n case 503: // Service Unavailable\n return Code.UNAVAILABLE;\n\n case 504: // Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n\n default:\n if (status >= 200 && status < 300) {\n return Code.OK;\n }\n if (status >= 400 && status < 500) {\n return Code.FAILED_PRECONDITION;\n }\n if (status >= 500 && status < 600) {\n return Code.INTERNAL;\n }\n return Code.UNKNOWN;\n }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpResponseErrorStatus(status: string): Code {\n const serverError = status.toLowerCase().replace(/_/g, '-');\n return Object.values(Code).indexOf(serverError as Code) >= 0\n ? (serverError as Code)\n : Code.UNKNOWN;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The global, singleton instance of TestingHooksSpi.\n *\n * This variable will be `null` in all cases _except_ when running from\n * integration tests that have registered callbacks to be notified of events\n * that happen during the test execution.\n */\nexport let testingHooksSpi: TestingHooksSpi | null = null;\n\n/**\n * Sets the value of the `testingHooksSpi` object.\n * @param instance the instance to set.\n */\nexport function setTestingHooksSpi(instance: TestingHooksSpi): void {\n if (testingHooksSpi) {\n throw new Error('a TestingHooksSpi instance is already set');\n }\n testingHooksSpi = instance;\n}\n\n/**\n * The \"service provider interface\" for the testing hooks.\n *\n * The implementation of this object will handle the callbacks made by the SDK\n * to be handled by the integration tests.\n *\n * This \"SPI\" is separated from the implementation to avoid import cycles and\n * to enable production builds to fully tree-shake away the testing hooks logic.\n */\nexport interface TestingHooksSpi {\n /**\n * Invokes all callbacks registered with\n * `TestingHooks.onExistenceFilterMismatch()` with the given info.\n */\n notifyOnExistenceFilterMismatch(info: ExistenceFilterMismatchInfo): void;\n}\n\n/**\n * Information about an existence filter mismatch.\n * @internal\n */\nexport interface ExistenceFilterMismatchInfo {\n /** The number of documents that matched the query in the local cache. */\n localCacheCount: number;\n\n /**\n * The number of documents that matched the query on the server, as specified\n * in the ExistenceFilter message's `count` field.\n */\n existenceFilterCount: number;\n\n /**\n * The projectId used when checking documents for membership in the bloom\n * filter.\n */\n projectId: string;\n\n /**\n * The databaseId used when checking documents for membership in the bloom\n * filter.\n */\n databaseId: string;\n\n /**\n * Information about the bloom filter provided by Watch in the ExistenceFilter\n * message's `unchangedNames` field. If this property is omitted or undefined\n * then that means that Watch did _not_ provide a bloom filter.\n */\n bloomFilter?: {\n /**\n * Whether a full requery was averted by using the bloom filter. If false,\n * then something happened, such as a false positive, to prevent using the\n * bloom filter to avoid a full requery.\n */\n applied: boolean;\n\n /** The number of hash functions used in the bloom filter. */\n hashCount: number;\n\n /** The number of bytes in the bloom filter's bitmask. */\n bitmapLength: number;\n\n /** The number of bits of padding in the last byte of the bloom filter. */\n padding: number;\n\n /**\n * Tests the given string for membership in the bloom filter created from\n * the existence filter; will be undefined if creating the bloom filter\n * failed.\n */\n mightContain?: (value: string) => boolean;\n };\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An instance of the Platform's 'TextEncoder' implementation.\n */\nexport function newTextEncoder(): TextEncoder {\n return new TextEncoder();\n}\n\n/**\n * An instance of the Platform's 'TextDecoder' implementation.\n */\nexport function newTextDecoder(): TextDecoder {\n return new TextDecoder('utf-8');\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Md5, Integer } from '@firebase/webchannel-wrapper';\n\nimport { newTextEncoder } from '../platform/text_serializer';\n\nconst MAX_64_BIT_UNSIGNED_INTEGER = new Integer([0xffffffff, 0xffffffff], 0);\n\n// Hash a string using md5 hashing algorithm.\nfunction getMd5HashValue(value: string): Uint8Array {\n const encodedValue = newTextEncoder().encode(value);\n const md5 = new Md5();\n md5.update(encodedValue);\n return new Uint8Array(md5.digest());\n}\n\n// Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using\n// 2’s complement using little endian.\nfunction get64BitUints(Bytes: Uint8Array): [Integer, Integer] {\n const dataView = new DataView(Bytes.buffer);\n const chunk1 = dataView.getUint32(0, /* littleEndian= */ true);\n const chunk2 = dataView.getUint32(4, /* littleEndian= */ true);\n const chunk3 = dataView.getUint32(8, /* littleEndian= */ true);\n const chunk4 = dataView.getUint32(12, /* littleEndian= */ true);\n const integer1 = new Integer([chunk1, chunk2], 0);\n const integer2 = new Integer([chunk3, chunk4], 0);\n return [integer1, integer2];\n}\n\nexport class BloomFilter {\n readonly bitCount: number;\n private readonly bitCountInInteger: Integer;\n\n constructor(\n readonly bitmap: Uint8Array,\n readonly padding: number,\n readonly hashCount: number\n ) {\n if (padding < 0 || padding >= 8) {\n throw new BloomFilterError(`Invalid padding: ${padding}`);\n }\n\n if (hashCount < 0) {\n throw new BloomFilterError(`Invalid hash count: ${hashCount}`);\n }\n\n if (bitmap.length > 0 && this.hashCount === 0) {\n // Only empty bloom filter can have 0 hash count.\n throw new BloomFilterError(`Invalid hash count: ${hashCount}`);\n }\n\n if (bitmap.length === 0 && padding !== 0) {\n // Empty bloom filter should have 0 padding.\n throw new BloomFilterError(\n `Invalid padding when bitmap length is 0: ${padding}`\n );\n }\n\n this.bitCount = bitmap.length * 8 - padding;\n // Set the bit count in Integer to avoid repetition in mightContain().\n this.bitCountInInteger = Integer.fromNumber(this.bitCount);\n }\n\n // Calculate the ith hash value based on the hashed 64bit integers,\n // and calculate its corresponding bit index in the bitmap to be checked.\n private getBitIndex(num1: Integer, num2: Integer, hashIndex: number): number {\n // Calculate hashed value h(i) = h1 + (i * h2).\n let hashValue = num1.add(num2.multiply(Integer.fromNumber(hashIndex)));\n // Wrap if hash value overflow 64bit.\n if (hashValue.compare(MAX_64_BIT_UNSIGNED_INTEGER) === 1) {\n hashValue = new Integer([hashValue.getBits(0), hashValue.getBits(1)], 0);\n }\n return hashValue.modulo(this.bitCountInInteger).toNumber();\n }\n\n // Return whether the bit on the given index in the bitmap is set to 1.\n private isBitSet(index: number): boolean {\n // To retrieve bit n, calculate: (bitmap[n / 8] & (0x01 << (n % 8))).\n const byte = this.bitmap[Math.floor(index / 8)];\n const offset = index % 8;\n return (byte & (0x01 << offset)) !== 0;\n }\n\n mightContain(value: string): boolean {\n // Empty bitmap should always return false on membership check.\n if (this.bitCount === 0) {\n return false;\n }\n const md5HashedValue = getMd5HashValue(value);\n const [hash1, hash2] = get64BitUints(md5HashedValue);\n for (let i = 0; i < this.hashCount; i++) {\n const index = this.getBitIndex(hash1, hash2, i);\n if (!this.isBitSet(index)) {\n return false;\n }\n }\n return true;\n }\n\n /** Create bloom filter for testing purposes only. */\n static create(\n bitCount: number,\n hashCount: number,\n contains: string[]\n ): BloomFilter {\n const padding = bitCount % 8 === 0 ? 0 : 8 - (bitCount % 8);\n const bitmap = new Uint8Array(Math.ceil(bitCount / 8));\n const bloomFilter = new BloomFilter(bitmap, padding, hashCount);\n contains.forEach(item => bloomFilter.insert(item));\n return bloomFilter;\n }\n\n private insert(value: string): void {\n if (this.bitCount === 0) {\n return;\n }\n\n const md5HashedValue = getMd5HashValue(value);\n const [hash1, hash2] = get64BitUints(md5HashedValue);\n for (let i = 0; i < this.hashCount; i++) {\n const index = this.getBitIndex(hash1, hash2, i);\n this.setBit(index);\n }\n }\n\n private setBit(index: number): void {\n const indexOfByte = Math.floor(index / 8);\n const offset = index % 8;\n this.bitmap[indexOfByte] |= 0x01 << offset;\n }\n}\n\nexport class BloomFilterError extends Error {\n readonly name = 'BloomFilterError';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { TargetPurpose } from '../local/target_data';\nimport {\n documentKeySet,\n DocumentKeySet,\n mutableDocumentMap,\n MutableDocumentMap\n} from '../model/collections';\nimport { ByteString } from '../util/byte_string';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\n\n/**\n * An event from the RemoteStore. It is split into targetChanges (changes to the\n * state or the set of documents in our watched targets) and documentUpdates\n * (changes to the actual documents).\n */\nexport class RemoteEvent {\n constructor(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n readonly snapshotVersion: SnapshotVersion,\n /**\n * A map from target to changes to the target. See TargetChange.\n */\n readonly targetChanges: Map<TargetId, TargetChange>,\n /**\n * A map of targets that is known to be inconsistent, and the purpose for\n * re-listening. Listens for these targets should be re-established without\n * resume tokens.\n */\n readonly targetMismatches: SortedMap<TargetId, TargetPurpose>,\n /**\n * A set of which documents have changed or been deleted, along with the\n * doc's new values (if not deleted).\n */\n readonly documentUpdates: MutableDocumentMap,\n /**\n * A set of which document updates are due only to limbo resolution targets.\n */\n readonly resolvedLimboDocuments: DocumentKeySet\n ) {}\n\n /**\n * HACK: Views require RemoteEvents in order to determine whether the view is\n * CURRENT, but secondary tabs don't receive remote events. So this method is\n * used to create a synthesized RemoteEvent that can be used to apply a\n * CURRENT status change to a View, for queries executed in a different tab.\n */\n // PORTING NOTE: Multi-tab only\n static createSynthesizedRemoteEventForCurrentChange(\n targetId: TargetId,\n current: boolean,\n resumeToken: ByteString\n ): RemoteEvent {\n const targetChanges = new Map<TargetId, TargetChange>();\n targetChanges.set(\n targetId,\n TargetChange.createSynthesizedTargetChangeForCurrentChange(\n targetId,\n current,\n resumeToken\n )\n );\n return new RemoteEvent(\n SnapshotVersion.min(),\n targetChanges,\n new SortedMap<TargetId, TargetPurpose>(primitiveComparator),\n mutableDocumentMap(),\n documentKeySet()\n );\n }\n}\n\n/**\n * A TargetChange specifies the set of changes for a specific target as part of\n * a RemoteEvent. These changes track which documents are added, modified or\n * removed, as well as the target's resume token and whether the target is\n * marked CURRENT.\n * The actual changes *to* documents are not part of the TargetChange since\n * documents may be part of multiple targets.\n */\nexport class TargetChange {\n constructor(\n /**\n * An opaque, server-assigned token that allows watching a query to be resumed\n * after disconnecting without retransmitting all the data that matches the\n * query. The resume token essentially identifies a point in time from which\n * the server should resume sending results.\n */\n readonly resumeToken: ByteString,\n /**\n * The \"current\" (synced) status of this target. Note that \"current\"\n * has special meaning in the RPC protocol that implies that a target is\n * both up-to-date and consistent with the rest of the watch stream.\n */\n readonly current: boolean,\n /**\n * The set of documents that were newly assigned to this target as part of\n * this remote event.\n */\n readonly addedDocuments: DocumentKeySet,\n /**\n * The set of documents that were already assigned to this target but received\n * an update during this remote event.\n */\n readonly modifiedDocuments: DocumentKeySet,\n /**\n * The set of documents that were removed from this target as part of this\n * remote event.\n */\n readonly removedDocuments: DocumentKeySet\n ) {}\n\n /**\n * This method is used to create a synthesized TargetChanges that can be used to\n * apply a CURRENT status change to a View (for queries executed in a different\n * tab) or for new queries (to raise snapshots with correct CURRENT status).\n */\n static createSynthesizedTargetChangeForCurrentChange(\n targetId: TargetId,\n current: boolean,\n resumeToken: ByteString\n ): TargetChange {\n return new TargetChange(\n resumeToken,\n current,\n documentKeySet(),\n documentKeySet(),\n documentKeySet()\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseId } from '../core/database_info';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { ChangeType } from '../core/view_snapshot';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport {\n documentKeySet,\n DocumentKeySet,\n mutableDocumentMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { normalizeByteString } from '../model/normalize';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { Base64DecodeError } from '../util/base64_decode_error';\nimport { ByteString } from '../util/byte_string';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport {\n testingHooksSpi,\n ExistenceFilterMismatchInfo as TestingHooksExistenceFilterMismatchInfo\n} from '../util/testing_hooks_spi';\n\nimport { BloomFilter, BloomFilterError } from './bloom_filter';\nimport { ExistenceFilter } from './existence_filter';\nimport { RemoteEvent, TargetChange } from './remote_event';\n\n/**\n * Internal representation of the watcher API protocol buffers.\n */\nexport type WatchChange =\n | DocumentWatchChange\n | WatchTargetChange\n | ExistenceFilterChange;\n\n/**\n * Represents a changed document and a list of target ids to which this change\n * applies.\n *\n * If document has been deleted NoDocument will be provided.\n */\nexport class DocumentWatchChange {\n constructor(\n /** The new document applies to all of these targets. */\n public updatedTargetIds: TargetId[],\n /** The new document is removed from all of these targets. */\n public removedTargetIds: TargetId[],\n /** The key of the document for this change. */\n public key: DocumentKey,\n /**\n * The new document or NoDocument if it was deleted. Is null if the\n * document went out of view without the server sending a new document.\n */\n public newDoc: MutableDocument | null\n ) {}\n}\n\nexport class ExistenceFilterChange {\n constructor(\n public targetId: TargetId,\n public existenceFilter: ExistenceFilter\n ) {}\n}\n\nexport const enum WatchTargetChangeState {\n NoChange,\n Added,\n Removed,\n Current,\n Reset\n}\n\nconst enum BloomFilterApplicationStatus {\n Success,\n Skipped,\n FalsePositive\n}\nexport class WatchTargetChange {\n constructor(\n /** What kind of change occurred to the watch target. */\n public state: WatchTargetChangeState,\n /** The target IDs that were added/removed/set. */\n public targetIds: TargetId[],\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n public resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING,\n /** An RPC error indicating why the watch failed. */\n public cause: FirestoreError | null = null\n ) {}\n}\n\n/** Tracks the internal state of a Watch target. */\nclass TargetState {\n /**\n * The number of pending responses (adds or removes) that we are waiting on.\n * We only consider targets active that have no pending responses.\n */\n private pendingResponses = 0;\n\n /**\n * Keeps track of the document changes since the last raised snapshot.\n *\n * These changes are continuously updated as we receive document updates and\n * always reflect the current set of changes against the last issued snapshot.\n */\n private documentChanges: SortedMap<DocumentKey, ChangeType> =\n snapshotChangesMap();\n\n /** See public getters for explanations of these fields. */\n private _resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING;\n private _current = false;\n\n /**\n * Whether this target state should be included in the next snapshot. We\n * initialize to true so that newly-added targets are included in the next\n * RemoteEvent.\n */\n private _hasPendingChanges = true;\n\n /**\n * Whether this target has been marked 'current'.\n *\n * 'Current' has special meaning in the RPC protocol: It implies that the\n * Watch backend has sent us all changes up to the point at which the target\n * was added and that the target is consistent with the rest of the watch\n * stream.\n */\n get current(): boolean {\n return this._current;\n }\n\n /** The last resume token sent to us for this target. */\n get resumeToken(): ByteString {\n return this._resumeToken;\n }\n\n /** Whether this target has pending target adds or target removes. */\n get isPending(): boolean {\n return this.pendingResponses !== 0;\n }\n\n /** Whether we have modified any state that should trigger a snapshot. */\n get hasPendingChanges(): boolean {\n return this._hasPendingChanges;\n }\n\n /**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. Empty resumeTokens are discarded.\n */\n updateResumeToken(resumeToken: ByteString): void {\n if (resumeToken.approximateByteSize() > 0) {\n this._hasPendingChanges = true;\n this._resumeToken = resumeToken;\n }\n }\n\n /**\n * Creates a target change from the current set of changes.\n *\n * To reset the document changes after raising this snapshot, call\n * `clearPendingChanges()`.\n */\n toTargetChange(): TargetChange {\n let addedDocuments = documentKeySet();\n let modifiedDocuments = documentKeySet();\n let removedDocuments = documentKeySet();\n\n this.documentChanges.forEach((key, changeType) => {\n switch (changeType) {\n case ChangeType.Added:\n addedDocuments = addedDocuments.add(key);\n break;\n case ChangeType.Modified:\n modifiedDocuments = modifiedDocuments.add(key);\n break;\n case ChangeType.Removed:\n removedDocuments = removedDocuments.add(key);\n break;\n default:\n fail('Encountered invalid change type: ' + changeType);\n }\n });\n\n return new TargetChange(\n this._resumeToken,\n this._current,\n addedDocuments,\n modifiedDocuments,\n removedDocuments\n );\n }\n\n /**\n * Resets the document changes and sets `hasPendingChanges` to false.\n */\n clearPendingChanges(): void {\n this._hasPendingChanges = false;\n this.documentChanges = snapshotChangesMap();\n }\n\n addDocumentChange(key: DocumentKey, changeType: ChangeType): void {\n this._hasPendingChanges = true;\n this.documentChanges = this.documentChanges.insert(key, changeType);\n }\n\n removeDocumentChange(key: DocumentKey): void {\n this._hasPendingChanges = true;\n this.documentChanges = this.documentChanges.remove(key);\n }\n\n recordPendingTargetRequest(): void {\n this.pendingResponses += 1;\n }\n\n recordTargetResponse(): void {\n this.pendingResponses -= 1;\n }\n\n markCurrent(): void {\n this._hasPendingChanges = true;\n this._current = true;\n }\n}\n\n/**\n * Interface implemented by RemoteStore to expose target metadata to the\n * WatchChangeAggregator.\n */\nexport interface TargetMetadataProvider {\n /**\n * Returns the set of remote document keys for the given target ID as of the\n * last raised snapshot.\n */\n getRemoteKeysForTarget(targetId: TargetId): DocumentKeySet;\n\n /**\n * Returns the TargetData for an active target ID or 'null' if this target\n * has become inactive\n */\n getTargetDataForTarget(targetId: TargetId): TargetData | null;\n\n /**\n * Returns the database ID of the Firestore instance.\n */\n getDatabaseId(): DatabaseId;\n}\n\nconst LOG_TAG = 'WatchChangeAggregator';\n\n/**\n * A helper class to accumulate watch changes into a RemoteEvent.\n */\nexport class WatchChangeAggregator {\n constructor(private metadataProvider: TargetMetadataProvider) {}\n\n /** The internal state of all tracked targets. */\n private targetStates = new Map<TargetId, TargetState>();\n\n /** Keeps track of the documents to update since the last raised snapshot. */\n private pendingDocumentUpdates = mutableDocumentMap();\n\n /** A mapping of document keys to their set of target IDs. */\n private pendingDocumentTargetMapping = documentTargetMap();\n\n /**\n * A map of targets with existence filter mismatches. These targets are\n * known to be inconsistent and their listens needs to be re-established by\n * RemoteStore.\n */\n private pendingTargetResets = new SortedMap<TargetId, TargetPurpose>(\n primitiveComparator\n );\n\n /**\n * Processes and adds the DocumentWatchChange to the current set of changes.\n */\n handleDocumentChange(docChange: DocumentWatchChange): void {\n for (const targetId of docChange.updatedTargetIds) {\n if (docChange.newDoc && docChange.newDoc.isFoundDocument()) {\n this.addDocumentToTarget(targetId, docChange.newDoc);\n } else {\n this.removeDocumentFromTarget(\n targetId,\n docChange.key,\n docChange.newDoc\n );\n }\n }\n\n for (const targetId of docChange.removedTargetIds) {\n this.removeDocumentFromTarget(targetId, docChange.key, docChange.newDoc);\n }\n }\n\n /** Processes and adds the WatchTargetChange to the current set of changes. */\n handleTargetChange(targetChange: WatchTargetChange): void {\n this.forEachTarget(targetChange, targetId => {\n const targetState = this.ensureTargetState(targetId);\n switch (targetChange.state) {\n case WatchTargetChangeState.NoChange:\n if (this.isActiveTarget(targetId)) {\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Added:\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n targetState.recordTargetResponse();\n if (!targetState.isPending) {\n // We have a freshly added target, so we need to reset any state\n // that we had previously. This can happen e.g. when remove and add\n // back a target for existence filter mismatches.\n targetState.clearPendingChanges();\n }\n targetState.updateResumeToken(targetChange.resumeToken);\n break;\n case WatchTargetChangeState.Removed:\n // We need to keep track of removed targets to we can post-filter and\n // remove any target changes.\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n targetState.recordTargetResponse();\n if (!targetState.isPending) {\n this.removeTarget(targetId);\n }\n debugAssert(\n !targetChange.cause,\n 'WatchChangeAggregator does not handle errored targets'\n );\n break;\n case WatchTargetChangeState.Current:\n if (this.isActiveTarget(targetId)) {\n targetState.markCurrent();\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Reset:\n if (this.isActiveTarget(targetId)) {\n // Reset the target and synthesizes removes for all existing\n // documents. The backend will re-add any documents that still\n // match the target before it sends the next global snapshot.\n this.resetTarget(targetId);\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n default:\n fail('Unknown target watch change state: ' + targetChange.state);\n }\n });\n }\n\n /**\n * Iterates over all targetIds that the watch change applies to: either the\n * targetIds explicitly listed in the change or the targetIds of all currently\n * active targets.\n */\n forEachTarget(\n targetChange: WatchTargetChange,\n fn: (targetId: TargetId) => void\n ): void {\n if (targetChange.targetIds.length > 0) {\n targetChange.targetIds.forEach(fn);\n } else {\n this.targetStates.forEach((_, targetId) => {\n if (this.isActiveTarget(targetId)) {\n fn(targetId);\n }\n });\n }\n }\n\n /**\n * Handles existence filters and synthesizes deletes for filter mismatches.\n * Targets that are invalidated by filter mismatches are added to\n * `pendingTargetResets`.\n */\n handleExistenceFilter(watchChange: ExistenceFilterChange): void {\n const targetId = watchChange.targetId;\n const expectedCount = watchChange.existenceFilter.count;\n\n const targetData = this.targetDataForActiveTarget(targetId);\n if (targetData) {\n const target = targetData.target;\n if (targetIsDocumentTarget(target)) {\n if (expectedCount === 0) {\n // The existence filter told us the document does not exist. We deduce\n // that this document does not exist and apply a deleted document to\n // our updates. Without applying this deleted document there might be\n // another query that will raise this document as part of a snapshot\n // until it is resolved, essentially exposing inconsistency between\n // queries.\n const key = new DocumentKey(target.path);\n this.removeDocumentFromTarget(\n targetId,\n key,\n MutableDocument.newNoDocument(key, SnapshotVersion.min())\n );\n } else {\n hardAssert(\n expectedCount === 1,\n 'Single document existence filter with count: ' + expectedCount\n );\n }\n } else {\n const currentSize = this.getCurrentDocumentCountForTarget(targetId);\n // Existence filter mismatch. Mark the documents as being in limbo, and\n // raise a snapshot with `isFromCache:true`.\n if (currentSize !== expectedCount) {\n // Apply bloom filter to identify and mark removed documents.\n const bloomFilter = this.parseBloomFilter(watchChange);\n const status = bloomFilter\n ? this.applyBloomFilter(bloomFilter, watchChange, currentSize)\n : BloomFilterApplicationStatus.Skipped;\n\n if (status !== BloomFilterApplicationStatus.Success) {\n // If bloom filter application fails, we reset the mapping and\n // trigger re-run of the query.\n this.resetTarget(targetId);\n\n const purpose: TargetPurpose =\n status === BloomFilterApplicationStatus.FalsePositive\n ? TargetPurpose.ExistenceFilterMismatchBloom\n : TargetPurpose.ExistenceFilterMismatch;\n this.pendingTargetResets = this.pendingTargetResets.insert(\n targetId,\n purpose\n );\n }\n testingHooksSpi?.notifyOnExistenceFilterMismatch(\n createExistenceFilterMismatchInfoForTestingHooks(\n currentSize,\n watchChange.existenceFilter,\n this.metadataProvider.getDatabaseId(),\n bloomFilter,\n status\n )\n );\n }\n }\n }\n }\n\n /**\n * Parse the bloom filter from the \"unchanged_names\" field of an existence\n * filter.\n */\n private parseBloomFilter(\n watchChange: ExistenceFilterChange\n ): BloomFilter | null {\n const unchangedNames = watchChange.existenceFilter.unchangedNames;\n if (!unchangedNames || !unchangedNames.bits) {\n return null;\n }\n\n const {\n bits: { bitmap = '', padding = 0 },\n hashCount = 0\n } = unchangedNames;\n\n let normalizedBitmap: Uint8Array;\n try {\n normalizedBitmap = normalizeByteString(bitmap).toUint8Array();\n } catch (err) {\n if (err instanceof Base64DecodeError) {\n logWarn(\n 'Decoding the base64 bloom filter in existence filter failed (' +\n err.message +\n '); ignoring the bloom filter and falling back to full re-query.'\n );\n return null;\n } else {\n throw err;\n }\n }\n\n let bloomFilter: BloomFilter;\n try {\n // BloomFilter throws error if the inputs are invalid.\n bloomFilter = new BloomFilter(normalizedBitmap, padding, hashCount);\n } catch (err) {\n if (err instanceof BloomFilterError) {\n logWarn('BloomFilter error: ', err);\n } else {\n logWarn('Applying bloom filter failed: ', err);\n }\n return null;\n }\n\n if (bloomFilter.bitCount === 0) {\n return null;\n }\n\n return bloomFilter;\n }\n\n /**\n * Apply bloom filter to remove the deleted documents, and return the\n * application status.\n */\n private applyBloomFilter(\n bloomFilter: BloomFilter,\n watchChange: ExistenceFilterChange,\n currentCount: number\n ): BloomFilterApplicationStatus {\n const expectedCount = watchChange.existenceFilter.count;\n\n const removedDocumentCount = this.filterRemovedDocuments(\n bloomFilter,\n watchChange.targetId\n );\n\n return expectedCount === currentCount - removedDocumentCount\n ? BloomFilterApplicationStatus.Success\n : BloomFilterApplicationStatus.FalsePositive;\n }\n\n /**\n * Filter out removed documents based on bloom filter membership result and\n * return number of documents removed.\n */\n private filterRemovedDocuments(\n bloomFilter: BloomFilter,\n targetId: number\n ): number {\n const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n let removalCount = 0;\n\n existingKeys.forEach(key => {\n const databaseId = this.metadataProvider.getDatabaseId();\n const documentPath =\n `projects/${databaseId.projectId}` +\n `/databases/${databaseId.database}` +\n `/documents/${key.path.canonicalString()}`;\n\n if (!bloomFilter.mightContain(documentPath)) {\n this.removeDocumentFromTarget(targetId, key, /*updatedDocument=*/ null);\n removalCount++;\n }\n });\n\n return removalCount;\n }\n\n /**\n * Converts the currently accumulated state into a remote event at the\n * provided snapshot version. Resets the accumulated changes before returning.\n */\n createRemoteEvent(snapshotVersion: SnapshotVersion): RemoteEvent {\n const targetChanges = new Map<TargetId, TargetChange>();\n\n this.targetStates.forEach((targetState, targetId) => {\n const targetData = this.targetDataForActiveTarget(targetId);\n if (targetData) {\n if (targetState.current && targetIsDocumentTarget(targetData.target)) {\n // Document queries for document that don't exist can produce an empty\n // result set. To update our local cache, we synthesize a document\n // delete if we have not previously received the document. This\n // resolves the limbo state of the document, removing it from\n // limboDocumentRefs.\n //\n // TODO(dimond): Ideally we would have an explicit lookup target\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n const key = new DocumentKey(targetData.target.path);\n if (\n this.pendingDocumentUpdates.get(key) === null &&\n !this.targetContainsDocument(targetId, key)\n ) {\n this.removeDocumentFromTarget(\n targetId,\n key,\n MutableDocument.newNoDocument(key, snapshotVersion)\n );\n }\n }\n\n if (targetState.hasPendingChanges) {\n targetChanges.set(targetId, targetState.toTargetChange());\n targetState.clearPendingChanges();\n }\n }\n });\n\n let resolvedLimboDocuments = documentKeySet();\n\n // We extract the set of limbo-only document updates as the GC logic\n // special-cases documents that do not appear in the target cache.\n //\n // TODO(gsoltis): Expand on this comment once GC is available in the JS\n // client.\n this.pendingDocumentTargetMapping.forEach((key, targets) => {\n let isOnlyLimboTarget = true;\n\n targets.forEachWhile(targetId => {\n const targetData = this.targetDataForActiveTarget(targetId);\n if (\n targetData &&\n targetData.purpose !== TargetPurpose.LimboResolution\n ) {\n isOnlyLimboTarget = false;\n return false;\n }\n\n return true;\n });\n\n if (isOnlyLimboTarget) {\n resolvedLimboDocuments = resolvedLimboDocuments.add(key);\n }\n });\n\n this.pendingDocumentUpdates.forEach((_, doc) =>\n doc.setReadTime(snapshotVersion)\n );\n\n const remoteEvent = new RemoteEvent(\n snapshotVersion,\n targetChanges,\n this.pendingTargetResets,\n this.pendingDocumentUpdates,\n resolvedLimboDocuments\n );\n\n this.pendingDocumentUpdates = mutableDocumentMap();\n this.pendingDocumentTargetMapping = documentTargetMap();\n this.pendingTargetResets = new SortedMap<TargetId, TargetPurpose>(\n primitiveComparator\n );\n\n return remoteEvent;\n }\n\n /**\n * Adds the provided document to the internal list of document updates and\n * its document key to the given target's mapping.\n */\n // Visible for testing.\n addDocumentToTarget(targetId: TargetId, document: MutableDocument): void {\n if (!this.isActiveTarget(targetId)) {\n return;\n }\n\n const changeType = this.targetContainsDocument(targetId, document.key)\n ? ChangeType.Modified\n : ChangeType.Added;\n\n const targetState = this.ensureTargetState(targetId);\n targetState.addDocumentChange(document.key, changeType);\n\n this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(\n document.key,\n document\n );\n\n this.pendingDocumentTargetMapping =\n this.pendingDocumentTargetMapping.insert(\n document.key,\n this.ensureDocumentTargetMapping(document.key).add(targetId)\n );\n }\n\n /**\n * Removes the provided document from the target mapping. If the\n * document no longer matches the target, but the document's state is still\n * known (e.g. we know that the document was deleted or we received the change\n * that caused the filter mismatch), the new document can be provided\n * to update the remote document cache.\n */\n // Visible for testing.\n removeDocumentFromTarget(\n targetId: TargetId,\n key: DocumentKey,\n updatedDocument: MutableDocument | null\n ): void {\n if (!this.isActiveTarget(targetId)) {\n return;\n }\n\n const targetState = this.ensureTargetState(targetId);\n if (this.targetContainsDocument(targetId, key)) {\n targetState.addDocumentChange(key, ChangeType.Removed);\n } else {\n // The document may have entered and left the target before we raised a\n // snapshot, so we can just ignore the change.\n targetState.removeDocumentChange(key);\n }\n\n this.pendingDocumentTargetMapping =\n this.pendingDocumentTargetMapping.insert(\n key,\n this.ensureDocumentTargetMapping(key).delete(targetId)\n );\n\n if (updatedDocument) {\n this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(\n key,\n updatedDocument\n );\n }\n }\n\n removeTarget(targetId: TargetId): void {\n this.targetStates.delete(targetId);\n }\n\n /**\n * Returns the current count of documents in the target. This includes both\n * the number of documents that the LocalStore considers to be part of the\n * target as well as any accumulated changes.\n */\n private getCurrentDocumentCountForTarget(targetId: TargetId): number {\n const targetState = this.ensureTargetState(targetId);\n const targetChange = targetState.toTargetChange();\n return (\n this.metadataProvider.getRemoteKeysForTarget(targetId).size +\n targetChange.addedDocuments.size -\n targetChange.removedDocuments.size\n );\n }\n\n /**\n * Increment the number of acks needed from watch before we can consider the\n * server to be 'in-sync' with the client's active targets.\n */\n recordPendingTargetRequest(targetId: TargetId): void {\n // For each request we get we need to record we need a response for it.\n const targetState = this.ensureTargetState(targetId);\n targetState.recordPendingTargetRequest();\n }\n\n private ensureTargetState(targetId: TargetId): TargetState {\n let result = this.targetStates.get(targetId);\n if (!result) {\n result = new TargetState();\n this.targetStates.set(targetId, result);\n }\n return result;\n }\n\n private ensureDocumentTargetMapping(key: DocumentKey): SortedSet<TargetId> {\n let targetMapping = this.pendingDocumentTargetMapping.get(key);\n\n if (!targetMapping) {\n targetMapping = new SortedSet<TargetId>(primitiveComparator);\n this.pendingDocumentTargetMapping =\n this.pendingDocumentTargetMapping.insert(key, targetMapping);\n }\n\n return targetMapping;\n }\n\n /**\n * Verifies that the user is still interested in this target (by calling\n * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs\n * from watch.\n */\n protected isActiveTarget(targetId: TargetId): boolean {\n const targetActive = this.targetDataForActiveTarget(targetId) !== null;\n if (!targetActive) {\n logDebug(LOG_TAG, 'Detected inactive target', targetId);\n }\n return targetActive;\n }\n\n /**\n * Returns the TargetData for an active target (i.e. a target that the user\n * is still interested in that has no outstanding target change requests).\n */\n protected targetDataForActiveTarget(targetId: TargetId): TargetData | null {\n const targetState = this.targetStates.get(targetId);\n return targetState && targetState.isPending\n ? null\n : this.metadataProvider.getTargetDataForTarget(targetId);\n }\n\n /**\n * Resets the state of a Watch target to its initial state (e.g. sets\n * 'current' to false, clears the resume token and removes its target mapping\n * from all documents).\n */\n private resetTarget(targetId: TargetId): void {\n debugAssert(\n !this.targetStates.get(targetId)!.isPending,\n 'Should only reset active targets'\n );\n this.targetStates.set(targetId, new TargetState());\n\n // Trigger removal for any documents currently mapped to this target.\n // These removals will be part of the initial snapshot if Watch does not\n // resend these documents.\n const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n existingKeys.forEach(key => {\n this.removeDocumentFromTarget(targetId, key, /*updatedDocument=*/ null);\n });\n }\n /**\n * Returns whether the LocalStore considers the document to be part of the\n * specified target.\n */\n private targetContainsDocument(\n targetId: TargetId,\n key: DocumentKey\n ): boolean {\n const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n return existingKeys.has(key);\n }\n}\n\nfunction documentTargetMap(): SortedMap<DocumentKey, SortedSet<TargetId>> {\n return new SortedMap<DocumentKey, SortedSet<TargetId>>(\n DocumentKey.comparator\n );\n}\n\nfunction snapshotChangesMap(): SortedMap<DocumentKey, ChangeType> {\n return new SortedMap<DocumentKey, ChangeType>(DocumentKey.comparator);\n}\n\nfunction createExistenceFilterMismatchInfoForTestingHooks(\n localCacheCount: number,\n existenceFilter: ExistenceFilter,\n databaseId: DatabaseId,\n bloomFilter: BloomFilter | null,\n bloomFilterStatus: BloomFilterApplicationStatus\n): TestingHooksExistenceFilterMismatchInfo {\n const result: TestingHooksExistenceFilterMismatchInfo = {\n localCacheCount,\n existenceFilterCount: existenceFilter.count,\n databaseId: databaseId.database,\n projectId: databaseId.projectId\n };\n\n const unchangedNames = existenceFilter.unchangedNames;\n if (unchangedNames) {\n result.bloomFilter = {\n applied: bloomFilterStatus === BloomFilterApplicationStatus.Success,\n hashCount: unchangedNames?.hashCount ?? 0,\n bitmapLength: unchangedNames?.bits?.bitmap?.length ?? 0,\n padding: unchangedNames?.bits?.padding ?? 0,\n mightContain: (value: string): boolean =>\n bloomFilter?.mightContain(value) ?? false\n };\n }\n\n return result;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Aggregate } from '../core/aggregate';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n compositeFilterIsFlatConjunction,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n LimitType,\n newQuery,\n newQueryForPath,\n Query,\n queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget, Target } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n DeleteMutation,\n FieldTransform,\n Mutation,\n MutationResult,\n PatchMutation,\n Precondition,\n SetMutation,\n VerifyMutation\n} from '../model/mutation';\nimport { normalizeTimestamp } from '../model/normalize';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform,\n TransformOperation\n} from '../model/transform_operation';\nimport { isNanValue, isNullValue } from '../model/values';\nimport {\n ApiClientObjectMap as ProtoApiClientObjectMap,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n CompositeFilterOp as ProtoCompositeFilterOp,\n Cursor as ProtoCursor,\n Document as ProtoDocument,\n DocumentMask as ProtoDocumentMask,\n DocumentsTarget as ProtoDocumentsTarget,\n FieldFilterOp as ProtoFieldFilterOp,\n FieldReference as ProtoFieldReference,\n FieldTransform as ProtoFieldTransform,\n Filter as ProtoFilter,\n ListenResponse as ProtoListenResponse,\n Order as ProtoOrder,\n OrderDirection as ProtoOrderDirection,\n Precondition as ProtoPrecondition,\n QueryTarget as ProtoQueryTarget,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n Aggregation as ProtoAggregation,\n Status as ProtoStatus,\n Target as ProtoTarget,\n TargetChangeTargetChangeType as ProtoTargetChangeTargetChangeType,\n Timestamp as ProtoTimestamp,\n Write as ProtoWrite,\n WriteResult as ProtoWriteResult\n} from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExistenceFilter } from './existence_filter';\nimport { Serializer } from './number_serializer';\nimport { mapCodeFromRpcCode } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n WatchChange,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst DIRECTIONS = (() => {\n const dirs: { [dir: string]: ProtoOrderDirection } = {};\n dirs[Direction.ASCENDING] = 'ASCENDING';\n dirs[Direction.DESCENDING] = 'DESCENDING';\n return dirs;\n})();\n\nconst OPERATORS = (() => {\n const ops: { [op: string]: ProtoFieldFilterOp } = {};\n ops[Operator.LESS_THAN] = 'LESS_THAN';\n ops[Operator.LESS_THAN_OR_EQUAL] = 'LESS_THAN_OR_EQUAL';\n ops[Operator.GREATER_THAN] = 'GREATER_THAN';\n ops[Operator.GREATER_THAN_OR_EQUAL] = 'GREATER_THAN_OR_EQUAL';\n ops[Operator.EQUAL] = 'EQUAL';\n ops[Operator.NOT_EQUAL] = 'NOT_EQUAL';\n ops[Operator.ARRAY_CONTAINS] = 'ARRAY_CONTAINS';\n ops[Operator.IN] = 'IN';\n ops[Operator.NOT_IN] = 'NOT_IN';\n ops[Operator.ARRAY_CONTAINS_ANY] = 'ARRAY_CONTAINS_ANY';\n return ops;\n})();\n\nconst COMPOSITE_OPERATORS = (() => {\n const ops: { [op: string]: ProtoCompositeFilterOp } = {};\n ops[CompositeOperator.AND] = 'AND';\n ops[CompositeOperator.OR] = 'OR';\n return ops;\n})();\n\nfunction assertPresent(value: unknown, description: string): asserts value {\n debugAssert(!isNullOrUndefined(value), description + ' is missing');\n}\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nexport class JsonProtoSerializer implements Serializer {\n constructor(\n readonly databaseId: DatabaseId,\n readonly useProto3Json: boolean\n ) {}\n}\n\nfunction fromRpcStatus(status: ProtoStatus): FirestoreError {\n const code =\n status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n}\n\n/**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: <number> } struct.\n */\nfunction toInt32Proto(\n serializer: JsonProtoSerializer,\n val: number | null\n): number | { value: number } | null {\n if (serializer.useProto3Json || isNullOrUndefined(val)) {\n return val;\n } else {\n return { value: val };\n }\n}\n\n/**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */\nfunction fromInt32Proto(\n val: number | { value: number } | undefined\n): number | null {\n let result;\n if (typeof val === 'object') {\n result = val.value;\n } else {\n result = val;\n }\n return isNullOrUndefined(result) ? null : result;\n}\n\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nexport function toTimestamp(\n serializer: JsonProtoSerializer,\n timestamp: Timestamp\n): ProtoTimestamp {\n if (serializer.useProto3Json) {\n // Serialize to ISO-8601 date format, but with full nano resolution.\n // Since JS Date has only millis, let's only use it for the seconds and\n // then manually add the fractions to the end.\n const jsDateStr = new Date(timestamp.seconds * 1000).toISOString();\n // Remove .xxx frac part and Z in the end.\n const strUntilSeconds = jsDateStr.replace(/\\.\\d*/, '').replace('Z', '');\n // Pad the fraction out to 9 digits (nanos).\n const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9);\n\n return `${strUntilSeconds}.${nanoStr}Z`;\n } else {\n return {\n seconds: '' + timestamp.seconds,\n nanos: timestamp.nanoseconds\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n}\n\nfunction fromTimestamp(date: ProtoTimestamp): Timestamp {\n const timestamp = normalizeTimestamp(date);\n return new Timestamp(timestamp.seconds, timestamp.nanos);\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nexport function toBytes(\n serializer: JsonProtoSerializer,\n bytes: ByteString\n): string | Uint8Array {\n if (serializer.useProto3Json) {\n return bytes.toBase64();\n } else {\n return bytes.toUint8Array();\n }\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */\nexport function fromBytes(\n serializer: JsonProtoSerializer,\n value: string | Uint8Array | undefined\n): ByteString {\n if (serializer.useProto3Json) {\n hardAssert(\n value === undefined || typeof value === 'string',\n 'value must be undefined or a string when using proto3 Json'\n );\n return ByteString.fromBase64String(value ? value : '');\n } else {\n hardAssert(\n value === undefined || value instanceof Uint8Array,\n 'value must be undefined or Uint8Array'\n );\n return ByteString.fromUint8Array(value ? value : new Uint8Array());\n }\n}\n\nexport function toVersion(\n serializer: JsonProtoSerializer,\n version: SnapshotVersion\n): ProtoTimestamp {\n return toTimestamp(serializer, version.toTimestamp());\n}\n\nexport function fromVersion(version: ProtoTimestamp): SnapshotVersion {\n hardAssert(!!version, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(fromTimestamp(version));\n}\n\nexport function toResourceName(\n databaseId: DatabaseId,\n path: ResourcePath\n): string {\n return fullyQualifiedPrefixPath(databaseId)\n .child('documents')\n .child(path)\n .canonicalString();\n}\n\nfunction fromResourceName(name: string): ResourcePath {\n const resource = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resource),\n 'Tried to deserialize invalid key ' + resource.toString()\n );\n return resource;\n}\n\nexport function toName(\n serializer: JsonProtoSerializer,\n key: DocumentKey\n): string {\n return toResourceName(serializer.databaseId, key.path);\n}\n\nexport function fromName(\n serializer: JsonProtoSerializer,\n name: string\n): DocumentKey {\n const resource = fromResourceName(name);\n\n if (resource.get(1) !== serializer.databaseId.projectId) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n serializer.databaseId.projectId\n );\n }\n\n if (resource.get(3) !== serializer.databaseId.database) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n serializer.databaseId.database\n );\n }\n return new DocumentKey(extractLocalPathFromResourceName(resource));\n}\n\nfunction toQueryPath(\n serializer: JsonProtoSerializer,\n path: ResourcePath\n): string {\n return toResourceName(serializer.databaseId, path);\n}\n\nfunction fromQueryPath(name: string): ResourcePath {\n const resourceName = fromResourceName(name);\n // In v1beta1 queries for collections at the root did not have a trailing\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n // ability to read the v1beta1 form for compatibility with queries persisted\n // in the local target cache.\n if (resourceName.length === 4) {\n return ResourcePath.emptyPath();\n }\n return extractLocalPathFromResourceName(resourceName);\n}\n\nexport function getEncodedDatabaseId(serializer: JsonProtoSerializer): string {\n const path = new ResourcePath([\n 'projects',\n serializer.databaseId.projectId,\n 'databases',\n serializer.databaseId.database\n ]);\n return path.canonicalString();\n}\n\nfunction fullyQualifiedPrefixPath(databaseId: DatabaseId): ResourcePath {\n return new ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n}\n\nfunction extractLocalPathFromResourceName(\n resourceName: ResourcePath\n): ResourcePath {\n hardAssert(\n resourceName.length > 4 && resourceName.get(4) === 'documents',\n 'tried to deserialize invalid key ' + resourceName.toString()\n );\n return resourceName.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */\nexport function toMutationDocument(\n serializer: JsonProtoSerializer,\n key: DocumentKey,\n fields: ObjectValue\n): ProtoDocument {\n return {\n name: toName(serializer, key),\n fields: fields.value.mapValue.fields\n };\n}\n\nexport function toDocument(\n serializer: JsonProtoSerializer,\n document: MutableDocument\n): ProtoDocument {\n debugAssert(\n !document.hasLocalMutations,\n \"Can't serialize documents with mutations.\"\n );\n return {\n name: toName(serializer, document.key),\n fields: document.data.value.mapValue.fields,\n updateTime: toTimestamp(serializer, document.version.toTimestamp()),\n createTime: toTimestamp(serializer, document.createTime.toTimestamp())\n };\n}\n\nexport function fromDocument(\n serializer: JsonProtoSerializer,\n document: ProtoDocument,\n hasCommittedMutations?: boolean\n): MutableDocument {\n const key = fromName(serializer, document.name!);\n const version = fromVersion(document.updateTime!);\n // If we read a document from persistence that is missing createTime, it's due\n // to older SDK versions not storing this information. In such cases, we'll\n // set the createTime to zero. This can be removed in the long term.\n const createTime = document.createTime\n ? fromVersion(document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: document.fields } });\n const result = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n if (hasCommittedMutations) {\n result.setHasCommittedMutations();\n }\n return hasCommittedMutations ? result.setHasCommittedMutations() : result;\n}\n\nfunction fromFound(\n serializer: JsonProtoSerializer,\n doc: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!doc.found,\n 'Tried to deserialize a found document from a missing document.'\n );\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n const key = fromName(serializer, doc.found.name);\n const version = fromVersion(doc.found.updateTime);\n const createTime = doc.found.createTime\n ? fromVersion(doc.found.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: doc.found.fields } });\n return MutableDocument.newFoundDocument(key, version, createTime, data);\n}\n\nfunction fromMissing(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!result.missing,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 'Tried to deserialize a missing document without a read time.'\n );\n const key = fromName(serializer, result.missing);\n const version = fromVersion(result.readTime);\n return MutableDocument.newNoDocument(key, version);\n}\n\nexport function fromBatchGetDocumentsResponse(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n if ('found' in result) {\n return fromFound(serializer, result);\n } else if ('missing' in result) {\n return fromMissing(serializer, result);\n }\n return fail('invalid batch get response: ' + JSON.stringify(result));\n}\n\nexport function fromWatchChange(\n serializer: JsonProtoSerializer,\n change: ProtoListenResponse\n): WatchChange {\n let watchChange: WatchChange;\n if ('targetChange' in change) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const state = fromWatchTargetChangeState(\n change.targetChange.targetChangeType || 'NO_CHANGE'\n );\n const targetIds: TargetId[] = change.targetChange.targetIds || [];\n\n const resumeToken = fromBytes(serializer, change.targetChange.resumeToken);\n const causeProto = change.targetChange!.cause;\n const cause = causeProto && fromRpcStatus(causeProto);\n watchChange = new WatchTargetChange(\n state,\n targetIds,\n resumeToken,\n cause || null\n );\n } else if ('documentChange' in change) {\n assertPresent(change.documentChange, 'documentChange');\n const entityChange = change.documentChange;\n assertPresent(entityChange.document, 'documentChange.name');\n assertPresent(entityChange.document.name, 'documentChange.document.name');\n assertPresent(\n entityChange.document.updateTime,\n 'documentChange.document.updateTime'\n );\n const key = fromName(serializer, entityChange.document.name);\n const version = fromVersion(entityChange.document.updateTime);\n const createTime = entityChange.document.createTime\n ? fromVersion(entityChange.document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({\n mapValue: { fields: entityChange.document.fields }\n });\n const doc = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n const updatedTargetIds = entityChange.targetIds || [];\n const removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(\n updatedTargetIds,\n removedTargetIds,\n doc.key,\n doc\n );\n } else if ('documentDelete' in change) {\n assertPresent(change.documentDelete, 'documentDelete');\n const docDelete = change.documentDelete;\n assertPresent(docDelete.document, 'documentDelete.document');\n const key = fromName(serializer, docDelete.document);\n const version = docDelete.readTime\n ? fromVersion(docDelete.readTime)\n : SnapshotVersion.min();\n const doc = MutableDocument.newNoDocument(key, version);\n const removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n } else if ('documentRemove' in change) {\n assertPresent(change.documentRemove, 'documentRemove');\n const docRemove = change.documentRemove;\n assertPresent(docRemove.document, 'documentRemove');\n const key = fromName(serializer, docRemove.document);\n const removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n } else if ('filter' in change) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n const filter = change.filter;\n assertPresent(filter.targetId, 'filter.targetId');\n const { count = 0, unchangedNames } = filter;\n const existenceFilter = new ExistenceFilter(count, unchangedNames);\n const targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n } else {\n return fail('Unknown change type ' + JSON.stringify(change));\n }\n return watchChange;\n}\n\nfunction fromWatchTargetChangeState(\n state: ProtoTargetChangeTargetChangeType\n): WatchTargetChangeState {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n } else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n } else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n } else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n } else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n } else {\n return fail('Got unexpected TargetChange.state: ' + state);\n }\n}\n\nexport function versionFromListenResponse(\n change: ProtoListenResponse\n): SnapshotVersion {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n if (!('targetChange' in change)) {\n return SnapshotVersion.min();\n }\n const targetChange = change.targetChange!;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return SnapshotVersion.min();\n }\n if (!targetChange.readTime) {\n return SnapshotVersion.min();\n }\n return fromVersion(targetChange.readTime);\n}\n\nexport function toMutation(\n serializer: JsonProtoSerializer,\n mutation: Mutation\n): ProtoWrite {\n let result: ProtoWrite;\n if (mutation instanceof SetMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.value)\n };\n } else if (mutation instanceof DeleteMutation) {\n result = { delete: toName(serializer, mutation.key) };\n } else if (mutation instanceof PatchMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.data),\n updateMask: toDocumentMask(mutation.fieldMask)\n };\n } else if (mutation instanceof VerifyMutation) {\n result = {\n verify: toName(serializer, mutation.key)\n };\n } else {\n return fail('Unknown mutation type ' + mutation.type);\n }\n\n if (mutation.fieldTransforms.length > 0) {\n result.updateTransforms = mutation.fieldTransforms.map(transform =>\n toFieldTransform(serializer, transform)\n );\n }\n\n if (!mutation.precondition.isNone) {\n result.currentDocument = toPrecondition(serializer, mutation.precondition);\n }\n\n return result;\n}\n\nexport function fromMutation(\n serializer: JsonProtoSerializer,\n proto: ProtoWrite\n): Mutation {\n const precondition = proto.currentDocument\n ? fromPrecondition(proto.currentDocument)\n : Precondition.none();\n\n const fieldTransforms = proto.updateTransforms\n ? proto.updateTransforms.map(transform =>\n fromFieldTransform(serializer, transform)\n )\n : [];\n\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n const key = fromName(serializer, proto.update.name);\n const value = new ObjectValue({\n mapValue: { fields: proto.update.fields }\n });\n\n if (proto.updateMask) {\n const fieldMask = fromDocumentMask(proto.updateMask);\n return new PatchMutation(\n key,\n value,\n fieldMask,\n precondition,\n fieldTransforms\n );\n } else {\n return new SetMutation(key, value, precondition, fieldTransforms);\n }\n } else if (proto.delete) {\n const key = fromName(serializer, proto.delete);\n return new DeleteMutation(key, precondition);\n } else if (proto.verify) {\n const key = fromName(serializer, proto.verify);\n return new VerifyMutation(key, precondition);\n } else {\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\n }\n}\n\nfunction toPrecondition(\n serializer: JsonProtoSerializer,\n precondition: Precondition\n): ProtoPrecondition {\n debugAssert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: toVersion(serializer, precondition.updateTime)\n };\n } else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n } else {\n return fail('Unknown precondition');\n }\n}\n\nfunction fromPrecondition(precondition: ProtoPrecondition): Precondition {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(fromVersion(precondition.updateTime));\n } else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n } else {\n return Precondition.none();\n }\n}\n\nfunction fromWriteResult(\n proto: ProtoWriteResult,\n commitTime: ProtoTimestamp\n): MutationResult {\n // NOTE: Deletes don't have an updateTime.\n let version = proto.updateTime\n ? fromVersion(proto.updateTime)\n : fromVersion(commitTime);\n\n if (version.isEqual(SnapshotVersion.min())) {\n // The Firestore Emulator currently returns an update time of 0 for\n // deletes of non-existing documents (rather than null). This breaks the\n // test \"get deleted doc while offline with source=cache\" as NoDocuments\n // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n // TODO(#2149): Remove this when Emulator is fixed\n version = fromVersion(commitTime);\n }\n\n return new MutationResult(version, proto.transformResults || []);\n}\n\nexport function fromWriteResults(\n protos: ProtoWriteResult[] | undefined,\n commitTime?: ProtoTimestamp\n): MutationResult[] {\n if (protos && protos.length > 0) {\n hardAssert(\n commitTime !== undefined,\n 'Received a write result without a commit time'\n );\n return protos.map(proto => fromWriteResult(proto, commitTime));\n } else {\n return [];\n }\n}\n\nfunction toFieldTransform(\n serializer: JsonProtoSerializer,\n fieldTransform: FieldTransform\n): ProtoFieldTransform {\n const transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n appendMissingElements: {\n values: transform.elements\n }\n };\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n removeAllFromArray: {\n values: transform.elements\n }\n };\n } else if (transform instanceof NumericIncrementTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n increment: transform.operand\n };\n } else {\n throw fail('Unknown transform: ' + fieldTransform.transform);\n }\n}\n\nfunction fromFieldTransform(\n serializer: JsonProtoSerializer,\n proto: ProtoFieldTransform\n): FieldTransform {\n let transform: TransformOperation | null = null;\n if ('setToServerValue' in proto) {\n hardAssert(\n proto.setToServerValue === 'REQUEST_TIME',\n 'Unknown server value transform proto: ' + JSON.stringify(proto)\n );\n transform = new ServerTimestampTransform();\n } else if ('appendMissingElements' in proto) {\n const values = proto.appendMissingElements!.values || [];\n transform = new ArrayUnionTransformOperation(values);\n } else if ('removeAllFromArray' in proto) {\n const values = proto.removeAllFromArray!.values || [];\n transform = new ArrayRemoveTransformOperation(values);\n } else if ('increment' in proto) {\n transform = new NumericIncrementTransformOperation(\n serializer,\n proto.increment!\n );\n } else {\n fail('Unknown transform proto: ' + JSON.stringify(proto));\n }\n const fieldPath = FieldPath.fromServerFormat(proto.fieldPath!);\n return new FieldTransform(fieldPath, transform!);\n}\n\nexport function toDocumentsTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): ProtoDocumentsTarget {\n return { documents: [toQueryPath(serializer, target.path)] };\n}\n\nexport function fromDocumentsTarget(\n documentsTarget: ProtoDocumentsTarget\n): Target {\n const count = documentsTarget.documents!.length;\n hardAssert(\n count === 1,\n 'DocumentsTarget contained other than 1 document: ' + count\n );\n const name = documentsTarget.documents![0];\n return queryToTarget(newQueryForPath(fromQueryPath(name)));\n}\n\nexport function toQueryTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): ProtoQueryTarget {\n // Dissect the path into parent, collectionId, and optional key filter.\n const result: ProtoQueryTarget = { structuredQuery: {} };\n const path = target.path;\n if (target.collectionGroup !== null) {\n debugAssert(\n path.length % 2 === 0,\n 'Collection Group queries should be within a document path or root.'\n );\n result.parent = toQueryPath(serializer, path);\n result.structuredQuery!.from = [\n {\n collectionId: target.collectionGroup,\n allDescendants: true\n }\n ];\n } else {\n debugAssert(\n path.length % 2 !== 0,\n 'Document queries with filters are not supported.'\n );\n result.parent = toQueryPath(serializer, path.popLast());\n result.structuredQuery!.from = [{ collectionId: path.lastSegment() }];\n }\n\n const where = toFilters(target.filters);\n if (where) {\n result.structuredQuery!.where = where;\n }\n\n const orderBy = toOrder(target.orderBy);\n if (orderBy) {\n result.structuredQuery!.orderBy = orderBy;\n }\n\n const limit = toInt32Proto(serializer, target.limit);\n if (limit !== null) {\n result.structuredQuery!.limit = limit;\n }\n\n if (target.startAt) {\n result.structuredQuery!.startAt = toStartAtCursor(target.startAt);\n }\n if (target.endAt) {\n result.structuredQuery!.endAt = toEndAtCursor(target.endAt);\n }\n\n return result;\n}\n\nexport function toRunAggregationQueryRequest(\n serializer: JsonProtoSerializer,\n target: Target,\n aggregates: Aggregate[]\n): {\n request: ProtoRunAggregationQueryRequest;\n aliasMap: Record<string, string>;\n} {\n const queryTarget = toQueryTarget(serializer, target);\n const aliasMap: Record<string, string> = {};\n\n const aggregations: ProtoAggregation[] = [];\n let aggregationNum = 0;\n\n aggregates.forEach(aggregate => {\n // Map all client-side aliases to a unique short-form\n // alias. This avoids issues with client-side aliases that\n // exceed the 1500-byte string size limit.\n const serverAlias = `aggregate_${aggregationNum++}`;\n aliasMap[serverAlias] = aggregate.alias;\n\n if (aggregate.aggregateType === 'count') {\n aggregations.push({\n alias: serverAlias,\n count: {}\n });\n } else if (aggregate.aggregateType === 'avg') {\n aggregations.push({\n alias: serverAlias,\n avg: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n } else if (aggregate.aggregateType === 'sum') {\n aggregations.push({\n alias: serverAlias,\n sum: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n }\n });\n\n return {\n request: {\n structuredAggregationQuery: {\n aggregations,\n structuredQuery: queryTarget.structuredQuery\n },\n parent: queryTarget.parent\n },\n aliasMap\n };\n}\n\nexport function convertQueryTargetToQuery(target: ProtoQueryTarget): Query {\n let path = fromQueryPath(target.parent!);\n\n const query = target.structuredQuery!;\n const fromCount = query.from ? query.from.length : 0;\n let collectionGroup: string | null = null;\n if (fromCount > 0) {\n hardAssert(\n fromCount === 1,\n 'StructuredQuery.from with more than one collection is not supported.'\n );\n const from = query.from![0];\n if (from.allDescendants) {\n collectionGroup = from.collectionId!;\n } else {\n path = path.child(from.collectionId!);\n }\n }\n\n let filterBy: Filter[] = [];\n if (query.where) {\n filterBy = fromFilters(query.where);\n }\n\n let orderBy: OrderBy[] = [];\n if (query.orderBy) {\n orderBy = fromOrder(query.orderBy);\n }\n\n let limit: number | null = null;\n if (query.limit) {\n limit = fromInt32Proto(query.limit);\n }\n\n let startAt: Bound | null = null;\n if (query.startAt) {\n startAt = fromStartAtCursor(query.startAt);\n }\n\n let endAt: Bound | null = null;\n if (query.endAt) {\n endAt = fromEndAtCursor(query.endAt);\n }\n\n return newQuery(\n path,\n collectionGroup,\n orderBy,\n filterBy,\n limit,\n LimitType.First,\n startAt,\n endAt\n );\n}\n\nexport function fromQueryTarget(target: ProtoQueryTarget): Target {\n return queryToTarget(convertQueryTargetToQuery(target));\n}\n\nexport function toListenRequestLabels(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoApiClientObjectMap<string> | null {\n const value = toLabel(targetData.purpose);\n if (value == null) {\n return null;\n } else {\n return {\n 'goog-listen-tags': value\n };\n }\n}\n\nexport function toLabel(purpose: TargetPurpose): string | null {\n switch (purpose) {\n case TargetPurpose.Listen:\n return null;\n case TargetPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case TargetPurpose.ExistenceFilterMismatchBloom:\n return 'existence-filter-mismatch-bloom';\n case TargetPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail('Unrecognized query purpose: ' + purpose);\n }\n}\n\nexport function toTarget(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoTarget {\n let result: ProtoTarget;\n const target = targetData.target;\n\n if (targetIsDocumentTarget(target)) {\n result = { documents: toDocumentsTarget(serializer, target) };\n } else {\n result = { query: toQueryTarget(serializer, target) };\n }\n\n result.targetId = targetData.targetId;\n\n if (targetData.resumeToken.approximateByteSize() > 0) {\n result.resumeToken = toBytes(serializer, targetData.resumeToken);\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n } else if (targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n // TODO(wuandy): Consider removing above check because it is most likely true.\n // Right now, many tests depend on this behaviour though (leaving min() out\n // of serialization).\n result.readTime = toTimestamp(\n serializer,\n targetData.snapshotVersion.toTimestamp()\n );\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n }\n\n return result;\n}\n\nfunction toFilters(filters: Filter[]): ProtoFilter | undefined {\n if (filters.length === 0) {\n return;\n }\n\n return toFilter(CompositeFilter.create(filters, CompositeOperator.AND));\n}\n\nfunction fromFilters(filter: ProtoFilter): Filter[] {\n const result = fromFilter(filter);\n\n if (\n result instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(result)\n ) {\n return result.getFilters();\n }\n\n return [result];\n}\n\nfunction fromFilter(filter: ProtoFilter): Filter {\n if (filter.unaryFilter !== undefined) {\n return fromUnaryFilter(filter);\n } else if (filter.fieldFilter !== undefined) {\n return fromFieldFilter(filter);\n } else if (filter.compositeFilter !== undefined) {\n return fromCompositeFilter(filter);\n } else {\n return fail('Unknown filter: ' + JSON.stringify(filter));\n }\n}\n\nfunction toOrder(orderBys: OrderBy[]): ProtoOrder[] | undefined {\n if (orderBys.length === 0) {\n return;\n }\n return orderBys.map(order => toPropertyOrder(order));\n}\n\nfunction fromOrder(orderBys: ProtoOrder[]): OrderBy[] {\n return orderBys.map(order => fromPropertyOrder(order));\n}\n\nfunction toStartAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction toEndAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: !cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction fromStartAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !!cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\nfunction fromEndAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\n// visible for testing\nexport function toDirection(dir: Direction): ProtoOrderDirection {\n return DIRECTIONS[dir];\n}\n\n// visible for testing\nexport function fromDirection(\n dir: ProtoOrderDirection | undefined\n): Direction | undefined {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n}\n\n// visible for testing\nexport function toOperatorName(op: Operator): ProtoFieldFilterOp {\n return OPERATORS[op];\n}\n\nexport function toCompositeOperatorName(\n op: CompositeOperator\n): ProtoCompositeFilterOp {\n return COMPOSITE_OPERATORS[op];\n}\n\nexport function fromOperatorName(op: ProtoFieldFilterOp): Operator {\n switch (op) {\n case 'EQUAL':\n return Operator.EQUAL;\n case 'NOT_EQUAL':\n return Operator.NOT_EQUAL;\n case 'GREATER_THAN':\n return Operator.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return Operator.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return Operator.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return Operator.LESS_THAN_OR_EQUAL;\n case 'ARRAY_CONTAINS':\n return Operator.ARRAY_CONTAINS;\n case 'IN':\n return Operator.IN;\n case 'NOT_IN':\n return Operator.NOT_IN;\n case 'ARRAY_CONTAINS_ANY':\n return Operator.ARRAY_CONTAINS_ANY;\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified operator');\n default:\n return fail('Unknown operator');\n }\n}\n\nexport function fromCompositeOperatorName(\n op: ProtoCompositeFilterOp\n): CompositeOperator {\n switch (op) {\n case 'AND':\n return CompositeOperator.AND;\n case 'OR':\n return CompositeOperator.OR;\n default:\n return fail('Unknown operator');\n }\n}\n\nexport function toFieldPathReference(path: FieldPath): ProtoFieldReference {\n return { fieldPath: path.canonicalString() };\n}\n\nexport function fromFieldPathReference(\n fieldReference: ProtoFieldReference\n): FieldPath {\n return FieldPath.fromServerFormat(fieldReference.fieldPath!);\n}\n\n// visible for testing\nexport function toPropertyOrder(orderBy: OrderBy): ProtoOrder {\n return {\n field: toFieldPathReference(orderBy.field),\n direction: toDirection(orderBy.dir)\n };\n}\n\nexport function fromPropertyOrder(orderBy: ProtoOrder): OrderBy {\n return new OrderBy(\n fromFieldPathReference(orderBy.field!),\n fromDirection(orderBy.direction)\n );\n}\n\n// visible for testing\nexport function toFilter(filter: Filter): ProtoFilter {\n if (filter instanceof FieldFilter) {\n return toUnaryOrFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return toCompositeFilter(filter);\n } else {\n return fail('Unrecognized filter type ' + JSON.stringify(filter));\n }\n}\n\nexport function toCompositeFilter(filter: CompositeFilter): ProtoFilter {\n const protos = filter.getFilters().map(filter => toFilter(filter));\n\n if (protos.length === 1) {\n return protos[0];\n }\n\n return {\n compositeFilter: {\n op: toCompositeOperatorName(filter.op),\n filters: protos\n }\n };\n}\n\nexport function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter {\n if (filter.op === Operator.EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n } else if (filter.op === Operator.NOT_EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NULL'\n }\n };\n }\n }\n return {\n fieldFilter: {\n field: toFieldPathReference(filter.field),\n op: toOperatorName(filter.op),\n value: filter.value\n }\n };\n}\n\nexport function fromUnaryFilter(filter: ProtoFilter): Filter {\n switch (filter.unaryFilter!.op!) {\n case 'IS_NAN':\n const nanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nanField, Operator.EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NULL':\n const nullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nullField, Operator.EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'IS_NOT_NAN':\n const notNanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNanField, Operator.NOT_EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NOT_NULL':\n const notNullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNullField, Operator.NOT_EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified filter');\n default:\n return fail('Unknown filter');\n }\n}\n\nexport function fromFieldFilter(filter: ProtoFilter): FieldFilter {\n return FieldFilter.create(\n fromFieldPathReference(filter.fieldFilter!.field!),\n fromOperatorName(filter.fieldFilter!.op!),\n filter.fieldFilter!.value!\n );\n}\n\nexport function fromCompositeFilter(filter: ProtoFilter): CompositeFilter {\n return CompositeFilter.create(\n filter.compositeFilter!.filters!.map(filter => fromFilter(filter)),\n fromCompositeOperatorName(filter.compositeFilter!.op!)\n );\n}\n\nexport function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask {\n const canonicalFields: string[] = [];\n fieldMask.fields.forEach(field =>\n canonicalFields.push(field.canonicalString())\n );\n return {\n fieldPaths: canonicalFields\n };\n}\n\nexport function fromDocumentMask(proto: ProtoDocumentMask): FieldMask {\n const paths = proto.fieldPaths || [];\n return new FieldMask(paths.map(path => FieldPath.fromServerFormat(path)));\n}\n\nexport function isValidResourceName(path: ResourcePath): boolean {\n // Resource names have at least 4 components (project ID, database ID)\n return (\n path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases'\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Target } from '../core/target';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { ByteString } from '../util/byte_string';\n\n/** An enumeration of the different purposes we have for targets. */\nexport const enum TargetPurpose {\n /** A regular, normal query target. */\n Listen = 'TargetPurposeListen',\n\n /**\n * The query target was used to refill a query after an existence filter\n * mismatch.\n */\n ExistenceFilterMismatch = 'TargetPurposeExistenceFilterMismatch',\n\n /**\n * The query target was used if the query is the result of a false positive in\n * the bloom filter.\n */\n ExistenceFilterMismatchBloom = 'TargetPurposeExistenceFilterMismatchBloom',\n\n /** The query target was used to resolve a limbo document. */\n LimboResolution = 'TargetPurposeLimboResolution'\n}\n\n/**\n * An immutable set of metadata that the local store tracks for each target.\n */\nexport class TargetData {\n constructor(\n /** The target being listened to. */\n readonly target: Target,\n /**\n * The target ID to which the target corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n readonly targetId: TargetId,\n /** The purpose of the target. */\n readonly purpose: TargetPurpose,\n /**\n * The sequence number of the last transaction during which this target data\n * was modified.\n */\n readonly sequenceNumber: ListenSequenceNumber,\n /** The latest snapshot version seen for this target. */\n readonly snapshotVersion: SnapshotVersion = SnapshotVersion.min(),\n /**\n * The maximum snapshot version at which the associated view\n * contained no limbo documents.\n */\n readonly lastLimboFreeSnapshotVersion: SnapshotVersion = SnapshotVersion.min(),\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n readonly resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING,\n /**\n * The number of documents that last matched the query at the resume token or\n * read time. Documents are counted only when making a listen request with\n * resume token or read time, otherwise, keep it null.\n */\n readonly expectedCount: number | null = null\n ) {}\n\n /** Creates a new target data instance with an updated sequence number. */\n withSequenceNumber(sequenceNumber: number): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n sequenceNumber,\n this.snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n this.resumeToken,\n this.expectedCount\n );\n }\n\n /**\n * Creates a new target data instance with an updated resume token and\n * snapshot version.\n */\n withResumeToken(\n resumeToken: ByteString,\n snapshotVersion: SnapshotVersion\n ): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n resumeToken,\n /* expectedCount= */ null\n );\n }\n\n /**\n * Creates a new target data instance with an updated expected count.\n */\n withExpectedCount(expectedCount: number): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n this.snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n this.resumeToken,\n expectedCount\n );\n }\n\n /**\n * Creates a new target data instance with an updated last limbo free\n * snapshot version number.\n */\n withLastLimboFreeSnapshotVersion(\n lastLimboFreeSnapshotVersion: SnapshotVersion\n ): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n this.snapshotVersion,\n lastLimboFreeSnapshotVersion,\n this.resumeToken,\n this.expectedCount\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../api/timestamp';\nimport { User } from '../auth/user';\nimport { BundleMetadata, NamedQuery } from '../core/bundle';\nimport { LimitType, Query, queryWithLimit } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetIsDocumentTarget } from '../core/target';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n IndexOffset,\n IndexSegment,\n IndexState\n} from '../model/field_index';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { Overlay } from '../model/overlay';\nimport { FieldPath } from '../model/path';\nimport {\n BundledQuery as ProtoBundledQuery,\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { DocumentsTarget as PublicDocumentsTarget } from '../protos/firestore_proto_api';\nimport {\n convertQueryTargetToQuery,\n fromDocument,\n fromDocumentsTarget,\n fromMutation,\n fromQueryTarget,\n fromVersion,\n JsonProtoSerializer,\n toDocument,\n toDocumentsTarget,\n toMutation,\n toQueryTarget\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport {\n DbBundle,\n DbDocumentOverlay,\n DbIndexConfiguration,\n DbIndexState,\n DbMutationBatch,\n DbNamedQuery,\n DbQuery,\n DbRemoteDocument,\n DbTarget,\n DbTimestamp\n} from './indexeddb_schema';\nimport { DbDocumentOverlayKey, DbTimestampKey } from './indexeddb_sentinels';\nimport { TargetData, TargetPurpose } from './target_data';\n\n/** Serializer for values stored in the LocalStore. */\nexport class LocalSerializer {\n constructor(readonly remoteSerializer: JsonProtoSerializer) {}\n}\n\n/** Decodes a remote document from storage locally to a Document. */\nexport function fromDbRemoteDocument(\n localSerializer: LocalSerializer,\n remoteDoc: DbRemoteDocument\n): MutableDocument {\n let doc: MutableDocument;\n if (remoteDoc.document) {\n doc = fromDocument(\n localSerializer.remoteSerializer,\n remoteDoc.document,\n !!remoteDoc.hasCommittedMutations\n );\n } else if (remoteDoc.noDocument) {\n const key = DocumentKey.fromSegments(remoteDoc.noDocument.path);\n const version = fromDbTimestamp(remoteDoc.noDocument.readTime);\n doc = MutableDocument.newNoDocument(key, version);\n if (remoteDoc.hasCommittedMutations) {\n doc.setHasCommittedMutations();\n }\n } else if (remoteDoc.unknownDocument) {\n const key = DocumentKey.fromSegments(remoteDoc.unknownDocument.path);\n const version = fromDbTimestamp(remoteDoc.unknownDocument.version);\n doc = MutableDocument.newUnknownDocument(key, version);\n } else {\n return fail('Unexpected DbRemoteDocument');\n }\n\n if (remoteDoc.readTime) {\n doc.setReadTime(fromDbTimestampKey(remoteDoc.readTime));\n }\n\n return doc;\n}\n\n/** Encodes a document for storage locally. */\nexport function toDbRemoteDocument(\n localSerializer: LocalSerializer,\n document: MutableDocument\n): DbRemoteDocument {\n const key = document.key;\n const remoteDoc: DbRemoteDocument = {\n prefixPath: key.getCollectionPath().popLast().toArray(),\n collectionGroup: key.collectionGroup,\n documentId: key.path.lastSegment(),\n readTime: toDbTimestampKey(document.readTime),\n hasCommittedMutations: document.hasCommittedMutations\n };\n\n if (document.isFoundDocument()) {\n remoteDoc.document = toDocument(localSerializer.remoteSerializer, document);\n } else if (document.isNoDocument()) {\n remoteDoc.noDocument = {\n path: key.path.toArray(),\n readTime: toDbTimestamp(document.version)\n };\n } else if (document.isUnknownDocument()) {\n remoteDoc.unknownDocument = {\n path: key.path.toArray(),\n version: toDbTimestamp(document.version)\n };\n } else {\n return fail('Unexpected Document ' + document);\n }\n return remoteDoc;\n}\n\nexport function toDbTimestampKey(\n snapshotVersion: SnapshotVersion\n): DbTimestampKey {\n const timestamp = snapshotVersion.toTimestamp();\n return [timestamp.seconds, timestamp.nanoseconds];\n}\n\nexport function fromDbTimestampKey(\n dbTimestampKey: DbTimestampKey\n): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestampKey[0], dbTimestampKey[1]);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\nexport function toDbTimestamp(snapshotVersion: SnapshotVersion): DbTimestamp {\n const timestamp = snapshotVersion.toTimestamp();\n return { seconds: timestamp.seconds, nanoseconds: timestamp.nanoseconds };\n}\n\nfunction fromDbTimestamp(dbTimestamp: DbTimestamp): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestamp.seconds, dbTimestamp.nanoseconds);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\n/** Encodes a batch of mutations into a DbMutationBatch for local storage. */\nexport function toDbMutationBatch(\n localSerializer: LocalSerializer,\n userId: string,\n batch: MutationBatch\n): DbMutationBatch {\n const serializedBaseMutations = batch.baseMutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n const serializedMutations = batch.mutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n return {\n userId,\n batchId: batch.batchId,\n localWriteTimeMs: batch.localWriteTime.toMillis(),\n baseMutations: serializedBaseMutations,\n mutations: serializedMutations\n };\n}\n\n/** Decodes a DbMutationBatch into a MutationBatch */\nexport function fromDbMutationBatch(\n localSerializer: LocalSerializer,\n dbBatch: DbMutationBatch\n): MutationBatch {\n const baseMutations = (dbBatch.baseMutations || []).map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n\n // Squash old transform mutations into existing patch or set mutations.\n // The replacement of representing `transforms` with `update_transforms`\n // on the SDK means that old `transform` mutations stored in IndexedDB need\n // to be updated to `update_transforms`.\n // TODO(b/174608374): Remove this code once we perform a schema migration.\n for (let i = 0; i < dbBatch.mutations.length - 1; ++i) {\n const currentMutation = dbBatch.mutations[i];\n const hasTransform =\n i + 1 < dbBatch.mutations.length &&\n dbBatch.mutations[i + 1].transform !== undefined;\n if (hasTransform) {\n debugAssert(\n dbBatch.mutations[i].transform === undefined &&\n dbBatch.mutations[i].update !== undefined,\n 'TransformMutation should be preceded by a patch or set mutation'\n );\n const transformMutation = dbBatch.mutations[i + 1];\n currentMutation.updateTransforms =\n transformMutation.transform!.fieldTransforms;\n dbBatch.mutations.splice(i + 1, 1);\n ++i;\n }\n }\n\n const mutations = dbBatch.mutations.map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n const timestamp = Timestamp.fromMillis(dbBatch.localWriteTimeMs);\n return new MutationBatch(\n dbBatch.batchId,\n timestamp,\n baseMutations,\n mutations\n );\n}\n\n/** Decodes a DbTarget into TargetData */\nexport function fromDbTarget(dbTarget: DbTarget): TargetData {\n const version = fromDbTimestamp(dbTarget.readTime);\n const lastLimboFreeSnapshotVersion =\n dbTarget.lastLimboFreeSnapshotVersion !== undefined\n ? fromDbTimestamp(dbTarget.lastLimboFreeSnapshotVersion)\n : SnapshotVersion.min();\n\n let target: Target;\n if (isDocumentQuery(dbTarget.query)) {\n target = fromDocumentsTarget(dbTarget.query);\n } else {\n target = fromQueryTarget(dbTarget.query);\n }\n return new TargetData(\n target,\n dbTarget.targetId,\n TargetPurpose.Listen,\n dbTarget.lastListenSequenceNumber,\n version,\n lastLimboFreeSnapshotVersion,\n ByteString.fromBase64String(dbTarget.resumeToken)\n );\n}\n\n/** Encodes TargetData into a DbTarget for storage locally. */\nexport function toDbTarget(\n localSerializer: LocalSerializer,\n targetData: TargetData\n): DbTarget {\n debugAssert(\n TargetPurpose.Listen === targetData.purpose,\n 'Only queries with purpose ' +\n TargetPurpose.Listen +\n ' may be stored, got ' +\n targetData.purpose\n );\n const dbTimestamp = toDbTimestamp(targetData.snapshotVersion);\n const dbLastLimboFreeTimestamp = toDbTimestamp(\n targetData.lastLimboFreeSnapshotVersion\n );\n let queryProto: DbQuery;\n if (targetIsDocumentTarget(targetData.target)) {\n queryProto = toDocumentsTarget(\n localSerializer.remoteSerializer,\n targetData.target\n );\n } else {\n queryProto = toQueryTarget(\n localSerializer.remoteSerializer,\n targetData.target\n );\n }\n\n // We can't store the resumeToken as a ByteString in IndexedDb, so we\n // convert it to a base64 string for storage.\n const resumeToken = targetData.resumeToken.toBase64();\n\n // lastListenSequenceNumber is always 0 until we do real GC.\n return {\n targetId: targetData.targetId,\n canonicalId: canonifyTarget(targetData.target),\n readTime: dbTimestamp,\n resumeToken,\n lastListenSequenceNumber: targetData.sequenceNumber,\n lastLimboFreeSnapshotVersion: dbLastLimboFreeTimestamp,\n query: queryProto\n };\n}\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\nfunction isDocumentQuery(dbQuery: DbQuery): dbQuery is PublicDocumentsTarget {\n return (dbQuery as PublicDocumentsTarget).documents !== undefined;\n}\n\n/** Encodes a DbBundle to a BundleMetadata object. */\nexport function fromDbBundle(dbBundle: DbBundle): BundleMetadata {\n return {\n id: dbBundle.bundleId,\n createTime: fromDbTimestamp(dbBundle.createTime),\n version: dbBundle.version\n };\n}\n\n/** Encodes a BundleMetadata to a DbBundle. */\nexport function toDbBundle(metadata: ProtoBundleMetadata): DbBundle {\n return {\n bundleId: metadata.id!,\n createTime: toDbTimestamp(fromVersion(metadata.createTime!)),\n version: metadata.version!\n };\n}\n\n/** Encodes a DbNamedQuery to a NamedQuery. */\nexport function fromDbNamedQuery(dbNamedQuery: DbNamedQuery): NamedQuery {\n return {\n name: dbNamedQuery.name,\n query: fromBundledQuery(dbNamedQuery.bundledQuery),\n readTime: fromDbTimestamp(dbNamedQuery.readTime)\n };\n}\n\n/** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */\nexport function toDbNamedQuery(query: ProtoNamedQuery): DbNamedQuery {\n return {\n name: query.name!,\n readTime: toDbTimestamp(fromVersion(query.readTime!)),\n bundledQuery: query.bundledQuery!\n };\n}\n\n/**\n * Encodes a `BundledQuery` from bundle proto to a Query object.\n *\n * This reconstructs the original query used to build the bundle being loaded,\n * including features exists only in SDKs (for example: limit-to-last).\n */\nexport function fromBundledQuery(bundledQuery: ProtoBundledQuery): Query {\n const query = convertQueryTargetToQuery({\n parent: bundledQuery.parent!,\n structuredQuery: bundledQuery.structuredQuery!\n });\n if (bundledQuery.limitType === 'LAST') {\n debugAssert(\n !!query.limit,\n 'Bundled query has limitType LAST, but limit is null'\n );\n return queryWithLimit(query, query.limit, LimitType.Last);\n }\n return query;\n}\n\n/** Encodes a NamedQuery proto object to a NamedQuery model object. */\nexport function fromProtoNamedQuery(namedQuery: ProtoNamedQuery): NamedQuery {\n return {\n name: namedQuery.name!,\n query: fromBundledQuery(namedQuery.bundledQuery!),\n readTime: fromVersion(namedQuery.readTime!)\n };\n}\n\n/** Decodes a BundleMetadata proto into a BundleMetadata object. */\nexport function fromBundleMetadata(\n metadata: ProtoBundleMetadata\n): BundleMetadata {\n return {\n id: metadata.id!,\n version: metadata.version!,\n createTime: fromVersion(metadata.createTime!)\n };\n}\n\n/** Encodes a DbDocumentOverlay object to an Overlay model object. */\nexport function fromDbDocumentOverlay(\n localSerializer: LocalSerializer,\n dbDocumentOverlay: DbDocumentOverlay\n): Overlay {\n return new Overlay(\n dbDocumentOverlay.largestBatchId,\n fromMutation(\n localSerializer.remoteSerializer,\n dbDocumentOverlay.overlayMutation\n )\n );\n}\n\n/** Decodes an Overlay model object into a DbDocumentOverlay object. */\nexport function toDbDocumentOverlay(\n localSerializer: LocalSerializer,\n userId: string,\n overlay: Overlay\n): DbDocumentOverlay {\n const [_, collectionPath, documentId] = toDbDocumentOverlayKey(\n userId,\n overlay.mutation.key\n );\n return {\n userId,\n collectionPath,\n documentId,\n collectionGroup: overlay.mutation.key.getCollectionGroup(),\n largestBatchId: overlay.largestBatchId,\n overlayMutation: toMutation(\n localSerializer.remoteSerializer,\n overlay.mutation\n )\n };\n}\n\n/**\n * Returns the DbDocumentOverlayKey corresponding to the given user and\n * document key.\n */\nexport function toDbDocumentOverlayKey(\n userId: string,\n docKey: DocumentKey\n): DbDocumentOverlayKey {\n const docId = docKey.path.lastSegment();\n const collectionPath = encodeResourcePath(docKey.path.popLast());\n return [userId, collectionPath, docId];\n}\n\nexport function toDbIndexConfiguration(\n index: FieldIndex\n): DbIndexConfiguration {\n return {\n indexId: index.indexId,\n collectionGroup: index.collectionGroup,\n fields: index.fields.map(s => [s.fieldPath.canonicalString(), s.kind])\n };\n}\n\nexport function fromDbIndexConfiguration(\n index: DbIndexConfiguration,\n state: DbIndexState | null\n): FieldIndex {\n const decodedState = state\n ? new IndexState(\n state.sequenceNumber,\n new IndexOffset(\n fromDbTimestamp(state.readTime),\n new DocumentKey(decodeResourcePath(state.documentKey)),\n state.largestBatchId\n )\n )\n : IndexState.empty();\n const decodedSegments = index.fields.map(\n ([fieldPath, kind]) =>\n new IndexSegment(FieldPath.fromServerFormat(fieldPath), kind)\n );\n return new FieldIndex(\n index.indexId!,\n index.collectionGroup,\n decodedSegments,\n decodedState\n );\n}\n\nexport function toDbIndexState(\n indexId: number,\n user: User,\n sequenceNumber: number,\n offset: IndexOffset\n): DbIndexState {\n return {\n indexId,\n uid: user.uid || '',\n sequenceNumber,\n readTime: toDbTimestamp(offset.readTime),\n documentKey: encodeResourcePath(offset.documentKey.path),\n largestBatchId: offset.largestBatchId\n };\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { normalizeByteString, normalizeNumber } from '../model/normalize';\nimport { isMaxValue } from '../model/values';\nimport { ArrayValue, MapValue, Value } from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport { isNegativeZero } from '../util/types';\n\nimport { DirectionalIndexByteEncoder } from './directional_index_byte_encoder';\n\n// Note: This code is copied from the backend. Code that is not used by\n// Firestore was removed.\n\nconst INDEX_TYPE_NULL = 5;\nconst INDEX_TYPE_BOOLEAN = 10;\nconst INDEX_TYPE_NAN = 13;\nconst INDEX_TYPE_NUMBER = 15;\nconst INDEX_TYPE_TIMESTAMP = 20;\nconst INDEX_TYPE_STRING = 25;\nconst INDEX_TYPE_BLOB = 30;\nconst INDEX_TYPE_REFERENCE = 37;\nconst INDEX_TYPE_GEOPOINT = 45;\nconst INDEX_TYPE_ARRAY = 50;\nconst INDEX_TYPE_MAP = 55;\nconst INDEX_TYPE_REFERENCE_SEGMENT = 60;\n\n// A terminator that indicates that a truncatable value was not truncated.\n// This must be smaller than all other type labels.\nconst NOT_TRUNCATED = 2;\n\n/** Firestore index value writer. */\nexport class FirestoreIndexValueWriter {\n static INSTANCE = new FirestoreIndexValueWriter();\n\n private constructor() {}\n\n // The write methods below short-circuit writing terminators for values\n // containing a (terminating) truncated value.\n //\n // As an example, consider the resulting encoding for:\n //\n // [\"bar\", [2, \"foo\"]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TERM, TERM, TERM)\n // [\"bar\", [2, truncated(\"foo\")]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TRUNC)\n // [\"bar\", truncated([\"foo\"])] -> (STRING, \"bar\", TERM, ARRAY. STRING, \"foo\", TERM, TRUNC)\n\n /** Writes an index value. */\n writeIndexValue(value: Value, encoder: DirectionalIndexByteEncoder): void {\n this.writeIndexValueAux(value, encoder);\n // Write separator to split index values\n // (see go/firestore-storage-format#encodings).\n encoder.writeInfinity();\n }\n\n private writeIndexValueAux(\n indexValue: Value,\n encoder: DirectionalIndexByteEncoder\n ): void {\n if ('nullValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NULL);\n } else if ('booleanValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_BOOLEAN);\n encoder.writeNumber(indexValue.booleanValue ? 1 : 0);\n } else if ('integerValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NUMBER);\n encoder.writeNumber(normalizeNumber(indexValue.integerValue));\n } else if ('doubleValue' in indexValue) {\n const n = normalizeNumber(indexValue.doubleValue);\n if (isNaN(n)) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NAN);\n } else {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NUMBER);\n if (isNegativeZero(n)) {\n // -0.0, 0 and 0.0 are all considered the same\n encoder.writeNumber(0.0);\n } else {\n encoder.writeNumber(n);\n }\n }\n } else if ('timestampValue' in indexValue) {\n const timestamp = indexValue.timestampValue!;\n this.writeValueTypeLabel(encoder, INDEX_TYPE_TIMESTAMP);\n if (typeof timestamp === 'string') {\n encoder.writeString(timestamp);\n } else {\n encoder.writeString(`${timestamp.seconds || ''}`);\n encoder.writeNumber(timestamp.nanos || 0);\n }\n } else if ('stringValue' in indexValue) {\n this.writeIndexString(indexValue.stringValue!, encoder);\n this.writeTruncationMarker(encoder);\n } else if ('bytesValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_BLOB);\n encoder.writeBytes(normalizeByteString(indexValue.bytesValue!));\n this.writeTruncationMarker(encoder);\n } else if ('referenceValue' in indexValue) {\n this.writeIndexEntityRef(indexValue.referenceValue!, encoder);\n } else if ('geoPointValue' in indexValue) {\n const geoPoint = indexValue.geoPointValue!;\n this.writeValueTypeLabel(encoder, INDEX_TYPE_GEOPOINT);\n encoder.writeNumber(geoPoint.latitude || 0);\n encoder.writeNumber(geoPoint.longitude || 0);\n } else if ('mapValue' in indexValue) {\n if (isMaxValue(indexValue)) {\n this.writeValueTypeLabel(encoder, Number.MAX_SAFE_INTEGER);\n } else {\n this.writeIndexMap(indexValue.mapValue!, encoder);\n this.writeTruncationMarker(encoder);\n }\n } else if ('arrayValue' in indexValue) {\n this.writeIndexArray(indexValue.arrayValue!, encoder);\n this.writeTruncationMarker(encoder);\n } else {\n fail('unknown index value type ' + indexValue);\n }\n }\n\n private writeIndexString(\n stringIndexValue: string,\n encoder: DirectionalIndexByteEncoder\n ): void {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_STRING);\n this.writeUnlabeledIndexString(stringIndexValue, encoder);\n }\n\n private writeUnlabeledIndexString(\n stringIndexValue: string,\n encoder: DirectionalIndexByteEncoder\n ): void {\n encoder.writeString(stringIndexValue);\n }\n\n private writeIndexMap(\n mapIndexValue: MapValue,\n encoder: DirectionalIndexByteEncoder\n ): void {\n const map = mapIndexValue.fields || {};\n this.writeValueTypeLabel(encoder, INDEX_TYPE_MAP);\n for (const key of Object.keys(map)) {\n this.writeIndexString(key, encoder);\n this.writeIndexValueAux(map[key], encoder);\n }\n }\n\n private writeIndexArray(\n arrayIndexValue: ArrayValue,\n encoder: DirectionalIndexByteEncoder\n ): void {\n const values = arrayIndexValue.values || [];\n this.writeValueTypeLabel(encoder, INDEX_TYPE_ARRAY);\n for (const element of values) {\n this.writeIndexValueAux(element, encoder);\n }\n }\n\n private writeIndexEntityRef(\n referenceValue: string,\n encoder: DirectionalIndexByteEncoder\n ): void {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_REFERENCE);\n const path = DocumentKey.fromName(referenceValue).path;\n path.forEach(segment => {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_REFERENCE_SEGMENT);\n this.writeUnlabeledIndexString(segment, encoder);\n });\n }\n\n private writeValueTypeLabel(\n encoder: DirectionalIndexByteEncoder,\n typeOrder: number\n ): void {\n encoder.writeNumber(typeOrder);\n }\n\n private writeTruncationMarker(encoder: DirectionalIndexByteEncoder): void {\n // While the SDK does not implement truncation, the truncation marker is\n // used to terminate all variable length values (which are strings, bytes,\n // references, arrays and maps).\n encoder.writeNumber(NOT_TRUNCATED);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Target } from '../core/target';\nimport { DocumentMap } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex, IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager, IndexType } from './index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory implementation of IndexManager.\n */\nexport class MemoryIndexManager implements IndexManager {\n private collectionParentIndex = new MemoryCollectionParentIndex();\n\n addToCollectionParentIndex(\n transaction: PersistenceTransaction,\n collectionPath: ResourcePath\n ): PersistencePromise<void> {\n this.collectionParentIndex.add(collectionPath);\n return PersistencePromise.resolve();\n }\n\n getCollectionParents(\n transaction: PersistenceTransaction,\n collectionId: string\n ): PersistencePromise<ResourcePath[]> {\n return PersistencePromise.resolve(\n this.collectionParentIndex.getEntries(collectionId)\n );\n }\n\n addFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n deleteFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n deleteAllFieldIndexes(\n transaction: PersistenceTransaction\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n createTargetIndexes(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n getDocumentsMatchingTarget(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<DocumentKey[] | null> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve<DocumentKey[] | null>(null);\n }\n\n getIndexType(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<IndexType> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve<IndexType>(IndexType.NONE);\n }\n\n getFieldIndexes(\n transaction: PersistenceTransaction,\n collectionGroup?: string\n ): PersistencePromise<FieldIndex[]> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve<FieldIndex[]>([]);\n }\n\n getNextCollectionGroupToUpdate(\n transaction: PersistenceTransaction\n ): PersistencePromise<string | null> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve<string | null>(null);\n }\n\n getMinOffset(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<IndexOffset> {\n return PersistencePromise.resolve(IndexOffset.min());\n }\n\n getMinOffsetFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string\n ): PersistencePromise<IndexOffset> {\n return PersistencePromise.resolve(IndexOffset.min());\n }\n\n updateCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n updateIndexEntries(\n transaction: PersistenceTransaction,\n documents: DocumentMap\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n}\n\n/**\n * Internal implementation of the collection-parent index exposed by MemoryIndexManager.\n * Also used for in-memory caching by IndexedDbIndexManager and initial index population\n * in indexeddb_schema.ts\n */\nexport class MemoryCollectionParentIndex {\n private index = {} as {\n [collectionId: string]: SortedSet<ResourcePath>;\n };\n\n // Returns false if the entry already existed.\n add(collectionPath: ResourcePath): boolean {\n debugAssert(collectionPath.length % 2 === 1, 'Expected a collection path.');\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n const existingParents =\n this.index[collectionId] ||\n new SortedSet<ResourcePath>(ResourcePath.comparator);\n const added = !existingParents.has(parentPath);\n this.index[collectionId] = existingParents.add(parentPath);\n return added;\n }\n\n has(collectionPath: ResourcePath): boolean {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n const existingParents = this.index[collectionId];\n return existingParents && existingParents.has(parentPath);\n }\n\n getEntries(collectionId: string): ResourcePath[] {\n const parentPaths =\n this.index[collectionId] ||\n new SortedSet<ResourcePath>(ResourcePath.comparator);\n return parentPaths.toArray();\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport {\n canonifyTarget,\n newTarget,\n Target,\n targetEquals,\n targetGetArrayValues,\n targetGetLowerBound,\n targetGetNotInValues,\n targetGetSegmentCount,\n targetGetUpperBound,\n targetHasLimit\n} from '../core/target';\nimport { FirestoreIndexValueWriter } from '../index/firestore_index_value_writer';\nimport { IndexByteEncoder } from '../index/index_byte_encoder';\nimport { IndexEntry, indexEntryComparator } from '../index/index_entry';\nimport { documentKeySet, DocumentMap } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n fieldIndexGetKeyOrder,\n fieldIndexToString,\n IndexKind,\n IndexOffset,\n indexOffsetComparator,\n IndexSegment\n} from '../model/field_index';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { TargetIndexMatcher } from '../model/target_index_matcher';\nimport { isArray, refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { logDebug } from '../util/log';\nimport { getDnfTerms } from '../util/logic_utils';\nimport { immediateSuccessor, primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { diffSortedSets, SortedSet } from '../util/sorted_set';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexManager, IndexType } from './index_manager';\nimport {\n DbCollectionParent,\n DbIndexConfiguration,\n DbIndexEntry,\n DbIndexState\n} from './indexeddb_schema';\nimport {\n DbCollectionParentKey,\n DbCollectionParentStore,\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationKey,\n DbIndexConfigurationStore,\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryKey,\n DbIndexEntryStore,\n DbIndexStateKey,\n DbIndexStateSequenceNumberIndex,\n DbIndexStateStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbIndexConfiguration,\n toDbIndexConfiguration,\n toDbIndexState\n} from './local_serializer';\nimport { MemoryCollectionParentIndex } from './memory_index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nconst LOG_TAG = 'IndexedDbIndexManager';\n\nconst EMPTY_VALUE = new Uint8Array(0);\n\n/**\n * A persisted implementation of IndexManager.\n *\n * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index\n * data as it supports multi-tab access.\n */\nexport class IndexedDbIndexManager implements IndexManager {\n /**\n * An in-memory copy of the index entries we've already written since the SDK\n * launched. Used to avoid re-writing the same entry repeatedly.\n *\n * This is *NOT* a complete cache of what's in persistence and so can never be\n * used to satisfy reads.\n */\n private collectionParentsCache = new MemoryCollectionParentIndex();\n\n private uid: string;\n\n /**\n * Maps from a target to its equivalent list of sub-targets. Each sub-target\n * contains only one term from the target's disjunctive normal form (DNF).\n */\n private targetToDnfSubTargets = new ObjectMap<Target, Target[]>(\n t => canonifyTarget(t),\n (l, r) => targetEquals(l, r)\n );\n\n constructor(private user: User, private readonly databaseId: DatabaseId) {\n this.uid = user.uid || '';\n }\n\n /**\n * Adds a new entry to the collection parent index.\n *\n * Repeated calls for the same collectionPath should be avoided within a\n * transaction as IndexedDbIndexManager only caches writes once a transaction\n * has been committed.\n */\n addToCollectionParentIndex(\n transaction: PersistenceTransaction,\n collectionPath: ResourcePath\n ): PersistencePromise<void> {\n debugAssert(collectionPath.length % 2 === 1, 'Expected a collection path.');\n if (!this.collectionParentsCache.has(collectionPath)) {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n\n transaction.addOnCommittedListener(() => {\n // Add the collection to the in memory cache only if the transaction was\n // successfully committed.\n this.collectionParentsCache.add(collectionPath);\n });\n\n const collectionParent: DbCollectionParent = {\n collectionId,\n parent: encodeResourcePath(parentPath)\n };\n return collectionParentsStore(transaction).put(collectionParent);\n }\n return PersistencePromise.resolve();\n }\n\n getCollectionParents(\n transaction: PersistenceTransaction,\n collectionId: string\n ): PersistencePromise<ResourcePath[]> {\n const parentPaths = [] as ResourcePath[];\n const range = IDBKeyRange.bound(\n [collectionId, ''],\n [immediateSuccessor(collectionId), ''],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n return collectionParentsStore(transaction)\n .loadAll(range)\n .next(entries => {\n for (const entry of entries) {\n // This collectionId guard shouldn't be necessary (and isn't as long\n // as we're running in a real browser), but there's a bug in\n // indexeddbshim that breaks our range in our tests running in node:\n // https://github.com/axemclion/IndexedDBShim/issues/334\n if (entry.collectionId !== collectionId) {\n break;\n }\n parentPaths.push(decodeResourcePath(entry.parent));\n }\n return parentPaths;\n });\n }\n\n addFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise<void> {\n // TODO(indexing): Verify that the auto-incrementing index ID works in\n // Safari & Firefox.\n const indexes = indexConfigurationStore(transaction);\n const dbIndex = toDbIndexConfiguration(index);\n delete dbIndex.indexId; // `indexId` is auto-populated by IndexedDb\n const result = indexes.add(dbIndex);\n if (index.indexState) {\n const states = indexStateStore(transaction);\n return result.next(indexId => {\n states.put(\n toDbIndexState(\n indexId,\n this.user,\n index.indexState.sequenceNumber,\n index.indexState.offset\n )\n );\n });\n } else {\n return result.next();\n }\n }\n\n deleteFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise<void> {\n const indexes = indexConfigurationStore(transaction);\n const states = indexStateStore(transaction);\n const entries = indexEntriesStore(transaction);\n return indexes\n .delete(index.indexId)\n .next(() =>\n states.delete(\n IDBKeyRange.bound(\n [index.indexId],\n [index.indexId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n )\n )\n )\n .next(() =>\n entries.delete(\n IDBKeyRange.bound(\n [index.indexId],\n [index.indexId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n )\n )\n );\n }\n\n deleteAllFieldIndexes(\n transaction: PersistenceTransaction\n ): PersistencePromise<void> {\n const indexes = indexConfigurationStore(transaction);\n const entries = indexEntriesStore(transaction);\n const states = indexStateStore(transaction);\n\n return indexes\n .deleteAll()\n .next(() => entries.deleteAll())\n .next(() => states.deleteAll());\n }\n\n createTargetIndexes(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<void> {\n return PersistencePromise.forEach(\n this.getSubTargets(target),\n (subTarget: Target) => {\n return this.getIndexType(transaction, subTarget).next(type => {\n if (type === IndexType.NONE || type === IndexType.PARTIAL) {\n const targetIndexMatcher = new TargetIndexMatcher(subTarget);\n const fieldIndex = targetIndexMatcher.buildTargetIndex();\n if (fieldIndex != null) {\n return this.addFieldIndex(transaction, fieldIndex);\n }\n }\n });\n }\n );\n }\n\n getDocumentsMatchingTarget(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<DocumentKey[] | null> {\n const indexEntries = indexEntriesStore(transaction);\n\n let canServeTarget = true;\n const indexes = new Map<Target, FieldIndex | null>();\n\n return PersistencePromise.forEach(\n this.getSubTargets(target),\n (subTarget: Target) => {\n return this.getFieldIndex(transaction, subTarget).next(index => {\n canServeTarget &&= !!index;\n indexes.set(subTarget, index);\n });\n }\n ).next(() => {\n if (!canServeTarget) {\n return PersistencePromise.resolve(null as DocumentKey[] | null);\n } else {\n let existingKeys = documentKeySet();\n const result: DocumentKey[] = [];\n return PersistencePromise.forEach(indexes, (index, subTarget) => {\n logDebug(\n LOG_TAG,\n `Using index ${fieldIndexToString(\n index!\n )} to execute ${canonifyTarget(target)}`\n );\n\n const arrayValues = targetGetArrayValues(subTarget, index!);\n const notInValues = targetGetNotInValues(subTarget, index!);\n const lowerBound = targetGetLowerBound(subTarget, index!);\n const upperBound = targetGetUpperBound(subTarget, index!);\n\n const lowerBoundEncoded = this.encodeBound(\n index!,\n subTarget,\n lowerBound\n );\n const upperBoundEncoded = this.encodeBound(\n index!,\n subTarget,\n upperBound\n );\n const notInEncoded = this.encodeValues(\n index!,\n subTarget,\n notInValues\n );\n\n const indexRanges = this.generateIndexRanges(\n index!.indexId,\n arrayValues,\n lowerBoundEncoded,\n lowerBound.inclusive,\n upperBoundEncoded,\n upperBound.inclusive,\n notInEncoded\n );\n return PersistencePromise.forEach(\n indexRanges,\n (indexRange: IDBKeyRange) => {\n return indexEntries\n .loadFirst(indexRange, target.limit)\n .next(entries => {\n entries.forEach(entry => {\n const documentKey = DocumentKey.fromSegments(\n entry.documentKey\n );\n if (!existingKeys.has(documentKey)) {\n existingKeys = existingKeys.add(documentKey);\n result.push(documentKey);\n }\n });\n });\n }\n );\n }).next(() => result as DocumentKey[] | null);\n }\n });\n }\n\n private getSubTargets(target: Target): Target[] {\n let subTargets = this.targetToDnfSubTargets.get(target);\n if (subTargets) {\n return subTargets;\n }\n\n if (target.filters.length === 0) {\n subTargets = [target];\n } else {\n // There is an implicit AND operation between all the filters stored in the target\n const dnf: Filter[] = getDnfTerms(\n CompositeFilter.create(target.filters, CompositeOperator.AND)\n );\n\n subTargets = dnf.map(term =>\n newTarget(\n target.path,\n target.collectionGroup,\n target.orderBy,\n term.getFilters(),\n target.limit,\n target.startAt,\n target.endAt\n )\n );\n }\n\n this.targetToDnfSubTargets.set(target, subTargets);\n return subTargets;\n }\n\n /**\n * Constructs a key range query on `DbIndexEntryStore` that unions all\n * bounds.\n */\n private generateIndexRanges(\n indexId: number,\n arrayValues: ProtoValue[] | null,\n lowerBounds: Uint8Array[],\n lowerBoundInclusive: boolean,\n upperBounds: Uint8Array[],\n upperBoundInclusive: boolean,\n notInValues: Uint8Array[]\n ): IDBKeyRange[] {\n // The number of total index scans we union together. This is similar to a\n // distributed normal form, but adapted for array values. We create a single\n // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter\n // combined with the values from the query bounds.\n const totalScans =\n (arrayValues != null ? arrayValues.length : 1) *\n Math.max(lowerBounds.length, upperBounds.length);\n const scansPerArrayElement =\n totalScans / (arrayValues != null ? arrayValues.length : 1);\n\n const indexRanges: IDBKeyRange[] = [];\n for (let i = 0; i < totalScans; ++i) {\n const arrayValue = arrayValues\n ? this.encodeSingleElement(arrayValues[i / scansPerArrayElement])\n : EMPTY_VALUE;\n\n const lowerBound = this.generateLowerBound(\n indexId,\n arrayValue,\n lowerBounds[i % scansPerArrayElement],\n lowerBoundInclusive\n );\n const upperBound = this.generateUpperBound(\n indexId,\n arrayValue,\n upperBounds[i % scansPerArrayElement],\n upperBoundInclusive\n );\n\n const notInBound = notInValues.map(notIn =>\n this.generateLowerBound(\n indexId,\n arrayValue,\n notIn,\n /* inclusive= */ true\n )\n );\n\n indexRanges.push(...this.createRange(lowerBound, upperBound, notInBound));\n }\n\n return indexRanges;\n }\n\n /** Generates the lower bound for `arrayValue` and `directionalValue`. */\n private generateLowerBound(\n indexId: number,\n arrayValue: Uint8Array,\n directionalValue: Uint8Array,\n inclusive: boolean\n ): IndexEntry {\n const entry = new IndexEntry(\n indexId,\n DocumentKey.empty(),\n arrayValue,\n directionalValue\n );\n return inclusive ? entry : entry.successor();\n }\n\n /** Generates the upper bound for `arrayValue` and `directionalValue`. */\n private generateUpperBound(\n indexId: number,\n arrayValue: Uint8Array,\n directionalValue: Uint8Array,\n inclusive: boolean\n ): IndexEntry {\n const entry = new IndexEntry(\n indexId,\n DocumentKey.empty(),\n arrayValue,\n directionalValue\n );\n return inclusive ? entry.successor() : entry;\n }\n\n private getFieldIndex(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<FieldIndex | null> {\n const targetIndexMatcher = new TargetIndexMatcher(target);\n const collectionGroup =\n target.collectionGroup != null\n ? target.collectionGroup\n : target.path.lastSegment();\n\n return this.getFieldIndexes(transaction, collectionGroup).next(indexes => {\n // Return the index with the most number of segments.\n let index: FieldIndex | null = null;\n for (const candidate of indexes) {\n const matches = targetIndexMatcher.servedByIndex(candidate);\n if (\n matches &&\n (!index || candidate.fields.length > index.fields.length)\n ) {\n index = candidate;\n }\n }\n return index;\n });\n }\n\n getIndexType(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<IndexType> {\n let indexType = IndexType.FULL;\n const subTargets = this.getSubTargets(target);\n return PersistencePromise.forEach(subTargets, (target: Target) => {\n return this.getFieldIndex(transaction, target).next(index => {\n if (!index) {\n indexType = IndexType.NONE;\n } else if (\n indexType !== IndexType.NONE &&\n index.fields.length < targetGetSegmentCount(target)\n ) {\n indexType = IndexType.PARTIAL;\n }\n });\n }).next(() => {\n // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider\n // OR queries that have a `limit` to have a partial index. For such queries we perform sorting\n // and apply the limit in memory as a post-processing step.\n if (\n targetHasLimit(target) &&\n subTargets.length > 1 &&\n indexType === IndexType.FULL\n ) {\n return IndexType.PARTIAL;\n }\n\n return indexType;\n });\n }\n\n /**\n * Returns the byte encoded form of the directional values in the field index.\n * Returns `null` if the document does not have all fields specified in the\n * index.\n */\n private encodeDirectionalElements(\n fieldIndex: FieldIndex,\n document: Document\n ): Uint8Array | null {\n const encoder = new IndexByteEncoder();\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const field = document.data.field(segment.fieldPath);\n if (field == null) {\n return null;\n }\n const directionalEncoder = encoder.forKind(segment.kind);\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n field,\n directionalEncoder\n );\n }\n return encoder.encodedBytes();\n }\n\n /** Encodes a single value to the ascending index format. */\n private encodeSingleElement(value: ProtoValue): Uint8Array {\n const encoder = new IndexByteEncoder();\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n value,\n encoder.forKind(IndexKind.ASCENDING)\n );\n return encoder.encodedBytes();\n }\n\n /**\n * Returns an encoded form of the document key that sorts based on the key\n * ordering of the field index.\n */\n private encodeDirectionalKey(\n fieldIndex: FieldIndex,\n documentKey: DocumentKey\n ): Uint8Array {\n const encoder = new IndexByteEncoder();\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n refValue(this.databaseId, documentKey),\n encoder.forKind(fieldIndexGetKeyOrder(fieldIndex))\n );\n return encoder.encodedBytes();\n }\n\n /**\n * Encodes the given field values according to the specification in `target`.\n * For IN queries, a list of possible values is returned.\n */\n private encodeValues(\n fieldIndex: FieldIndex,\n target: Target,\n values: ProtoValue[] | null\n ): Uint8Array[] {\n if (values === null) {\n return [];\n }\n\n let encoders: IndexByteEncoder[] = [];\n encoders.push(new IndexByteEncoder());\n\n let valueIdx = 0;\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const value = values[valueIdx++];\n for (const encoder of encoders) {\n if (this.isInFilter(target, segment.fieldPath) && isArray(value)) {\n encoders = this.expandIndexValues(encoders, segment, value);\n } else {\n const directionalEncoder = encoder.forKind(segment.kind);\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n value,\n directionalEncoder\n );\n }\n }\n }\n return this.getEncodedBytes(encoders);\n }\n\n /**\n * Encodes the given bounds according to the specification in `target`. For IN\n * queries, a list of possible values is returned.\n */\n private encodeBound(\n fieldIndex: FieldIndex,\n target: Target,\n bound: Bound\n ): Uint8Array[] {\n return this.encodeValues(fieldIndex, target, bound.position);\n }\n\n /** Returns the byte representation for the provided encoders. */\n private getEncodedBytes(encoders: IndexByteEncoder[]): Uint8Array[] {\n const result: Uint8Array[] = [];\n for (let i = 0; i < encoders.length; ++i) {\n result[i] = encoders[i].encodedBytes();\n }\n return result;\n }\n\n /**\n * Creates a separate encoder for each element of an array.\n *\n * The method appends each value to all existing encoders (e.g. filter(\"a\",\n * \"==\", \"a1\").filter(\"b\", \"in\", [\"b1\", \"b2\"]) becomes [\"a1,b1\", \"a1,b2\"]). A\n * list of new encoders is returned.\n */\n private expandIndexValues(\n encoders: IndexByteEncoder[],\n segment: IndexSegment,\n value: ProtoValue\n ): IndexByteEncoder[] {\n const prefixes = [...encoders];\n const results: IndexByteEncoder[] = [];\n for (const arrayElement of value.arrayValue!.values || []) {\n for (const prefix of prefixes) {\n const clonedEncoder = new IndexByteEncoder();\n clonedEncoder.seed(prefix.encodedBytes());\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n arrayElement,\n clonedEncoder.forKind(segment.kind)\n );\n results.push(clonedEncoder);\n }\n }\n return results;\n }\n\n private isInFilter(target: Target, fieldPath: FieldPath): boolean {\n return !!target.filters.find(\n f =>\n f instanceof FieldFilter &&\n f.field.isEqual(fieldPath) &&\n (f.op === Operator.IN || f.op === Operator.NOT_IN)\n );\n }\n\n getFieldIndexes(\n transaction: PersistenceTransaction,\n collectionGroup?: string\n ): PersistencePromise<FieldIndex[]> {\n const indexes = indexConfigurationStore(transaction);\n const states = indexStateStore(transaction);\n\n return (\n collectionGroup\n ? indexes.loadAll(\n DbIndexConfigurationCollectionGroupIndex,\n IDBKeyRange.bound(collectionGroup, collectionGroup)\n )\n : indexes.loadAll()\n ).next(indexConfigs => {\n const result: FieldIndex[] = [];\n return PersistencePromise.forEach(\n indexConfigs,\n (indexConfig: DbIndexConfiguration) => {\n return states\n .get([indexConfig.indexId!, this.uid])\n .next(indexState => {\n result.push(fromDbIndexConfiguration(indexConfig, indexState));\n });\n }\n ).next(() => result);\n });\n }\n\n getNextCollectionGroupToUpdate(\n transaction: PersistenceTransaction\n ): PersistencePromise<string | null> {\n return this.getFieldIndexes(transaction).next(indexes => {\n if (indexes.length === 0) {\n return null;\n }\n indexes.sort((l, r) => {\n const cmp = l.indexState.sequenceNumber - r.indexState.sequenceNumber;\n return cmp !== 0\n ? cmp\n : primitiveComparator(l.collectionGroup, r.collectionGroup);\n });\n return indexes[0].collectionGroup;\n });\n }\n\n updateCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset\n ): PersistencePromise<void> {\n const indexes = indexConfigurationStore(transaction);\n const states = indexStateStore(transaction);\n return this.getNextSequenceNumber(transaction).next(nextSequenceNumber =>\n indexes\n .loadAll(\n DbIndexConfigurationCollectionGroupIndex,\n IDBKeyRange.bound(collectionGroup, collectionGroup)\n )\n .next(configs =>\n PersistencePromise.forEach(configs, (config: DbIndexConfiguration) =>\n states.put(\n toDbIndexState(\n config.indexId!,\n this.user,\n nextSequenceNumber,\n offset\n )\n )\n )\n )\n );\n }\n\n updateIndexEntries(\n transaction: PersistenceTransaction,\n documents: DocumentMap\n ): PersistencePromise<void> {\n // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as\n // it could be used across different IndexedDB transactions. As any cached\n // data might be invalidated by other multi-tab clients, we can only trust\n // data within a single IndexedDB transaction. We therefore add a cache\n // here.\n const memoizedIndexes = new Map<string, FieldIndex[]>();\n return PersistencePromise.forEach(documents, (key, doc) => {\n const memoizedCollectionIndexes = memoizedIndexes.get(\n key.collectionGroup\n );\n const fieldIndexes = memoizedCollectionIndexes\n ? PersistencePromise.resolve(memoizedCollectionIndexes)\n : this.getFieldIndexes(transaction, key.collectionGroup);\n\n return fieldIndexes.next(fieldIndexes => {\n memoizedIndexes.set(key.collectionGroup, fieldIndexes);\n return PersistencePromise.forEach(\n fieldIndexes,\n (fieldIndex: FieldIndex) => {\n return this.getExistingIndexEntries(\n transaction,\n key,\n fieldIndex\n ).next(existingEntries => {\n const newEntries = this.computeIndexEntries(doc, fieldIndex);\n if (!existingEntries.isEqual(newEntries)) {\n return this.updateEntries(\n transaction,\n doc,\n fieldIndex,\n existingEntries,\n newEntries\n );\n }\n return PersistencePromise.resolve();\n });\n }\n );\n });\n });\n }\n\n private addIndexEntry(\n transaction: PersistenceTransaction,\n document: Document,\n fieldIndex: FieldIndex,\n indexEntry: IndexEntry\n ): PersistencePromise<void> {\n const indexEntries = indexEntriesStore(transaction);\n return indexEntries.put({\n indexId: indexEntry.indexId,\n uid: this.uid,\n arrayValue: indexEntry.arrayValue,\n directionalValue: indexEntry.directionalValue,\n orderedDocumentKey: this.encodeDirectionalKey(fieldIndex, document.key),\n documentKey: document.key.path.toArray()\n });\n }\n\n private deleteIndexEntry(\n transaction: PersistenceTransaction,\n document: Document,\n fieldIndex: FieldIndex,\n indexEntry: IndexEntry\n ): PersistencePromise<void> {\n const indexEntries = indexEntriesStore(transaction);\n return indexEntries.delete([\n indexEntry.indexId,\n this.uid,\n indexEntry.arrayValue,\n indexEntry.directionalValue,\n this.encodeDirectionalKey(fieldIndex, document.key),\n document.key.path.toArray()\n ]);\n }\n\n private getExistingIndexEntries(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey,\n fieldIndex: FieldIndex\n ): PersistencePromise<SortedSet<IndexEntry>> {\n const indexEntries = indexEntriesStore(transaction);\n let results = new SortedSet<IndexEntry>(indexEntryComparator);\n return indexEntries\n .iterate(\n {\n index: DbIndexEntryDocumentKeyIndex,\n range: IDBKeyRange.only([\n fieldIndex.indexId,\n this.uid,\n this.encodeDirectionalKey(fieldIndex, documentKey)\n ])\n },\n (_, entry) => {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n documentKey,\n entry.arrayValue,\n entry.directionalValue\n )\n );\n }\n )\n .next(() => results);\n }\n\n /** Creates the index entries for the given document. */\n private computeIndexEntries(\n document: Document,\n fieldIndex: FieldIndex\n ): SortedSet<IndexEntry> {\n let results = new SortedSet<IndexEntry>(indexEntryComparator);\n\n const directionalValue = this.encodeDirectionalElements(\n fieldIndex,\n document\n );\n if (directionalValue == null) {\n return results;\n }\n\n const arraySegment = fieldIndexGetArraySegment(fieldIndex);\n if (arraySegment != null) {\n const value = document.data.field(arraySegment.fieldPath);\n if (isArray(value)) {\n for (const arrayValue of value.arrayValue!.values || []) {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n document.key,\n this.encodeSingleElement(arrayValue),\n directionalValue\n )\n );\n }\n }\n } else {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n document.key,\n EMPTY_VALUE,\n directionalValue\n )\n );\n }\n\n return results;\n }\n\n /**\n * Updates the index entries for the provided document by deleting entries\n * that are no longer referenced in `newEntries` and adding all newly added\n * entries.\n */\n private updateEntries(\n transaction: PersistenceTransaction,\n document: Document,\n fieldIndex: FieldIndex,\n existingEntries: SortedSet<IndexEntry>,\n newEntries: SortedSet<IndexEntry>\n ): PersistencePromise<void> {\n logDebug(LOG_TAG, \"Updating index entries for document '%s'\", document.key);\n\n const promises: Array<PersistencePromise<void>> = [];\n diffSortedSets(\n existingEntries,\n newEntries,\n indexEntryComparator,\n /* onAdd= */ entry => {\n promises.push(\n this.addIndexEntry(transaction, document, fieldIndex, entry)\n );\n },\n /* onRemove= */ entry => {\n promises.push(\n this.deleteIndexEntry(transaction, document, fieldIndex, entry)\n );\n }\n );\n\n return PersistencePromise.waitFor(promises);\n }\n\n private getNextSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise<number> {\n let nextSequenceNumber = 1;\n const states = indexStateStore(transaction);\n return states\n .iterate(\n {\n index: DbIndexStateSequenceNumberIndex,\n reverse: true,\n range: IDBKeyRange.upperBound([this.uid, Number.MAX_SAFE_INTEGER])\n },\n (_, state, controller) => {\n controller.done();\n nextSequenceNumber = state.sequenceNumber + 1;\n }\n )\n .next(() => nextSequenceNumber);\n }\n\n /**\n * Returns a new set of IDB ranges that splits the existing range and excludes\n * any values that match the `notInValue` from these ranges. As an example,\n * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.\n */\n private createRange(\n lower: IndexEntry,\n upper: IndexEntry,\n notInValues: IndexEntry[]\n ): IDBKeyRange[] {\n // The notIn values need to be sorted and unique so that we can return a\n // sorted set of non-overlapping ranges.\n notInValues = notInValues\n .sort((l, r) => indexEntryComparator(l, r))\n .filter(\n (el, i, values) => !i || indexEntryComparator(el, values[i - 1]) !== 0\n );\n\n const bounds: IndexEntry[] = [];\n bounds.push(lower);\n for (const notInValue of notInValues) {\n const cmpToLower = indexEntryComparator(notInValue, lower);\n const cmpToUpper = indexEntryComparator(notInValue, upper);\n\n if (cmpToLower === 0) {\n // `notInValue` is the lower bound. We therefore need to raise the bound\n // to the next value.\n bounds[0] = lower.successor();\n } else if (cmpToLower > 0 && cmpToUpper < 0) {\n // `notInValue` is in the middle of the range\n bounds.push(notInValue);\n bounds.push(notInValue.successor());\n } else if (cmpToUpper > 0) {\n // `notInValue` (and all following values) are out of the range\n break;\n }\n }\n bounds.push(upper);\n\n const ranges: IDBKeyRange[] = [];\n for (let i = 0; i < bounds.length; i += 2) {\n // If we encounter two bounds that will create an unmatchable key range,\n // then we return an empty set of key ranges.\n if (this.isRangeMatchable(bounds[i], bounds[i + 1])) {\n return [];\n }\n\n const lowerBound = [\n bounds[i].indexId,\n this.uid,\n bounds[i].arrayValue,\n bounds[i].directionalValue,\n EMPTY_VALUE,\n []\n ] as DbIndexEntryKey;\n\n const upperBound = [\n bounds[i + 1].indexId,\n this.uid,\n bounds[i + 1].arrayValue,\n bounds[i + 1].directionalValue,\n EMPTY_VALUE,\n []\n ] as DbIndexEntryKey;\n\n ranges.push(IDBKeyRange.bound(lowerBound, upperBound));\n }\n return ranges;\n }\n\n isRangeMatchable(lowerBound: IndexEntry, upperBound: IndexEntry): boolean {\n // If lower bound is greater than the upper bound, then the key\n // range can never be matched.\n return indexEntryComparator(lowerBound, upperBound) > 0;\n }\n\n getMinOffsetFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string\n ): PersistencePromise<IndexOffset> {\n return this.getFieldIndexes(transaction, collectionGroup).next(\n getMinOffsetFromFieldIndexes\n );\n }\n\n getMinOffset(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<IndexOffset> {\n return PersistencePromise.mapArray(\n this.getSubTargets(target),\n (subTarget: Target) =>\n this.getFieldIndex(transaction, subTarget).next(index =>\n index ? index : fail('Target cannot be served from index')\n )\n ).next(getMinOffsetFromFieldIndexes);\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the collectionParents\n * document store.\n */\nfunction collectionParentsStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbCollectionParentKey, DbCollectionParent> {\n return getStore<DbCollectionParentKey, DbCollectionParent>(\n txn,\n DbCollectionParentStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index entry object store.\n */\nfunction indexEntriesStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbIndexEntryKey, DbIndexEntry> {\n return getStore<DbIndexEntryKey, DbIndexEntry>(txn, DbIndexEntryStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index configuration object store.\n */\nfunction indexConfigurationStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbIndexConfigurationKey, DbIndexConfiguration> {\n return getStore<DbIndexConfigurationKey, DbIndexConfiguration>(\n txn,\n DbIndexConfigurationStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index state object store.\n */\nfunction indexStateStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbIndexStateKey, DbIndexState> {\n return getStore<DbIndexStateKey, DbIndexState>(txn, DbIndexStateStore);\n}\n\nfunction getMinOffsetFromFieldIndexes(fieldIndexes: FieldIndex[]): IndexOffset {\n hardAssert(\n fieldIndexes.length !== 0,\n 'Found empty index group when looking for least recent index offset.'\n );\n\n let minOffset: IndexOffset = fieldIndexes[0].indexState.offset;\n let maxBatchId: number = minOffset.largestBatchId;\n for (let i = 1; i < fieldIndexes.length; i++) {\n const newOffset: IndexOffset = fieldIndexes[i].indexState.offset;\n if (indexOffsetComparator(newOffset, minOffset) < 0) {\n minOffset = newOffset;\n }\n if (maxBatchId < newOffset.largestBatchId) {\n maxBatchId = newOffset.largestBatchId;\n }\n }\n return new IndexOffset(minOffset.readTime, minOffset.documentKey, maxBatchId);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/**\n * Describes a map whose keys are active target ids. We do not care about the type of the\n * values.\n */\nexport type ActiveTargets = SortedMap<TargetId, unknown>;\n\nexport const GC_DID_NOT_RUN: LruResults = {\n didRun: false,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nexport const LRU_COLLECTION_DISABLED = -1;\nexport const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\n\nexport class LruParams {\n private static readonly DEFAULT_COLLECTION_PERCENTILE = 10;\n private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000;\n\n static withCacheSize(cacheSize: number): LruParams {\n return new LruParams(\n cacheSize,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n }\n\n static readonly DEFAULT: LruParams = new LruParams(\n LRU_DEFAULT_CACHE_SIZE_BYTES,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n\n static readonly DISABLED: LruParams = new LruParams(\n LRU_COLLECTION_DISABLED,\n 0,\n 0\n );\n\n constructor(\n // When we attempt to collect, we will only do so if the cache size is greater than this\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n readonly cacheSizeCollectionThreshold: number,\n // The percentage of sequence numbers that we will attempt to collect\n readonly percentileToCollect: number,\n // A cap on the total number of sequence numbers that will be collected. This prevents\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\n readonly maximumSequenceNumbersToCollect: number\n ) {}\n}\n\nexport interface LruGarbageCollector {\n readonly params: LruParams;\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<LruResults>;\n\n /** Given a percentile of target to collect, returns the number of targets to collect. */\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise<number>;\n\n /** Returns the nth sequence number, counting in order from the smallest. */\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise<number>;\n\n /**\n * Removes documents that have a sequence number equal to or less than the\n * upper bound and are not otherwise pinned.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number>;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number>;\n\n /**\n * Removes targets with a sequence number equal to or less than the given\n * upper bound, and removes document associations with those targets.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number>;\n}\n\n/**\n * Describes the results of a garbage collection run. `didRun` will be set to\n * `false` if collection was skipped (either it is disabled or the cache size\n * has not hit the threshold). If collection ran, the other fields will be\n * filled in with the details of the results.\n */\nexport interface LruResults {\n readonly didRun: boolean;\n readonly sequenceNumbersCollected: number;\n readonly targetsRemoved: number;\n readonly documentsRemoved: number;\n}\n\n/**\n * Persistence layers intending to use LRU Garbage collection should have\n * reference delegates that implement this interface. This interface defines the\n * operations that the LRU garbage collector needs from the persistence layer.\n */\nexport interface LruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n /** Enumerates all the targets in the TargetCache. */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (target: TargetData) => void\n ): PersistencePromise<void>;\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number>;\n\n /**\n * Enumerates sequence numbers for documents not associated with a target.\n * Note that this may include duplicate sequence numbers.\n */\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise<void>;\n\n /**\n * Removes all targets that have a sequence number less than or equal to\n * `upperBound`, and are not present in the `activeTargetIds` set.\n *\n * @returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number>;\n\n /**\n * Removes all unreferenced documents from the cache that have a sequence\n * number less than or equal to the given `upperBound`.\n *\n * @returns the number of documents removed.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number>;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number>;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TargetId } from './types';\n\n/** Offset to ensure non-overlapping target ids. */\nconst OFFSET = 2;\n\n/**\n * Generates monotonically increasing target IDs for sending targets to the\n * watch stream.\n *\n * The client constructs two generators, one for the target cache, and one for\n * for the sync engine (to generate limbo documents targets). These\n * generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\nexport class TargetIdGenerator {\n constructor(private lastId: number) {}\n\n next(): TargetId {\n this.lastId += OFFSET;\n return this.lastId;\n }\n\n static forTargetCache(): TargetIdGenerator {\n // The target cache generator must return '2' in its first call to `next()`\n // as there is no differentiation in the protocol layer between an unset\n // number and the number '0'. If we were to sent a target with target ID\n // '0', the backend would consider it unset and replace it with its own ID.\n return new TargetIdGenerator(2 - OFFSET);\n }\n\n static forSyncEngine(): TargetIdGenerator {\n // Sync engine assigns target IDs for limbo document detection.\n return new TargetIdGenerator(1 - OFFSET);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, MutableDocumentMap } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */\nexport abstract class RemoteDocumentChangeBuffer {\n // A mapping of document key to the new cache entry that should be written.\n protected changes: ObjectMap<DocumentKey, MutableDocument> = new ObjectMap(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\n\n private changesApplied = false;\n\n protected abstract getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MutableDocument>;\n\n protected abstract getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<MutableDocumentMap>;\n\n protected abstract applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise<void>;\n\n /**\n * Buffers a `RemoteDocumentCache.addEntry()` call.\n *\n * You can only modify documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */\n addEntry(document: MutableDocument): void {\n this.assertNotApplied();\n this.changes.set(document.key, document);\n }\n\n /**\n * Buffers a `RemoteDocumentCache.removeEntry()` call.\n *\n * You can only remove documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */\n removeEntry(key: DocumentKey, readTime: SnapshotVersion): void {\n this.assertNotApplied();\n this.changes.set(\n key,\n MutableDocument.newInvalidDocument(key).setReadTime(readTime)\n );\n }\n\n /**\n * Looks up an entry in the cache. The buffered changes will first be checked,\n * and if no buffered change applies, this will forward to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document or an invalid document if we have nothing\n * cached.\n */\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MutableDocument> {\n this.assertNotApplied();\n const bufferedEntry = this.changes.get(documentKey);\n if (bufferedEntry !== undefined) {\n return PersistencePromise.resolve(bufferedEntry);\n } else {\n return this.getFromCache(transaction, documentKey);\n }\n }\n\n /**\n * Looks up several entries in the cache, forwarding to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKeys - The keys of the entries to look up.\n * @returns A map of cached documents, indexed by key. If an entry cannot be\n * found, the corresponding key will be mapped to an invalid document.\n */\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<MutableDocumentMap> {\n return this.getAllFromCache(transaction, documentKeys);\n }\n\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */\n apply(transaction: PersistenceTransaction): PersistencePromise<void> {\n this.assertNotApplied();\n this.changesApplied = true;\n return this.applyChanges(transaction);\n }\n\n /** Helper to assert this.changes is not null */\n protected assertNotApplied(): void {\n debugAssert(!this.changesApplied, 'Changes have already been applied.');\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { FieldMask } from '../model/field_mask';\n\n/**\n * Represents a local view (overlay) of a document, and the fields that are\n * locally mutated.\n */\nexport class OverlayedDocument {\n constructor(\n readonly overlayedDocument: Document,\n\n /**\n * The fields that are locally mutated by patch mutations.\n *\n * If the overlayed\tdocument is from set or delete mutations, this is `null`.\n * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.\n */\n readonly mutatedFields: FieldMask | null\n ) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n asCollectionQueryAtPath,\n isCollectionGroupQuery,\n isDocumentQuery,\n Query,\n queryMatches\n} from '../core/query';\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n DocumentKeySet,\n OverlayMap,\n DocumentMap,\n MutableDocumentMap,\n newDocumentKeyMap,\n newMutationMap,\n newOverlayMap,\n documentMap,\n mutableDocumentMap,\n documentKeySet,\n DocumentKeyMap,\n convertOverlayedDocumentMapToDocumentMap,\n OverlayedDocumentMap,\n newOverlayedDocumentMap\n} from '../model/collections';\nimport { Document, MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexOffset, INITIAL_LARGEST_BATCH_ID } from '../model/field_index';\nimport { FieldMask } from '../model/field_mask';\nimport {\n calculateOverlayMutation,\n mutationApplyToLocalView,\n PatchMutation\n} from '../model/mutation';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { LocalWriteResult } from './local_store_impl';\nimport { MutationQueue } from './mutation_queue';\nimport { OverlayedDocument } from './overlayed_document';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { RemoteDocumentCache } from './remote_document_cache';\n\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */\nexport class LocalDocumentsView {\n constructor(\n readonly remoteDocumentCache: RemoteDocumentCache,\n readonly mutationQueue: MutationQueue,\n readonly documentOverlayCache: DocumentOverlayCache,\n readonly indexManager: IndexManager\n ) {}\n\n /**\n * Get the local view of the document identified by `key`.\n *\n * @returns Local view of the document or null if we don't have any cached\n * state for it.\n */\n getDocument(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<Document> {\n let overlay: Overlay | null = null;\n return this.documentOverlayCache\n .getOverlay(transaction, key)\n .next(value => {\n overlay = value;\n return this.remoteDocumentCache.getEntry(transaction, key);\n })\n .next(document => {\n if (overlay !== null) {\n mutationApplyToLocalView(\n overlay.mutation,\n document,\n FieldMask.empty(),\n Timestamp.now()\n );\n }\n return document as Document;\n });\n }\n\n /**\n * Gets the local view of the documents identified by `keys`.\n *\n * If we don't have cached state for a document in `keys`, a NoDocument will\n * be stored for that key in the resulting set.\n */\n getDocuments(\n transaction: PersistenceTransaction,\n keys: DocumentKeySet\n ): PersistencePromise<DocumentMap> {\n return this.remoteDocumentCache\n .getEntries(transaction, keys)\n .next(docs =>\n this.getLocalViewOfDocuments(transaction, docs, documentKeySet()).next(\n () => docs as DocumentMap\n )\n );\n }\n\n /**\n * Similar to `getDocuments`, but creates the local view from the given\n * `baseDocs` without retrieving documents from the local store.\n *\n * @param transaction - The transaction this operation is scoped to.\n * @param docs - The documents to apply local mutations to get the local views.\n * @param existenceStateChanged - The set of document keys whose existence state\n * is changed. This is useful to determine if some documents overlay needs\n * to be recalculated.\n */\n getLocalViewOfDocuments(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap,\n existenceStateChanged: DocumentKeySet = documentKeySet()\n ): PersistencePromise<DocumentMap> {\n const overlays = newOverlayMap();\n return this.populateOverlays(transaction, overlays, docs).next(() => {\n return this.computeViews(\n transaction,\n docs,\n overlays,\n existenceStateChanged\n ).next(computeViewsResult => {\n let result = documentMap();\n computeViewsResult.forEach((documentKey, overlayedDocument) => {\n result = result.insert(\n documentKey,\n overlayedDocument.overlayedDocument\n );\n });\n return result;\n });\n });\n }\n\n /**\n * Gets the overlayed documents for the given document map, which will include\n * the local view of those documents and a `FieldMask` indicating which fields\n * are mutated locally, `null` if overlay is a Set or Delete mutation.\n */\n getOverlayedDocuments(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap\n ): PersistencePromise<OverlayedDocumentMap> {\n const overlays = newOverlayMap();\n return this.populateOverlays(transaction, overlays, docs).next(() =>\n this.computeViews(transaction, docs, overlays, documentKeySet())\n );\n }\n\n /**\n * Fetches the overlays for {@code docs} and adds them to provided overlay map\n * if the map does not already contain an entry for the given document key.\n */\n private populateOverlays(\n transaction: PersistenceTransaction,\n overlays: OverlayMap,\n docs: MutableDocumentMap\n ): PersistencePromise<void> {\n const missingOverlays: DocumentKey[] = [];\n docs.forEach(key => {\n if (!overlays.has(key)) {\n missingOverlays.push(key);\n }\n });\n return this.documentOverlayCache\n .getOverlays(transaction, missingOverlays)\n .next(result => {\n result.forEach((key, val) => {\n overlays.set(key, val);\n });\n });\n }\n\n /**\n * Computes the local view for the given documents.\n *\n * @param docs - The documents to compute views for. It also has the base\n * version of the documents.\n * @param overlays - The overlays that need to be applied to the given base\n * version of the documents.\n * @param existenceStateChanged - A set of documents whose existence states\n * might have changed. This is used to determine if we need to re-calculate\n * overlays from mutation queues.\n * @return A map represents the local documents view.\n */\n computeViews(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap,\n overlays: OverlayMap,\n existenceStateChanged: DocumentKeySet\n ): PersistencePromise<OverlayedDocumentMap> {\n let recalculateDocuments = mutableDocumentMap();\n const mutatedFields = newDocumentKeyMap<FieldMask | null>();\n const results = newOverlayedDocumentMap();\n docs.forEach((_, doc) => {\n const overlay = overlays.get(doc.key);\n // Recalculate an overlay if the document's existence state changed due to\n // a remote event *and* the overlay is a PatchMutation. This is because\n // document existence state can change if some patch mutation's\n // preconditions are met.\n // NOTE: we recalculate when `overlay` is undefined as well, because there\n // might be a patch mutation whose precondition does not match before the\n // change (hence overlay is undefined), but would now match.\n if (\n existenceStateChanged.has(doc.key) &&\n (overlay === undefined || overlay.mutation instanceof PatchMutation)\n ) {\n recalculateDocuments = recalculateDocuments.insert(doc.key, doc);\n } else if (overlay !== undefined) {\n mutatedFields.set(doc.key, overlay.mutation.getFieldMask());\n mutationApplyToLocalView(\n overlay.mutation,\n doc,\n overlay.mutation.getFieldMask(),\n Timestamp.now()\n );\n } else {\n // no overlay exists\n // Using EMPTY to indicate there is no overlay for the document.\n mutatedFields.set(doc.key, FieldMask.empty());\n }\n });\n\n return this.recalculateAndSaveOverlays(\n transaction,\n recalculateDocuments\n ).next(recalculatedFields => {\n recalculatedFields.forEach((documentKey, mask) =>\n mutatedFields.set(documentKey, mask)\n );\n docs.forEach((documentKey, document) =>\n results.set(\n documentKey,\n new OverlayedDocument(\n document,\n mutatedFields.get(documentKey) ?? null\n )\n )\n );\n return results;\n });\n }\n\n private recalculateAndSaveOverlays(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap\n ): PersistencePromise<DocumentKeyMap<FieldMask | null>> {\n const masks = newDocumentKeyMap<FieldMask | null>();\n // A reverse lookup map from batch id to the documents within that batch.\n let documentsByBatchId = new SortedMap<number, DocumentKeySet>(\n (key1: number, key2: number) => key1 - key2\n );\n let processed = documentKeySet();\n return this.mutationQueue\n .getAllMutationBatchesAffectingDocumentKeys(transaction, docs)\n .next(batches => {\n for (const batch of batches) {\n batch.keys().forEach(key => {\n const baseDoc = docs.get(key);\n if (baseDoc === null) {\n return;\n }\n let mask: FieldMask | null = masks.get(key) || FieldMask.empty();\n mask = batch.applyToLocalView(baseDoc, mask);\n masks.set(key, mask);\n const newSet = (\n documentsByBatchId.get(batch.batchId) || documentKeySet()\n ).add(key);\n documentsByBatchId = documentsByBatchId.insert(\n batch.batchId,\n newSet\n );\n });\n }\n })\n .next(() => {\n const promises: Array<PersistencePromise<void>> = [];\n // Iterate in descending order of batch IDs, and skip documents that are\n // already saved.\n const iter = documentsByBatchId.getReverseIterator();\n while (iter.hasNext()) {\n const entry = iter.getNext();\n const batchId = entry.key;\n const keys = entry.value;\n const overlays = newMutationMap();\n keys.forEach(key => {\n if (!processed.has(key)) {\n const overlayMutation = calculateOverlayMutation(\n docs.get(key)!,\n masks.get(key)!\n );\n if (overlayMutation !== null) {\n overlays.set(key, overlayMutation);\n }\n processed = processed.add(key);\n }\n });\n promises.push(\n this.documentOverlayCache.saveOverlays(\n transaction,\n batchId,\n overlays\n )\n );\n }\n return PersistencePromise.waitFor(promises);\n })\n .next(() => masks);\n }\n\n /**\n * Recalculates overlays by reading the documents from remote document cache\n * first, and saves them after they are calculated.\n */\n recalculateAndSaveOverlaysForDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<DocumentKeyMap<FieldMask | null>> {\n return this.remoteDocumentCache\n .getEntries(transaction, documentKeys)\n .next(docs => this.recalculateAndSaveOverlays(transaction, docs));\n }\n\n /**\n * Performs a query against the local view of all documents.\n *\n * @param transaction - The persistence transaction.\n * @param query - The query to match documents against.\n * @param offset - Read time and key to start scanning by (exclusive).\n * @param context - A optional tracker to keep a record of important details\n * during database local query execution.\n */\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n context?: QueryContext\n ): PersistencePromise<DocumentMap> {\n if (isDocumentQuery(query)) {\n return this.getDocumentsMatchingDocumentQuery(transaction, query.path);\n } else if (isCollectionGroupQuery(query)) {\n return this.getDocumentsMatchingCollectionGroupQuery(\n transaction,\n query,\n offset,\n context\n );\n } else {\n return this.getDocumentsMatchingCollectionQuery(\n transaction,\n query,\n offset,\n context\n );\n }\n }\n\n /**\n * Given a collection group, returns the next documents that follow the provided offset, along\n * with an updated batch ID.\n *\n * <p>The documents returned by this method are ordered by remote version from the provided\n * offset. If there are no more remote documents after the provided offset, documents with\n * mutations in order of batch id from the offset are returned. Since all documents in a batch are\n * returned together, the total number of documents returned can exceed {@code count}.\n *\n * @param transaction\n * @param collectionGroup The collection group for the documents.\n * @param offset The offset to index into.\n * @param count The number of documents to return\n * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.\n */\n getNextDocuments(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n count: number\n ): PersistencePromise<LocalWriteResult> {\n return this.remoteDocumentCache\n .getAllFromCollectionGroup(transaction, collectionGroup, offset, count)\n .next((originalDocs: MutableDocumentMap) => {\n const overlaysPromise: PersistencePromise<OverlayMap> =\n count - originalDocs.size > 0\n ? this.documentOverlayCache.getOverlaysForCollectionGroup(\n transaction,\n collectionGroup,\n offset.largestBatchId,\n count - originalDocs.size\n )\n : PersistencePromise.resolve(newOverlayMap());\n // The callsite will use the largest batch ID together with the latest read time to create\n // a new index offset. Since we only process batch IDs if all remote documents have been read,\n // no overlay will increase the overall read time. This is why we only need to special case\n // the batch id.\n let largestBatchId = INITIAL_LARGEST_BATCH_ID;\n let modifiedDocs = originalDocs;\n return overlaysPromise.next(overlays => {\n return PersistencePromise.forEach(\n overlays,\n (key: DocumentKey, overlay: Overlay) => {\n if (largestBatchId < overlay.largestBatchId) {\n largestBatchId = overlay.largestBatchId;\n }\n if (originalDocs.get(key)) {\n return PersistencePromise.resolve();\n }\n return this.remoteDocumentCache\n .getEntry(transaction, key)\n .next(doc => {\n modifiedDocs = modifiedDocs.insert(key, doc);\n });\n }\n )\n .next(() =>\n this.populateOverlays(transaction, overlays, originalDocs)\n )\n .next(() =>\n this.computeViews(\n transaction,\n modifiedDocs,\n overlays,\n documentKeySet()\n )\n )\n .next(localDocs => ({\n batchId: largestBatchId,\n changes: convertOverlayedDocumentMapToDocumentMap(localDocs)\n }));\n });\n });\n }\n\n private getDocumentsMatchingDocumentQuery(\n transaction: PersistenceTransaction,\n docPath: ResourcePath\n ): PersistencePromise<DocumentMap> {\n // Just do a simple document lookup.\n return this.getDocument(transaction, new DocumentKey(docPath)).next(\n document => {\n let result = documentMap();\n if (document.isFoundDocument()) {\n result = result.insert(document.key, document);\n }\n return result;\n }\n );\n }\n\n private getDocumentsMatchingCollectionGroupQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n context?: QueryContext\n ): PersistencePromise<DocumentMap> {\n debugAssert(\n query.path.isEmpty(),\n 'Currently we only support collection group queries at the root.'\n );\n const collectionId = query.collectionGroup!;\n let results = documentMap();\n return this.indexManager\n .getCollectionParents(transaction, collectionId)\n .next(parents => {\n // Perform a collection query against each parent that contains the\n // collectionId and aggregate the results.\n return PersistencePromise.forEach(parents, (parent: ResourcePath) => {\n const collectionQuery = asCollectionQueryAtPath(\n query,\n parent.child(collectionId)\n );\n return this.getDocumentsMatchingCollectionQuery(\n transaction,\n collectionQuery,\n offset,\n context\n ).next(r => {\n r.forEach((key, doc) => {\n results = results.insert(key, doc);\n });\n });\n }).next(() => results);\n });\n }\n\n private getDocumentsMatchingCollectionQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n context?: QueryContext\n ): PersistencePromise<DocumentMap> {\n // Query the remote documents and overlay mutations.\n let overlays: OverlayMap;\n return this.documentOverlayCache\n .getOverlaysForCollection(transaction, query.path, offset.largestBatchId)\n .next(result => {\n overlays = result;\n return this.remoteDocumentCache.getDocumentsMatchingQuery(\n transaction,\n query,\n offset,\n overlays,\n context\n );\n })\n .next(remoteDocuments => {\n // As documents might match the query because of their overlay we need to\n // include documents for all overlays in the initial document set.\n overlays.forEach((_, overlay) => {\n const key = overlay.getKey();\n if (remoteDocuments.get(key) === null) {\n remoteDocuments = remoteDocuments.insert(\n key,\n MutableDocument.newInvalidDocument(key)\n );\n }\n });\n\n // Apply the overlays and match against the query.\n let results = documentMap();\n remoteDocuments.forEach((key, document) => {\n const overlay = overlays.get(key);\n if (overlay !== undefined) {\n mutationApplyToLocalView(\n overlay.mutation,\n document,\n FieldMask.empty(),\n Timestamp.now()\n );\n }\n // Finally, insert the documents that still match the query\n if (queryMatches(query, document)) {\n results = results.insert(key, document);\n }\n });\n return results;\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleMetadata, NamedQuery } from '../core/bundle';\nimport {\n NamedQuery as ProtoNamedQuery,\n BundleMetadata as ProtoBundleMetadata\n} from '../protos/firestore_bundle_proto';\n\nimport { BundleCache } from './bundle_cache';\nimport {\n fromBundleMetadata,\n fromProtoNamedQuery,\n LocalSerializer\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\nexport class MemoryBundleCache implements BundleCache {\n private bundles = new Map<string, BundleMetadata>();\n private namedQueries = new Map<string, NamedQuery>();\n\n constructor(private serializer: LocalSerializer) {}\n\n getBundleMetadata(\n transaction: PersistenceTransaction,\n bundleId: string\n ): PersistencePromise<BundleMetadata | undefined> {\n return PersistencePromise.resolve(this.bundles.get(bundleId));\n }\n\n saveBundleMetadata(\n transaction: PersistenceTransaction,\n bundleMetadata: ProtoBundleMetadata\n ): PersistencePromise<void> {\n this.bundles.set(bundleMetadata.id!, fromBundleMetadata(bundleMetadata));\n return PersistencePromise.resolve();\n }\n\n getNamedQuery(\n transaction: PersistenceTransaction,\n queryName: string\n ): PersistencePromise<NamedQuery | undefined> {\n return PersistencePromise.resolve(this.namedQueries.get(queryName));\n }\n\n saveNamedQuery(\n transaction: PersistenceTransaction,\n query: ProtoNamedQuery\n ): PersistencePromise<void> {\n this.namedQueries.set(query.name!, fromProtoNamedQuery(query));\n return PersistencePromise.resolve();\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n documentKeySet,\n DocumentKeySet,\n MutationMap,\n OverlayMap,\n newOverlayMap\n} from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory implementation of DocumentOverlayCache.\n */\nexport class MemoryDocumentOverlayCache implements DocumentOverlayCache {\n // A map sorted by DocumentKey, whose value is a pair of the largest batch id\n // for the overlay and the overlay itself.\n private overlays = new SortedMap<DocumentKey, Overlay>(\n DocumentKey.comparator\n );\n private overlayByBatchId = new Map<number, DocumentKeySet>();\n\n getOverlay(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<Overlay | null> {\n return PersistencePromise.resolve(this.overlays.get(key));\n }\n\n getOverlays(\n transaction: PersistenceTransaction,\n keys: DocumentKey[]\n ): PersistencePromise<OverlayMap> {\n const result = newOverlayMap();\n return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n return this.getOverlay(transaction, key).next(overlay => {\n if (overlay !== null) {\n result.set(key, overlay);\n }\n });\n }).next(() => result);\n }\n\n saveOverlays(\n transaction: PersistenceTransaction,\n largestBatchId: number,\n overlays: MutationMap\n ): PersistencePromise<void> {\n overlays.forEach((_, mutation) => {\n this.saveOverlay(transaction, largestBatchId, mutation);\n });\n return PersistencePromise.resolve();\n }\n\n removeOverlaysForBatchId(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n batchId: number\n ): PersistencePromise<void> {\n const keys = this.overlayByBatchId.get(batchId);\n if (keys !== undefined) {\n keys.forEach(key => (this.overlays = this.overlays.remove(key)));\n this.overlayByBatchId.delete(batchId);\n }\n return PersistencePromise.resolve();\n }\n\n getOverlaysForCollection(\n transaction: PersistenceTransaction,\n collection: ResourcePath,\n sinceBatchId: number\n ): PersistencePromise<OverlayMap> {\n const result = newOverlayMap();\n\n const immediateChildrenPathLength = collection.length + 1;\n const prefix = new DocumentKey(collection.child(''));\n const iter = this.overlays.getIteratorFrom(prefix);\n while (iter.hasNext()) {\n const entry = iter.getNext();\n const overlay = entry.value;\n const key = overlay.getKey();\n if (!collection.isPrefixOf(key.path)) {\n break;\n }\n // Documents from sub-collections\n if (key.path.length !== immediateChildrenPathLength) {\n continue;\n }\n if (overlay.largestBatchId > sinceBatchId) {\n result.set(overlay.getKey(), overlay);\n }\n }\n\n return PersistencePromise.resolve(result);\n }\n\n getOverlaysForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n sinceBatchId: number,\n count: number\n ): PersistencePromise<OverlayMap> {\n let batchIdToOverlays = new SortedMap<number, OverlayMap>(\n (key1: number, key2: number) => key1 - key2\n );\n\n const iter = this.overlays.getIterator();\n while (iter.hasNext()) {\n const entry = iter.getNext();\n const overlay = entry.value;\n const key = overlay.getKey();\n if (key.getCollectionGroup() !== collectionGroup) {\n continue;\n }\n if (overlay.largestBatchId > sinceBatchId) {\n let overlaysForBatchId = batchIdToOverlays.get(overlay.largestBatchId);\n if (overlaysForBatchId === null) {\n overlaysForBatchId = newOverlayMap();\n batchIdToOverlays = batchIdToOverlays.insert(\n overlay.largestBatchId,\n overlaysForBatchId\n );\n }\n overlaysForBatchId.set(overlay.getKey(), overlay);\n }\n }\n\n const result = newOverlayMap();\n const batchIter = batchIdToOverlays.getIterator();\n while (batchIter.hasNext()) {\n const entry = batchIter.getNext();\n const overlays = entry.value;\n overlays.forEach((key, overlay) => result.set(key, overlay));\n if (result.size() >= count) {\n break;\n }\n }\n return PersistencePromise.resolve(result);\n }\n\n private saveOverlay(\n transaction: PersistenceTransaction,\n largestBatchId: number,\n mutation: Mutation\n ): void {\n // Remove the association of the overlay to its batch id.\n const existing = this.overlays.get(mutation.key);\n if (existing !== null) {\n const newSet = this.overlayByBatchId\n .get(existing.largestBatchId)!\n .delete(mutation.key);\n this.overlayByBatchId.set(existing.largestBatchId, newSet);\n }\n\n this.overlays = this.overlays.insert(\n mutation.key,\n new Overlay(largestBatchId, mutation)\n );\n\n // Create the association of this overlay to the given largestBatchId.\n let batch = this.overlayByBatchId.get(largestBatchId);\n if (batch === undefined) {\n batch = documentKeySet();\n this.overlayByBatchId.set(largestBatchId, batch);\n }\n this.overlayByBatchId.set(largestBatchId, batch.add(mutation.key));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchId, TargetId } from '../core/types';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\n/**\n * A collection of references to a document from some kind of numbered entity\n * (either a target ID or batch ID). As references are added to or removed from\n * the set corresponding events are emitted to a registered garbage collector.\n *\n * Each reference is represented by a DocumentReference object. Each of them\n * contains enough information to uniquely identify the reference. They are all\n * stored primarily in a set sorted by key. A document is considered garbage if\n * there's no references in that set (this can be efficiently checked thanks to\n * sorting by key).\n *\n * ReferenceSet also keeps a secondary set that contains references sorted by\n * IDs. This one is used to efficiently implement removal of all references by\n * some target ID.\n */\nexport class ReferenceSet {\n // A set of outstanding references to a document sorted by key.\n private refsByKey = new SortedSet(DocReference.compareByKey);\n\n // A set of outstanding references to a document sorted by target id.\n private refsByTarget = new SortedSet(DocReference.compareByTargetId);\n\n /** Returns true if the reference set contains no references. */\n isEmpty(): boolean {\n return this.refsByKey.isEmpty();\n }\n\n /** Adds a reference to the given document key for the given ID. */\n addReference(key: DocumentKey, id: TargetId | BatchId): void {\n const ref = new DocReference(key, id);\n this.refsByKey = this.refsByKey.add(ref);\n this.refsByTarget = this.refsByTarget.add(ref);\n }\n\n /** Add references to the given document keys for the given ID. */\n addReferences(keys: DocumentKeySet, id: TargetId | BatchId): void {\n keys.forEach(key => this.addReference(key, id));\n }\n\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */\n removeReference(key: DocumentKey, id: TargetId | BatchId): void {\n this.removeRef(new DocReference(key, id));\n }\n\n removeReferences(keys: DocumentKeySet, id: TargetId | BatchId): void {\n keys.forEach(key => this.removeReference(key, id));\n }\n\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */\n removeReferencesForId(id: TargetId | BatchId): DocumentKey[] {\n const emptyKey = new DocumentKey(new ResourcePath([]));\n const startRef = new DocReference(emptyKey, id);\n const endRef = new DocReference(emptyKey, id + 1);\n const keys: DocumentKey[] = [];\n this.refsByTarget.forEachInRange([startRef, endRef], ref => {\n this.removeRef(ref);\n keys.push(ref.key);\n });\n return keys;\n }\n\n removeAllReferences(): void {\n this.refsByKey.forEach(ref => this.removeRef(ref));\n }\n\n private removeRef(ref: DocReference): void {\n this.refsByKey = this.refsByKey.delete(ref);\n this.refsByTarget = this.refsByTarget.delete(ref);\n }\n\n referencesForId(id: TargetId | BatchId): DocumentKeySet {\n const emptyKey = new DocumentKey(new ResourcePath([]));\n const startRef = new DocReference(emptyKey, id);\n const endRef = new DocReference(emptyKey, id + 1);\n let keys = documentKeySet();\n this.refsByTarget.forEachInRange([startRef, endRef], ref => {\n keys = keys.add(ref.key);\n });\n return keys;\n }\n\n containsKey(key: DocumentKey): boolean {\n const ref = new DocReference(key, 0);\n const firstRef = this.refsByKey.firstAfterOrEqual(ref);\n return firstRef !== null && key.isEqual(firstRef.key);\n }\n}\n\nexport class DocReference {\n constructor(\n public key: DocumentKey,\n public targetOrBatchId: TargetId | BatchId\n ) {}\n\n /** Compare by key then by ID */\n static compareByKey(left: DocReference, right: DocReference): number {\n return (\n DocumentKey.comparator(left.key, right.key) ||\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId)\n );\n }\n\n /** Compare by ID then by key */\n static compareByTargetId(left: DocReference, right: DocReference): number {\n return (\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId) ||\n DocumentKey.comparator(left.key, right.key)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isCollectionGroupQuery, Query } from '../core/query';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { IndexManager } from './index_manager';\nimport { MutationQueue } from './mutation_queue';\nimport { ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { DocReference } from './reference_set';\n\nexport class MemoryMutationQueue implements MutationQueue {\n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n private mutationQueue: MutationBatch[] = [];\n\n /** Next value to use when assigning sequential IDs to each mutation batch. */\n private nextBatchId: BatchId = 1;\n\n /** An ordered mapping between documents and the mutations batch IDs. */\n private batchesByDocumentKey = new SortedSet(DocReference.compareByKey);\n\n constructor(\n private readonly indexManager: IndexManager,\n private readonly referenceDelegate: ReferenceDelegate\n ) {}\n\n checkEmpty(transaction: PersistenceTransaction): PersistencePromise<boolean> {\n return PersistencePromise.resolve(this.mutationQueue.length === 0);\n }\n\n addMutationBatch(\n transaction: PersistenceTransaction,\n localWriteTime: Timestamp,\n baseMutations: Mutation[],\n mutations: Mutation[]\n ): PersistencePromise<MutationBatch> {\n debugAssert(mutations.length !== 0, 'Mutation batches should not be empty');\n\n const batchId = this.nextBatchId;\n this.nextBatchId++;\n\n if (this.mutationQueue.length > 0) {\n const prior = this.mutationQueue[this.mutationQueue.length - 1];\n debugAssert(\n prior.batchId < batchId,\n 'Mutation batchIDs must be monotonically increasing order'\n );\n }\n\n const batch = new MutationBatch(\n batchId,\n localWriteTime,\n baseMutations,\n mutations\n );\n this.mutationQueue.push(batch);\n\n // Track references by document key and index collection parents.\n for (const mutation of mutations) {\n this.batchesByDocumentKey = this.batchesByDocumentKey.add(\n new DocReference(mutation.key, batchId)\n );\n\n this.indexManager.addToCollectionParentIndex(\n transaction,\n mutation.key.path.popLast()\n );\n }\n\n return PersistencePromise.resolve(batch);\n }\n\n lookupMutationBatch(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise<MutationBatch | null> {\n return PersistencePromise.resolve(this.findMutationBatch(batchId));\n }\n\n getNextMutationBatchAfterBatchId(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise<MutationBatch | null> {\n const nextBatchId = batchId + 1;\n\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n const rawIndex = this.indexOfBatchId(nextBatchId);\n const index = rawIndex < 0 ? 0 : rawIndex;\n return PersistencePromise.resolve(\n this.mutationQueue.length > index ? this.mutationQueue[index] : null\n );\n }\n\n getHighestUnacknowledgedBatchId(): PersistencePromise<BatchId> {\n return PersistencePromise.resolve(\n this.mutationQueue.length === 0 ? BATCHID_UNKNOWN : this.nextBatchId - 1\n );\n }\n\n getAllMutationBatches(\n transaction: PersistenceTransaction\n ): PersistencePromise<MutationBatch[]> {\n return PersistencePromise.resolve(this.mutationQueue.slice());\n }\n\n getAllMutationBatchesAffectingDocumentKey(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MutationBatch[]> {\n const start = new DocReference(documentKey, 0);\n const end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n const result: MutationBatch[] = [];\n this.batchesByDocumentKey.forEachInRange([start, end], ref => {\n debugAssert(\n documentKey.isEqual(ref.key),\n \"Should only iterate over a single key's batches\"\n );\n const batch = this.findMutationBatch(ref.targetOrBatchId);\n debugAssert(\n batch !== null,\n 'Batches in the index must exist in the main table'\n );\n result.push(batch!);\n });\n\n return PersistencePromise.resolve(result);\n }\n\n getAllMutationBatchesAffectingDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: SortedMap<DocumentKey, unknown>\n ): PersistencePromise<MutationBatch[]> {\n let uniqueBatchIDs = new SortedSet<number>(primitiveComparator);\n\n documentKeys.forEach(documentKey => {\n const start = new DocReference(documentKey, 0);\n const end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n this.batchesByDocumentKey.forEachInRange([start, end], ref => {\n debugAssert(\n documentKey.isEqual(ref.key),\n \"For each key, should only iterate over a single key's batches\"\n );\n\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n });\n });\n\n return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\n }\n\n getAllMutationBatchesAffectingQuery(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise<MutationBatch[]> {\n debugAssert(\n !isCollectionGroupQuery(query),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n // Use the query path as a prefix for testing if a document matches the\n // query.\n const prefix = query.path;\n const immediateChildrenPathLength = prefix.length + 1;\n\n // Construct a document reference for actually scanning the index. Unlike\n // the prefix the document key in this reference must have an even number of\n // segments. The empty segment can be used a suffix of the query path\n // because it precedes all other segments in an ordered traversal.\n let startPath = prefix;\n if (!DocumentKey.isDocumentKey(startPath)) {\n startPath = startPath.child('');\n }\n\n const start = new DocReference(new DocumentKey(startPath), 0);\n\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n let uniqueBatchIDs = new SortedSet<number>(primitiveComparator);\n\n this.batchesByDocumentKey.forEachWhile(ref => {\n const rowKeyPath = ref.key.path;\n if (!prefix.isPrefixOf(rowKeyPath)) {\n return false;\n } else {\n // Rows with document keys more than one segment longer than the query\n // path can't be matches. For example, a query on 'rooms' can't match\n // the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n if (rowKeyPath.length === immediateChildrenPathLength) {\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n }\n return true;\n }\n }, start);\n\n return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\n }\n\n private findMutationBatches(batchIDs: SortedSet<number>): MutationBatch[] {\n // Construct an array of matching batches, sorted by batchID to ensure that\n // multiple mutations affecting the same document key are applied in order.\n const result: MutationBatch[] = [];\n batchIDs.forEach(batchId => {\n const batch = this.findMutationBatch(batchId);\n if (batch !== null) {\n result.push(batch);\n }\n });\n return result;\n }\n\n removeMutationBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch\n ): PersistencePromise<void> {\n // Find the position of the first batch for removal.\n const batchIndex = this.indexOfExistingBatchId(batch.batchId, 'removed');\n hardAssert(\n batchIndex === 0,\n 'Can only remove the first entry of the mutation queue'\n );\n this.mutationQueue.shift();\n\n let references = this.batchesByDocumentKey;\n return PersistencePromise.forEach(batch.mutations, (mutation: Mutation) => {\n const ref = new DocReference(mutation.key, batch.batchId);\n references = references.delete(ref);\n return this.referenceDelegate.markPotentiallyOrphaned(\n transaction,\n mutation.key\n );\n }).next(() => {\n this.batchesByDocumentKey = references;\n });\n }\n\n removeCachedMutationKeys(batchId: BatchId): void {\n // No-op since the memory mutation queue does not maintain a separate cache.\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n const ref = new DocReference(key, 0);\n const firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref);\n return PersistencePromise.resolve(key.isEqual(firstRef && firstRef.key));\n }\n\n performConsistencyCheck(\n txn: PersistenceTransaction\n ): PersistencePromise<void> {\n if (this.mutationQueue.length === 0) {\n debugAssert(\n this.batchesByDocumentKey.isEmpty(),\n 'Document leak -- detected dangling mutation references when queue is empty.'\n );\n }\n return PersistencePromise.resolve();\n }\n\n /**\n * Finds the index of the given batchId in the mutation queue and asserts that\n * the resulting index is within the bounds of the queue.\n *\n * @param batchId - The batchId to search for\n * @param action - A description of what the caller is doing, phrased in passive\n * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\n */\n private indexOfExistingBatchId(batchId: BatchId, action: string): number {\n const index = this.indexOfBatchId(batchId);\n debugAssert(\n index >= 0 && index < this.mutationQueue.length,\n 'Batches must exist to be ' + action\n );\n return index;\n }\n\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @returns The computed index of the batch with the given batchId, based on\n * the state of the queue. Note this index can be negative if the requested\n * batchId has already been remvoed from the queue or past the end of the\n * queue if the batchId is larger than the last added batch.\n */\n private indexOfBatchId(batchId: BatchId): number {\n if (this.mutationQueue.length === 0) {\n // As an index this is past the end of the queue\n return 0;\n }\n\n // Examine the front of the queue to figure out the difference between the\n // batchId and indexes in the array. Note that since the queue is ordered\n // by batchId, if the first batch has a larger batchId then the requested\n // batchId doesn't exist in the queue.\n const firstBatchId = this.mutationQueue[0].batchId;\n return batchId - firstBatchId;\n }\n\n /**\n * A version of lookupMutationBatch that doesn't return a promise, this makes\n * other functions that uses this code easier to read and more efficent.\n */\n private findMutationBatch(batchId: BatchId): MutationBatch | null {\n const index = this.indexOfBatchId(batchId);\n if (index < 0 || index >= this.mutationQueue.length) {\n return null;\n }\n\n const batch = this.mutationQueue[index];\n debugAssert(batch.batchId === batchId, 'If found batch must match');\n return batch;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Query, queryMatches } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n DocumentKeySet,\n MutableDocumentMap,\n mutableDocumentMap,\n OverlayMap\n} from '../model/collections';\nimport { Document, MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n IndexOffset,\n indexOffsetComparator,\n newIndexOffsetFromDocument\n} from '../model/field_index';\nimport { debugAssert, fail } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { IndexManager } from './index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\n\nexport type DocumentSizer = (doc: Document) => number;\n\n/** Miscellaneous collection types / constants. */\ninterface MemoryRemoteDocumentCacheEntry {\n document: Document;\n size: number;\n}\n\ntype DocumentEntryMap = SortedMap<DocumentKey, MemoryRemoteDocumentCacheEntry>;\nfunction documentEntryMap(): DocumentEntryMap {\n return new SortedMap<DocumentKey, MemoryRemoteDocumentCacheEntry>(\n DocumentKey.comparator\n );\n}\n\nexport interface MemoryRemoteDocumentCache extends RemoteDocumentCache {\n forEachDocumentKey(\n transaction: PersistenceTransaction,\n f: (key: DocumentKey) => PersistencePromise<void>\n ): PersistencePromise<void>;\n}\n\n/**\n * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newMemoryRemoteDocumentCache()`.\n */\nclass MemoryRemoteDocumentCacheImpl implements MemoryRemoteDocumentCache {\n /** Underlying cache of documents and their read times. */\n private docs = documentEntryMap();\n private indexManager!: IndexManager;\n\n /** Size of all cached documents. */\n private size = 0;\n\n /**\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n constructor(private readonly sizer: DocumentSizer) {}\n\n setIndexManager(indexManager: IndexManager): void {\n this.indexManager = indexManager;\n }\n\n /**\n * Adds the supplied entry to the cache and updates the cache size as appropriate.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */\n addEntry(\n transaction: PersistenceTransaction,\n doc: MutableDocument\n ): PersistencePromise<void> {\n debugAssert(\n !doc.readTime.isEqual(SnapshotVersion.min()),\n 'Cannot add a document with a read time of zero'\n );\n\n const key = doc.key;\n const entry = this.docs.get(key);\n const previousSize = entry ? entry.size : 0;\n const currentSize = this.sizer(doc);\n\n this.docs = this.docs.insert(key, {\n document: doc.mutableCopy(),\n size: currentSize\n });\n\n this.size += currentSize - previousSize;\n\n return this.indexManager.addToCollectionParentIndex(\n transaction,\n key.path.popLast()\n );\n }\n\n /**\n * Removes the specified entry from the cache and updates the cache size as appropriate.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */\n removeEntry(documentKey: DocumentKey): void {\n const entry = this.docs.get(documentKey);\n if (entry) {\n this.docs = this.docs.remove(documentKey);\n this.size -= entry.size;\n }\n }\n\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MutableDocument> {\n const entry = this.docs.get(documentKey);\n return PersistencePromise.resolve(\n entry\n ? entry.document.mutableCopy()\n : MutableDocument.newInvalidDocument(documentKey)\n );\n }\n\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<MutableDocumentMap> {\n let results = mutableDocumentMap();\n documentKeys.forEach(documentKey => {\n const entry = this.docs.get(documentKey);\n results = results.insert(\n documentKey,\n entry\n ? entry.document.mutableCopy()\n : MutableDocument.newInvalidDocument(documentKey)\n );\n });\n return PersistencePromise.resolve(results);\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n mutatedDocs: OverlayMap\n ): PersistencePromise<MutableDocumentMap> {\n let results = mutableDocumentMap();\n\n // Documents are ordered by key, so we can use a prefix scan to narrow down\n // the documents we need to match the query against.\n const collectionPath = query.path;\n const prefix = new DocumentKey(collectionPath.child(''));\n const iterator = this.docs.getIteratorFrom(prefix);\n while (iterator.hasNext()) {\n const {\n key,\n value: { document }\n } = iterator.getNext();\n if (!collectionPath.isPrefixOf(key.path)) {\n break;\n }\n if (key.path.length > collectionPath.length + 1) {\n // Exclude entries from subcollections.\n continue;\n }\n if (\n indexOffsetComparator(newIndexOffsetFromDocument(document), offset) <= 0\n ) {\n // The document sorts before the offset.\n continue;\n }\n if (!mutatedDocs.has(document.key) && !queryMatches(query, document)) {\n // The document cannot possibly match the query.\n continue;\n }\n\n results = results.insert(document.key, document.mutableCopy());\n }\n return PersistencePromise.resolve(results);\n }\n\n getAllFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n limti: number\n ): PersistencePromise<MutableDocumentMap> {\n // This method should only be called from the IndexBackfiller if persistence\n // is enabled.\n fail('getAllFromCollectionGroup() is not supported.');\n }\n\n forEachDocumentKey(\n transaction: PersistenceTransaction,\n f: (key: DocumentKey) => PersistencePromise<void>\n ): PersistencePromise<void> {\n return PersistencePromise.forEach(this.docs, (key: DocumentKey) => f(key));\n }\n\n newChangeBuffer(options?: {\n trackRemovals: boolean;\n }): RemoteDocumentChangeBuffer {\n // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps\n // a separate changelog and does not need special handling for removals.\n return new MemoryRemoteDocumentChangeBuffer(this);\n }\n\n getSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return PersistencePromise.resolve(this.size);\n }\n}\n\n/**\n * Creates a new memory-only RemoteDocumentCache.\n *\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\nexport function newMemoryRemoteDocumentCache(\n sizer: DocumentSizer\n): MemoryRemoteDocumentCache {\n return new MemoryRemoteDocumentCacheImpl(sizer);\n}\n\n/**\n * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.\n */\nclass MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n constructor(private readonly documentCache: MemoryRemoteDocumentCacheImpl) {\n super();\n }\n\n protected applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise<void> {\n const promises: Array<PersistencePromise<void>> = [];\n this.changes.forEach((key, doc) => {\n if (doc.isValidDocument()) {\n promises.push(this.documentCache.addEntry(transaction, doc));\n } else {\n this.documentCache.removeEntry(key);\n }\n });\n return PersistencePromise.waitFor(promises);\n }\n\n protected getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MutableDocument> {\n return this.documentCache.getEntry(transaction, documentKey);\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<MutableDocumentMap> {\n return this.documentCache.getEntries(transaction, documentKeys);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { ReferenceSet } from './reference_set';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\n\nexport class MemoryTargetCache implements TargetCache {\n /**\n * Maps a target to the data about that target\n */\n private targets = new ObjectMap<Target, TargetData>(\n t => canonifyTarget(t),\n targetEquals\n );\n\n /** The last received snapshot version. */\n private lastRemoteSnapshotVersion = SnapshotVersion.min();\n /** The highest numbered target ID encountered. */\n private highestTargetId: TargetId = 0;\n /** The highest sequence number encountered. */\n private highestSequenceNumber: ListenSequenceNumber = 0;\n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n private references = new ReferenceSet();\n\n private targetCount = 0;\n\n private targetIdGenerator = TargetIdGenerator.forTargetCache();\n\n constructor(private readonly persistence: Persistence) {}\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise<void> {\n this.targets.forEach((_, targetData) => f(targetData));\n return PersistencePromise.resolve();\n }\n\n getLastRemoteSnapshotVersion(\n transaction: PersistenceTransaction\n ): PersistencePromise<SnapshotVersion> {\n return PersistencePromise.resolve(this.lastRemoteSnapshotVersion);\n }\n\n getHighestSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise<ListenSequenceNumber> {\n return PersistencePromise.resolve(this.highestSequenceNumber);\n }\n\n allocateTargetId(\n transaction: PersistenceTransaction\n ): PersistencePromise<TargetId> {\n this.highestTargetId = this.targetIdGenerator.next();\n return PersistencePromise.resolve(this.highestTargetId);\n }\n\n setTargetsMetadata(\n transaction: PersistenceTransaction,\n highestListenSequenceNumber: number,\n lastRemoteSnapshotVersion?: SnapshotVersion\n ): PersistencePromise<void> {\n if (lastRemoteSnapshotVersion) {\n this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\n }\n if (highestListenSequenceNumber > this.highestSequenceNumber) {\n this.highestSequenceNumber = highestListenSequenceNumber;\n }\n return PersistencePromise.resolve();\n }\n\n private saveTargetData(targetData: TargetData): void {\n this.targets.set(targetData.target, targetData);\n const targetId = targetData.targetId;\n if (targetId > this.highestTargetId) {\n this.targetIdGenerator = new TargetIdGenerator(targetId);\n this.highestTargetId = targetId;\n }\n if (targetData.sequenceNumber > this.highestSequenceNumber) {\n this.highestSequenceNumber = targetData.sequenceNumber;\n }\n }\n\n addTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n debugAssert(\n !this.targets.has(targetData.target),\n 'Adding a target that already exists'\n );\n this.saveTargetData(targetData);\n this.targetCount += 1;\n return PersistencePromise.resolve();\n }\n\n updateTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n debugAssert(\n this.targets.has(targetData.target),\n 'Updating a non-existent target'\n );\n this.saveTargetData(targetData);\n return PersistencePromise.resolve();\n }\n\n removeTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n debugAssert(this.targetCount > 0, 'Removing a target from an empty cache');\n debugAssert(\n this.targets.has(targetData.target),\n 'Removing a non-existent target from the cache'\n );\n this.targets.delete(targetData.target);\n this.references.removeReferencesForId(targetData.targetId);\n this.targetCount -= 1;\n return PersistencePromise.resolve();\n }\n\n removeTargets(\n transaction: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n let count = 0;\n const removals: Array<PersistencePromise<void>> = [];\n this.targets.forEach((key, targetData) => {\n if (\n targetData.sequenceNumber <= upperBound &&\n activeTargetIds.get(targetData.targetId) === null\n ) {\n this.targets.delete(key);\n removals.push(\n this.removeMatchingKeysForTargetId(transaction, targetData.targetId)\n );\n count++;\n }\n });\n return PersistencePromise.waitFor(removals).next(() => count);\n }\n\n getTargetCount(\n transaction: PersistenceTransaction\n ): PersistencePromise<number> {\n return PersistencePromise.resolve(this.targetCount);\n }\n\n getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<TargetData | null> {\n const targetData = this.targets.get(target) || null;\n return PersistencePromise.resolve(targetData);\n }\n\n addMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise<void> {\n this.references.addReferences(keys, targetId);\n return PersistencePromise.resolve();\n }\n\n removeMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise<void> {\n this.references.removeReferences(keys, targetId);\n const referenceDelegate = this.persistence.referenceDelegate;\n const promises: Array<PersistencePromise<void>> = [];\n if (referenceDelegate) {\n keys.forEach(key => {\n promises.push(referenceDelegate.markPotentiallyOrphaned(txn, key));\n });\n }\n return PersistencePromise.waitFor(promises);\n }\n\n removeMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise<void> {\n this.references.removeReferencesForId(targetId);\n return PersistencePromise.resolve();\n }\n\n getMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise<DocumentKeySet> {\n const matchingKeys = this.references.referencesForId(targetId);\n return PersistencePromise.resolve(matchingKeys);\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n return PersistencePromise.resolve(this.references.containsKey(key));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { estimateByteSize } from '../model/values';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { fail } from '../util/assert';\nimport { logDebug } from '../util/log';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { encodeResourcePath } from './encoded_resource_path';\nimport { IndexManager } from './index_manager';\nimport { LocalSerializer } from './local_serializer';\nimport {\n ActiveTargets,\n LruDelegate,\n LruGarbageCollector,\n LruParams\n} from './lru_garbage_collector';\nimport { newLruGarbageCollector } from './lru_garbage_collector_impl';\nimport { MemoryBundleCache } from './memory_bundle_cache';\nimport { MemoryDocumentOverlayCache } from './memory_document_overlay_cache';\nimport { MemoryIndexManager } from './memory_index_manager';\nimport { MemoryMutationQueue } from './memory_mutation_queue';\nimport {\n MemoryRemoteDocumentCache,\n newMemoryRemoteDocumentCache\n} from './memory_remote_document_cache';\nimport { MemoryTargetCache } from './memory_target_cache';\nimport { MutationQueue } from './mutation_queue';\nimport { Persistence, ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport {\n PersistenceTransaction,\n PersistenceTransactionMode\n} from './persistence_transaction';\nimport { ReferenceSet } from './reference_set';\nimport { TargetData } from './target_data';\n\nconst LOG_TAG = 'MemoryPersistence';\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nexport class MemoryPersistence implements Persistence {\n /**\n * Note that these are retained here to make it easier to write tests\n * affecting both the in-memory and IndexedDB-backed persistence layers. Tests\n * can create a new LocalStore wrapping this Persistence instance and this\n * will make the in-memory persistence layer behave as if it were actually\n * persisting values.\n */\n private readonly indexManager: MemoryIndexManager;\n private mutationQueues: { [user: string]: MemoryMutationQueue } = {};\n private overlays: { [user: string]: MemoryDocumentOverlayCache } = {};\n private readonly remoteDocumentCache: MemoryRemoteDocumentCache;\n private readonly targetCache: MemoryTargetCache;\n private readonly bundleCache: MemoryBundleCache;\n private readonly listenSequence = new ListenSequence(0);\n private serializer: LocalSerializer;\n\n private _started = false;\n\n readonly referenceDelegate: MemoryReferenceDelegate;\n\n /**\n * The constructor accepts a factory for creating a reference delegate. This\n * allows both the delegate and this instance to have strong references to\n * each other without having nullable fields that would then need to be\n * checked or asserted on every access.\n */\n constructor(\n referenceDelegateFactory: (p: MemoryPersistence) => MemoryReferenceDelegate,\n serializer: JsonProtoSerializer\n ) {\n this._started = true;\n this.referenceDelegate = referenceDelegateFactory(this);\n this.targetCache = new MemoryTargetCache(this);\n const sizer = (doc: Document): number =>\n this.referenceDelegate.documentSize(doc);\n this.indexManager = new MemoryIndexManager();\n this.remoteDocumentCache = newMemoryRemoteDocumentCache(sizer);\n this.serializer = new LocalSerializer(serializer);\n this.bundleCache = new MemoryBundleCache(this.serializer);\n }\n\n start(): Promise<void> {\n return Promise.resolve();\n }\n\n shutdown(): Promise<void> {\n // No durable state to ensure is closed on shutdown.\n this._started = false;\n return Promise.resolve();\n }\n\n get started(): boolean {\n return this._started;\n }\n\n setDatabaseDeletedListener(): void {\n // No op.\n }\n\n setNetworkEnabled(): void {\n // No op.\n }\n\n getIndexManager(user: User): MemoryIndexManager {\n // We do not currently support indices for memory persistence, so we can\n // return the same shared instance of the memory index manager.\n return this.indexManager;\n }\n\n getDocumentOverlayCache(user: User): DocumentOverlayCache {\n let overlay = this.overlays[user.toKey()];\n if (!overlay) {\n overlay = new MemoryDocumentOverlayCache();\n this.overlays[user.toKey()] = overlay;\n }\n return overlay;\n }\n\n getMutationQueue(user: User, indexManager: IndexManager): MutationQueue {\n let queue = this.mutationQueues[user.toKey()];\n if (!queue) {\n queue = new MemoryMutationQueue(indexManager, this.referenceDelegate);\n this.mutationQueues[user.toKey()] = queue;\n }\n return queue;\n }\n\n getTargetCache(): MemoryTargetCache {\n return this.targetCache;\n }\n\n getRemoteDocumentCache(): MemoryRemoteDocumentCache {\n return this.remoteDocumentCache;\n }\n\n getBundleCache(): MemoryBundleCache {\n return this.bundleCache;\n }\n\n runTransaction<T>(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise<T>\n ): Promise<T> {\n logDebug(LOG_TAG, 'Starting transaction:', action);\n const txn = new MemoryTransaction(this.listenSequence.next());\n this.referenceDelegate.onTransactionStarted();\n return transactionOperation(txn)\n .next(result => {\n return this.referenceDelegate\n .onTransactionCommitted(txn)\n .next(() => result);\n })\n .toPromise()\n .then(result => {\n txn.raiseOnCommittedEvent();\n return result;\n });\n }\n\n mutationQueuesContainKey(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n return PersistencePromise.or(\n Object.values(this.mutationQueues).map(\n queue => () => queue.containsKey(transaction, key)\n )\n );\n }\n}\n\n/**\n * Memory persistence is not actually transactional, but future implementations\n * may have transaction-scoped state.\n */\nexport class MemoryTransaction extends PersistenceTransaction {\n constructor(readonly currentSequenceNumber: ListenSequenceNumber) {\n super();\n }\n}\n\nexport interface MemoryReferenceDelegate extends ReferenceDelegate {\n documentSize(doc: Document): number;\n onTransactionStarted(): void;\n onTransactionCommitted(txn: PersistenceTransaction): PersistencePromise<void>;\n}\n\nexport class MemoryEagerDelegate implements MemoryReferenceDelegate {\n /** Tracks all documents that are active in Query views. */\n private localViewReferences: ReferenceSet = new ReferenceSet();\n /** The list of documents that are potentially GCed after each transaction. */\n private _orphanedDocuments: Set</* path= */ string> | null = null;\n\n private constructor(private readonly persistence: MemoryPersistence) {}\n\n static factory(persistence: MemoryPersistence): MemoryEagerDelegate {\n return new MemoryEagerDelegate(persistence);\n }\n\n private get orphanedDocuments(): Set<string> {\n if (!this._orphanedDocuments) {\n throw fail('orphanedDocuments is only valid during a transaction.');\n } else {\n return this._orphanedDocuments;\n }\n }\n\n addReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.localViewReferences.addReference(key, targetId);\n this.orphanedDocuments.delete(key.toString());\n return PersistencePromise.resolve();\n }\n\n removeReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.localViewReferences.removeReference(key, targetId);\n this.orphanedDocuments.add(key.toString());\n return PersistencePromise.resolve();\n }\n\n markPotentiallyOrphaned(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedDocuments.add(key.toString());\n return PersistencePromise.resolve();\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n const orphaned = this.localViewReferences.removeReferencesForId(\n targetData.targetId\n );\n orphaned.forEach(key => this.orphanedDocuments.add(key.toString()));\n const cache = this.persistence.getTargetCache();\n return cache\n .getMatchingKeysForTargetId(txn, targetData.targetId)\n .next(keys => {\n keys.forEach(key => this.orphanedDocuments.add(key.toString()));\n })\n .next(() => cache.removeTargetData(txn, targetData));\n }\n\n onTransactionStarted(): void {\n this._orphanedDocuments = new Set<string>();\n }\n\n onTransactionCommitted(\n txn: PersistenceTransaction\n ): PersistencePromise<void> {\n // Remove newly orphaned documents.\n const cache = this.persistence.getRemoteDocumentCache();\n const changeBuffer = cache.newChangeBuffer();\n return PersistencePromise.forEach(\n this.orphanedDocuments,\n (path: string) => {\n const key = DocumentKey.fromPath(path);\n return this.isReferenced(txn, key).next(isReferenced => {\n if (!isReferenced) {\n changeBuffer.removeEntry(key, SnapshotVersion.min());\n }\n });\n }\n ).next(() => {\n this._orphanedDocuments = null;\n return changeBuffer.apply(txn);\n });\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n return this.isReferenced(txn, key).next(isReferenced => {\n if (isReferenced) {\n this.orphanedDocuments.delete(key.toString());\n } else {\n this.orphanedDocuments.add(key.toString());\n }\n });\n }\n\n documentSize(doc: Document): number {\n // For eager GC, we don't care about the document size, there are no size thresholds.\n return 0;\n }\n\n private isReferenced(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n return PersistencePromise.or([\n () =>\n PersistencePromise.resolve(this.localViewReferences.containsKey(key)),\n () => this.persistence.getTargetCache().containsKey(txn, key),\n () => this.persistence.mutationQueuesContainKey(txn, key)\n ]);\n }\n}\n\nexport class MemoryLruDelegate implements ReferenceDelegate, LruDelegate {\n private orphanedSequenceNumbers: ObjectMap<\n DocumentKey,\n ListenSequenceNumber\n > = new ObjectMap(\n k => encodeResourcePath(k.path),\n (l, r) => l.isEqual(r)\n );\n\n readonly garbageCollector: LruGarbageCollector;\n\n constructor(\n private readonly persistence: MemoryPersistence,\n lruParams: LruParams\n ) {\n this.garbageCollector = newLruGarbageCollector(this, lruParams);\n }\n\n static factory(\n persistence: MemoryPersistence,\n lruParams: LruParams\n ): MemoryLruDelegate {\n return new MemoryLruDelegate(persistence, lruParams);\n }\n\n // No-ops, present so memory persistence doesn't have to care which delegate\n // it has.\n onTransactionStarted(): void {}\n\n onTransactionCommitted(\n txn: PersistenceTransaction\n ): PersistencePromise<void> {\n return PersistencePromise.resolve();\n }\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise<void> {\n return this.persistence.getTargetCache().forEachTarget(txn, f);\n }\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number> {\n const docCountPromise = this.orphanedDocumentCount(txn);\n const targetCountPromise = this.persistence\n .getTargetCache()\n .getTargetCount(txn);\n return targetCountPromise.next(targetCount =>\n docCountPromise.next(docCount => targetCount + docCount)\n );\n }\n\n private orphanedDocumentCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number> {\n let orphanedCount = 0;\n return this.forEachOrphanedDocumentSequenceNumber(txn, _ => {\n orphanedCount++;\n }).next(() => orphanedCount);\n }\n\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise<void> {\n return PersistencePromise.forEach(\n this.orphanedSequenceNumbers,\n (key, sequenceNumber) => {\n // Pass in the exact sequence number as the upper bound so we know it won't be pinned by\n // being too recent.\n return this.isPinned(txn, key, sequenceNumber).next(isPinned => {\n if (!isPinned) {\n return f(sequenceNumber);\n } else {\n return PersistencePromise.resolve();\n }\n });\n }\n );\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n return this.persistence\n .getTargetCache()\n .removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number> {\n let count = 0;\n const cache = this.persistence.getRemoteDocumentCache();\n const changeBuffer = cache.newChangeBuffer();\n const p = cache.forEachDocumentKey(txn, key => {\n return this.isPinned(txn, key, upperBound).next(isPinned => {\n if (!isPinned) {\n count++;\n changeBuffer.removeEntry(key, SnapshotVersion.min());\n }\n });\n });\n return p.next(() => changeBuffer.apply(txn)).next(() => count);\n }\n\n markPotentiallyOrphaned(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n const updated = targetData.withSequenceNumber(txn.currentSequenceNumber);\n return this.persistence.getTargetCache().updateTargetData(txn, updated);\n }\n\n addReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n removeReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n documentSize(document: Document): number {\n let documentSize = document.key.toString().length;\n if (document.isFoundDocument()) {\n documentSize += estimateByteSize(document.data.value);\n }\n return documentSize;\n }\n\n private isPinned(\n txn: PersistenceTransaction,\n key: DocumentKey,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<boolean> {\n return PersistencePromise.or([\n () => this.persistence.mutationQueuesContainKey(txn, key),\n () => this.persistence.getTargetCache().containsKey(txn, key),\n () => {\n const orphanedAt = this.orphanedSequenceNumbers.get(key);\n return PersistencePromise.resolve(\n orphanedAt !== undefined && orphanedAt > upperBound\n );\n }\n ]);\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return this.persistence.getRemoteDocumentCache().getSize(txn);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TargetId } from '../core/types';\nimport { ChangeType, ViewSnapshot } from '../core/view_snapshot';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\n\n/**\n * A set of changes to what documents are currently in view and out of view for\n * a given query. These changes are sent to the LocalStore by the View (via\n * the SyncEngine) and are used to pin / unpin documents as appropriate.\n */\nexport class LocalViewChanges {\n constructor(\n readonly targetId: TargetId,\n readonly fromCache: boolean,\n readonly addedKeys: DocumentKeySet,\n readonly removedKeys: DocumentKeySet\n ) {}\n\n static fromSnapshot(\n targetId: TargetId,\n viewSnapshot: ViewSnapshot\n ): LocalViewChanges {\n let addedKeys = documentKeySet();\n let removedKeys = documentKeySet();\n\n for (const docChange of viewSnapshot.docChanges) {\n switch (docChange.type) {\n case ChangeType.Added:\n addedKeys = addedKeys.add(docChange.doc.key);\n break;\n case ChangeType.Removed:\n removedKeys = removedKeys.add(docChange.doc.key);\n break;\n default:\n // do nothing\n }\n }\n\n return new LocalViewChanges(\n targetId,\n viewSnapshot.fromCache,\n addedKeys,\n removedKeys\n );\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A tracker to keep a record of important details during database local query\n * execution.\n */\nexport class QueryContext {\n /**\n * Counts the number of documents passed through during local query execution.\n */\n private _documentReadCount = 0;\n\n get documentReadCount(): number {\n return this._documentReadCount;\n }\n\n incrementDocumentReadCount(amount: number): void {\n this._documentReadCount += amount;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n LimitType,\n newQueryComparator,\n Query,\n queryMatches,\n queryMatchesAllDocuments,\n queryToTarget,\n queryWithLimit,\n stringifyQuery\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n documentKeySet,\n DocumentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport {\n IndexOffset,\n INITIAL_LARGEST_BATCH_ID,\n newIndexOffsetSuccessorFromReadTime\n} from '../model/field_index';\nimport { debugAssert } from '../util/assert';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { Iterable } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager, IndexType } from './index_manager';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\n\nconst DEFAULT_INDEX_AUTO_CREATION_MIN_COLLECTION_SIZE = 100;\n\n/**\n * This cost represents the evaluation result of\n * (([index, docKey] + [docKey, docContent]) per document in the result set)\n * / ([docKey, docContent] per documents in full collection scan) coming from\n * experiment [enter PR experiment URL here].\n * TODO(b/299284287) Choose a value appropriate for the browser/OS combination,\n * as determined by more data points from running the experiment.\n */\nconst DEFAULT_RELATIVE_INDEX_READ_COST_PER_DOCUMENT = 8;\n\n/**\n * The Firestore query engine.\n *\n * Firestore queries can be executed in three modes. The Query Engine determines\n * what mode to use based on what data is persisted. The mode only determines\n * the runtime complexity of the query - the result set is equivalent across all\n * implementations.\n *\n * The Query engine will use indexed-based execution if a user has configured\n * any index that can be used to execute query (via `setIndexConfiguration()`).\n * Otherwise, the engine will try to optimize the query by re-using a previously\n * persisted query result. If that is not possible, the query will be executed\n * via a full collection scan.\n *\n * Index-based execution is the default when available. The query engine\n * supports partial indexed execution and merges the result from the index\n * lookup with documents that have not yet been indexed. The index evaluation\n * matches the backend's format and as such, the SDK can use indexing for all\n * queries that the backend supports.\n *\n * If no index exists, the query engine tries to take advantage of the target\n * document mapping in the TargetCache. These mappings exists for all queries\n * that have been synced with the backend at least once and allow the query\n * engine to only read documents that previously matched a query plus any\n * documents that were edited after the query was last listened to.\n *\n * There are some cases when this optimization is not guaranteed to produce\n * the same results as full collection scans. In these cases, query\n * processing falls back to full scans. These cases are:\n *\n * - Limit queries where a document that matched the query previously no longer\n * matches the query.\n *\n * - Limit queries where a document edit may cause the document to sort below\n * another document that is in the local cache.\n *\n * - Queries that have never been CURRENT or free of limbo documents.\n */\nexport class QueryEngine {\n private localDocumentsView!: LocalDocumentsView;\n private indexManager!: IndexManager;\n private initialized = false;\n\n indexAutoCreationEnabled = false;\n\n /**\n * SDK only decides whether it should create index when collection size is\n * larger than this.\n */\n indexAutoCreationMinCollectionSize =\n DEFAULT_INDEX_AUTO_CREATION_MIN_COLLECTION_SIZE;\n\n relativeIndexReadCostPerDocument =\n DEFAULT_RELATIVE_INDEX_READ_COST_PER_DOCUMENT;\n\n /** Sets the document view to query against. */\n initialize(\n localDocuments: LocalDocumentsView,\n indexManager: IndexManager\n ): void {\n this.localDocumentsView = localDocuments;\n this.indexManager = indexManager;\n this.initialized = true;\n }\n\n /** Returns all local documents matching the specified query. */\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n lastLimboFreeSnapshotVersion: SnapshotVersion,\n remoteKeys: DocumentKeySet\n ): PersistencePromise<DocumentMap> {\n debugAssert(this.initialized, 'initialize() not called');\n\n // Stores the result from executing the query; using this object is more\n // convenient than passing the result between steps of the persistence\n // transaction and improves readability comparatively.\n const queryResult: { result: DocumentMap | null } = { result: null };\n\n return this.performQueryUsingIndex(transaction, query)\n .next(result => {\n queryResult.result = result;\n })\n .next(() => {\n if (queryResult.result) {\n return;\n }\n return this.performQueryUsingRemoteKeys(\n transaction,\n query,\n remoteKeys,\n lastLimboFreeSnapshotVersion\n ).next(result => {\n queryResult.result = result;\n });\n })\n .next(() => {\n if (queryResult.result) {\n return;\n }\n const context = new QueryContext();\n return this.executeFullCollectionScan(transaction, query, context).next(\n result => {\n queryResult.result = result;\n if (this.indexAutoCreationEnabled) {\n return this.createCacheIndexes(\n transaction,\n query,\n context,\n result.size\n );\n }\n }\n );\n })\n .next(() => queryResult.result!);\n }\n\n createCacheIndexes(\n transaction: PersistenceTransaction,\n query: Query,\n context: QueryContext,\n resultSize: number\n ): PersistencePromise<void> {\n if (context.documentReadCount < this.indexAutoCreationMinCollectionSize) {\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'SDK will not create cache indexes for query:',\n stringifyQuery(query),\n 'since it only creates cache indexes for collection contains',\n 'more than or equal to',\n this.indexAutoCreationMinCollectionSize,\n 'documents'\n );\n }\n return PersistencePromise.resolve();\n }\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'Query:',\n stringifyQuery(query),\n 'scans',\n context.documentReadCount,\n 'local documents and returns',\n resultSize,\n 'documents as results.'\n );\n }\n\n if (\n context.documentReadCount >\n this.relativeIndexReadCostPerDocument * resultSize\n ) {\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'The SDK decides to create cache indexes for query:',\n stringifyQuery(query),\n 'as using cache indexes may help improve performance.'\n );\n }\n return this.indexManager.createTargetIndexes(\n transaction,\n queryToTarget(query)\n );\n }\n\n return PersistencePromise.resolve();\n }\n\n /**\n * Performs an indexed query that evaluates the query based on a collection's\n * persisted index values. Returns `null` if an index is not available.\n */\n private performQueryUsingIndex(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise<DocumentMap | null> {\n if (queryMatchesAllDocuments(query)) {\n // Queries that match all documents don't benefit from using\n // key-based lookups. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n return PersistencePromise.resolve<DocumentMap | null>(null);\n }\n\n let target = queryToTarget(query);\n return this.indexManager\n .getIndexType(transaction, target)\n .next(indexType => {\n if (indexType === IndexType.NONE) {\n // The target cannot be served from any index.\n return null;\n }\n\n if (query.limit !== null && indexType === IndexType.PARTIAL) {\n // We cannot apply a limit for targets that are served using a partial\n // index. If a partial index will be used to serve the target, the\n // query may return a superset of documents that match the target\n // (e.g. if the index doesn't include all the target's filters), or\n // may return the correct set of documents in the wrong order (e.g. if\n // the index doesn't include a segment for one of the orderBys).\n // Therefore, a limit should not be applied in such cases.\n query = queryWithLimit(query, null, LimitType.First);\n target = queryToTarget(query);\n }\n\n return this.indexManager\n .getDocumentsMatchingTarget(transaction, target)\n .next(keys => {\n debugAssert(\n !!keys,\n 'Index manager must return results for partial and full indexes.'\n );\n const sortedKeys = documentKeySet(...keys);\n return this.localDocumentsView\n .getDocuments(transaction, sortedKeys)\n .next(indexedDocuments => {\n return this.indexManager\n .getMinOffset(transaction, target)\n .next(offset => {\n const previousResults = this.applyQuery(\n query,\n indexedDocuments\n );\n\n if (\n this.needsRefill(\n query,\n previousResults,\n sortedKeys,\n offset.readTime\n )\n ) {\n // A limit query whose boundaries change due to local\n // edits can be re-run against the cache by excluding the\n // limit. This ensures that all documents that match the\n // query's filters are included in the result set. The SDK\n // can then apply the limit once all local edits are\n // incorporated.\n return this.performQueryUsingIndex(\n transaction,\n queryWithLimit(query, null, LimitType.First)\n );\n }\n\n return this.appendRemainingResults(\n transaction,\n previousResults,\n query,\n offset\n ) as PersistencePromise<DocumentMap | null>;\n });\n });\n });\n });\n }\n\n /**\n * Performs a query based on the target's persisted query mapping. Returns\n * `null` if the mapping is not available or cannot be used.\n */\n private performQueryUsingRemoteKeys(\n transaction: PersistenceTransaction,\n query: Query,\n remoteKeys: DocumentKeySet,\n lastLimboFreeSnapshotVersion: SnapshotVersion\n ): PersistencePromise<DocumentMap | null> {\n if (queryMatchesAllDocuments(query)) {\n // Queries that match all documents don't benefit from using\n // key-based lookups. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n return PersistencePromise.resolve<DocumentMap | null>(null);\n }\n\n // Queries that have never seen a snapshot without limbo free documents\n // should also be run as a full collection scan.\n if (lastLimboFreeSnapshotVersion.isEqual(SnapshotVersion.min())) {\n return PersistencePromise.resolve<DocumentMap | null>(null);\n }\n\n return this.localDocumentsView!.getDocuments(transaction, remoteKeys).next(\n documents => {\n const previousResults = this.applyQuery(query, documents);\n\n if (\n this.needsRefill(\n query,\n previousResults,\n remoteKeys,\n lastLimboFreeSnapshotVersion\n )\n ) {\n return PersistencePromise.resolve<DocumentMap | null>(null);\n }\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'Re-using previous result from %s to execute query: %s',\n lastLimboFreeSnapshotVersion.toString(),\n stringifyQuery(query)\n );\n }\n\n // Retrieve all results for documents that were updated since the last\n // limbo-document free remote snapshot.\n return this.appendRemainingResults(\n transaction,\n previousResults,\n query,\n newIndexOffsetSuccessorFromReadTime(\n lastLimboFreeSnapshotVersion,\n INITIAL_LARGEST_BATCH_ID\n )\n ).next<DocumentMap | null>(results => results);\n }\n );\n }\n\n /** Applies the query filter and sorting to the provided documents. */\n private applyQuery(\n query: Query,\n documents: DocumentMap\n ): SortedSet<Document> {\n // Sort the documents and re-apply the query filter since previously\n // matching documents do not necessarily still match the query.\n let queryResults = new SortedSet<Document>(newQueryComparator(query));\n documents.forEach((_, maybeDoc) => {\n if (queryMatches(query, maybeDoc)) {\n queryResults = queryResults.add(maybeDoc);\n }\n });\n return queryResults;\n }\n\n /**\n * Determines if a limit query needs to be refilled from cache, making it\n * ineligible for index-free execution.\n *\n * @param query - The query.\n * @param sortedPreviousResults - The documents that matched the query when it\n * was last synchronized, sorted by the query's comparator.\n * @param remoteKeys - The document keys that matched the query at the last\n * snapshot.\n * @param limboFreeSnapshotVersion - The version of the snapshot when the\n * query was last synchronized.\n */\n private needsRefill(\n query: Query,\n sortedPreviousResults: SortedSet<Document>,\n remoteKeys: DocumentKeySet,\n limboFreeSnapshotVersion: SnapshotVersion\n ): boolean {\n if (query.limit === null) {\n // Queries without limits do not need to be refilled.\n return false;\n }\n\n if (remoteKeys.size !== sortedPreviousResults.size) {\n // The query needs to be refilled if a previously matching document no\n // longer matches.\n return true;\n }\n\n // Limit queries are not eligible for index-free query execution if there is\n // a potential that an older document from cache now sorts before a document\n // that was previously part of the limit. This, however, can only happen if\n // the document at the edge of the limit goes out of limit.\n // If a document that is not the limit boundary sorts differently,\n // the boundary of the limit itself did not change and documents from cache\n // will continue to be \"rejected\" by this boundary. Therefore, we can ignore\n // any modifications that don't affect the last document.\n const docAtLimitEdge =\n query.limitType === LimitType.First\n ? sortedPreviousResults.last()\n : sortedPreviousResults.first();\n if (!docAtLimitEdge) {\n // We don't need to refill the query if there were already no documents.\n return false;\n }\n return (\n docAtLimitEdge.hasPendingWrites ||\n docAtLimitEdge.version.compareTo(limboFreeSnapshotVersion) > 0\n );\n }\n\n private executeFullCollectionScan(\n transaction: PersistenceTransaction,\n query: Query,\n context: QueryContext\n ): PersistencePromise<DocumentMap> {\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'Using full collection scan to execute query:',\n stringifyQuery(query)\n );\n }\n\n return this.localDocumentsView!.getDocumentsMatchingQuery(\n transaction,\n query,\n IndexOffset.min(),\n context\n );\n }\n\n /**\n * Combines the results from an indexed execution with the remaining documents\n * that have not yet been indexed.\n */\n private appendRemainingResults(\n transaction: PersistenceTransaction,\n indexedResults: Iterable<Document>,\n query: Query,\n offset: IndexOffset\n ): PersistencePromise<DocumentMap> {\n // Retrieve all results for documents that were updated since the offset.\n return this.localDocumentsView\n .getDocumentsMatchingQuery(transaction, query, offset)\n .next(remainingResults => {\n // Merge with existing results\n indexedResults.forEach(d => {\n remainingResults = remainingResults.insert(d.key, d);\n });\n return remainingResults;\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { BundleConverter, BundledDocuments, NamedQuery } from '../core/bundle';\nimport {\n newQueryForPath,\n Query,\n queryCollectionGroup,\n queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\nimport { BatchId, TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n convertOverlayedDocumentMapToDocumentMap,\n documentKeySet,\n DocumentKeySet,\n DocumentMap,\n mutableDocumentMap,\n MutableDocumentMap,\n OverlayedDocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexSemanticComparator,\n INITIAL_LARGEST_BATCH_ID,\n newIndexOffsetSuccessorFromReadTime\n} from '../model/field_index';\nimport {\n mutationExtractBaseValue,\n Mutation,\n PatchMutation,\n Precondition\n} from '../model/mutation';\nimport { MutationBatch, MutationBatchResult } from '../model/mutation_batch';\nimport { extractFieldMask } from '../model/object_value';\nimport { ResourcePath } from '../model/path';\nimport {\n BundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { RemoteEvent, TargetChange } from '../remote/remote_event';\nimport { fromVersion, JsonProtoSerializer } from '../remote/serializer';\nimport { diffArrays } from '../util/array';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logDebug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { BundleCache } from './bundle_cache';\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport { IndexedDbPersistence } from './indexeddb_persistence';\nimport { IndexedDbTargetCache } from './indexeddb_target_cache';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { fromBundledQuery } from './local_serializer';\nimport { LocalStore } from './local_store';\nimport { LocalViewChanges } from './local_view_changes';\nimport { LruGarbageCollector, LruResults } from './lru_garbage_collector';\nimport { MutationQueue } from './mutation_queue';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryEngine } from './query_engine';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { ClientId } from './shared_client_state';\nimport { isIndexedDbTransactionError } from './simple_db';\nimport { TargetCache } from './target_cache';\nimport { TargetData, TargetPurpose } from './target_data';\n\nexport const LOG_TAG = 'LocalStore';\n\n/**\n * The maximum time to leave a resume token buffered without writing it out.\n * This value is arbitrary: it's long enough to avoid several writes\n * (possibly indefinitely if updates come more frequently than this) but\n * short enough that restarting after crashing will still have a pretty\n * recent resume token.\n */\nconst RESUME_TOKEN_MAX_AGE_MICROS = 5 * 60 * 1e6;\n\n/** The result of a write to the local store. */\nexport interface LocalWriteResult {\n batchId: BatchId;\n changes: DocumentMap;\n}\n\n/** The result of a user-change operation in the local store. */\nexport interface UserChangeResult {\n readonly affectedDocuments: DocumentMap;\n readonly removedBatchIds: BatchId[];\n readonly addedBatchIds: BatchId[];\n}\n\n/** The result of executing a query against the local store. */\nexport interface QueryResult {\n readonly documents: DocumentMap;\n readonly remoteKeys: DocumentKeySet;\n}\n\n/**\n * Implements `LocalStore` interface.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass LocalStoreImpl implements LocalStore {\n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n mutationQueue!: MutationQueue;\n\n /**\n * The overlays that can be used to short circuit applying all mutations from\n * mutation queue.\n */\n documentOverlayCache!: DocumentOverlayCache;\n\n /** The set of all cached remote documents. */\n remoteDocuments: RemoteDocumentCache;\n\n /**\n * The \"local\" view of all documents (layering mutationQueue on top of\n * remoteDocumentCache).\n */\n localDocuments!: LocalDocumentsView;\n\n /** Manages the list of active field and collection indices. */\n indexManager!: IndexManager;\n\n /** The set of all cached bundle metadata and named queries. */\n bundleCache: BundleCache;\n\n /** Maps a target to its `TargetData`. */\n targetCache: TargetCache;\n\n /**\n * Maps a targetID to data about its target.\n *\n * PORTING NOTE: We are using an immutable data structure on Web to make re-runs\n * of `applyRemoteEvent()` idempotent.\n */\n targetDataByTarget = new SortedMap<TargetId, TargetData>(primitiveComparator);\n\n /** Maps a target to its targetID. */\n // TODO(wuandy): Evaluate if TargetId can be part of Target.\n targetIdByTarget = new ObjectMap<Target, TargetId>(\n t => canonifyTarget(t),\n targetEquals\n );\n\n /**\n * A per collection group index of the last read time processed by\n * `getNewDocumentChanges()`.\n *\n * PORTING NOTE: This is only used for multi-tab synchronization.\n */\n collectionGroupReadTime = new Map<string, SnapshotVersion>();\n\n constructor(\n /** Manages our in-memory or durable persistence. */\n readonly persistence: Persistence,\n readonly queryEngine: QueryEngine,\n initialUser: User,\n readonly serializer: JsonProtoSerializer\n ) {\n debugAssert(\n persistence.started,\n 'LocalStore was passed an unstarted persistence implementation'\n );\n this.remoteDocuments = persistence.getRemoteDocumentCache();\n this.targetCache = persistence.getTargetCache();\n this.bundleCache = persistence.getBundleCache();\n\n this.initializeUserComponents(initialUser);\n }\n\n initializeUserComponents(user: User): void {\n // TODO(indexing): Add spec tests that test these components change after a\n // user change\n this.documentOverlayCache = this.persistence.getDocumentOverlayCache(user);\n this.indexManager = this.persistence.getIndexManager(user);\n this.mutationQueue = this.persistence.getMutationQueue(\n user,\n this.indexManager\n );\n this.localDocuments = new LocalDocumentsView(\n this.remoteDocuments,\n this.mutationQueue,\n this.documentOverlayCache,\n this.indexManager\n );\n this.remoteDocuments.setIndexManager(this.indexManager);\n this.queryEngine.initialize(this.localDocuments, this.indexManager);\n }\n\n collectGarbage(garbageCollector: LruGarbageCollector): Promise<LruResults> {\n return this.persistence.runTransaction(\n 'Collect garbage',\n 'readwrite-primary',\n txn => garbageCollector.collect(txn, this.targetDataByTarget)\n );\n }\n}\n\ninterface DocumentChangeResult {\n changedDocuments: MutableDocumentMap;\n existenceChangedKeys: DocumentKeySet;\n}\n\nexport function newLocalStore(\n /** Manages our in-memory or durable persistence. */\n persistence: Persistence,\n queryEngine: QueryEngine,\n initialUser: User,\n serializer: JsonProtoSerializer\n): LocalStore {\n return new LocalStoreImpl(persistence, queryEngine, initialUser, serializer);\n}\n\n/**\n * Tells the LocalStore that the currently authenticated user has changed.\n *\n * In response the local store switches the mutation queue to the new user and\n * returns any resulting document changes.\n */\n// PORTING NOTE: Android and iOS only return the documents affected by the\n// change.\nexport async function localStoreHandleUserChange(\n localStore: LocalStore,\n user: User\n): Promise<UserChangeResult> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n\n const result = await localStoreImpl.persistence.runTransaction(\n 'Handle user change',\n 'readonly',\n txn => {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n let oldBatches: MutationBatch[];\n return localStoreImpl.mutationQueue\n .getAllMutationBatches(txn)\n .next(promisedOldBatches => {\n oldBatches = promisedOldBatches;\n localStoreImpl.initializeUserComponents(user);\n return localStoreImpl.mutationQueue.getAllMutationBatches(txn);\n })\n .next(newBatches => {\n const removedBatchIds: BatchId[] = [];\n const addedBatchIds: BatchId[] = [];\n\n // Union the old/new changed keys.\n let changedKeys = documentKeySet();\n\n for (const batch of oldBatches) {\n removedBatchIds.push(batch.batchId);\n for (const mutation of batch.mutations) {\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n\n for (const batch of newBatches) {\n addedBatchIds.push(batch.batchId);\n for (const mutation of batch.mutations) {\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n\n // Return the set of all (potentially) changed documents and the list\n // of mutation batch IDs that were affected by change.\n return localStoreImpl.localDocuments\n .getDocuments(txn, changedKeys)\n .next(affectedDocuments => {\n return {\n affectedDocuments,\n removedBatchIds,\n addedBatchIds\n };\n });\n });\n }\n );\n\n return result;\n}\n\n/* Accepts locally generated Mutations and commit them to storage. */\nexport function localStoreWriteLocally(\n localStore: LocalStore,\n mutations: Mutation[]\n): Promise<LocalWriteResult> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const localWriteTime = Timestamp.now();\n const keys = mutations.reduce((keys, m) => keys.add(m.key), documentKeySet());\n\n let overlayedDocuments: OverlayedDocumentMap;\n let mutationBatch: MutationBatch;\n\n return localStoreImpl.persistence\n .runTransaction('Locally write mutations', 'readwrite', txn => {\n // Figure out which keys do not have a remote version in the cache, this\n // is needed to create the right overlay mutation: if no remote version\n // presents, we do not need to create overlays as patch mutations.\n // TODO(Overlay): Is there a better way to determine this? Using the\n // document version does not work because local mutations set them back\n // to 0.\n let remoteDocs = mutableDocumentMap();\n let docsWithoutRemoteVersion = documentKeySet();\n return localStoreImpl.remoteDocuments\n .getEntries(txn, keys)\n .next(docs => {\n remoteDocs = docs;\n remoteDocs.forEach((key, doc) => {\n if (!doc.isValidDocument()) {\n docsWithoutRemoteVersion = docsWithoutRemoteVersion.add(key);\n }\n });\n })\n .next(() => {\n // Load and apply all existing mutations. This lets us compute the\n // current base state for all non-idempotent transforms before applying\n // any additional user-provided writes.\n return localStoreImpl.localDocuments.getOverlayedDocuments(\n txn,\n remoteDocs\n );\n })\n .next((docs: OverlayedDocumentMap) => {\n overlayedDocuments = docs;\n\n // For non-idempotent mutations (such as `FieldValue.increment()`),\n // we record the base state in a separate patch mutation. This is\n // later used to guarantee consistent values and prevents flicker\n // even if the backend sends us an update that already includes our\n // transform.\n const baseMutations: Mutation[] = [];\n\n for (const mutation of mutations) {\n const baseValue = mutationExtractBaseValue(\n mutation,\n overlayedDocuments.get(mutation.key)!.overlayedDocument\n );\n if (baseValue != null) {\n // NOTE: The base state should only be applied if there's some\n // existing document to override, so use a Precondition of\n // exists=true\n baseMutations.push(\n new PatchMutation(\n mutation.key,\n baseValue,\n extractFieldMask(baseValue.value.mapValue),\n Precondition.exists(true)\n )\n );\n }\n }\n\n return localStoreImpl.mutationQueue.addMutationBatch(\n txn,\n localWriteTime,\n baseMutations,\n mutations\n );\n })\n .next(batch => {\n mutationBatch = batch;\n const overlays = batch.applyToLocalDocumentSet(\n overlayedDocuments,\n docsWithoutRemoteVersion\n );\n return localStoreImpl.documentOverlayCache.saveOverlays(\n txn,\n batch.batchId,\n overlays\n );\n });\n })\n .then(() => ({\n batchId: mutationBatch.batchId,\n changes: convertOverlayedDocumentMapToDocumentMap(overlayedDocuments)\n }));\n}\n\n/**\n * Acknowledges the given batch.\n *\n * On the happy path when a batch is acknowledged, the local store will\n *\n * + remove the batch from the mutation queue;\n * + apply the changes to the remote document cache;\n * + recalculate the latency compensated view implied by those changes (there\n * may be mutations in the queue that affect the documents but haven't been\n * acknowledged yet); and\n * + give the changed documents back the sync engine\n *\n * @returns The resulting (modified) documents.\n */\nexport function localStoreAcknowledgeBatch(\n localStore: LocalStore,\n batchResult: MutationBatchResult\n): Promise<DocumentMap> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Acknowledge batch',\n 'readwrite-primary',\n txn => {\n const affected = batchResult.batch.keys();\n const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n return applyWriteToRemoteDocuments(\n localStoreImpl,\n txn,\n batchResult,\n documentBuffer\n )\n .next(() => documentBuffer.apply(txn))\n .next(() => localStoreImpl.mutationQueue.performConsistencyCheck(txn))\n .next(() =>\n localStoreImpl.documentOverlayCache.removeOverlaysForBatchId(\n txn,\n affected,\n batchResult.batch.batchId\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(\n txn,\n getKeysWithTransformResults(batchResult)\n )\n )\n .next(() => localStoreImpl.localDocuments.getDocuments(txn, affected));\n }\n );\n}\n\nfunction getKeysWithTransformResults(\n batchResult: MutationBatchResult\n): DocumentKeySet {\n let result = documentKeySet();\n\n for (let i = 0; i < batchResult.mutationResults.length; ++i) {\n const mutationResult = batchResult.mutationResults[i];\n if (mutationResult.transformResults.length > 0) {\n result = result.add(batchResult.batch.mutations[i].key);\n }\n }\n return result;\n}\n\n/**\n * Removes mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */\nexport function localStoreRejectBatch(\n localStore: LocalStore,\n batchId: BatchId\n): Promise<DocumentMap> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Reject batch',\n 'readwrite-primary',\n txn => {\n let affectedKeys: DocumentKeySet;\n return localStoreImpl.mutationQueue\n .lookupMutationBatch(txn, batchId)\n .next((batch: MutationBatch | null) => {\n hardAssert(batch !== null, 'Attempt to reject nonexistent batch!');\n affectedKeys = batch.keys();\n return localStoreImpl.mutationQueue.removeMutationBatch(txn, batch);\n })\n .next(() => localStoreImpl.mutationQueue.performConsistencyCheck(txn))\n .next(() =>\n localStoreImpl.documentOverlayCache.removeOverlaysForBatchId(\n txn,\n affectedKeys,\n batchId\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(\n txn,\n affectedKeys\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.getDocuments(txn, affectedKeys)\n );\n }\n );\n}\n\n/**\n * Returns the largest (latest) batch id in mutation queue that is pending\n * server response.\n *\n * Returns `BATCHID_UNKNOWN` if the queue is empty.\n */\nexport function localStoreGetHighestUnacknowledgedBatchId(\n localStore: LocalStore\n): Promise<BatchId> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get highest unacknowledged batch id',\n 'readonly',\n txn => localStoreImpl.mutationQueue.getHighestUnacknowledgedBatchId(txn)\n );\n}\n\n/**\n * Returns the last consistent snapshot processed (used by the RemoteStore to\n * determine whether to buffer incoming snapshots from the backend).\n */\nexport function localStoreGetLastRemoteSnapshotVersion(\n localStore: LocalStore\n): Promise<SnapshotVersion> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get last remote snapshot version',\n 'readonly',\n txn => localStoreImpl.targetCache.getLastRemoteSnapshotVersion(txn)\n );\n}\n\n/**\n * Updates the \"ground-state\" (remote) documents. We assume that the remote\n * event reflects any write batches that have been acknowledged or rejected\n * (i.e. we do not re-apply local mutations to updates from this event).\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nexport function localStoreApplyRemoteEventToLocalCache(\n localStore: LocalStore,\n remoteEvent: RemoteEvent\n): Promise<DocumentMap> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const remoteVersion = remoteEvent.snapshotVersion;\n let newTargetDataByTargetMap = localStoreImpl.targetDataByTarget;\n\n return localStoreImpl.persistence\n .runTransaction('Apply remote event', 'readwrite-primary', txn => {\n const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n\n // Reset newTargetDataByTargetMap in case this transaction gets re-run.\n newTargetDataByTargetMap = localStoreImpl.targetDataByTarget;\n\n const promises = [] as Array<PersistencePromise<void>>;\n remoteEvent.targetChanges.forEach((change, targetId) => {\n const oldTargetData = newTargetDataByTargetMap.get(targetId);\n if (!oldTargetData) {\n return;\n }\n\n // Only update the remote keys if the target is still active. This\n // ensures that we can persist the updated target data along with\n // the updated assignment.\n promises.push(\n localStoreImpl.targetCache\n .removeMatchingKeys(txn, change.removedDocuments, targetId)\n .next(() => {\n return localStoreImpl.targetCache.addMatchingKeys(\n txn,\n change.addedDocuments,\n targetId\n );\n })\n );\n\n let newTargetData = oldTargetData.withSequenceNumber(\n txn.currentSequenceNumber\n );\n if (remoteEvent.targetMismatches.get(targetId) !== null) {\n newTargetData = newTargetData\n .withResumeToken(\n ByteString.EMPTY_BYTE_STRING,\n SnapshotVersion.min()\n )\n .withLastLimboFreeSnapshotVersion(SnapshotVersion.min());\n } else if (change.resumeToken.approximateByteSize() > 0) {\n newTargetData = newTargetData.withResumeToken(\n change.resumeToken,\n remoteVersion\n );\n }\n\n newTargetDataByTargetMap = newTargetDataByTargetMap.insert(\n targetId,\n newTargetData\n );\n\n // Update the target data if there are target changes (or if\n // sufficient time has passed since the last update).\n if (shouldPersistTargetData(oldTargetData, newTargetData, change)) {\n promises.push(\n localStoreImpl.targetCache.updateTargetData(txn, newTargetData)\n );\n }\n });\n\n let changedDocs = mutableDocumentMap();\n let existenceChangedKeys = documentKeySet();\n remoteEvent.documentUpdates.forEach(key => {\n if (remoteEvent.resolvedLimboDocuments.has(key)) {\n promises.push(\n localStoreImpl.persistence.referenceDelegate.updateLimboDocument(\n txn,\n key\n )\n );\n }\n });\n\n // Each loop iteration only affects its \"own\" doc, so it's safe to get all\n // the remote documents in advance in a single call.\n promises.push(\n populateDocumentChangeBuffer(\n txn,\n documentBuffer,\n remoteEvent.documentUpdates\n ).next(result => {\n changedDocs = result.changedDocuments;\n existenceChangedKeys = result.existenceChangedKeys;\n })\n );\n\n // HACK: The only reason we allow a null snapshot version is so that we\n // can synthesize remote events when we get permission denied errors while\n // trying to resolve the state of a locally cached document that is in\n // limbo.\n if (!remoteVersion.isEqual(SnapshotVersion.min())) {\n const updateRemoteVersion = localStoreImpl.targetCache\n .getLastRemoteSnapshotVersion(txn)\n .next(lastRemoteSnapshotVersion => {\n debugAssert(\n remoteVersion.compareTo(lastRemoteSnapshotVersion) >= 0,\n 'Watch stream reverted to previous snapshot?? ' +\n remoteVersion +\n ' < ' +\n lastRemoteSnapshotVersion\n );\n return localStoreImpl.targetCache.setTargetsMetadata(\n txn,\n txn.currentSequenceNumber,\n remoteVersion\n );\n });\n promises.push(updateRemoteVersion);\n }\n\n return PersistencePromise.waitFor(promises)\n .next(() => documentBuffer.apply(txn))\n .next(() =>\n localStoreImpl.localDocuments.getLocalViewOfDocuments(\n txn,\n changedDocs,\n existenceChangedKeys\n )\n )\n .next(() => changedDocs);\n })\n .then(changedDocs => {\n localStoreImpl.targetDataByTarget = newTargetDataByTargetMap;\n return changedDocs;\n });\n}\n\n/**\n * Populates document change buffer with documents from backend or a bundle.\n * Returns the document changes resulting from applying those documents, and\n * also a set of documents whose existence state are changed as a result.\n *\n * @param txn - Transaction to use to read existing documents from storage.\n * @param documentBuffer - Document buffer to collect the resulted changes to be\n * applied to storage.\n * @param documents - Documents to be applied.\n */\nfunction populateDocumentChangeBuffer(\n txn: PersistenceTransaction,\n documentBuffer: RemoteDocumentChangeBuffer,\n documents: MutableDocumentMap\n): PersistencePromise<DocumentChangeResult> {\n let updatedKeys = documentKeySet();\n let existenceChangedKeys = documentKeySet();\n documents.forEach(k => (updatedKeys = updatedKeys.add(k)));\n return documentBuffer.getEntries(txn, updatedKeys).next(existingDocs => {\n let changedDocuments = mutableDocumentMap();\n documents.forEach((key, doc) => {\n const existingDoc = existingDocs.get(key)!;\n\n // Check if see if there is a existence state change for this document.\n if (doc.isFoundDocument() !== existingDoc.isFoundDocument()) {\n existenceChangedKeys = existenceChangedKeys.add(key);\n }\n\n // Note: The order of the steps below is important, since we want\n // to ensure that rejected limbo resolutions (which fabricate\n // NoDocuments with SnapshotVersion.min()) never add documents to\n // cache.\n if (doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min())) {\n // NoDocuments with SnapshotVersion.min() are used in manufactured\n // events. We remove these documents from cache since we lost\n // access.\n documentBuffer.removeEntry(key, doc.readTime);\n changedDocuments = changedDocuments.insert(key, doc);\n } else if (\n !existingDoc.isValidDocument() ||\n doc.version.compareTo(existingDoc.version) > 0 ||\n (doc.version.compareTo(existingDoc.version) === 0 &&\n existingDoc.hasPendingWrites)\n ) {\n debugAssert(\n !SnapshotVersion.min().isEqual(doc.readTime),\n 'Cannot add a document when the remote version is zero'\n );\n documentBuffer.addEntry(doc);\n changedDocuments = changedDocuments.insert(key, doc);\n } else {\n logDebug(\n LOG_TAG,\n 'Ignoring outdated watch update for ',\n key,\n '. Current version:',\n existingDoc.version,\n ' Watch version:',\n doc.version\n );\n }\n });\n return { changedDocuments, existenceChangedKeys };\n });\n}\n\n/**\n * Returns true if the newTargetData should be persisted during an update of\n * an active target. TargetData should always be persisted when a target is\n * being released and should not call this function.\n *\n * While the target is active, TargetData updates can be omitted when nothing\n * about the target has changed except metadata like the resume token or\n * snapshot version. Occasionally it's worth the extra write to prevent these\n * values from getting too stale after a crash, but this doesn't have to be\n * too frequent.\n */\nfunction shouldPersistTargetData(\n oldTargetData: TargetData,\n newTargetData: TargetData,\n change: TargetChange\n): boolean {\n // Always persist target data if we don't already have a resume token.\n if (oldTargetData.resumeToken.approximateByteSize() === 0) {\n return true;\n }\n\n // Don't allow resume token changes to be buffered indefinitely. This\n // allows us to be reasonably up-to-date after a crash and avoids needing\n // to loop over all active queries on shutdown. Especially in the browser\n // we may not get time to do anything interesting while the current tab is\n // closing.\n const timeDelta =\n newTargetData.snapshotVersion.toMicroseconds() -\n oldTargetData.snapshotVersion.toMicroseconds();\n if (timeDelta >= RESUME_TOKEN_MAX_AGE_MICROS) {\n return true;\n }\n\n // Otherwise if the only thing that has changed about a target is its resume\n // token it's not worth persisting. Note that the RemoteStore keeps an\n // in-memory view of the currently active targets which includes the current\n // resume token, so stream failure or user changes will still use an\n // up-to-date resume token regardless of what we do here.\n const changes =\n change.addedDocuments.size +\n change.modifiedDocuments.size +\n change.removedDocuments.size;\n return changes > 0;\n}\n\n/**\n * Notifies local store of the changed views to locally pin documents.\n */\nexport async function localStoreNotifyLocalViewChanges(\n localStore: LocalStore,\n viewChanges: LocalViewChanges[]\n): Promise<void> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n try {\n await localStoreImpl.persistence.runTransaction(\n 'notifyLocalViewChanges',\n 'readwrite',\n txn => {\n return PersistencePromise.forEach(\n viewChanges,\n (viewChange: LocalViewChanges) => {\n return PersistencePromise.forEach(\n viewChange.addedKeys,\n (key: DocumentKey) =>\n localStoreImpl.persistence.referenceDelegate.addReference(\n txn,\n viewChange.targetId,\n key\n )\n ).next(() =>\n PersistencePromise.forEach(\n viewChange.removedKeys,\n (key: DocumentKey) =>\n localStoreImpl.persistence.referenceDelegate.removeReference(\n txn,\n viewChange.targetId,\n key\n )\n )\n );\n }\n );\n }\n );\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n // If `notifyLocalViewChanges` fails, we did not advance the sequence\n // number for the documents that were included in this transaction.\n // This might trigger them to be deleted earlier than they otherwise\n // would have, but it should not invalidate the integrity of the data.\n logDebug(LOG_TAG, 'Failed to update sequence numbers: ' + e);\n } else {\n throw e;\n }\n }\n\n for (const viewChange of viewChanges) {\n const targetId = viewChange.targetId;\n\n if (!viewChange.fromCache) {\n const targetData = localStoreImpl.targetDataByTarget.get(targetId);\n debugAssert(\n targetData !== null,\n `Can't set limbo-free snapshot version for unknown target: ${targetId}`\n );\n\n // Advance the last limbo free snapshot version\n const lastLimboFreeSnapshotVersion = targetData.snapshotVersion;\n const updatedTargetData = targetData.withLastLimboFreeSnapshotVersion(\n lastLimboFreeSnapshotVersion\n );\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.insert(targetId, updatedTargetData);\n\n // TODO(b/272564316): Apply the optimization done on other platforms.\n // This is a problem for web because saving the updated targetData from\n // non-primary client conflicts with what primary client saved.\n }\n }\n}\n\n/**\n * Gets the mutation batch after the passed in batchId in the mutation queue\n * or null if empty.\n * @param afterBatchId - If provided, the batch to search after.\n * @returns The next mutation or null if there wasn't one.\n */\nexport function localStoreGetNextMutationBatch(\n localStore: LocalStore,\n afterBatchId?: BatchId\n): Promise<MutationBatch | null> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get next mutation batch',\n 'readonly',\n txn => {\n if (afterBatchId === undefined) {\n afterBatchId = BATCHID_UNKNOWN;\n }\n return localStoreImpl.mutationQueue.getNextMutationBatchAfterBatchId(\n txn,\n afterBatchId\n );\n }\n );\n}\n\n/**\n * Reads the current value of a Document with a given key or null if not\n * found - used for testing.\n */\nexport function localStoreReadDocument(\n localStore: LocalStore,\n key: DocumentKey\n): Promise<Document> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'read document',\n 'readonly',\n txn => localStoreImpl.localDocuments.getDocument(txn, key)\n );\n}\n\n/**\n * Assigns the given target an internal ID so that its results can be pinned so\n * they don't get GC'd. A target must be allocated in the local store before\n * the store can be used to manage its view.\n *\n * Allocating an already allocated `Target` will return the existing `TargetData`\n * for that `Target`.\n */\nexport function localStoreAllocateTarget(\n localStore: LocalStore,\n target: Target\n): Promise<TargetData> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence\n .runTransaction('Allocate target', 'readwrite', txn => {\n let targetData: TargetData;\n return localStoreImpl.targetCache\n .getTargetData(txn, target)\n .next((cached: TargetData | null) => {\n if (cached) {\n // This target has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n targetData = cached;\n return PersistencePromise.resolve(targetData);\n } else {\n return localStoreImpl.targetCache\n .allocateTargetId(txn)\n .next(targetId => {\n targetData = new TargetData(\n target,\n targetId,\n TargetPurpose.Listen,\n txn.currentSequenceNumber\n );\n return localStoreImpl.targetCache\n .addTargetData(txn, targetData)\n .next(() => targetData);\n });\n }\n });\n })\n .then(targetData => {\n // If Multi-Tab is enabled, the existing target data may be newer than\n // the in-memory data\n const cachedTargetData = localStoreImpl.targetDataByTarget.get(\n targetData.targetId\n );\n if (\n cachedTargetData === null ||\n targetData.snapshotVersion.compareTo(cachedTargetData.snapshotVersion) >\n 0\n ) {\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.insert(\n targetData.targetId,\n targetData\n );\n localStoreImpl.targetIdByTarget.set(target, targetData.targetId);\n }\n return targetData;\n });\n}\n\n/**\n * Returns the TargetData as seen by the LocalStore, including updates that may\n * have not yet been persisted to the TargetCache.\n */\n// Visible for testing.\nexport function localStoreGetTargetData(\n localStore: LocalStore,\n transaction: PersistenceTransaction,\n target: Target\n): PersistencePromise<TargetData | null> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const targetId = localStoreImpl.targetIdByTarget.get(target);\n if (targetId !== undefined) {\n return PersistencePromise.resolve<TargetData | null>(\n localStoreImpl.targetDataByTarget.get(targetId)\n );\n } else {\n return localStoreImpl.targetCache.getTargetData(transaction, target);\n }\n}\n\n/**\n * Unpins all the documents associated with the given target. If\n * `keepPersistedTargetData` is set to false and Eager GC enabled, the method\n * directly removes the associated target data from the target cache.\n *\n * Releasing a non-existing `Target` is a no-op.\n */\n// PORTING NOTE: `keepPersistedTargetData` is multi-tab only.\nexport async function localStoreReleaseTarget(\n localStore: LocalStore,\n targetId: number,\n keepPersistedTargetData: boolean\n): Promise<void> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const targetData = localStoreImpl.targetDataByTarget.get(targetId);\n debugAssert(\n targetData !== null,\n `Tried to release nonexistent target: ${targetId}`\n );\n\n const mode = keepPersistedTargetData ? 'readwrite' : 'readwrite-primary';\n\n try {\n if (!keepPersistedTargetData) {\n await localStoreImpl.persistence.runTransaction(\n 'Release target',\n mode,\n txn => {\n return localStoreImpl.persistence.referenceDelegate.removeTarget(\n txn,\n targetData!\n );\n }\n );\n }\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n // All `releaseTarget` does is record the final metadata state for the\n // target, but we've been recording this periodically during target\n // activity. If we lose this write this could cause a very slight\n // difference in the order of target deletion during GC, but we\n // don't define exact LRU semantics so this is acceptable.\n logDebug(\n LOG_TAG,\n `Failed to update sequence numbers for target ${targetId}: ${e}`\n );\n } else {\n throw e;\n }\n }\n\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.remove(targetId);\n localStoreImpl.targetIdByTarget.delete(targetData!.target);\n}\n\n/**\n * Runs the specified query against the local store and returns the results,\n * potentially taking advantage of query data from previous executions (such\n * as the set of remote keys).\n *\n * @param usePreviousResults - Whether results from previous executions can\n * be used to optimize this query execution.\n */\nexport function localStoreExecuteQuery(\n localStore: LocalStore,\n query: Query,\n usePreviousResults: boolean\n): Promise<QueryResult> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n let lastLimboFreeSnapshotVersion = SnapshotVersion.min();\n let remoteKeys = documentKeySet();\n\n return localStoreImpl.persistence.runTransaction(\n 'Execute query',\n 'readwrite', // Use readwrite instead of readonly so indexes can be created\n txn => {\n return localStoreGetTargetData(localStoreImpl, txn, queryToTarget(query))\n .next(targetData => {\n if (targetData) {\n lastLimboFreeSnapshotVersion =\n targetData.lastLimboFreeSnapshotVersion;\n return localStoreImpl.targetCache\n .getMatchingKeysForTargetId(txn, targetData.targetId)\n .next(result => {\n remoteKeys = result;\n });\n }\n })\n .next(() =>\n localStoreImpl.queryEngine.getDocumentsMatchingQuery(\n txn,\n query,\n usePreviousResults\n ? lastLimboFreeSnapshotVersion\n : SnapshotVersion.min(),\n usePreviousResults ? remoteKeys : documentKeySet()\n )\n )\n .next(documents => {\n setMaxReadTime(\n localStoreImpl,\n queryCollectionGroup(query),\n documents\n );\n return { documents, remoteKeys };\n });\n }\n );\n}\n\nfunction applyWriteToRemoteDocuments(\n localStoreImpl: LocalStoreImpl,\n txn: PersistenceTransaction,\n batchResult: MutationBatchResult,\n documentBuffer: RemoteDocumentChangeBuffer\n): PersistencePromise<void> {\n const batch = batchResult.batch;\n const docKeys = batch.keys();\n let promiseChain = PersistencePromise.resolve();\n docKeys.forEach(docKey => {\n promiseChain = promiseChain\n .next(() => documentBuffer.getEntry(txn, docKey))\n .next(doc => {\n const ackVersion = batchResult.docVersions.get(docKey);\n hardAssert(\n ackVersion !== null,\n 'ackVersions should contain every doc in the write.'\n );\n if (doc.version.compareTo(ackVersion!) < 0) {\n batch.applyToRemoteDocument(doc, batchResult);\n if (doc.isValidDocument()) {\n // We use the commitVersion as the readTime rather than the\n // document's updateTime since the updateTime is not advanced\n // for updates that do not modify the underlying document.\n doc.setReadTime(batchResult.commitVersion);\n documentBuffer.addEntry(doc);\n }\n }\n });\n });\n return promiseChain.next(() =>\n localStoreImpl.mutationQueue.removeMutationBatch(txn, batch)\n );\n}\n\n/** Returns the local view of the documents affected by a mutation batch. */\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreLookupMutationDocuments(\n localStore: LocalStore,\n batchId: BatchId\n): Promise<DocumentMap | null> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const mutationQueueImpl = debugCast(\n localStoreImpl.mutationQueue,\n IndexedDbMutationQueue // We only support IndexedDb in multi-tab mode.\n );\n return localStoreImpl.persistence.runTransaction(\n 'Lookup mutation documents',\n 'readonly',\n txn => {\n return mutationQueueImpl.lookupMutationKeys(txn, batchId).next(keys => {\n if (keys) {\n return localStoreImpl.localDocuments.getDocuments(\n txn,\n keys\n ) as PersistencePromise<DocumentMap | null>;\n } else {\n return PersistencePromise.resolve<DocumentMap | null>(null);\n }\n });\n }\n );\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreRemoveCachedMutationBatchMetadata(\n localStore: LocalStore,\n batchId: BatchId\n): void {\n const mutationQueueImpl = debugCast(\n debugCast(localStore, LocalStoreImpl).mutationQueue,\n IndexedDbMutationQueue // We only support IndexedDb in multi-tab mode.\n );\n mutationQueueImpl.removeCachedMutationKeys(batchId);\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetActiveClients(\n localStore: LocalStore\n): Promise<ClientId[]> {\n const persistenceImpl = debugCast(\n debugCast(localStore, LocalStoreImpl).persistence,\n IndexedDbPersistence // We only support IndexedDb in multi-tab mode.\n );\n return persistenceImpl.getActiveClients();\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetCachedTarget(\n localStore: LocalStore,\n targetId: TargetId\n): Promise<Target | null> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const targetCacheImpl = debugCast(\n localStoreImpl.targetCache,\n IndexedDbTargetCache // We only support IndexedDb in multi-tab mode.\n );\n const cachedTargetData = localStoreImpl.targetDataByTarget.get(targetId);\n if (cachedTargetData) {\n return Promise.resolve(cachedTargetData.target);\n } else {\n return localStoreImpl.persistence.runTransaction(\n 'Get target data',\n 'readonly',\n txn => {\n return targetCacheImpl\n .getTargetDataForTarget(txn, targetId)\n .next(targetData => (targetData ? targetData.target : null));\n }\n );\n }\n}\n\n/**\n * Returns the set of documents that have been updated since the last call.\n * If this is the first call, returns the set of changes since client\n * initialization. Further invocations will return document that have changed\n * since the prior call.\n */\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetNewDocumentChanges(\n localStore: LocalStore,\n collectionGroup: string\n): Promise<DocumentMap> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n\n // Get the current maximum read time for the collection. This should always\n // exist, but to reduce the chance for regressions we default to\n // SnapshotVersion.Min()\n // TODO(indexing): Consider removing the default value.\n const readTime =\n localStoreImpl.collectionGroupReadTime.get(collectionGroup) ||\n SnapshotVersion.min();\n\n return localStoreImpl.persistence\n .runTransaction('Get new document changes', 'readonly', txn =>\n localStoreImpl.remoteDocuments.getAllFromCollectionGroup(\n txn,\n collectionGroup,\n newIndexOffsetSuccessorFromReadTime(readTime, INITIAL_LARGEST_BATCH_ID),\n /* limit= */ Number.MAX_SAFE_INTEGER\n )\n )\n .then(changedDocs => {\n setMaxReadTime(localStoreImpl, collectionGroup, changedDocs);\n return changedDocs;\n });\n}\n\n/** Sets the collection group's maximum read time from the given documents. */\n// PORTING NOTE: Multi-Tab only.\nfunction setMaxReadTime(\n localStoreImpl: LocalStoreImpl,\n collectionGroup: string,\n changedDocs: SortedMap<DocumentKey, Document>\n): void {\n let readTime =\n localStoreImpl.collectionGroupReadTime.get(collectionGroup) ||\n SnapshotVersion.min();\n changedDocs.forEach((_, doc) => {\n if (doc.readTime.compareTo(readTime) > 0) {\n readTime = doc.readTime;\n }\n });\n localStoreImpl.collectionGroupReadTime.set(collectionGroup, readTime);\n}\n\n/**\n * Creates a new target using the given bundle name, which will be used to\n * hold the keys of all documents from the bundle in query-document mappings.\n * This ensures that the loaded documents do not get garbage collected\n * right away.\n */\nfunction umbrellaTarget(bundleName: string): Target {\n // It is OK that the path used for the query is not valid, because this will\n // not be read and queried.\n return queryToTarget(\n newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${bundleName}`))\n );\n}\n\n/**\n * Applies the documents from a bundle to the \"ground-state\" (remote)\n * documents.\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nexport async function localStoreApplyBundledDocuments(\n localStore: LocalStore,\n bundleConverter: BundleConverter,\n documents: BundledDocuments,\n bundleName: string\n): Promise<DocumentMap> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n let documentKeys = documentKeySet();\n let documentMap = mutableDocumentMap();\n for (const bundleDoc of documents) {\n const documentKey = bundleConverter.toDocumentKey(bundleDoc.metadata.name!);\n if (bundleDoc.document) {\n documentKeys = documentKeys.add(documentKey);\n }\n const doc = bundleConverter.toMutableDocument(bundleDoc);\n doc.setReadTime(\n bundleConverter.toSnapshotVersion(bundleDoc.metadata.readTime!)\n );\n documentMap = documentMap.insert(documentKey, doc);\n }\n\n const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n\n // Allocates a target to hold all document keys from the bundle, such that\n // they will not get garbage collected right away.\n const umbrellaTargetData = await localStoreAllocateTarget(\n localStoreImpl,\n umbrellaTarget(bundleName)\n );\n return localStoreImpl.persistence.runTransaction(\n 'Apply bundle documents',\n 'readwrite',\n txn => {\n return populateDocumentChangeBuffer(txn, documentBuffer, documentMap)\n .next(documentChangeResult => {\n documentBuffer.apply(txn);\n return documentChangeResult;\n })\n .next(documentChangeResult => {\n return localStoreImpl.targetCache\n .removeMatchingKeysForTargetId(txn, umbrellaTargetData.targetId)\n .next(() =>\n localStoreImpl.targetCache.addMatchingKeys(\n txn,\n documentKeys,\n umbrellaTargetData.targetId\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.getLocalViewOfDocuments(\n txn,\n documentChangeResult.changedDocuments,\n documentChangeResult.existenceChangedKeys\n )\n )\n .next(() => documentChangeResult.changedDocuments);\n });\n }\n );\n}\n\n/**\n * Returns a promise of a boolean to indicate if the given bundle has already\n * been loaded and the create time is newer than the current loading bundle.\n */\nexport function localStoreHasNewerBundle(\n localStore: LocalStore,\n bundleMetadata: BundleMetadata\n): Promise<boolean> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const currentReadTime = fromVersion(bundleMetadata.createTime!);\n return localStoreImpl.persistence\n .runTransaction('hasNewerBundle', 'readonly', transaction => {\n return localStoreImpl.bundleCache.getBundleMetadata(\n transaction,\n bundleMetadata.id!\n );\n })\n .then(cached => {\n return !!cached && cached.createTime!.compareTo(currentReadTime) >= 0;\n });\n}\n\n/**\n * Saves the given `BundleMetadata` to local persistence.\n */\nexport function localStoreSaveBundle(\n localStore: LocalStore,\n bundleMetadata: BundleMetadata\n): Promise<void> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Save bundle',\n 'readwrite',\n transaction => {\n return localStoreImpl.bundleCache.saveBundleMetadata(\n transaction,\n bundleMetadata\n );\n }\n );\n}\n\n/**\n * Returns a promise of a `NamedQuery` associated with given query name. Promise\n * resolves to undefined if no persisted data can be found.\n */\nexport function localStoreGetNamedQuery(\n localStore: LocalStore,\n queryName: string\n): Promise<NamedQuery | undefined> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get named query',\n 'readonly',\n transaction =>\n localStoreImpl.bundleCache.getNamedQuery(transaction, queryName)\n );\n}\n\n/**\n * Saves the given `NamedQuery` to local persistence.\n */\nexport async function localStoreSaveNamedQuery(\n localStore: LocalStore,\n query: ProtoNamedQuery,\n documents: DocumentKeySet = documentKeySet()\n): Promise<void> {\n // Allocate a target for the named query such that it can be resumed\n // from associated read time if users use it to listen.\n // NOTE: this also means if no corresponding target exists, the new target\n // will remain active and will not get collected, unless users happen to\n // unlisten the query somehow.\n const allocated = await localStoreAllocateTarget(\n localStore,\n queryToTarget(fromBundledQuery(query.bundledQuery!))\n );\n\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Save named query',\n 'readwrite',\n transaction => {\n const readTime = fromVersion(query.readTime!);\n // Simply save the query itself if it is older than what the SDK already\n // has.\n if (allocated.snapshotVersion.compareTo(readTime) >= 0) {\n return localStoreImpl.bundleCache.saveNamedQuery(transaction, query);\n }\n\n // Update existing target data because the query from the bundle is newer.\n const newTargetData = allocated.withResumeToken(\n ByteString.EMPTY_BYTE_STRING,\n readTime\n );\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.insert(\n newTargetData.targetId,\n newTargetData\n );\n return localStoreImpl.targetCache\n .updateTargetData(transaction, newTargetData)\n .next(() =>\n localStoreImpl.targetCache.removeMatchingKeysForTargetId(\n transaction,\n allocated.targetId\n )\n )\n .next(() =>\n localStoreImpl.targetCache.addMatchingKeys(\n transaction,\n documents,\n allocated.targetId\n )\n )\n .next(() =>\n localStoreImpl.bundleCache.saveNamedQuery(transaction, query)\n );\n }\n );\n}\n\nexport async function localStoreConfigureFieldIndexes(\n localStore: LocalStore,\n newFieldIndexes: FieldIndex[]\n): Promise<void> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const indexManager = localStoreImpl.indexManager;\n const promises: Array<PersistencePromise<void>> = [];\n return localStoreImpl.persistence.runTransaction(\n 'Configure indexes',\n 'readwrite',\n transaction =>\n indexManager\n .getFieldIndexes(transaction)\n .next(oldFieldIndexes =>\n diffArrays(\n oldFieldIndexes,\n newFieldIndexes,\n fieldIndexSemanticComparator,\n fieldIndex => {\n promises.push(\n indexManager.addFieldIndex(transaction, fieldIndex)\n );\n },\n fieldIndex => {\n promises.push(\n indexManager.deleteFieldIndex(transaction, fieldIndex)\n );\n }\n )\n )\n .next(() => PersistencePromise.waitFor(promises))\n );\n}\n\nexport function localStoreSetIndexAutoCreationEnabled(\n localStore: LocalStore,\n isEnabled: boolean\n): void {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n localStoreImpl.queryEngine.indexAutoCreationEnabled = isEnabled;\n}\n\nexport function localStoreDeleteAllFieldIndexes(\n localStore: LocalStore\n): Promise<void> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const indexManager = localStoreImpl.indexManager;\n return localStoreImpl.persistence.runTransaction(\n 'Delete All Indexes',\n 'readwrite',\n transaction => indexManager.deleteAllFieldIndexes(transaction)\n );\n}\n\n/**\n * Test-only hooks into the SDK for use exclusively by tests.\n */\nexport class TestingHooks {\n private constructor() {\n throw new Error('creating instances is not supported');\n }\n\n static setIndexAutoCreationSettings(\n localStore: LocalStore,\n settings: {\n indexAutoCreationMinCollectionSize?: number;\n relativeIndexReadCostPerDocument?: number;\n }\n ): void {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n if (settings.indexAutoCreationMinCollectionSize !== undefined) {\n localStoreImpl.queryEngine.indexAutoCreationMinCollectionSize =\n settings.indexAutoCreationMinCollectionSize;\n }\n if (settings.relativeIndexReadCostPerDocument !== undefined) {\n localStoreImpl.queryEngine.relativeIndexReadCostPerDocument =\n settings.relativeIndexReadCostPerDocument;\n }\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport {\n BatchId,\n ListenSequenceNumber,\n MutationBatchState,\n OnlineState,\n TargetId\n} from '../core/types';\nimport { TargetIdSet, targetIdSet } from '../model/collections';\nimport { hardAssert, debugAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logError, logDebug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { isSafeInteger, WindowLike } from '../util/types';\n\nimport {\n CLIENT_STATE_KEY_PREFIX,\n ClientStateSchema,\n createBundleLoadedKey,\n createWebStorageClientStateKey,\n createWebStorageMutationBatchKey,\n createWebStorageOnlineStateKey,\n createWebStorageQueryTargetMetadataKey,\n createWebStorageSequenceNumberKey,\n MUTATION_BATCH_KEY_PREFIX,\n MutationMetadataSchema,\n QUERY_TARGET_KEY_PREFIX,\n QueryTargetStateSchema,\n SharedOnlineStateSchema\n} from './shared_client_state_schema';\nimport {\n QueryTargetState,\n SharedClientStateSyncer\n} from './shared_client_state_syncer';\n\nconst LOG_TAG = 'SharedClientState';\n\n/**\n * A randomly-generated key assigned to each Firestore instance at startup.\n */\nexport type ClientId = string;\n\n/**\n * A `SharedClientState` keeps track of the global state of the mutations\n * and query targets for all active clients with the same persistence key (i.e.\n * project ID and FirebaseApp name). It relays local changes to other clients\n * and updates its local state as new state is observed.\n *\n * `SharedClientState` is primarily used for synchronization in Multi-Tab\n * environments. Each tab is responsible for registering its active query\n * targets and mutations. `SharedClientState` will then notify the listener\n * assigned to `.syncEngine` for updates to mutations and queries that\n * originated in other clients.\n *\n * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be\n * assigned before calling `start()`.\n */\nexport interface SharedClientState {\n onlineStateHandler: ((onlineState: OnlineState) => void) | null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n\n /** Registers the Mutation Batch ID of a newly pending mutation. */\n addPendingMutation(batchId: BatchId): void;\n\n /**\n * Records that a pending mutation has been acknowledged or rejected.\n * Called by the primary client to notify secondary clients of mutation\n * results as they come back from the backend.\n */\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void;\n\n /**\n * Associates a new Query Target ID with the local Firestore client. Returns\n * the new query state for the query (which can be 'current' if the query is\n * already associated with another tab).\n *\n * If the target id is already associated with local client, the method simply\n * returns its `QueryTargetState`.\n */\n addLocalQueryTarget(targetId: TargetId): QueryTargetState;\n\n /** Removes the Query Target ID association from the local client. */\n removeLocalQueryTarget(targetId: TargetId): void;\n\n /** Checks whether the target is associated with the local client. */\n isLocalQueryTarget(targetId: TargetId): boolean;\n\n /**\n * Processes an update to a query target.\n *\n * Called by the primary client to notify secondary clients of document\n * changes or state transitions that affect the provided query target.\n */\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void;\n\n /**\n * Removes the target's metadata entry.\n *\n * Called by the primary client when all clients stopped listening to a query\n * target.\n */\n clearQueryState(targetId: TargetId): void;\n\n /**\n * Gets the active Query Targets IDs for all active clients.\n *\n * The implementation for this may require O(n) runtime, where 'n' is the size\n * of the result set.\n */\n // Visible for testing\n getAllActiveQueryTargets(): SortedSet<TargetId>;\n\n /**\n * Checks whether the provided target ID is currently being listened to by\n * any of the active clients.\n *\n * The implementation may require O(n*log m) runtime, where 'n' is the number\n * of clients and 'm' the number of targets.\n */\n isActiveQueryTarget(targetId: TargetId): boolean;\n\n /**\n * Starts the SharedClientState, reads existing client data and registers\n * listeners for updates to new and existing clients.\n */\n start(): Promise<void>;\n\n /** Shuts down the `SharedClientState` and its listeners. */\n shutdown(): void;\n\n /**\n * Changes the active user and removes all existing user-specific data. The\n * user change does not call back into SyncEngine (for example, no mutations\n * will be marked as removed).\n */\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void;\n\n /** Changes the shared online state of all clients. */\n setOnlineState(onlineState: OnlineState): void;\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n\n /**\n * Notifies other clients when remote documents have changed due to loading\n * a bundle.\n *\n * @param collectionGroups The collection groups affected by this bundle.\n */\n notifyBundleLoaded(collectionGroups: Set<string>): void;\n}\n\n/**\n * Holds the state of a mutation batch, including its user ID, batch ID and\n * whether the batch is 'pending', 'acknowledged' or 'rejected'.\n */\n// Visible for testing\nexport class MutationMetadata {\n constructor(\n readonly user: User,\n readonly batchId: BatchId,\n readonly state: MutationBatchState,\n readonly error?: FirestoreError\n ) {\n debugAssert(\n (error !== undefined) === (state === 'rejected'),\n `MutationMetadata must contain an error iff state is 'rejected'`\n );\n }\n\n /**\n * Parses a MutationMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(\n user: User,\n batchId: BatchId,\n value: string\n ): MutationMetadata | null {\n const mutationBatch = JSON.parse(value) as MutationMetadataSchema;\n\n let validData =\n typeof mutationBatch === 'object' &&\n ['pending', 'acknowledged', 'rejected'].indexOf(mutationBatch.state) !==\n -1 &&\n (mutationBatch.error === undefined ||\n typeof mutationBatch.error === 'object');\n\n let firestoreError: FirestoreError | undefined = undefined;\n\n if (validData && mutationBatch.error) {\n validData =\n typeof mutationBatch.error.message === 'string' &&\n typeof mutationBatch.error.code === 'string';\n if (validData) {\n firestoreError = new FirestoreError(\n mutationBatch.error.code as Code,\n mutationBatch.error.message\n );\n }\n }\n\n if (validData) {\n return new MutationMetadata(\n user,\n batchId,\n mutationBatch.state,\n firestoreError\n );\n } else {\n logError(\n LOG_TAG,\n `Failed to parse mutation state for ID '${batchId}': ${value}`\n );\n return null;\n }\n }\n\n toWebStorageJSON(): string {\n const batchMetadata: MutationMetadataSchema = {\n state: this.state,\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n\n if (this.error) {\n batchMetadata.error = {\n code: this.error.code,\n message: this.error.message\n };\n }\n\n return JSON.stringify(batchMetadata);\n }\n}\n\n/**\n * Holds the state of a query target, including its target ID and whether the\n * target is 'not-current', 'current' or 'rejected'.\n */\n// Visible for testing\nexport class QueryTargetMetadata {\n constructor(\n readonly targetId: TargetId,\n readonly state: QueryTargetState,\n readonly error?: FirestoreError\n ) {\n debugAssert(\n (error !== undefined) === (state === 'rejected'),\n `QueryTargetMetadata must contain an error iff state is 'rejected'`\n );\n }\n\n /**\n * Parses a QueryTargetMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(\n targetId: TargetId,\n value: string\n ): QueryTargetMetadata | null {\n const targetState = JSON.parse(value) as QueryTargetStateSchema;\n\n let validData =\n typeof targetState === 'object' &&\n ['not-current', 'current', 'rejected'].indexOf(targetState.state) !==\n -1 &&\n (targetState.error === undefined ||\n typeof targetState.error === 'object');\n\n let firestoreError: FirestoreError | undefined = undefined;\n\n if (validData && targetState.error) {\n validData =\n typeof targetState.error.message === 'string' &&\n typeof targetState.error.code === 'string';\n if (validData) {\n firestoreError = new FirestoreError(\n targetState.error.code as Code,\n targetState.error.message\n );\n }\n }\n\n if (validData) {\n return new QueryTargetMetadata(\n targetId,\n targetState.state,\n firestoreError\n );\n } else {\n logError(\n LOG_TAG,\n `Failed to parse target state for ID '${targetId}': ${value}`\n );\n return null;\n }\n }\n\n toWebStorageJSON(): string {\n const targetState: QueryTargetStateSchema = {\n state: this.state,\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n\n if (this.error) {\n targetState.error = {\n code: this.error.code,\n message: this.error.message\n };\n }\n\n return JSON.stringify(targetState);\n }\n}\n\n/**\n * Metadata state of a single client denoting the query targets it is actively\n * listening to.\n */\n// Visible for testing.\nexport interface ClientState {\n readonly activeTargetIds: TargetIdSet;\n}\n\n/**\n * This class represents the immutable ClientState for a client read from\n * WebStorage, containing the list of active query targets.\n */\nclass RemoteClientState implements ClientState {\n private constructor(\n readonly clientId: ClientId,\n readonly activeTargetIds: TargetIdSet\n ) {}\n\n /**\n * Parses a RemoteClientState from the JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(\n clientId: ClientId,\n value: string\n ): RemoteClientState | null {\n const clientState = JSON.parse(value) as ClientStateSchema;\n\n let validData =\n typeof clientState === 'object' &&\n clientState.activeTargetIds instanceof Array;\n\n let activeTargetIdsSet = targetIdSet();\n\n for (let i = 0; validData && i < clientState.activeTargetIds.length; ++i) {\n validData = isSafeInteger(clientState.activeTargetIds[i]);\n activeTargetIdsSet = activeTargetIdsSet.add(\n clientState.activeTargetIds[i]\n );\n }\n\n if (validData) {\n return new RemoteClientState(clientId, activeTargetIdsSet);\n } else {\n logError(\n LOG_TAG,\n `Failed to parse client data for instance '${clientId}': ${value}`\n );\n return null;\n }\n }\n}\n\n/**\n * This class represents the online state for all clients participating in\n * multi-tab. The online state is only written to by the primary client, and\n * used in secondary clients to update their query views.\n */\nexport class SharedOnlineState {\n constructor(readonly clientId: string, readonly onlineState: OnlineState) {}\n\n /**\n * Parses a SharedOnlineState from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(value: string): SharedOnlineState | null {\n const onlineState = JSON.parse(value) as SharedOnlineStateSchema;\n\n const validData =\n typeof onlineState === 'object' &&\n ['Unknown', 'Online', 'Offline'].indexOf(onlineState.onlineState) !==\n -1 &&\n typeof onlineState.clientId === 'string';\n\n if (validData) {\n return new SharedOnlineState(\n onlineState.clientId,\n onlineState.onlineState as OnlineState\n );\n } else {\n logError(LOG_TAG, `Failed to parse online state: ${value}`);\n return null;\n }\n }\n}\n\n/**\n * Metadata state of the local client. Unlike `RemoteClientState`, this class is\n * mutable and keeps track of all pending mutations, which allows us to\n * update the range of pending mutation batch IDs as new mutations are added or\n * removed.\n *\n * The data in `LocalClientState` is not read from WebStorage and instead\n * updated via its instance methods. The updated state can be serialized via\n * `toWebStorageJSON()`.\n */\n// Visible for testing.\nexport class LocalClientState implements ClientState {\n activeTargetIds = targetIdSet();\n\n addQueryTarget(targetId: TargetId): void {\n this.activeTargetIds = this.activeTargetIds.add(targetId);\n }\n\n removeQueryTarget(targetId: TargetId): void {\n this.activeTargetIds = this.activeTargetIds.delete(targetId);\n }\n\n /**\n * Converts this entry into a JSON-encoded format we can use for WebStorage.\n * Does not encode `clientId` as it is part of the key in WebStorage.\n */\n toWebStorageJSON(): string {\n const data: ClientStateSchema = {\n activeTargetIds: this.activeTargetIds.toArray(),\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n return JSON.stringify(data);\n }\n}\n\n/**\n * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the\n * backing store for the SharedClientState. It keeps track of all active\n * clients and supports modifications of the local client's data.\n */\nexport class WebStorageSharedClientState implements SharedClientState {\n syncEngine: SharedClientStateSyncer | null = null;\n onlineStateHandler: ((onlineState: OnlineState) => void) | null = null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null = null;\n\n private readonly storage: Storage;\n private readonly localClientStorageKey: string;\n private readonly sequenceNumberKey: string;\n private readonly storageListener = this.handleWebStorageEvent.bind(this);\n private readonly onlineStateKey: string;\n private readonly bundleLoadedKey: string;\n private readonly clientStateKeyRe: RegExp;\n private readonly mutationBatchKeyRe: RegExp;\n private readonly queryTargetKeyRe: RegExp;\n private activeClients = new SortedMap<string, ClientState>(\n primitiveComparator\n );\n private started = false;\n private currentUser: User;\n\n /**\n * Captures WebStorage events that occur before `start()` is called. These\n * events are replayed once `WebStorageSharedClientState` is started.\n */\n private earlyEvents: StorageEvent[] = [];\n\n constructor(\n private readonly window: WindowLike,\n private readonly queue: AsyncQueue,\n private readonly persistenceKey: string,\n private readonly localClientId: ClientId,\n initialUser: User\n ) {\n // Escape the special characters mentioned here:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n const escapedPersistenceKey = persistenceKey.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n '\\\\$&'\n );\n\n this.storage = this.window.localStorage;\n this.currentUser = initialUser;\n this.localClientStorageKey = createWebStorageClientStateKey(\n this.persistenceKey,\n this.localClientId\n );\n this.sequenceNumberKey = createWebStorageSequenceNumberKey(\n this.persistenceKey\n );\n this.activeClients = this.activeClients.insert(\n this.localClientId,\n new LocalClientState()\n );\n\n this.clientStateKeyRe = new RegExp(\n `^${CLIENT_STATE_KEY_PREFIX}_${escapedPersistenceKey}_([^_]*)$`\n );\n this.mutationBatchKeyRe = new RegExp(\n `^${MUTATION_BATCH_KEY_PREFIX}_${escapedPersistenceKey}_(\\\\d+)(?:_(.*))?$`\n );\n this.queryTargetKeyRe = new RegExp(\n `^${QUERY_TARGET_KEY_PREFIX}_${escapedPersistenceKey}_(\\\\d+)$`\n );\n\n this.onlineStateKey = createWebStorageOnlineStateKey(this.persistenceKey);\n\n this.bundleLoadedKey = createBundleLoadedKey(this.persistenceKey);\n\n // Rather than adding the storage observer during start(), we add the\n // storage observer during initialization. This ensures that we collect\n // events before other components populate their initial state (during their\n // respective start() calls). Otherwise, we might for example miss a\n // mutation that is added after LocalStore's start() processed the existing\n // mutations but before we observe WebStorage events.\n this.window.addEventListener('storage', this.storageListener);\n }\n\n /** Returns 'true' if WebStorage is available in the current environment. */\n static isAvailable(window: WindowLike | null): window is WindowLike {\n return !!(window && window.localStorage);\n }\n\n async start(): Promise<void> {\n debugAssert(!this.started, 'WebStorageSharedClientState already started');\n debugAssert(\n this.syncEngine !== null,\n 'syncEngine property must be set before calling start()'\n );\n debugAssert(\n this.onlineStateHandler !== null,\n 'onlineStateHandler property must be set before calling start()'\n );\n\n // Retrieve the list of existing clients to backfill the data in\n // SharedClientState.\n const existingClients = await this.syncEngine!.getActiveClients();\n\n for (const clientId of existingClients) {\n if (clientId === this.localClientId) {\n continue;\n }\n\n const storageItem = this.getItem(\n createWebStorageClientStateKey(this.persistenceKey, clientId)\n );\n if (storageItem) {\n const clientState = RemoteClientState.fromWebStorageEntry(\n clientId,\n storageItem\n );\n if (clientState) {\n this.activeClients = this.activeClients.insert(\n clientState.clientId,\n clientState\n );\n }\n }\n }\n\n this.persistClientState();\n\n // Check if there is an existing online state and call the callback handler\n // if applicable.\n const onlineStateJSON = this.storage.getItem(this.onlineStateKey);\n if (onlineStateJSON) {\n const onlineState = this.fromWebStorageOnlineState(onlineStateJSON);\n if (onlineState) {\n this.handleOnlineStateEvent(onlineState);\n }\n }\n\n for (const event of this.earlyEvents) {\n this.handleWebStorageEvent(event);\n }\n\n this.earlyEvents = [];\n\n // Register a window unload hook to remove the client metadata entry from\n // WebStorage even if `shutdown()` was not called.\n this.window.addEventListener('pagehide', () => this.shutdown());\n\n this.started = true;\n }\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void {\n this.setItem(this.sequenceNumberKey, JSON.stringify(sequenceNumber));\n }\n\n getAllActiveQueryTargets(): TargetIdSet {\n return this.extractActiveQueryTargets(this.activeClients);\n }\n\n isActiveQueryTarget(targetId: TargetId): boolean {\n let found = false;\n this.activeClients.forEach((key, value) => {\n if (value.activeTargetIds.has(targetId)) {\n found = true;\n }\n });\n return found;\n }\n\n addPendingMutation(batchId: BatchId): void {\n this.persistMutationState(batchId, 'pending');\n }\n\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void {\n this.persistMutationState(batchId, state, error);\n\n // Once a final mutation result is observed by other clients, they no longer\n // access the mutation's metadata entry. Since WebStorage replays events\n // in order, it is safe to delete the entry right after updating it.\n this.removeMutationState(batchId);\n }\n\n addLocalQueryTarget(targetId: TargetId): QueryTargetState {\n let queryState: QueryTargetState = 'not-current';\n\n // Lookup an existing query state if the target ID was already registered\n // by another tab\n if (this.isActiveQueryTarget(targetId)) {\n const storageItem = this.storage.getItem(\n createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId)\n );\n\n if (storageItem) {\n const metadata = QueryTargetMetadata.fromWebStorageEntry(\n targetId,\n storageItem\n );\n if (metadata) {\n queryState = metadata.state;\n }\n }\n }\n\n this.localClientState.addQueryTarget(targetId);\n this.persistClientState();\n\n return queryState;\n }\n\n removeLocalQueryTarget(targetId: TargetId): void {\n this.localClientState.removeQueryTarget(targetId);\n this.persistClientState();\n }\n\n isLocalQueryTarget(targetId: TargetId): boolean {\n return this.localClientState.activeTargetIds.has(targetId);\n }\n\n clearQueryState(targetId: TargetId): void {\n this.removeItem(\n createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId)\n );\n }\n\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n this.persistQueryTargetState(targetId, state, error);\n }\n\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void {\n removedBatchIds.forEach(batchId => {\n this.removeMutationState(batchId);\n });\n this.currentUser = user;\n addedBatchIds.forEach(batchId => {\n this.addPendingMutation(batchId);\n });\n }\n\n setOnlineState(onlineState: OnlineState): void {\n this.persistOnlineState(onlineState);\n }\n\n notifyBundleLoaded(collectionGroups: Set<string>): void {\n this.persistBundleLoadedState(collectionGroups);\n }\n\n shutdown(): void {\n if (this.started) {\n this.window.removeEventListener('storage', this.storageListener);\n this.removeItem(this.localClientStorageKey);\n this.started = false;\n }\n }\n\n private getItem(key: string): string | null {\n const value = this.storage.getItem(key);\n logDebug(LOG_TAG, 'READ', key, value);\n return value;\n }\n\n private setItem(key: string, value: string): void {\n logDebug(LOG_TAG, 'SET', key, value);\n this.storage.setItem(key, value);\n }\n\n private removeItem(key: string): void {\n logDebug(LOG_TAG, 'REMOVE', key);\n this.storage.removeItem(key);\n }\n\n private handleWebStorageEvent(event: Event): void {\n // Note: The function is typed to take Event to be interface-compatible with\n // `Window.addEventListener`.\n const storageEvent = event as StorageEvent;\n if (storageEvent.storageArea === this.storage) {\n logDebug(LOG_TAG, 'EVENT', storageEvent.key, storageEvent.newValue);\n\n if (storageEvent.key === this.localClientStorageKey) {\n logError(\n 'Received WebStorage notification for local change. Another client might have ' +\n 'garbage-collected our state'\n );\n return;\n }\n\n this.queue.enqueueRetryable(async () => {\n if (!this.started) {\n this.earlyEvents.push(storageEvent);\n return;\n }\n\n if (storageEvent.key === null) {\n return;\n }\n\n if (this.clientStateKeyRe.test(storageEvent.key)) {\n if (storageEvent.newValue != null) {\n const clientState = this.fromWebStorageClientState(\n storageEvent.key,\n storageEvent.newValue\n );\n if (clientState) {\n return this.handleClientStateEvent(\n clientState.clientId,\n clientState\n );\n }\n } else {\n const clientId = this.fromWebStorageClientStateKey(\n storageEvent.key\n )!;\n return this.handleClientStateEvent(clientId, null);\n }\n } else if (this.mutationBatchKeyRe.test(storageEvent.key)) {\n if (storageEvent.newValue !== null) {\n const mutationMetadata = this.fromWebStorageMutationMetadata(\n storageEvent.key,\n storageEvent.newValue\n );\n if (mutationMetadata) {\n return this.handleMutationBatchEvent(mutationMetadata);\n }\n }\n } else if (this.queryTargetKeyRe.test(storageEvent.key)) {\n if (storageEvent.newValue !== null) {\n const queryTargetMetadata = this.fromWebStorageQueryTargetMetadata(\n storageEvent.key,\n storageEvent.newValue\n );\n if (queryTargetMetadata) {\n return this.handleQueryTargetEvent(queryTargetMetadata);\n }\n }\n } else if (storageEvent.key === this.onlineStateKey) {\n if (storageEvent.newValue !== null) {\n const onlineState = this.fromWebStorageOnlineState(\n storageEvent.newValue\n );\n if (onlineState) {\n return this.handleOnlineStateEvent(onlineState);\n }\n }\n } else if (storageEvent.key === this.sequenceNumberKey) {\n debugAssert(\n !!this.sequenceNumberHandler,\n 'Missing sequenceNumberHandler'\n );\n const sequenceNumber = fromWebStorageSequenceNumber(\n storageEvent.newValue\n );\n if (sequenceNumber !== ListenSequence.INVALID) {\n this.sequenceNumberHandler!(sequenceNumber);\n }\n } else if (storageEvent.key === this.bundleLoadedKey) {\n const collectionGroups = this.fromWebStoreBundleLoadedState(\n storageEvent.newValue!\n );\n await Promise.all(\n collectionGroups.map(cg =>\n this.syncEngine!.synchronizeWithChangedDocuments(cg)\n )\n );\n }\n });\n }\n }\n\n private get localClientState(): LocalClientState {\n return this.activeClients.get(this.localClientId) as LocalClientState;\n }\n\n private persistClientState(): void {\n this.setItem(\n this.localClientStorageKey,\n this.localClientState.toWebStorageJSON()\n );\n }\n\n private persistMutationState(\n batchId: BatchId,\n state: MutationBatchState,\n error?: FirestoreError\n ): void {\n const mutationState = new MutationMetadata(\n this.currentUser,\n batchId,\n state,\n error\n );\n const mutationKey = createWebStorageMutationBatchKey(\n this.persistenceKey,\n this.currentUser,\n batchId\n );\n this.setItem(mutationKey, mutationState.toWebStorageJSON());\n }\n\n private removeMutationState(batchId: BatchId): void {\n const mutationKey = createWebStorageMutationBatchKey(\n this.persistenceKey,\n this.currentUser,\n batchId\n );\n this.removeItem(mutationKey);\n }\n\n private persistOnlineState(onlineState: OnlineState): void {\n const entry: SharedOnlineStateSchema = {\n clientId: this.localClientId,\n onlineState\n };\n this.storage.setItem(this.onlineStateKey, JSON.stringify(entry));\n }\n\n private persistQueryTargetState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n const targetKey = createWebStorageQueryTargetMetadataKey(\n this.persistenceKey,\n targetId\n );\n const targetMetadata = new QueryTargetMetadata(targetId, state, error);\n this.setItem(targetKey, targetMetadata.toWebStorageJSON());\n }\n\n private persistBundleLoadedState(collectionGroups: Set<string>): void {\n const json = JSON.stringify(Array.from(collectionGroups));\n this.setItem(this.bundleLoadedKey, json);\n }\n\n /**\n * Parses a client state key in WebStorage. Returns null if the key does not\n * match the expected key format.\n */\n private fromWebStorageClientStateKey(key: string): ClientId | null {\n const match = this.clientStateKeyRe.exec(key);\n return match ? match[1] : null;\n }\n\n /**\n * Parses a client state in WebStorage. Returns 'null' if the value could not\n * be parsed.\n */\n private fromWebStorageClientState(\n key: string,\n value: string\n ): RemoteClientState | null {\n const clientId = this.fromWebStorageClientStateKey(key);\n debugAssert(clientId !== null, `Cannot parse client state key '${key}'`);\n return RemoteClientState.fromWebStorageEntry(clientId, value);\n }\n\n /**\n * Parses a mutation batch state in WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageMutationMetadata(\n key: string,\n value: string\n ): MutationMetadata | null {\n const match = this.mutationBatchKeyRe.exec(key);\n debugAssert(match !== null, `Cannot parse mutation batch key '${key}'`);\n\n const batchId = Number(match[1]);\n const userId = match[2] !== undefined ? match[2] : null;\n return MutationMetadata.fromWebStorageEntry(\n new User(userId),\n batchId,\n value\n );\n }\n\n /**\n * Parses a query target state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageQueryTargetMetadata(\n key: string,\n value: string\n ): QueryTargetMetadata | null {\n const match = this.queryTargetKeyRe.exec(key);\n debugAssert(match !== null, `Cannot parse query target key '${key}'`);\n\n const targetId = Number(match[1]);\n return QueryTargetMetadata.fromWebStorageEntry(targetId, value);\n }\n\n /**\n * Parses an online state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageOnlineState(value: string): SharedOnlineState | null {\n return SharedOnlineState.fromWebStorageEntry(value);\n }\n\n private fromWebStoreBundleLoadedState(value: string): string[] {\n return JSON.parse(value) as string[];\n }\n\n private async handleMutationBatchEvent(\n mutationBatch: MutationMetadata\n ): Promise<void> {\n if (mutationBatch.user.uid !== this.currentUser.uid) {\n logDebug(\n LOG_TAG,\n `Ignoring mutation for non-active user ${mutationBatch.user.uid}`\n );\n return;\n }\n\n return this.syncEngine!.applyBatchState(\n mutationBatch.batchId,\n mutationBatch.state,\n mutationBatch.error\n );\n }\n\n private handleQueryTargetEvent(\n targetMetadata: QueryTargetMetadata\n ): Promise<void> {\n return this.syncEngine!.applyTargetState(\n targetMetadata.targetId,\n targetMetadata.state,\n targetMetadata.error\n );\n }\n\n private handleClientStateEvent(\n clientId: ClientId,\n clientState: RemoteClientState | null\n ): Promise<void> {\n const updatedClients = clientState\n ? this.activeClients.insert(clientId, clientState)\n : this.activeClients.remove(clientId);\n\n const existingTargets = this.extractActiveQueryTargets(this.activeClients);\n const newTargets = this.extractActiveQueryTargets(updatedClients);\n\n const addedTargets: TargetId[] = [];\n const removedTargets: TargetId[] = [];\n\n newTargets.forEach(targetId => {\n if (!existingTargets.has(targetId)) {\n addedTargets.push(targetId);\n }\n });\n\n existingTargets.forEach(targetId => {\n if (!newTargets.has(targetId)) {\n removedTargets.push(targetId);\n }\n });\n\n return this.syncEngine!.applyActiveTargetsChange(\n addedTargets,\n removedTargets\n ).then(() => {\n this.activeClients = updatedClients;\n });\n }\n\n private handleOnlineStateEvent(onlineState: SharedOnlineState): void {\n // We check whether the client that wrote this online state is still active\n // by comparing its client ID to the list of clients kept active in\n // IndexedDb. If a client does not update their IndexedDb client state\n // within 5 seconds, it is considered inactive and we don't emit an online\n // state event.\n if (this.activeClients.get(onlineState.clientId)) {\n this.onlineStateHandler!(onlineState.onlineState);\n }\n }\n\n private extractActiveQueryTargets(\n clients: SortedMap<string, ClientState>\n ): SortedSet<TargetId> {\n let activeTargets = targetIdSet();\n clients.forEach((kev, value) => {\n activeTargets = activeTargets.unionWith(value.activeTargetIds);\n });\n return activeTargets;\n }\n}\n\nfunction fromWebStorageSequenceNumber(\n seqString: string | null\n): ListenSequenceNumber {\n let sequenceNumber = ListenSequence.INVALID;\n if (seqString != null) {\n try {\n const parsed = JSON.parse(seqString);\n hardAssert(\n typeof parsed === 'number',\n 'Found non-numeric sequence number'\n );\n sequenceNumber = parsed;\n } catch (e) {\n logError(LOG_TAG, 'Failed to read sequence number from WebStorage', e);\n }\n }\n return sequenceNumber;\n}\n\n/**\n * `MemorySharedClientState` is a simple implementation of SharedClientState for\n * clients using memory persistence. The state in this class remains fully\n * isolated and no synchronization is performed.\n */\nexport class MemorySharedClientState implements SharedClientState {\n private localState = new LocalClientState();\n private queryState: { [targetId: number]: QueryTargetState } = {};\n onlineStateHandler: ((onlineState: OnlineState) => void) | null = null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null = null;\n\n addPendingMutation(batchId: BatchId): void {\n // No op.\n }\n\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void {\n // No op.\n }\n\n addLocalQueryTarget(targetId: TargetId): QueryTargetState {\n this.localState.addQueryTarget(targetId);\n return this.queryState[targetId] || 'not-current';\n }\n\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n this.queryState[targetId] = state;\n }\n\n removeLocalQueryTarget(targetId: TargetId): void {\n this.localState.removeQueryTarget(targetId);\n }\n\n isLocalQueryTarget(targetId: TargetId): boolean {\n return this.localState.activeTargetIds.has(targetId);\n }\n\n clearQueryState(targetId: TargetId): void {\n delete this.queryState[targetId];\n }\n\n getAllActiveQueryTargets(): TargetIdSet {\n return this.localState.activeTargetIds;\n }\n\n isActiveQueryTarget(targetId: TargetId): boolean {\n return this.localState.activeTargetIds.has(targetId);\n }\n\n start(): Promise<void> {\n this.localState = new LocalClientState();\n return Promise.resolve();\n }\n\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void {\n // No op.\n }\n\n setOnlineState(onlineState: OnlineState): void {\n // No op.\n }\n\n shutdown(): void {}\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void {}\n\n notifyBundleLoaded(collectionGroups: Set<string>): void {\n // No op.\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ConnectivityMonitor, NetworkStatus } from './connectivity_monitor';\n\nexport class NoopConnectivityMonitor implements ConnectivityMonitor {\n addCallback(callback: (status: NetworkStatus) => void): void {\n // No-op.\n }\n\n shutdown(): void {\n // No-op.\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ConnectivityMonitor,\n ConnectivityMonitorCallback,\n NetworkStatus\n} from '../../remote/connectivity_monitor';\nimport { logDebug } from '../../util/log';\n\n// References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()\n/* eslint-disable no-restricted-globals */\n\nconst LOG_TAG = 'ConnectivityMonitor';\n\n/**\n * Browser implementation of ConnectivityMonitor.\n */\nexport class BrowserConnectivityMonitor implements ConnectivityMonitor {\n private readonly networkAvailableListener = (): void =>\n this.onNetworkAvailable();\n private readonly networkUnavailableListener = (): void =>\n this.onNetworkUnavailable();\n private callbacks: ConnectivityMonitorCallback[] = [];\n\n constructor() {\n this.configureNetworkMonitoring();\n }\n\n addCallback(callback: (status: NetworkStatus) => void): void {\n this.callbacks.push(callback);\n }\n\n shutdown(): void {\n window.removeEventListener('online', this.networkAvailableListener);\n window.removeEventListener('offline', this.networkUnavailableListener);\n }\n\n private configureNetworkMonitoring(): void {\n window.addEventListener('online', this.networkAvailableListener);\n window.addEventListener('offline', this.networkUnavailableListener);\n }\n\n private onNetworkAvailable(): void {\n logDebug(LOG_TAG, 'Network connectivity changed: AVAILABLE');\n for (const callback of this.callbacks) {\n callback(NetworkStatus.AVAILABLE);\n }\n }\n\n private onNetworkUnavailable(): void {\n logDebug(LOG_TAG, 'Network connectivity changed: UNAVAILABLE');\n for (const callback of this.callbacks) {\n callback(NetworkStatus.UNAVAILABLE);\n }\n }\n\n // TODO(chenbrian): Consider passing in window either into this component or\n // here for testing via FakeWindow.\n /** Checks that all used attributes of window are available. */\n static isAvailable(): boolean {\n return (\n typeof window !== 'undefined' &&\n window.addEventListener !== undefined &&\n window.removeEventListener !== undefined\n );\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The value returned from the most recent invocation of\n * `generateUniqueDebugId()`, or null if it has never been invoked.\n */\nlet lastUniqueDebugId: number | null = null;\n\n/**\n * Generates and returns an initial value for `lastUniqueDebugId`.\n *\n * The returned value is randomly selected from a range of integers that are\n * represented as 8 hexadecimal digits. This means that (within reason) any\n * numbers generated by incrementing the returned number by 1 will also be\n * represented by 8 hexadecimal digits. This leads to all \"IDs\" having the same\n * length when converted to a hexadecimal string, making reading logs containing\n * these IDs easier to follow. And since the return value is randomly selected\n * it will help to differentiate between logs from different executions.\n */\nfunction generateInitialUniqueDebugId(): number {\n const minResult = 0x10000000;\n const maxResult = 0x90000000;\n const resultRange = maxResult - minResult;\n const resultOffset = Math.round(resultRange * Math.random());\n return minResult + resultOffset;\n}\n\n/**\n * Generates and returns a unique ID as a hexadecimal string.\n *\n * The returned ID is intended to be used in debug logging messages to help\n * correlate log messages that may be spatially separated in the logs, but\n * logically related. For example, a network connection could include the same\n * \"debug ID\" string in all of its log messages to help trace a specific\n * connection over time.\n *\n * @return the 10-character generated ID (e.g. \"0xa1b2c3d4\").\n */\nexport function generateUniqueDebugId(): string {\n if (lastUniqueDebugId === null) {\n lastUniqueDebugId = generateInitialUniqueDebugId();\n } else {\n lastUniqueDebugId++;\n }\n return '0x' + lastUniqueDebugId.toString(16);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../../src/core/version';\nimport { Token } from '../api/credentials';\nimport {\n DatabaseId,\n DatabaseInfo,\n DEFAULT_DATABASE_NAME\n} from '../core/database_info';\nimport { debugAssert } from '../util/assert';\nimport { generateUniqueDebugId } from '../util/debug_uid';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { StringMap } from '../util/types';\n\nimport { Connection, Stream } from './connection';\n\nconst LOG_TAG = 'RestConnection';\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\nconst RPC_NAME_URL_MAPPING: StringMap = {};\n\nRPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet';\nRPC_NAME_URL_MAPPING['Commit'] = 'commit';\nRPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery';\nRPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery';\n\nconst RPC_URL_VERSION = 'v1';\n\n// SDK_VERSION is updated to different value at runtime depending on the entry point,\n// so we need to get its value when we need it in a function.\nfunction getGoogApiClientValue(): string {\n return 'gl-js/ fire/' + SDK_VERSION;\n}\n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nexport abstract class RestConnection implements Connection {\n protected readonly databaseId: DatabaseId;\n protected readonly baseUrl: string;\n private readonly databasePath: string;\n private readonly requestParams: string;\n\n get shouldResourcePathBeIncludedInRequest(): boolean {\n // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n // where to run the query, and expect the `request` to NOT specify the \"path\".\n return false;\n }\n\n constructor(private readonly databaseInfo: DatabaseInfo) {\n this.databaseId = databaseInfo.databaseId;\n const proto = databaseInfo.ssl ? 'https' : 'http';\n const projectId = encodeURIComponent(this.databaseId.projectId);\n const databaseId = encodeURIComponent(this.databaseId.database);\n this.baseUrl = proto + '://' + databaseInfo.host;\n this.databasePath = `projects/${projectId}/databases/${databaseId}`;\n this.requestParams =\n this.databaseId.database === DEFAULT_DATABASE_NAME\n ? `project_id=${projectId}`\n : `project_id=${projectId}&database_id=${databaseId}`;\n }\n\n invokeRPC<Req, Resp>(\n rpcName: string,\n path: string,\n req: Req,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Promise<Resp> {\n const streamId = generateUniqueDebugId();\n const url = this.makeUrl(rpcName, path);\n logDebug(LOG_TAG, `Sending RPC '${rpcName}' ${streamId}:`, url, req);\n\n const headers: StringMap = {\n 'google-cloud-resource-prefix': this.databasePath,\n 'x-goog-request-params': this.requestParams\n };\n this.modifyHeadersForRequest(headers, authToken, appCheckToken);\n\n return this.performRPCRequest<Req, Resp>(rpcName, url, headers, req).then(\n response => {\n logDebug(LOG_TAG, `Received RPC '${rpcName}' ${streamId}: `, response);\n return response;\n },\n (err: FirestoreError) => {\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with error: `,\n err,\n 'url: ',\n url,\n 'request:',\n req\n );\n throw err;\n }\n );\n }\n\n invokeStreamingRPC<Req, Resp>(\n rpcName: string,\n path: string,\n request: Req,\n authToken: Token | null,\n appCheckToken: Token | null,\n expectedResponseCount?: number\n ): Promise<Resp[]> {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.invokeRPC<Req, Resp[]>(\n rpcName,\n path,\n request,\n authToken,\n appCheckToken\n );\n }\n\n abstract openStream<Req, Resp>(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream<Req, Resp>;\n\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n protected modifyHeadersForRequest(\n headers: StringMap,\n authToken: Token | null,\n appCheckToken: Token | null\n ): void {\n headers['X-Goog-Api-Client'] = getGoogApiClientValue();\n\n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the $httpOverwrite\n // parameter supported by ESF to avoid triggering preflight requests.\n headers['Content-Type'] = 'text/plain';\n\n if (this.databaseInfo.appId) {\n headers['X-Firebase-GMPID'] = this.databaseInfo.appId;\n }\n\n if (authToken) {\n authToken.headers.forEach((value, key) => (headers[key] = value));\n }\n if (appCheckToken) {\n appCheckToken.headers.forEach((value, key) => (headers[key] = value));\n }\n }\n\n /**\n * Performs an RPC request using an implementation specific networking layer.\n */\n protected abstract performRPCRequest<Req, Resp>(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req\n ): Promise<Resp>;\n\n private makeUrl(rpcName: string, path: string): string {\n const urlRpcName = RPC_NAME_URL_MAPPING[rpcName];\n debugAssert(\n urlRpcName !== undefined,\n 'Unknown REST mapping for: ' + rpcName\n );\n return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\nimport { FirestoreError } from '../util/error';\n\nimport { Stream } from './connection';\n\n/**\n * Provides a simple helper class that implements the Stream interface to\n * bridge to other implementations that are streams but do not implement the\n * interface. The stream callbacks are invoked with the callOn... methods.\n */\nexport class StreamBridge<I, O> implements Stream<I, O> {\n private wrappedOnOpen: (() => void) | undefined;\n private wrappedOnClose: ((err?: FirestoreError) => void) | undefined;\n private wrappedOnMessage: ((msg: O) => void) | undefined;\n\n private sendFn: (msg: I) => void;\n private closeFn: () => void;\n\n constructor(args: { sendFn: (msg: I) => void; closeFn: () => void }) {\n this.sendFn = args.sendFn;\n this.closeFn = args.closeFn;\n }\n\n onOpen(callback: () => void): void {\n debugAssert(!this.wrappedOnOpen, 'Called onOpen on stream twice!');\n this.wrappedOnOpen = callback;\n }\n\n onClose(callback: (err?: FirestoreError) => void): void {\n debugAssert(!this.wrappedOnClose, 'Called onClose on stream twice!');\n this.wrappedOnClose = callback;\n }\n\n onMessage(callback: (msg: O) => void): void {\n debugAssert(!this.wrappedOnMessage, 'Called onMessage on stream twice!');\n this.wrappedOnMessage = callback;\n }\n\n close(): void {\n this.closeFn();\n }\n\n send(msg: I): void {\n this.sendFn(msg);\n }\n\n callOnOpen(): void {\n debugAssert(\n this.wrappedOnOpen !== undefined,\n 'Cannot call onOpen because no callback was set'\n );\n this.wrappedOnOpen();\n }\n\n callOnClose(err?: FirestoreError): void {\n debugAssert(\n this.wrappedOnClose !== undefined,\n 'Cannot call onClose because no callback was set'\n );\n this.wrappedOnClose(err);\n }\n\n callOnMessage(msg: O): void {\n debugAssert(\n this.wrappedOnMessage !== undefined,\n 'Cannot call onMessage because no callback was set'\n );\n this.wrappedOnMessage(msg);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createWebChannelTransport,\n ErrorCode,\n EventType,\n WebChannel,\n WebChannelError,\n WebChannelOptions,\n XhrIo,\n getStatEventTarget,\n EventTarget,\n StatEvent,\n Event,\n Stat,\n FetchXmlHttpFactory\n} from '@firebase/webchannel-wrapper';\n\nimport { Token } from '../../api/credentials';\nimport { ExperimentalLongPollingOptions } from '../../api/long_polling_options';\nimport { DatabaseInfo } from '../../core/database_info';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport {\n mapCodeFromRpcStatus,\n mapCodeFromHttpResponseErrorStatus\n} from '../../remote/rpc_error';\nimport { StreamBridge } from '../../remote/stream_bridge';\nimport { fail, hardAssert } from '../../util/assert';\nimport { generateUniqueDebugId } from '../../util/debug_uid';\nimport { Code, FirestoreError } from '../../util/error';\nimport { logDebug, logWarn } from '../../util/log';\nimport { Rejecter, Resolver } from '../../util/promise';\nimport { StringMap } from '../../util/types';\n\nconst LOG_TAG = 'WebChannelConnection';\n\nconst RPC_STREAM_SERVICE = 'google.firestore.v1.Firestore';\n\nconst XHR_TIMEOUT_SECS = 15;\n\nexport class WebChannelConnection extends RestConnection {\n private readonly forceLongPolling: boolean;\n private readonly autoDetectLongPolling: boolean;\n private readonly useFetchStreams: boolean;\n private readonly longPollingOptions: ExperimentalLongPollingOptions;\n\n constructor(info: DatabaseInfo) {\n super(info);\n this.forceLongPolling = info.forceLongPolling;\n this.autoDetectLongPolling = info.autoDetectLongPolling;\n this.useFetchStreams = info.useFetchStreams;\n this.longPollingOptions = info.longPollingOptions;\n }\n\n protected performRPCRequest<Req, Resp>(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req\n ): Promise<Resp> {\n const streamId = generateUniqueDebugId();\n return new Promise((resolve: Resolver<Resp>, reject: Rejecter) => {\n const xhr = new XhrIo();\n xhr.setWithCredentials(true);\n xhr.listenOnce(EventType.COMPLETE, () => {\n try {\n switch (xhr.getLastErrorCode()) {\n case ErrorCode.NO_ERROR:\n const json = xhr.getResponseJson() as Resp;\n logDebug(\n LOG_TAG,\n `XHR for RPC '${rpcName}' ${streamId} received:`,\n JSON.stringify(json)\n );\n resolve(json);\n break;\n case ErrorCode.TIMEOUT:\n logDebug(LOG_TAG, `RPC '${rpcName}' ${streamId} timed out`);\n reject(\n new FirestoreError(Code.DEADLINE_EXCEEDED, 'Request time out')\n );\n break;\n case ErrorCode.HTTP_ERROR:\n const status = xhr.getStatus();\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with status:`,\n status,\n 'response text:',\n xhr.getResponseText()\n );\n if (status > 0) {\n let response = xhr.getResponseJson();\n if (Array.isArray(response)) {\n response = response[0];\n }\n const responseError = (response as WebChannelError)?.error;\n if (\n !!responseError &&\n !!responseError.status &&\n !!responseError.message\n ) {\n const firestoreErrorCode = mapCodeFromHttpResponseErrorStatus(\n responseError.status\n );\n reject(\n new FirestoreError(\n firestoreErrorCode,\n responseError.message\n )\n );\n } else {\n reject(\n new FirestoreError(\n Code.UNKNOWN,\n 'Server responded with status ' + xhr.getStatus()\n )\n );\n }\n } else {\n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue\n reject(\n new FirestoreError(Code.UNAVAILABLE, 'Connection failed.')\n );\n }\n break;\n default:\n fail(\n `RPC '${rpcName}' ${streamId} ` +\n 'failed with unanticipated webchannel error: ' +\n xhr.getLastErrorCode() +\n ': ' +\n xhr.getLastError() +\n ', giving up.'\n );\n }\n } finally {\n logDebug(LOG_TAG, `RPC '${rpcName}' ${streamId} completed.`);\n }\n });\n\n const requestString = JSON.stringify(body);\n logDebug(LOG_TAG, `RPC '${rpcName}' ${streamId} sending request:`, body);\n xhr.send(url, 'POST', requestString, headers, XHR_TIMEOUT_SECS);\n });\n }\n\n openStream<Req, Resp>(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream<Req, Resp> {\n const streamId = generateUniqueDebugId();\n const urlParts = [\n this.baseUrl,\n '/',\n RPC_STREAM_SERVICE,\n '/',\n rpcName,\n '/channel'\n ];\n const webchannelTransport = createWebChannelTransport();\n const requestStats = getStatEventTarget();\n const request: WebChannelOptions = {\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: 'gsessionid',\n initMessageHeaders: {},\n messageUrlParams: {\n // This param is used to improve routing and project isolation by the\n // backend and must be included in every request.\n database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`\n },\n sendRawJson: true,\n supportsCrossDomainXhr: true,\n internalChannelParams: {\n // Override the default timeout (randomized between 10-20 seconds) since\n // a large write batch on a slow internet connection may take a long\n // time to send to the backend. Rather than have WebChannel impose a\n // tight timeout which could lead to infinite timeouts and retries, we\n // set it very large (5-10 minutes) and rely on the browser's builtin\n // timeouts to kick in if the request isn't working.\n forwardChannelRequestTimeoutMs: 10 * 60 * 1000\n },\n forceLongPolling: this.forceLongPolling,\n detectBufferingProxy: this.autoDetectLongPolling\n };\n\n const longPollingTimeoutSeconds = this.longPollingOptions.timeoutSeconds;\n if (longPollingTimeoutSeconds !== undefined) {\n request.longPollingTimeout = Math.round(longPollingTimeoutSeconds * 1000);\n }\n\n if (this.useFetchStreams) {\n // TODO(b/307942499): switch to `useFetchStreams` once WebChannel is fixed.\n request.xmlHttpFactory = new FetchXmlHttpFactory({});\n }\n\n this.modifyHeadersForRequest(\n request.initMessageHeaders!,\n authToken,\n appCheckToken\n );\n\n // Sending the custom headers we just added to request.initMessageHeaders\n // (Authorization, etc.) will trigger the browser to make a CORS preflight\n // request because the XHR will no longer meet the criteria for a \"simple\"\n // CORS request:\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests\n //\n // Therefore to avoid the CORS preflight request (an extra network\n // roundtrip), we use the encodeInitMessageHeaders option to specify that\n // the headers should instead be encoded in the request's POST payload,\n // which is recognized by the webchannel backend.\n request.encodeInitMessageHeaders = true;\n\n const url = urlParts.join('');\n logDebug(\n LOG_TAG,\n `Creating RPC '${rpcName}' stream ${streamId}: ${url}`,\n request\n );\n const channel = webchannelTransport.createWebChannel(url, request);\n\n // WebChannel supports sending the first message with the handshake - saving\n // a network round trip. However, it will have to call send in the same\n // JS event loop as open. In order to enforce this, we delay actually\n // opening the WebChannel until send is called. Whether we have called\n // open is tracked with this variable.\n let opened = false;\n\n // A flag to determine whether the stream was closed (by us or through an\n // error/close event) to avoid delivering multiple close events or sending\n // on a closed stream\n let closed = false;\n\n const streamBridge = new StreamBridge<Req, Resp>({\n sendFn: (msg: Req) => {\n if (!closed) {\n if (!opened) {\n logDebug(\n LOG_TAG,\n `Opening RPC '${rpcName}' stream ${streamId} transport.`\n );\n channel.open();\n opened = true;\n }\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} sending:`,\n msg\n );\n channel.send(msg);\n } else {\n logDebug(\n LOG_TAG,\n `Not sending because RPC '${rpcName}' stream ${streamId} ` +\n 'is closed:',\n msg\n );\n }\n },\n closeFn: () => channel.close()\n });\n\n // Closure events are guarded and exceptions are swallowed, so catch any\n // exception and rethrow using a setTimeout so they become visible again.\n // Note that eventually this function could go away if we are confident\n // enough the code is exception free.\n const unguardedEventListen = <T>(\n target: EventTarget,\n type: string | number,\n fn: (param: T) => void\n ): void => {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n target.listen(type, (param: unknown) => {\n try {\n fn(param as T);\n } catch (e) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n });\n };\n\n unguardedEventListen(channel, WebChannel.EventType.OPEN, () => {\n if (!closed) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} transport opened.`\n );\n }\n });\n\n unguardedEventListen(channel, WebChannel.EventType.CLOSE, () => {\n if (!closed) {\n closed = true;\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} transport closed`\n );\n streamBridge.callOnClose();\n }\n });\n\n unguardedEventListen<Error>(channel, WebChannel.EventType.ERROR, err => {\n if (!closed) {\n closed = true;\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} transport errored:`,\n err\n );\n streamBridge.callOnClose(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'The operation could not be completed'\n )\n );\n }\n });\n\n // WebChannel delivers message events as array. If batching is not enabled\n // (it's off by default) each message will be delivered alone, resulting in\n // a single element array.\n interface WebChannelResponse {\n data: Resp[];\n }\n\n unguardedEventListen<WebChannelResponse>(\n channel,\n WebChannel.EventType.MESSAGE,\n msg => {\n if (!closed) {\n const msgData = msg.data[0];\n hardAssert(!!msgData, 'Got a webchannel message without data.');\n // TODO(b/35143891): There is a bug in One Platform that caused errors\n // (and only errors) to be wrapped in an extra array. To be forward\n // compatible with the bug we need to check either condition. The latter\n // can be removed once the fix has been rolled out.\n // Use any because msgData.error is not typed.\n const msgDataOrError: WebChannelError | object = msgData;\n const error =\n msgDataOrError.error ||\n (msgDataOrError as WebChannelError[])[0]?.error;\n if (error) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} received error:`,\n error\n );\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n const status: string = error.status;\n let code = mapCodeFromRpcStatus(status);\n let message = error.message;\n if (code === undefined) {\n code = Code.INTERNAL;\n message =\n 'Unknown error status: ' +\n status +\n ' with message ' +\n error.message;\n }\n // Mark closed so no further events are propagated\n closed = true;\n streamBridge.callOnClose(new FirestoreError(code, message));\n channel.close();\n } else {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} received:`,\n msgData\n );\n streamBridge.callOnMessage(msgData);\n }\n }\n }\n );\n\n unguardedEventListen<StatEvent>(requestStats, Event.STAT_EVENT, event => {\n if (event.stat === Stat.PROXY) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} detected buffering proxy`\n );\n } else if (event.stat === Stat.NOPROXY) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} detected no buffering proxy`\n );\n }\n });\n\n setTimeout(() => {\n // Technically we could/should wait for the WebChannel opened event,\n // but because we want to send the first message with the WebChannel\n // handshake we pretend the channel opened here (asynchronously), and\n // then delay the actual open until the first message is sent.\n streamBridge.callOnOpen();\n }, 0);\n return streamBridge;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The Platform's 'window' implementation or null if not available. */\nexport function getWindow(): Window | null {\n // `window` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' ? window : null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */\nexport function getDocument(): Document | null {\n // `document` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof document !== 'undefined' ? document : null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Return the Platform-specific serializer monitor. */\nimport { DatabaseId } from '../../core/database_info';\nimport { JsonProtoSerializer } from '../../remote/serializer';\n\nexport function newSerializer(databaseId: DatabaseId): JsonProtoSerializer {\n return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nconst LOG_TAG = 'ExponentialBackoff';\n\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nconst DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;\n\nconst DEFAULT_BACKOFF_FACTOR = 1.5;\n\n/** Maximum backoff time in milliseconds */\nconst DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;\n\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nexport class ExponentialBackoff {\n private currentBaseMs: number = 0;\n private timerPromise: DelayedOperation<void> | null = null;\n /** The last backoff attempt, as epoch milliseconds. */\n private lastAttemptTime = Date.now();\n\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n private readonly queue: AsyncQueue,\n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n private readonly timerId: TimerId,\n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n private readonly initialDelayMs: number = DEFAULT_BACKOFF_INITIAL_DELAY_MS,\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n private readonly backoffFactor: number = DEFAULT_BACKOFF_FACTOR,\n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */\n private readonly maxDelayMs: number = DEFAULT_BACKOFF_MAX_DELAY_MS\n ) {\n this.reset();\n }\n\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */\n reset(): void {\n this.currentBaseMs = 0;\n }\n\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n resetToMax(): void {\n this.currentBaseMs = this.maxDelayMs;\n }\n\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts. If there was a pending backoff operation\n * already, it will be canceled.\n */\n backoffAndRun(op: () => Promise<void>): void {\n // Cancel any pending backoff operation.\n this.cancel();\n\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const desiredDelayWithJitterMs = Math.floor(\n this.currentBaseMs + this.jitterDelayMs()\n );\n\n // Guard against lastAttemptTime being in the future due to a clock change.\n const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);\n\n // Guard against the backoff delay already being past.\n const remainingDelayMs = Math.max(\n 0,\n desiredDelayWithJitterMs - delaySoFarMs\n );\n\n if (remainingDelayMs > 0) {\n logDebug(\n LOG_TAG,\n `Backing off for ${remainingDelayMs} ms ` +\n `(base delay: ${this.currentBaseMs} ms, ` +\n `delay with jitter: ${desiredDelayWithJitterMs} ms, ` +\n `last attempt: ${delaySoFarMs} ms ago)`\n );\n }\n\n this.timerPromise = this.queue.enqueueAfterDelay(\n this.timerId,\n remainingDelayMs,\n () => {\n this.lastAttemptTime = Date.now();\n return op();\n }\n );\n\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n }\n\n skipBackoff(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.skipDelay();\n this.timerPromise = null;\n }\n }\n\n cancel(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.cancel();\n this.timerPromise = null;\n }\n }\n\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n private jitterDelayMs(): number {\n return (Math.random() - 0.5) * this.currentBaseMs;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider, Token } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { TargetData } from '../local/target_data';\nimport { Mutation, MutationResult } from '../model/mutation';\nimport {\n ListenRequest as ProtoListenRequest,\n ListenResponse as ProtoListenResponse,\n WriteRequest as ProtoWriteRequest,\n WriteResponse as ProtoWriteResponse\n} from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExponentialBackoff } from './backoff';\nimport { Connection, Stream } from './connection';\nimport {\n fromVersion,\n fromWatchChange,\n fromWriteResults,\n getEncodedDatabaseId,\n JsonProtoSerializer,\n toListenRequestLabels,\n toMutation,\n toTarget,\n versionFromListenResponse\n} from './serializer';\nimport { WatchChange } from './watch_change';\n\nconst LOG_TAG = 'PersistentStream';\n\n// The generated proto interfaces for these class are missing the database\n// field. So we add it here.\n// TODO(b/36015800): Remove this once the api generator is fixed.\ninterface ListenRequest extends ProtoListenRequest {\n database?: string;\n}\nexport interface WriteRequest extends ProtoWriteRequest {\n database?: string;\n}\n/**\n * PersistentStream can be in one of 5 states (each described in detail below)\n * based on the following state transition diagram:\n *\n * start() called auth & connection succeeded\n * INITIAL ----------------> STARTING -----------------------------> OPEN\n * ^ | |\n * | | error occurred |\n * | \\-----------------------------v-----/\n * | |\n * backoff | |\n * elapsed | start() called |\n * \\--- BACKOFF <---------------- ERROR\n *\n * [any state] --------------------------> INITIAL\n * stop() called or\n * idle timer expired\n */\nconst enum PersistentStreamState {\n /**\n * The streaming RPC is not yet running and there's no error condition.\n * Calling start() will start the stream immediately without backoff.\n * While in this state isStarted() will return false.\n */\n Initial,\n\n /**\n * The stream is starting, either waiting for an auth token or for the stream\n * to successfully open. While in this state, isStarted() will return true but\n * isOpen() will return false.\n */\n Starting,\n\n /**\n * The streaming RPC is up and running. Requests and responses can flow\n * freely. Both isStarted() and isOpen() will return true.\n */\n Open,\n\n /**\n * The stream is healthy and has been connected for more than 10 seconds. We\n * therefore assume that the credentials we passed were valid. Both\n * isStarted() and isOpen() will return true.\n */\n Healthy,\n\n /**\n * The stream encountered an error. The next start attempt will back off.\n * While in this state isStarted() will return false.\n */\n Error,\n\n /**\n * An in-between state after an error where the stream is waiting before\n * re-starting. After waiting is complete, the stream will try to open.\n * While in this state isStarted() will return true but isOpen() will return\n * false.\n */\n Backoff\n}\n\n/**\n * Provides a common interface that is shared by the listeners for stream\n * events by the concrete implementation classes.\n */\nexport interface PersistentStreamListener {\n /**\n * Called after the stream was established and can accept outgoing\n * messages\n */\n onOpen: () => Promise<void>;\n /**\n * Called after the stream has closed. If there was an error, the\n * FirestoreError will be set.\n */\n onClose: (err?: FirestoreError) => Promise<void>;\n}\n\n/** The time a stream stays open after it is marked idle. */\nconst IDLE_TIMEOUT_MS = 60 * 1000;\n\n/** The time a stream stays open until we consider it healthy. */\nconst HEALTHY_TIMEOUT_MS = 10 * 1000;\n\n/**\n * A PersistentStream is an abstract base class that represents a streaming RPC\n * to the Firestore backend. It's built on top of the connections own support\n * for streaming RPCs, and adds several critical features for our clients:\n *\n * - Exponential backoff on failure\n * - Authentication via CredentialsProvider\n * - Dispatching all callbacks into the shared worker queue\n * - Closing idle streams after 60 seconds of inactivity\n *\n * Subclasses of PersistentStream implement serialization of models to and\n * from the JSON representation of the protocol buffers for a specific\n * streaming RPC.\n *\n * ## Starting and Stopping\n *\n * Streaming RPCs are stateful and need to be start()ed before messages can\n * be sent and received. The PersistentStream will call the onOpen() function\n * of the listener once the stream is ready to accept requests.\n *\n * Should a start() fail, PersistentStream will call the registered onClose()\n * listener with a FirestoreError indicating what went wrong.\n *\n * A PersistentStream can be started and stopped repeatedly.\n *\n * Generic types:\n * SendType: The type of the outgoing message of the underlying\n * connection stream\n * ReceiveType: The type of the incoming message of the underlying\n * connection stream\n * ListenerType: The type of the listener that will be used for callbacks\n */\nexport abstract class PersistentStream<\n SendType,\n ReceiveType,\n ListenerType extends PersistentStreamListener\n> {\n private state = PersistentStreamState.Initial;\n /**\n * A close count that's incremented every time the stream is closed; used by\n * getCloseGuardedDispatcher() to invalidate callbacks that happen after\n * close.\n */\n private closeCount = 0;\n\n private idleTimer: DelayedOperation<void> | null = null;\n private healthCheck: DelayedOperation<void> | null = null;\n private stream: Stream<SendType, ReceiveType> | null = null;\n\n protected backoff: ExponentialBackoff;\n\n constructor(\n private queue: AsyncQueue,\n connectionTimerId: TimerId,\n private idleTimerId: TimerId,\n private healthTimerId: TimerId,\n protected connection: Connection,\n private authCredentialsProvider: CredentialsProvider<User>,\n private appCheckCredentialsProvider: CredentialsProvider<string>,\n protected listener: ListenerType\n ) {\n this.backoff = new ExponentialBackoff(queue, connectionTimerId);\n }\n\n /**\n * Returns true if start() has been called and no error has occurred. True\n * indicates the stream is open or in the process of opening (which\n * encompasses respecting backoff, getting auth tokens, and starting the\n * actual RPC). Use isOpen() to determine if the stream is open and ready for\n * outbound requests.\n */\n isStarted(): boolean {\n return (\n this.state === PersistentStreamState.Starting ||\n this.state === PersistentStreamState.Backoff ||\n this.isOpen()\n );\n }\n\n /**\n * Returns true if the underlying RPC is open (the onOpen() listener has been\n * called) and the stream is ready for outbound requests.\n */\n isOpen(): boolean {\n return (\n this.state === PersistentStreamState.Open ||\n this.state === PersistentStreamState.Healthy\n );\n }\n\n /**\n * Starts the RPC. Only allowed if isStarted() returns false. The stream is\n * not immediately ready for use: onOpen() will be invoked when the RPC is\n * ready for outbound requests, at which point isOpen() will return true.\n *\n * When start returns, isStarted() will return true.\n */\n start(): void {\n if (this.state === PersistentStreamState.Error) {\n this.performBackoff();\n return;\n }\n\n debugAssert(\n this.state === PersistentStreamState.Initial,\n 'Already started'\n );\n this.auth();\n }\n\n /**\n * Stops the RPC. This call is idempotent and allowed regardless of the\n * current isStarted() state.\n *\n * When stop returns, isStarted() and isOpen() will both return false.\n */\n async stop(): Promise<void> {\n if (this.isStarted()) {\n await this.close(PersistentStreamState.Initial);\n }\n }\n\n /**\n * After an error the stream will usually back off on the next attempt to\n * start it. If the error warrants an immediate restart of the stream, the\n * sender can use this to indicate that the receiver should not back off.\n *\n * Each error will call the onClose() listener. That function can decide to\n * inhibit backoff if required.\n */\n inhibitBackoff(): void {\n debugAssert(\n !this.isStarted(),\n 'Can only inhibit backoff in a stopped state'\n );\n\n this.state = PersistentStreamState.Initial;\n this.backoff.reset();\n }\n\n /**\n * Marks this stream as idle. If no further actions are performed on the\n * stream for one minute, the stream will automatically close itself and\n * notify the stream's onClose() handler with Status.OK. The stream will then\n * be in a !isStarted() state, requiring the caller to start the stream again\n * before further use.\n *\n * Only streams that are in state 'Open' can be marked idle, as all other\n * states imply pending network operations.\n */\n markIdle(): void {\n // Starts the idle time if we are in state 'Open' and are not yet already\n // running a timer (in which case the previous idle timeout still applies).\n if (this.isOpen() && this.idleTimer === null) {\n this.idleTimer = this.queue.enqueueAfterDelay(\n this.idleTimerId,\n IDLE_TIMEOUT_MS,\n () => this.handleIdleCloseTimer()\n );\n }\n }\n\n /** Sends a message to the underlying stream. */\n protected sendRequest(msg: SendType): void {\n this.cancelIdleCheck();\n this.stream!.send(msg);\n }\n\n /** Called by the idle timer when the stream should close due to inactivity. */\n private async handleIdleCloseTimer(): Promise<void> {\n if (this.isOpen()) {\n // When timing out an idle stream there's no reason to force the stream into backoff when\n // it restarts so set the stream state to Initial instead of Error.\n return this.close(PersistentStreamState.Initial);\n }\n }\n\n /** Marks the stream as active again. */\n private cancelIdleCheck(): void {\n if (this.idleTimer) {\n this.idleTimer.cancel();\n this.idleTimer = null;\n }\n }\n\n /** Cancels the health check delayed operation. */\n private cancelHealthCheck(): void {\n if (this.healthCheck) {\n this.healthCheck.cancel();\n this.healthCheck = null;\n }\n }\n\n /**\n * Closes the stream and cleans up as necessary:\n *\n * * closes the underlying GRPC stream;\n * * calls the onClose handler with the given 'error';\n * * sets internal stream state to 'finalState';\n * * adjusts the backoff timer based on the error\n *\n * A new stream can be opened by calling start().\n *\n * @param finalState - the intended state of the stream after closing.\n * @param error - the error the connection was closed with.\n */\n private async close(\n finalState: PersistentStreamState,\n error?: FirestoreError\n ): Promise<void> {\n debugAssert(this.isStarted(), 'Only started streams should be closed.');\n debugAssert(\n finalState === PersistentStreamState.Error || isNullOrUndefined(error),\n \"Can't provide an error when not in an error state.\"\n );\n\n // Cancel any outstanding timers (they're guaranteed not to execute).\n this.cancelIdleCheck();\n this.cancelHealthCheck();\n this.backoff.cancel();\n\n // Invalidates any stream-related callbacks (e.g. from auth or the\n // underlying stream), guaranteeing they won't execute.\n this.closeCount++;\n\n if (finalState !== PersistentStreamState.Error) {\n // If this is an intentional close ensure we don't delay our next connection attempt.\n this.backoff.reset();\n } else if (error && error.code === Code.RESOURCE_EXHAUSTED) {\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n logError(error.toString());\n logError(\n 'Using maximum backoff delay to prevent overloading the backend.'\n );\n this.backoff.resetToMax();\n } else if (\n error &&\n error.code === Code.UNAUTHENTICATED &&\n this.state !== PersistentStreamState.Healthy\n ) {\n // \"unauthenticated\" error means the token was rejected. This should rarely\n // happen since both Auth and AppCheck ensure a sufficient TTL when we\n // request a token. If a user manually resets their system clock this can\n // fail, however. In this case, we should get a Code.UNAUTHENTICATED error\n // before we received the first message and we need to invalidate the token\n // to ensure that we fetch a new token.\n this.authCredentialsProvider.invalidateToken();\n this.appCheckCredentialsProvider.invalidateToken();\n }\n\n // Clean up the underlying stream because we are no longer interested in events.\n if (this.stream !== null) {\n this.tearDown();\n this.stream.close();\n this.stream = null;\n }\n\n // This state must be assigned before calling onClose() to allow the callback to\n // inhibit backoff or otherwise manipulate the state in its non-started state.\n this.state = finalState;\n\n // Notify the listener that the stream closed.\n await this.listener.onClose(error);\n }\n\n /**\n * Can be overridden to perform additional cleanup before the stream is closed.\n * Calling super.tearDown() is not required.\n */\n protected tearDown(): void {}\n\n /**\n * Used by subclasses to start the concrete RPC and return the underlying\n * connection stream.\n */\n protected abstract startRpc(\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream<SendType, ReceiveType>;\n\n /**\n * Called after the stream has received a message. The function will be\n * called on the right queue and must return a Promise.\n * @param message - The message received from the stream.\n */\n protected abstract onMessage(message: ReceiveType): Promise<void>;\n\n private auth(): void {\n debugAssert(\n this.state === PersistentStreamState.Initial,\n 'Must be in initial state to auth'\n );\n\n this.state = PersistentStreamState.Starting;\n\n const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount);\n\n // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.\n const closeCount = this.closeCount;\n\n Promise.all([\n this.authCredentialsProvider.getToken(),\n this.appCheckCredentialsProvider.getToken()\n ]).then(\n ([authToken, appCheckToken]) => {\n // Stream can be stopped while waiting for authentication.\n // TODO(mikelehen): We really should just use dispatchIfNotClosed\n // and let this dispatch onto the queue, but that opened a spec test can\n // of worms that I don't want to deal with in this PR.\n if (this.closeCount === closeCount) {\n // Normally we'd have to schedule the callback on the AsyncQueue.\n // However, the following calls are safe to be called outside the\n // AsyncQueue since they don't chain asynchronous calls\n this.startStream(authToken, appCheckToken);\n }\n },\n (error: Error) => {\n dispatchIfNotClosed(() => {\n const rpcError = new FirestoreError(\n Code.UNKNOWN,\n 'Fetching auth token failed: ' + error.message\n );\n return this.handleStreamClose(rpcError);\n });\n }\n );\n }\n\n private startStream(\n authToken: Token | null,\n appCheckToken: Token | null\n ): void {\n debugAssert(\n this.state === PersistentStreamState.Starting,\n 'Trying to start stream in a non-starting state'\n );\n\n const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount);\n\n this.stream = this.startRpc(authToken, appCheckToken);\n this.stream.onOpen(() => {\n dispatchIfNotClosed(() => {\n debugAssert(\n this.state === PersistentStreamState.Starting,\n 'Expected stream to be in state Starting, but was ' + this.state\n );\n this.state = PersistentStreamState.Open;\n debugAssert(\n this.healthCheck === null,\n 'Expected healthCheck to be null'\n );\n this.healthCheck = this.queue.enqueueAfterDelay(\n this.healthTimerId,\n HEALTHY_TIMEOUT_MS,\n () => {\n if (this.isOpen()) {\n this.state = PersistentStreamState.Healthy;\n }\n return Promise.resolve();\n }\n );\n return this.listener!.onOpen();\n });\n });\n this.stream.onClose((error?: FirestoreError) => {\n dispatchIfNotClosed(() => {\n return this.handleStreamClose(error);\n });\n });\n this.stream.onMessage((msg: ReceiveType) => {\n dispatchIfNotClosed(() => {\n return this.onMessage(msg);\n });\n });\n }\n\n private performBackoff(): void {\n debugAssert(\n this.state === PersistentStreamState.Error,\n 'Should only perform backoff when in Error state'\n );\n this.state = PersistentStreamState.Backoff;\n\n this.backoff.backoffAndRun(async () => {\n debugAssert(\n this.state === PersistentStreamState.Backoff,\n 'Backoff elapsed but state is now: ' + this.state\n );\n\n this.state = PersistentStreamState.Initial;\n this.start();\n debugAssert(this.isStarted(), 'PersistentStream should have started');\n });\n }\n\n // Visible for tests\n handleStreamClose(error?: FirestoreError): Promise<void> {\n debugAssert(\n this.isStarted(),\n \"Can't handle server close on non-started stream\"\n );\n logDebug(LOG_TAG, `close with error: ${error}`);\n\n this.stream = null;\n\n // In theory the stream could close cleanly, however, in our current model\n // we never expect this to happen because if we stop a stream ourselves,\n // this callback will never be called. To prevent cases where we retry\n // without a backoff accidentally, we set the stream to error in all cases.\n return this.close(PersistentStreamState.Error, error);\n }\n\n /**\n * Returns a \"dispatcher\" function that dispatches operations onto the\n * AsyncQueue but only runs them if closeCount remains unchanged. This allows\n * us to turn auth / stream callbacks into no-ops if the stream is closed /\n * re-opened, etc.\n */\n private getCloseGuardedDispatcher(\n startCloseCount: number\n ): (fn: () => Promise<void>) => void {\n return (fn: () => Promise<void>): void => {\n this.queue.enqueueAndForget(() => {\n if (this.closeCount === startCloseCount) {\n return fn();\n } else {\n logDebug(\n LOG_TAG,\n 'stream callback skipped by getCloseGuardedDispatcher.'\n );\n return Promise.resolve();\n }\n });\n };\n }\n}\n\n/** Listener for the PersistentWatchStream */\nexport interface WatchStreamListener extends PersistentStreamListener {\n /**\n * Called on a watchChange. The snapshot parameter will be MIN if the watch\n * change did not have a snapshot associated with it.\n */\n onWatchChange: (\n watchChange: WatchChange,\n snapshot: SnapshotVersion\n ) => Promise<void>;\n}\n\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the onOpen() listener, any number of\n * listen() and unlisten() calls can be made to control what changes will be\n * sent from the server for ListenResponses.\n */\nexport class PersistentListenStream extends PersistentStream<\n ProtoListenRequest,\n ProtoListenResponse,\n WatchStreamListener\n> {\n constructor(\n queue: AsyncQueue,\n connection: Connection,\n authCredentials: CredentialsProvider<User>,\n appCheckCredentials: CredentialsProvider<string>,\n private serializer: JsonProtoSerializer,\n listener: WatchStreamListener\n ) {\n super(\n queue,\n TimerId.ListenStreamConnectionBackoff,\n TimerId.ListenStreamIdle,\n TimerId.HealthCheckTimeout,\n connection,\n authCredentials,\n appCheckCredentials,\n listener\n );\n }\n\n protected startRpc(\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream<ProtoListenRequest, ProtoListenResponse> {\n return this.connection.openStream<ProtoListenRequest, ProtoListenResponse>(\n 'Listen',\n authToken,\n appCheckToken\n );\n }\n\n protected onMessage(watchChangeProto: ProtoListenResponse): Promise<void> {\n // A successful response means the stream is healthy\n this.backoff.reset();\n\n const watchChange = fromWatchChange(this.serializer, watchChangeProto);\n const snapshot = versionFromListenResponse(watchChangeProto);\n return this.listener!.onWatchChange(watchChange, snapshot);\n }\n\n /**\n * Registers interest in the results of the given target. If the target\n * includes a resumeToken it will be included in the request. Results that\n * affect the target will be streamed back as WatchChange messages that\n * reference the targetId.\n */\n watch(targetData: TargetData): void {\n const request: ListenRequest = {};\n request.database = getEncodedDatabaseId(this.serializer);\n request.addTarget = toTarget(this.serializer, targetData);\n\n const labels = toListenRequestLabels(this.serializer, targetData);\n if (labels) {\n request.labels = labels;\n }\n\n this.sendRequest(request);\n }\n\n /**\n * Unregisters interest in the results of the target associated with the\n * given targetId.\n */\n unwatch(targetId: TargetId): void {\n const request: ListenRequest = {};\n request.database = getEncodedDatabaseId(this.serializer);\n request.removeTarget = targetId;\n this.sendRequest(request);\n }\n}\n\n/** Listener for the PersistentWriteStream */\nexport interface WriteStreamListener extends PersistentStreamListener {\n /**\n * Called by the PersistentWriteStream upon a successful handshake response\n * from the server, which is the receiver's cue to send any pending writes.\n */\n onHandshakeComplete: () => Promise<void>;\n\n /**\n * Called by the PersistentWriteStream upon receiving a StreamingWriteResponse\n * from the server that contains a mutation result.\n */\n onMutationResult: (\n commitVersion: SnapshotVersion,\n results: MutationResult[]\n ) => Promise<void>;\n}\n\n/**\n * A Stream that implements the Write RPC.\n *\n * The Write RPC requires the caller to maintain special streamToken\n * state in between calls, to help the server understand which responses the\n * client has processed by the time the next request is made. Every response\n * will contain a streamToken; this value must be passed to the next\n * request.\n *\n * After calling start() on this stream, the next request must be a handshake,\n * containing whatever streamToken is on hand. Once a response to this\n * request is received, all pending mutations may be submitted. When\n * submitting multiple batches of mutations at the same time, it's\n * okay to use the same streamToken for the calls to writeMutations.\n *\n * TODO(b/33271235): Use proto types\n */\nexport class PersistentWriteStream extends PersistentStream<\n ProtoWriteRequest,\n ProtoWriteResponse,\n WriteStreamListener\n> {\n private handshakeComplete_ = false;\n\n constructor(\n queue: AsyncQueue,\n connection: Connection,\n authCredentials: CredentialsProvider<User>,\n appCheckCredentials: CredentialsProvider<string>,\n private serializer: JsonProtoSerializer,\n listener: WriteStreamListener\n ) {\n super(\n queue,\n TimerId.WriteStreamConnectionBackoff,\n TimerId.WriteStreamIdle,\n TimerId.HealthCheckTimeout,\n connection,\n authCredentials,\n appCheckCredentials,\n listener\n );\n }\n\n /**\n * The last received stream token from the server, used to acknowledge which\n * responses the client has processed. Stream tokens are opaque checkpoint\n * markers whose only real value is their inclusion in the next request.\n *\n * PersistentWriteStream manages propagating this value from responses to the\n * next request.\n */\n private lastStreamToken: string | Uint8Array | undefined;\n\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */\n get handshakeComplete(): boolean {\n return this.handshakeComplete_;\n }\n\n // Override of PersistentStream.start\n start(): void {\n this.handshakeComplete_ = false;\n this.lastStreamToken = undefined;\n super.start();\n }\n\n protected tearDown(): void {\n if (this.handshakeComplete_) {\n this.writeMutations([]);\n }\n }\n\n protected startRpc(\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream<ProtoWriteRequest, ProtoWriteResponse> {\n return this.connection.openStream<ProtoWriteRequest, ProtoWriteResponse>(\n 'Write',\n authToken,\n appCheckToken\n );\n }\n\n protected onMessage(responseProto: ProtoWriteResponse): Promise<void> {\n // Always capture the last stream token.\n hardAssert(\n !!responseProto.streamToken,\n 'Got a write response without a stream token'\n );\n this.lastStreamToken = responseProto.streamToken;\n\n if (!this.handshakeComplete_) {\n // The first response is always the handshake response\n hardAssert(\n !responseProto.writeResults || responseProto.writeResults.length === 0,\n 'Got mutation results for handshake'\n );\n this.handshakeComplete_ = true;\n return this.listener!.onHandshakeComplete();\n } else {\n // A successful first write response means the stream is healthy,\n // Note, that we could consider a successful handshake healthy, however,\n // the write itself might be causing an error we want to back off from.\n this.backoff.reset();\n\n const results = fromWriteResults(\n responseProto.writeResults,\n responseProto.commitTime\n );\n const commitVersion = fromVersion(responseProto.commitTime!);\n return this.listener!.onMutationResult(commitVersion, results);\n }\n }\n\n /**\n * Sends an initial streamToken to the server, performing the handshake\n * required to make the StreamingWrite RPC work. Subsequent\n * calls should wait until onHandshakeComplete was called.\n */\n writeHandshake(): void {\n debugAssert(this.isOpen(), 'Writing handshake requires an opened stream');\n debugAssert(!this.handshakeComplete_, 'Handshake already completed');\n debugAssert(\n !this.lastStreamToken,\n 'Stream token should be empty during handshake'\n );\n // TODO(dimond): Support stream resumption. We intentionally do not set the\n // stream token on the handshake, ignoring any stream token we might have.\n const request: WriteRequest = {};\n request.database = getEncodedDatabaseId(this.serializer);\n this.sendRequest(request);\n }\n\n /** Sends a group of mutations to the Firestore backend to apply. */\n writeMutations(mutations: Mutation[]): void {\n debugAssert(this.isOpen(), 'Writing mutations requires an opened stream');\n debugAssert(\n this.handshakeComplete_,\n 'Handshake must be complete before writing mutations'\n );\n debugAssert(\n !!this.lastStreamToken,\n 'Trying to write mutation without a token'\n );\n\n const request: WriteRequest = {\n streamToken: this.lastStreamToken,\n writes: mutations.map(mutation => toMutation(this.serializer, mutation))\n };\n\n this.sendRequest(request);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { Aggregate } from '../core/aggregate';\nimport { queryToAggregateTarget, Query, queryToTarget } from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport {\n ApiClientObjectMap,\n BatchGetDocumentsRequest as ProtoBatchGetDocumentsRequest,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n RunAggregationQueryResponse as ProtoRunAggregationQueryResponse,\n RunQueryRequest as ProtoRunQueryRequest,\n RunQueryResponse as ProtoRunQueryResponse,\n Value\n} from '../protos/firestore_proto_api';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Connection } from './connection';\nimport {\n PersistentListenStream,\n PersistentWriteStream,\n WatchStreamListener,\n WriteStreamListener\n} from './persistent_stream';\nimport {\n fromDocument,\n fromBatchGetDocumentsResponse,\n getEncodedDatabaseId,\n JsonProtoSerializer,\n toMutation,\n toName,\n toQueryTarget,\n toRunAggregationQueryRequest\n} from './serializer';\n\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\nexport abstract class Datastore {\n abstract terminate(): void;\n abstract serializer: JsonProtoSerializer;\n}\n\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass DatastoreImpl extends Datastore {\n terminated = false;\n\n constructor(\n readonly authCredentials: CredentialsProvider<User>,\n readonly appCheckCredentials: CredentialsProvider<string>,\n readonly connection: Connection,\n readonly serializer: JsonProtoSerializer\n ) {\n super();\n }\n\n verifyInitialized(): void {\n debugAssert(!!this.connection, 'Datastore.start() not called');\n if (this.terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n /** Invokes the provided RPC with auth and AppCheck tokens. */\n invokeRPC<Req, Resp>(\n rpcName: string,\n path: string,\n request: Req\n ): Promise<Resp> {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeRPC<Req, Resp>(\n rpcName,\n path,\n request,\n authToken,\n appCheckToken\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */\n invokeStreamingRPC<Req, Resp>(\n rpcName: string,\n path: string,\n request: Req,\n expectedResponseCount?: number\n ): Promise<Resp[]> {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeStreamingRPC<Req, Resp>(\n rpcName,\n path,\n request,\n authToken,\n appCheckToken,\n expectedResponseCount\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n terminate(): void {\n this.terminated = true;\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nexport function newDatastore(\n authCredentials: CredentialsProvider<User>,\n appCheckCredentials: CredentialsProvider<string>,\n connection: Connection,\n serializer: JsonProtoSerializer\n): Datastore {\n return new DatastoreImpl(\n authCredentials,\n appCheckCredentials,\n connection,\n serializer\n );\n}\n\nexport async function invokeCommitRpc(\n datastore: Datastore,\n mutations: Mutation[]\n): Promise<void> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const path = getEncodedDatabaseId(datastoreImpl.serializer) + '/documents';\n const request = {\n writes: mutations.map(m => toMutation(datastoreImpl.serializer, m))\n };\n await datastoreImpl.invokeRPC('Commit', path, request);\n}\n\nexport async function invokeBatchGetDocumentsRpc(\n datastore: Datastore,\n keys: DocumentKey[]\n): Promise<Document[]> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const path = getEncodedDatabaseId(datastoreImpl.serializer) + '/documents';\n const request = {\n documents: keys.map(k => toName(datastoreImpl.serializer, k))\n };\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoBatchGetDocumentsRequest,\n ProtoBatchGetDocumentsResponse\n >('BatchGetDocuments', path, request, keys.length);\n\n const docs = new Map<string, Document>();\n response.forEach(proto => {\n const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto);\n docs.set(doc.key.toString(), doc);\n });\n const result: Document[] = [];\n keys.forEach(key => {\n const doc = docs.get(key.toString());\n hardAssert(!!doc, 'Missing entity in write response for ' + key);\n result.push(doc);\n });\n return result;\n}\n\nexport async function invokeRunQueryRpc(\n datastore: Datastore,\n query: Query\n): Promise<Document[]> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = toQueryTarget(datastoreImpl.serializer, queryToTarget(query));\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunQueryRequest,\n ProtoRunQueryResponse\n >('RunQuery', request.parent!, { structuredQuery: request.structuredQuery });\n return (\n response\n // Omit RunQueryResponses that only contain readTimes.\n .filter(proto => !!proto.document)\n .map(proto =>\n fromDocument(datastoreImpl.serializer, proto.document!, undefined)\n )\n );\n}\n\nexport async function invokeRunAggregationQueryRpc(\n datastore: Datastore,\n query: Query,\n aggregates: Aggregate[]\n): Promise<ApiClientObjectMap<Value>> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { request, aliasMap } = toRunAggregationQueryRequest(\n datastoreImpl.serializer,\n queryToAggregateTarget(query),\n aggregates\n );\n\n const parent = request.parent;\n if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) {\n delete request.parent;\n }\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunAggregationQueryRequest,\n ProtoRunAggregationQueryResponse\n >('RunAggregationQuery', parent!, request, /*expectedResponseCount=*/ 1);\n\n // Omit RunAggregationQueryResponse that only contain readTimes.\n const filteredResult = response.filter(proto => !!proto.result);\n\n hardAssert(\n filteredResult.length === 1,\n 'Aggregation fields are missing from result.'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result),\n 'aggregationQueryResponse.result'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result.aggregateFields),\n 'aggregationQueryResponse.result.aggregateFields'\n );\n\n // Remap the short-form aliases that were sent to the server\n // to the client-side aliases. Users will access the results\n // using the client-side alias.\n const unmappedAggregateFields = filteredResult[0].result?.aggregateFields;\n const remappedFields = Object.keys(unmappedAggregateFields).reduce<\n ApiClientObjectMap<Value>\n >((accumulator, key) => {\n debugAssert(\n !isNullOrUndefined(aliasMap[key]),\n `'${key}' not present in aliasMap result`\n );\n accumulator[aliasMap[key]] = unmappedAggregateFields[key]!;\n return accumulator;\n }, {});\n\n return remappedFields;\n}\n\nexport function newPersistentWriteStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WriteStreamListener\n): PersistentWriteStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentWriteStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n\nexport function newPersistentWatchStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WatchStreamListener\n): PersistentListenStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentListenStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { OnlineState } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { logError, logDebug } from '../util/log';\n\nconst LOG_TAG = 'OnlineStateTracker';\n\n// To deal with transient failures, we allow multiple stream attempts before\n// giving up and transitioning from OnlineState.Unknown to Offline.\n// TODO(mikelehen): This used to be set to 2 as a mitigation for b/66228394.\n// @jdimond thinks that bug is sufficiently fixed so that we can set this back\n// to 1. If that works okay, we could potentially remove this logic entirely.\nconst MAX_WATCH_STREAM_FAILURES = 1;\n\n// To deal with stream attempts that don't succeed or fail in a timely manner,\n// we have a timeout for OnlineState to reach Online or Offline.\n// If the timeout is reached, we transition to Offline rather than waiting\n// indefinitely.\nconst ONLINE_STATE_TIMEOUT_MS = 10 * 1000;\n\n/**\n * A component used by the RemoteStore to track the OnlineState (that is,\n * whether or not the client as a whole should be considered to be online or\n * offline), implementing the appropriate heuristics.\n *\n * In particular, when the client is trying to connect to the backend, we\n * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for\n * a connection to succeed. If we have too many failures or the timeout elapses,\n * then we set the OnlineState to Offline, and the client will behave as if\n * it is offline (get()s will return cached data, etc.).\n */\nexport class OnlineStateTracker {\n /** The current OnlineState. */\n private state = OnlineState.Unknown;\n\n /**\n * A count of consecutive failures to open the stream. If it reaches the\n * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to\n * Offline.\n */\n private watchStreamFailures = 0;\n\n /**\n * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we\n * transition from OnlineState.Unknown to OnlineState.Offline without waiting\n * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).\n */\n private onlineStateTimer: DelayedOperation<void> | null = null;\n\n /**\n * Whether the client should log a warning message if it fails to connect to\n * the backend (initially true, cleared after a successful stream, or if we've\n * logged the message already).\n */\n private shouldWarnClientIsOffline = true;\n\n constructor(\n private asyncQueue: AsyncQueue,\n private onlineStateHandler: (onlineState: OnlineState) => void\n ) {}\n\n /**\n * Called by RemoteStore when a watch stream is started (including on each\n * backoff attempt).\n *\n * If this is the first attempt, it sets the OnlineState to Unknown and starts\n * the onlineStateTimer.\n */\n handleWatchStreamStart(): void {\n if (this.watchStreamFailures === 0) {\n this.setAndBroadcast(OnlineState.Unknown);\n\n debugAssert(\n this.onlineStateTimer === null,\n `onlineStateTimer shouldn't be started yet`\n );\n this.onlineStateTimer = this.asyncQueue.enqueueAfterDelay(\n TimerId.OnlineStateTimeout,\n ONLINE_STATE_TIMEOUT_MS,\n () => {\n this.onlineStateTimer = null;\n debugAssert(\n this.state === OnlineState.Unknown,\n 'Timer should be canceled if we transitioned to a different state.'\n );\n this.logClientOfflineWarningIfNecessary(\n `Backend didn't respond within ${ONLINE_STATE_TIMEOUT_MS / 1000} ` +\n `seconds.`\n );\n this.setAndBroadcast(OnlineState.Offline);\n\n // NOTE: handleWatchStreamFailure() will continue to increment\n // watchStreamFailures even though we are already marked Offline,\n // but this is non-harmful.\n\n return Promise.resolve();\n }\n );\n }\n }\n\n /**\n * Updates our OnlineState as appropriate after the watch stream reports a\n * failure. The first failure moves us to the 'Unknown' state. We then may\n * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we\n * actually transition to the 'Offline' state.\n */\n handleWatchStreamFailure(error: FirestoreError): void {\n if (this.state === OnlineState.Online) {\n this.setAndBroadcast(OnlineState.Unknown);\n\n // To get to OnlineState.Online, set() must have been called which would\n // have reset our heuristics.\n debugAssert(\n this.watchStreamFailures === 0,\n 'watchStreamFailures must be 0'\n );\n debugAssert(\n this.onlineStateTimer === null,\n 'onlineStateTimer must be null'\n );\n } else {\n this.watchStreamFailures++;\n if (this.watchStreamFailures >= MAX_WATCH_STREAM_FAILURES) {\n this.clearOnlineStateTimer();\n\n this.logClientOfflineWarningIfNecessary(\n `Connection failed ${MAX_WATCH_STREAM_FAILURES} ` +\n `times. Most recent error: ${error.toString()}`\n );\n\n this.setAndBroadcast(OnlineState.Offline);\n }\n }\n }\n\n /**\n * Explicitly sets the OnlineState to the specified state.\n *\n * Note that this resets our timers / failure counters, etc. used by our\n * Offline heuristics, so must not be used in place of\n * handleWatchStreamStart() and handleWatchStreamFailure().\n */\n set(newState: OnlineState): void {\n this.clearOnlineStateTimer();\n this.watchStreamFailures = 0;\n\n if (newState === OnlineState.Online) {\n // We've connected to watch at least once. Don't warn the developer\n // about being offline going forward.\n this.shouldWarnClientIsOffline = false;\n }\n\n this.setAndBroadcast(newState);\n }\n\n private setAndBroadcast(newState: OnlineState): void {\n if (newState !== this.state) {\n this.state = newState;\n this.onlineStateHandler(newState);\n }\n }\n\n private logClientOfflineWarningIfNecessary(details: string): void {\n const message =\n `Could not reach Cloud Firestore backend. ${details}\\n` +\n `This typically indicates that your device does not have a healthy ` +\n `Internet connection at the moment. The client will operate in offline ` +\n `mode until it is able to successfully connect to the backend.`;\n if (this.shouldWarnClientIsOffline) {\n logError(message);\n this.shouldWarnClientIsOffline = false;\n } else {\n logDebug(LOG_TAG, message);\n }\n }\n\n private clearOnlineStateTimer(): void {\n if (this.onlineStateTimer !== null) {\n this.onlineStateTimer.cancel();\n this.onlineStateTimer = null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { OnlineState, TargetId } from '../core/types';\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreGetLastRemoteSnapshotVersion,\n localStoreGetNextMutationBatch\n} from '../local/local_store_impl';\nimport { isIndexedDbTransactionError } from '../local/simple_db';\nimport { TargetData } from '../local/target_data';\nimport { MutationResult } from '../model/mutation';\nimport { MutationBatch, MutationBatchResult } from '../model/mutation_batch';\nimport { debugAssert, debugCast } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { ByteString } from '../util/byte_string';\nimport { FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { ConnectivityMonitor, NetworkStatus } from './connectivity_monitor';\nimport {\n Datastore,\n newPersistentWatchStream,\n newPersistentWriteStream\n} from './datastore';\nimport { OnlineStateTracker } from './online_state_tracker';\nimport {\n PersistentListenStream,\n PersistentWriteStream\n} from './persistent_stream';\nimport { RemoteSyncer } from './remote_syncer';\nimport { isPermanentWriteError } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n WatchChange,\n WatchChangeAggregator,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst LOG_TAG = 'RemoteStore';\n\n// TODO(b/35853402): Negotiate this with the stream.\nconst MAX_PENDING_WRITES = 10;\n\n/** Reasons for why the RemoteStore may be offline. */\nconst enum OfflineCause {\n /** The user has explicitly disabled the network (via `disableNetwork()`). */\n UserDisabled,\n /** An IndexedDb failure occurred while persisting a stream update. */\n IndexedDbFailed,\n /** The tab is not the primary tab (only relevant with multi-tab). */\n IsSecondary,\n /** We are restarting the streams due to an Auth credential change. */\n CredentialChange,\n /** The connectivity state of the environment has changed. */\n ConnectivityChange,\n /** The RemoteStore has been shut down. */\n Shutdown\n}\n\n/**\n * RemoteStore - An interface to remotely stored data, basically providing a\n * wrapper around the Datastore that is more reliable for the rest of the\n * system.\n *\n * RemoteStore is responsible for maintaining the connection to the server.\n * - maintaining a list of active listens.\n * - reconnecting when the connection is dropped.\n * - resuming all the active listens on reconnect.\n *\n * RemoteStore handles all incoming events from the Datastore.\n * - listening to the watch stream and repackaging the events as RemoteEvents\n * - notifying SyncEngine of any changes to the active listens.\n *\n * RemoteStore takes writes from other components and handles them reliably.\n * - pulling pending mutations from LocalStore and sending them to Datastore.\n * - retrying mutations that failed because of network problems.\n * - acking mutations to the SyncEngine once they are accepted or rejected.\n */\nexport interface RemoteStore {\n /**\n * SyncEngine to notify of watch and write events. This must be set\n * immediately after construction.\n */\n remoteSyncer: RemoteSyncer;\n}\n\nclass RemoteStoreImpl implements RemoteStore {\n remoteSyncer: RemoteSyncer = {};\n\n /**\n * A list of up to MAX_PENDING_WRITES writes that we have fetched from the\n * LocalStore via fillWritePipeline() and have or will send to the write\n * stream.\n *\n * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or\n * restart the write stream. When the stream is established the writes in the\n * pipeline will be sent in order.\n *\n * Writes remain in writePipeline until they are acknowledged by the backend\n * and thus will automatically be re-sent if the stream is interrupted /\n * restarted before they're acknowledged.\n *\n * Write responses from the backend are linked to their originating request\n * purely based on order, and so we can just shift() writes from the front of\n * the writePipeline as we receive responses.\n */\n writePipeline: MutationBatch[] = [];\n\n /**\n * A mapping of watched targets that the client cares about tracking and the\n * user has explicitly called a 'listen' for this target.\n *\n * These targets may or may not have been sent to or acknowledged by the\n * server. On re-establishing the listen stream, these targets should be sent\n * to the server. The targets removed with unlistens are removed eagerly\n * without waiting for confirmation from the listen stream.\n */\n listenTargets = new Map<TargetId, TargetData>();\n\n connectivityMonitor: ConnectivityMonitor;\n watchStream?: PersistentListenStream;\n writeStream?: PersistentWriteStream;\n watchChangeAggregator?: WatchChangeAggregator;\n\n /**\n * A set of reasons for why the RemoteStore may be offline. If empty, the\n * RemoteStore may start its network connections.\n */\n offlineCauses = new Set<OfflineCause>();\n\n /**\n * Event handlers that get called when the network is disabled or enabled.\n *\n * PORTING NOTE: These functions are used on the Web client to create the\n * underlying streams (to support tree-shakeable streams). On Android and iOS,\n * the streams are created during construction of RemoteStore.\n */\n onNetworkStatusChange: Array<(enabled: boolean) => Promise<void>> = [];\n\n onlineStateTracker: OnlineStateTracker;\n\n constructor(\n /**\n * The local store, used to fill the write pipeline with outbound mutations.\n */\n readonly localStore: LocalStore,\n /** The client-side proxy for interacting with the backend. */\n readonly datastore: Datastore,\n readonly asyncQueue: AsyncQueue,\n onlineStateHandler: (onlineState: OnlineState) => void,\n connectivityMonitor: ConnectivityMonitor\n ) {\n this.connectivityMonitor = connectivityMonitor;\n this.connectivityMonitor.addCallback((_: NetworkStatus) => {\n asyncQueue.enqueueAndForget(async () => {\n // Porting Note: Unlike iOS, `restartNetwork()` is called even when the\n // network becomes unreachable as we don't have any other way to tear\n // down our streams.\n if (canUseNetwork(this)) {\n logDebug(\n LOG_TAG,\n 'Restarting streams for network reachability change.'\n );\n await restartNetwork(this);\n }\n });\n });\n\n this.onlineStateTracker = new OnlineStateTracker(\n asyncQueue,\n onlineStateHandler\n );\n }\n}\n\nexport function newRemoteStore(\n localStore: LocalStore,\n datastore: Datastore,\n asyncQueue: AsyncQueue,\n onlineStateHandler: (onlineState: OnlineState) => void,\n connectivityMonitor: ConnectivityMonitor\n): RemoteStore {\n return new RemoteStoreImpl(\n localStore,\n datastore,\n asyncQueue,\n onlineStateHandler,\n connectivityMonitor\n );\n}\n\n/** Re-enables the network. Idempotent. */\nexport function remoteStoreEnableNetwork(\n remoteStore: RemoteStore\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.offlineCauses.delete(OfflineCause.UserDisabled);\n return enableNetworkInternal(remoteStoreImpl);\n}\n\nasync function enableNetworkInternal(\n remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n if (canUseNetwork(remoteStoreImpl)) {\n for (const networkStatusHandler of remoteStoreImpl.onNetworkStatusChange) {\n await networkStatusHandler(/* enabled= */ true);\n }\n }\n}\n\n/**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */\nexport async function remoteStoreDisableNetwork(\n remoteStore: RemoteStore\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.offlineCauses.add(OfflineCause.UserDisabled);\n await disableNetworkInternal(remoteStoreImpl);\n\n // Set the OnlineState to Offline so get()s return from cache, etc.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Offline);\n}\n\nasync function disableNetworkInternal(\n remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n for (const networkStatusHandler of remoteStoreImpl.onNetworkStatusChange) {\n await networkStatusHandler(/* enabled= */ false);\n }\n}\n\nexport async function remoteStoreShutdown(\n remoteStore: RemoteStore\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n logDebug(LOG_TAG, 'RemoteStore shutting down.');\n remoteStoreImpl.offlineCauses.add(OfflineCause.Shutdown);\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.connectivityMonitor.shutdown();\n\n // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\n // triggering spurious listener events with cached data, etc.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n}\n\n/**\n * Starts new listen for the given target. Uses resume token if provided. It\n * is a no-op if the target of given `TargetData` is already being listened to.\n */\nexport function remoteStoreListen(\n remoteStore: RemoteStore,\n targetData: TargetData\n): void {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n\n if (remoteStoreImpl.listenTargets.has(targetData.targetId)) {\n return;\n }\n\n // Mark this as something the client is currently listening for.\n remoteStoreImpl.listenTargets.set(targetData.targetId, targetData);\n\n if (shouldStartWatchStream(remoteStoreImpl)) {\n // The listen will be sent in onWatchStreamOpen\n startWatchStream(remoteStoreImpl);\n } else if (ensureWatchStream(remoteStoreImpl).isOpen()) {\n sendWatchRequest(remoteStoreImpl, targetData);\n }\n}\n\n/**\n * Removes the listen from server. It is a no-op if the given target id is\n * not being listened to.\n */\nexport function remoteStoreUnlisten(\n remoteStore: RemoteStore,\n targetId: TargetId\n): void {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n const watchStream = ensureWatchStream(remoteStoreImpl);\n\n debugAssert(\n remoteStoreImpl.listenTargets.has(targetId),\n `unlisten called on target no currently watched: ${targetId}`\n );\n\n remoteStoreImpl.listenTargets.delete(targetId);\n if (watchStream.isOpen()) {\n sendUnwatchRequest(remoteStoreImpl, targetId);\n }\n\n if (remoteStoreImpl.listenTargets.size === 0) {\n if (watchStream.isOpen()) {\n watchStream.markIdle();\n } else if (canUseNetwork(remoteStoreImpl)) {\n // Revert to OnlineState.Unknown if the watch stream is not open and we\n // have no listeners, since without any listens to send we cannot\n // confirm if the stream is healthy and upgrade to OnlineState.Online.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n }\n}\n\n/**\n * We need to increment the the expected number of pending responses we're due\n * from watch so we wait for the ack to process any messages from this target.\n */\nfunction sendWatchRequest(\n remoteStoreImpl: RemoteStoreImpl,\n targetData: TargetData\n): void {\n remoteStoreImpl.watchChangeAggregator!.recordPendingTargetRequest(\n targetData.targetId\n );\n\n if (\n targetData.resumeToken.approximateByteSize() > 0 ||\n targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0\n ) {\n const expectedCount = remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget!(\n targetData.targetId\n ).size;\n targetData = targetData.withExpectedCount(expectedCount);\n }\n\n ensureWatchStream(remoteStoreImpl).watch(targetData);\n}\n\n/**\n * We need to increment the expected number of pending responses we're due\n * from watch so we wait for the removal on the server before we process any\n * messages from this target.\n */\nfunction sendUnwatchRequest(\n remoteStoreImpl: RemoteStoreImpl,\n targetId: TargetId\n): void {\n remoteStoreImpl.watchChangeAggregator!.recordPendingTargetRequest(targetId);\n ensureWatchStream(remoteStoreImpl).unwatch(targetId);\n}\n\nfunction startWatchStream(remoteStoreImpl: RemoteStoreImpl): void {\n debugAssert(\n shouldStartWatchStream(remoteStoreImpl),\n 'startWatchStream() called when shouldStartWatchStream() is false.'\n );\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget,\n 'getRemoteKeysForTarget() not set'\n );\n\n remoteStoreImpl.watchChangeAggregator = new WatchChangeAggregator({\n getRemoteKeysForTarget: targetId =>\n remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget!(targetId),\n getTargetDataForTarget: targetId =>\n remoteStoreImpl.listenTargets.get(targetId) || null,\n getDatabaseId: () => remoteStoreImpl.datastore.serializer.databaseId\n });\n ensureWatchStream(remoteStoreImpl).start();\n remoteStoreImpl.onlineStateTracker.handleWatchStreamStart();\n}\n\n/**\n * Returns whether the watch stream should be started because it's necessary\n * and has not yet been started.\n */\nfunction shouldStartWatchStream(remoteStoreImpl: RemoteStoreImpl): boolean {\n return (\n canUseNetwork(remoteStoreImpl) &&\n !ensureWatchStream(remoteStoreImpl).isStarted() &&\n remoteStoreImpl.listenTargets.size > 0\n );\n}\n\nexport function canUseNetwork(remoteStore: RemoteStore): boolean {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n return remoteStoreImpl.offlineCauses.size === 0;\n}\n\nfunction cleanUpWatchStreamState(remoteStoreImpl: RemoteStoreImpl): void {\n remoteStoreImpl.watchChangeAggregator = undefined;\n}\n\nasync function onWatchStreamOpen(\n remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n remoteStoreImpl.listenTargets.forEach((targetData, targetId) => {\n sendWatchRequest(remoteStoreImpl, targetData);\n });\n}\n\nasync function onWatchStreamClose(\n remoteStoreImpl: RemoteStoreImpl,\n error?: FirestoreError\n): Promise<void> {\n if (error === undefined) {\n // Graceful stop (due to stop() or idle timeout). Make sure that's\n // desirable.\n debugAssert(\n !shouldStartWatchStream(remoteStoreImpl),\n 'Watch stream was stopped gracefully while still needed.'\n );\n }\n\n cleanUpWatchStreamState(remoteStoreImpl);\n\n // If we still need the watch stream, retry the connection.\n if (shouldStartWatchStream(remoteStoreImpl)) {\n remoteStoreImpl.onlineStateTracker.handleWatchStreamFailure(error!);\n\n startWatchStream(remoteStoreImpl);\n } else {\n // No need to restart watch stream because there are no active targets.\n // The online state is set to unknown because there is no active attempt\n // at establishing a connection\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n}\n\nasync function onWatchStreamChange(\n remoteStoreImpl: RemoteStoreImpl,\n watchChange: WatchChange,\n snapshotVersion: SnapshotVersion\n): Promise<void> {\n // Mark the client as online since we got a message from the server\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Online);\n\n if (\n watchChange instanceof WatchTargetChange &&\n watchChange.state === WatchTargetChangeState.Removed &&\n watchChange.cause\n ) {\n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n try {\n await handleTargetError(remoteStoreImpl, watchChange);\n } catch (e) {\n logDebug(\n LOG_TAG,\n 'Failed to remove targets %s: %s ',\n watchChange.targetIds.join(','),\n e\n );\n await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n }\n return;\n }\n\n if (watchChange instanceof DocumentWatchChange) {\n remoteStoreImpl.watchChangeAggregator!.handleDocumentChange(watchChange);\n } else if (watchChange instanceof ExistenceFilterChange) {\n remoteStoreImpl.watchChangeAggregator!.handleExistenceFilter(watchChange);\n } else {\n debugAssert(\n watchChange instanceof WatchTargetChange,\n 'Expected watchChange to be an instance of WatchTargetChange'\n );\n remoteStoreImpl.watchChangeAggregator!.handleTargetChange(watchChange);\n }\n\n if (!snapshotVersion.isEqual(SnapshotVersion.min())) {\n try {\n const lastRemoteSnapshotVersion =\n await localStoreGetLastRemoteSnapshotVersion(\n remoteStoreImpl.localStore\n );\n if (snapshotVersion.compareTo(lastRemoteSnapshotVersion) >= 0) {\n // We have received a target change with a global snapshot if the snapshot\n // version is not equal to SnapshotVersion.min().\n await raiseWatchSnapshot(remoteStoreImpl, snapshotVersion);\n }\n } catch (e) {\n logDebug(LOG_TAG, 'Failed to raise snapshot:', e);\n await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n }\n }\n}\n\n/**\n * Recovery logic for IndexedDB errors that takes the network offline until\n * `op` succeeds. Retries are scheduled with backoff using\n * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is\n * validated via a generic operation.\n *\n * The returned Promise is resolved once the network is disabled and before\n * any retry attempt.\n */\nasync function disableNetworkUntilRecovery(\n remoteStoreImpl: RemoteStoreImpl,\n e: FirestoreError,\n op?: () => Promise<unknown>\n): Promise<void> {\n if (isIndexedDbTransactionError(e)) {\n debugAssert(\n !remoteStoreImpl.offlineCauses.has(OfflineCause.IndexedDbFailed),\n 'Unexpected network event when IndexedDB was marked failed.'\n );\n remoteStoreImpl.offlineCauses.add(OfflineCause.IndexedDbFailed);\n\n // Disable network and raise offline snapshots\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Offline);\n\n if (!op) {\n // Use a simple read operation to determine if IndexedDB recovered.\n // Ideally, we would expose a health check directly on SimpleDb, but\n // RemoteStore only has access to persistence through LocalStore.\n op = () =>\n localStoreGetLastRemoteSnapshotVersion(remoteStoreImpl.localStore);\n }\n\n // Probe IndexedDB periodically and re-enable network\n remoteStoreImpl.asyncQueue.enqueueRetryable(async () => {\n logDebug(LOG_TAG, 'Retrying IndexedDB access');\n await op!();\n remoteStoreImpl.offlineCauses.delete(OfflineCause.IndexedDbFailed);\n await enableNetworkInternal(remoteStoreImpl);\n });\n } else {\n throw e;\n }\n}\n\n/**\n * Executes `op`. If `op` fails, takes the network offline until `op`\n * succeeds. Returns after the first attempt.\n */\nfunction executeWithRecovery(\n remoteStoreImpl: RemoteStoreImpl,\n op: () => Promise<void>\n): Promise<void> {\n return op().catch(e => disableNetworkUntilRecovery(remoteStoreImpl, e, op));\n}\n\n/**\n * Takes a batch of changes from the Datastore, repackages them as a\n * RemoteEvent, and passes that on to the listener, which is typically the\n * SyncEngine.\n */\nfunction raiseWatchSnapshot(\n remoteStoreImpl: RemoteStoreImpl,\n snapshotVersion: SnapshotVersion\n): Promise<void> {\n debugAssert(\n !snapshotVersion.isEqual(SnapshotVersion.min()),\n \"Can't raise event for unknown SnapshotVersion\"\n );\n const remoteEvent =\n remoteStoreImpl.watchChangeAggregator!.createRemoteEvent(snapshotVersion);\n\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n remoteEvent.targetChanges.forEach((change, targetId) => {\n if (change.resumeToken.approximateByteSize() > 0) {\n const targetData = remoteStoreImpl.listenTargets.get(targetId);\n // A watched target might have been removed already.\n if (targetData) {\n remoteStoreImpl.listenTargets.set(\n targetId,\n targetData.withResumeToken(change.resumeToken, snapshotVersion)\n );\n }\n }\n });\n\n // Re-establish listens for the targets that have been invalidated by\n // existence filter mismatches.\n remoteEvent.targetMismatches.forEach((targetId, targetPurpose) => {\n const targetData = remoteStoreImpl.listenTargets.get(targetId);\n if (!targetData) {\n // A watched target might have been removed already.\n return;\n }\n\n // Clear the resume token for the target, since we're in a known mismatch\n // state.\n remoteStoreImpl.listenTargets.set(\n targetId,\n targetData.withResumeToken(\n ByteString.EMPTY_BYTE_STRING,\n targetData.snapshotVersion\n )\n );\n\n // Cause a hard reset by unwatching and rewatching immediately, but\n // deliberately don't send a resume token so that we get a full update.\n sendUnwatchRequest(remoteStoreImpl, targetId);\n\n // Mark the target we send as being on behalf of an existence filter\n // mismatch, but don't actually retain that in listenTargets. This ensures\n // that we flag the first re-listen this way without impacting future\n // listens of this target (that might happen e.g. on reconnect).\n const requestTargetData = new TargetData(\n targetData.target,\n targetId,\n targetPurpose,\n targetData.sequenceNumber\n );\n sendWatchRequest(remoteStoreImpl, requestTargetData);\n });\n\n // Finally raise remote event\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.applyRemoteEvent,\n 'applyRemoteEvent() not set'\n );\n return remoteStoreImpl.remoteSyncer.applyRemoteEvent(remoteEvent);\n}\n\n/** Handles an error on a target */\nasync function handleTargetError(\n remoteStoreImpl: RemoteStoreImpl,\n watchChange: WatchTargetChange\n): Promise<void> {\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.rejectListen,\n 'rejectListen() not set'\n );\n debugAssert(!!watchChange.cause, 'Handling target error without a cause');\n const error = watchChange.cause!;\n for (const targetId of watchChange.targetIds) {\n // A watched target might have been removed already.\n if (remoteStoreImpl.listenTargets.has(targetId)) {\n await remoteStoreImpl.remoteSyncer.rejectListen(targetId, error);\n remoteStoreImpl.listenTargets.delete(targetId);\n remoteStoreImpl.watchChangeAggregator!.removeTarget(targetId);\n }\n }\n}\n\n/**\n * Attempts to fill our write pipeline with writes from the LocalStore.\n *\n * Called internally to bootstrap or refill the write pipeline and by\n * SyncEngine whenever there are new mutations to process.\n *\n * Starts the write stream if necessary.\n */\nexport async function fillWritePipeline(\n remoteStore: RemoteStore\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n const writeStream = ensureWriteStream(remoteStoreImpl);\n\n let lastBatchIdRetrieved =\n remoteStoreImpl.writePipeline.length > 0\n ? remoteStoreImpl.writePipeline[remoteStoreImpl.writePipeline.length - 1]\n .batchId\n : BATCHID_UNKNOWN;\n\n while (canAddToWritePipeline(remoteStoreImpl)) {\n try {\n const batch = await localStoreGetNextMutationBatch(\n remoteStoreImpl.localStore,\n lastBatchIdRetrieved\n );\n\n if (batch === null) {\n if (remoteStoreImpl.writePipeline.length === 0) {\n writeStream.markIdle();\n }\n break;\n } else {\n lastBatchIdRetrieved = batch.batchId;\n addToWritePipeline(remoteStoreImpl, batch);\n }\n } catch (e) {\n await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n }\n }\n\n if (shouldStartWriteStream(remoteStoreImpl)) {\n startWriteStream(remoteStoreImpl);\n }\n}\n\n/**\n * Returns true if we can add to the write pipeline (i.e. the network is\n * enabled and the write pipeline is not full).\n */\nfunction canAddToWritePipeline(remoteStoreImpl: RemoteStoreImpl): boolean {\n return (\n canUseNetwork(remoteStoreImpl) &&\n remoteStoreImpl.writePipeline.length < MAX_PENDING_WRITES\n );\n}\n\n// For testing\nexport function outstandingWrites(remoteStore: RemoteStore): number {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n return remoteStoreImpl.writePipeline.length;\n}\n\n/**\n * Queues additional writes to be sent to the write stream, sending them\n * immediately if the write stream is established.\n */\nfunction addToWritePipeline(\n remoteStoreImpl: RemoteStoreImpl,\n batch: MutationBatch\n): void {\n debugAssert(\n canAddToWritePipeline(remoteStoreImpl),\n 'addToWritePipeline called when pipeline is full'\n );\n remoteStoreImpl.writePipeline.push(batch);\n\n const writeStream = ensureWriteStream(remoteStoreImpl);\n if (writeStream.isOpen() && writeStream.handshakeComplete) {\n writeStream.writeMutations(batch.mutations);\n }\n}\n\nfunction shouldStartWriteStream(remoteStoreImpl: RemoteStoreImpl): boolean {\n return (\n canUseNetwork(remoteStoreImpl) &&\n !ensureWriteStream(remoteStoreImpl).isStarted() &&\n remoteStoreImpl.writePipeline.length > 0\n );\n}\n\nfunction startWriteStream(remoteStoreImpl: RemoteStoreImpl): void {\n debugAssert(\n shouldStartWriteStream(remoteStoreImpl),\n 'startWriteStream() called when shouldStartWriteStream() is false.'\n );\n ensureWriteStream(remoteStoreImpl).start();\n}\n\nasync function onWriteStreamOpen(\n remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n ensureWriteStream(remoteStoreImpl).writeHandshake();\n}\n\nasync function onWriteHandshakeComplete(\n remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n const writeStream = ensureWriteStream(remoteStoreImpl);\n // Send the write pipeline now that the stream is established.\n for (const batch of remoteStoreImpl.writePipeline) {\n writeStream.writeMutations(batch.mutations);\n }\n}\n\nasync function onMutationResult(\n remoteStoreImpl: RemoteStoreImpl,\n commitVersion: SnapshotVersion,\n results: MutationResult[]\n): Promise<void> {\n // This is a response to a write containing mutations and should be\n // correlated to the first write in our write pipeline.\n debugAssert(\n remoteStoreImpl.writePipeline.length > 0,\n 'Got result for empty write pipeline'\n );\n const batch = remoteStoreImpl.writePipeline.shift()!;\n const success = MutationBatchResult.from(batch, commitVersion, results);\n\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.applySuccessfulWrite,\n 'applySuccessfulWrite() not set'\n );\n await executeWithRecovery(remoteStoreImpl, () =>\n remoteStoreImpl.remoteSyncer.applySuccessfulWrite!(success)\n );\n\n // It's possible that with the completion of this mutation another\n // slot has freed up.\n await fillWritePipeline(remoteStoreImpl);\n}\n\nasync function onWriteStreamClose(\n remoteStoreImpl: RemoteStoreImpl,\n error?: FirestoreError\n): Promise<void> {\n if (error === undefined) {\n // Graceful stop (due to stop() or idle timeout). Make sure that's\n // desirable.\n debugAssert(\n !shouldStartWriteStream(remoteStoreImpl),\n 'Write stream was stopped gracefully while still needed.'\n );\n }\n\n // If the write stream closed after the write handshake completes, a write\n // operation failed and we fail the pending operation.\n if (error && ensureWriteStream(remoteStoreImpl).handshakeComplete) {\n // This error affects the actual write.\n await handleWriteError(remoteStoreImpl, error!);\n }\n\n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n if (shouldStartWriteStream(remoteStoreImpl)) {\n startWriteStream(remoteStoreImpl);\n }\n}\n\nasync function handleWriteError(\n remoteStoreImpl: RemoteStoreImpl,\n error: FirestoreError\n): Promise<void> {\n // Only handle permanent errors here. If it's transient, just let the retry\n // logic kick in.\n if (isPermanentWriteError(error.code)) {\n // This was a permanent error, the request itself was the problem\n // so it's not going to succeed if we resend it.\n const batch = remoteStoreImpl.writePipeline.shift()!;\n\n // In this case it's also unlikely that the server itself is melting\n // down -- this was just a bad request so inhibit backoff on the next\n // restart.\n ensureWriteStream(remoteStoreImpl).inhibitBackoff();\n\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.rejectFailedWrite,\n 'rejectFailedWrite() not set'\n );\n await executeWithRecovery(remoteStoreImpl, () =>\n remoteStoreImpl.remoteSyncer.rejectFailedWrite!(batch.batchId, error)\n );\n\n // It's possible that with the completion of this mutation\n // another slot has freed up.\n await fillWritePipeline(remoteStoreImpl);\n } else {\n // Transient error, just let the retry logic kick in.\n }\n}\n\nasync function restartNetwork(remoteStore: RemoteStore): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.offlineCauses.add(OfflineCause.ConnectivityChange);\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n remoteStoreImpl.offlineCauses.delete(OfflineCause.ConnectivityChange);\n await enableNetworkInternal(remoteStoreImpl);\n}\n\nexport async function remoteStoreHandleCredentialChange(\n remoteStore: RemoteStore,\n user: User\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.asyncQueue.verifyOperationInProgress();\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.handleCredentialChange,\n 'handleCredentialChange() not set'\n );\n\n logDebug(LOG_TAG, 'RemoteStore received new credentials');\n const usesNetwork = canUseNetwork(remoteStoreImpl);\n\n // Tear down and re-create our network streams. This will ensure we get a\n // fresh auth token for the new user and re-fill the write pipeline with\n // new mutations from the LocalStore (since mutations are per-user).\n remoteStoreImpl.offlineCauses.add(OfflineCause.CredentialChange);\n await disableNetworkInternal(remoteStoreImpl);\n if (usesNetwork) {\n // Don't set the network status to Unknown if we are offline.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n await remoteStoreImpl.remoteSyncer.handleCredentialChange(user);\n remoteStoreImpl.offlineCauses.delete(OfflineCause.CredentialChange);\n await enableNetworkInternal(remoteStoreImpl);\n}\n\n/**\n * Toggles the network state when the client gains or loses its primary lease.\n */\nexport async function remoteStoreApplyPrimaryState(\n remoteStore: RemoteStore,\n isPrimary: boolean\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n if (isPrimary) {\n remoteStoreImpl.offlineCauses.delete(OfflineCause.IsSecondary);\n await enableNetworkInternal(remoteStoreImpl);\n } else if (!isPrimary) {\n remoteStoreImpl.offlineCauses.add(OfflineCause.IsSecondary);\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n}\n\n/**\n * If not yet initialized, registers the WatchStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */\nfunction ensureWatchStream(\n remoteStoreImpl: RemoteStoreImpl\n): PersistentListenStream {\n if (!remoteStoreImpl.watchStream) {\n // Create stream (but note that it is not started yet).\n remoteStoreImpl.watchStream = newPersistentWatchStream(\n remoteStoreImpl.datastore,\n remoteStoreImpl.asyncQueue,\n {\n onOpen: onWatchStreamOpen.bind(null, remoteStoreImpl),\n onClose: onWatchStreamClose.bind(null, remoteStoreImpl),\n onWatchChange: onWatchStreamChange.bind(null, remoteStoreImpl)\n }\n );\n\n remoteStoreImpl.onNetworkStatusChange.push(async enabled => {\n if (enabled) {\n remoteStoreImpl.watchStream!.inhibitBackoff();\n if (shouldStartWatchStream(remoteStoreImpl)) {\n startWatchStream(remoteStoreImpl);\n } else {\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n } else {\n await remoteStoreImpl.watchStream!.stop();\n cleanUpWatchStreamState(remoteStoreImpl);\n }\n });\n }\n\n return remoteStoreImpl.watchStream;\n}\n\n/**\n * If not yet initialized, registers the WriteStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */\nfunction ensureWriteStream(\n remoteStoreImpl: RemoteStoreImpl\n): PersistentWriteStream {\n if (!remoteStoreImpl.writeStream) {\n debugAssert(\n remoteStoreImpl.writePipeline.length === 0,\n 'Should not issue writes before WriteStream is enabled'\n );\n\n // Create stream (but note that it is not started yet).\n remoteStoreImpl.writeStream = newPersistentWriteStream(\n remoteStoreImpl.datastore,\n remoteStoreImpl.asyncQueue,\n {\n onOpen: onWriteStreamOpen.bind(null, remoteStoreImpl),\n onClose: onWriteStreamClose.bind(null, remoteStoreImpl),\n onHandshakeComplete: onWriteHandshakeComplete.bind(\n null,\n remoteStoreImpl\n ),\n onMutationResult: onMutationResult.bind(null, remoteStoreImpl)\n }\n );\n\n remoteStoreImpl.onNetworkStatusChange.push(async enabled => {\n if (enabled) {\n remoteStoreImpl.writeStream!.inhibitBackoff();\n\n // This will start the write stream if necessary.\n await fillWritePipeline(remoteStoreImpl);\n } else {\n await remoteStoreImpl.writeStream!.stop();\n\n if (remoteStoreImpl.writePipeline.length > 0) {\n logDebug(\n LOG_TAG,\n `Stopping write stream with ${remoteStoreImpl.writePipeline.length} pending writes`\n );\n remoteStoreImpl.writePipeline = [];\n }\n }\n });\n }\n\n return remoteStoreImpl.writeStream;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\n\nimport { Code, FirestoreError } from './error';\nimport { logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TimerHandle = any;\n\n/**\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\n * AsyncQueue. These IDs can then be used from tests to check for the presence\n * of operations or to run them early.\n *\n * The string values are used when encoding these timer IDs in JSON spec tests.\n */\nexport const enum TimerId {\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\n All = 'all',\n\n /**\n * The following 5 timers are used in persistent_stream.ts for the listen and\n * write streams. The \"Idle\" timer is used to close the stream due to\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\n * the appropriate backoff delay has elapsed. The health check is used to mark\n * a stream healthy if it has not received an error during its initial setup.\n */\n ListenStreamIdle = 'listen_stream_idle',\n ListenStreamConnectionBackoff = 'listen_stream_connection_backoff',\n WriteStreamIdle = 'write_stream_idle',\n WriteStreamConnectionBackoff = 'write_stream_connection_backoff',\n HealthCheckTimeout = 'health_check_timeout',\n\n /**\n * A timer used in online_state_tracker.ts to transition from\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\n * indefinitely for success or failure.\n */\n OnlineStateTimeout = 'online_state_timeout',\n\n /**\n * A timer used to update the client metadata in IndexedDb, which is used\n * to determine the primary leaseholder.\n */\n ClientMetadataRefresh = 'client_metadata_refresh',\n\n /** A timer used to periodically attempt LRU Garbage collection */\n LruGarbageCollection = 'lru_garbage_collection',\n\n /**\n * A timer used to retry transactions. Since there can be multiple concurrent\n * transactions, multiple of these may be in the queue at a given time.\n */\n TransactionRetry = 'transaction_retry',\n\n /**\n * A timer used to retry operations scheduled via retryable AsyncQueue\n * operations.\n */\n AsyncQueueRetry = 'async_queue_retry',\n\n /**\n * A timer used to periodically attempt index backfill.\n */\n IndexBackfill = 'index_backfill'\n}\n\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nexport class DelayedOperation<T extends unknown> implements PromiseLike<T> {\n // handle for use with clearTimeout(), or null if the operation has been\n // executed or canceled already.\n private timerHandle: TimerHandle | null;\n\n private readonly deferred = new Deferred<T>();\n\n private constructor(\n private readonly asyncQueue: AsyncQueue,\n readonly timerId: TimerId,\n readonly targetTimeMs: number,\n private readonly op: () => Promise<T>,\n private readonly removalCallback: (op: DelayedOperation<T>) => void\n ) {\n // It's normal for the deferred promise to be canceled (due to cancellation)\n // and so we attach a dummy catch callback to avoid\n // 'UnhandledPromiseRejectionWarning' log spam.\n this.deferred.promise.catch(err => {});\n }\n\n get promise(): Promise<T> {\n return this.deferred.promise;\n }\n\n /**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue - The queue to schedule the operation on.\n * @param id - A Timer ID identifying the type of operation this is.\n * @param delayMs - The delay (ms) before the operation should be scheduled.\n * @param op - The operation to run.\n * @param removalCallback - A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */\n static createAndSchedule<R extends unknown>(\n asyncQueue: AsyncQueue,\n timerId: TimerId,\n delayMs: number,\n op: () => Promise<R>,\n removalCallback: (op: DelayedOperation<R>) => void\n ): DelayedOperation<R> {\n const targetTime = Date.now() + delayMs;\n const delayedOp = new DelayedOperation(\n asyncQueue,\n timerId,\n targetTime,\n op,\n removalCallback\n );\n delayedOp.start(delayMs);\n return delayedOp;\n }\n\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */\n private start(delayMs: number): void {\n this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs);\n }\n\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */\n skipDelay(): void {\n return this.handleDelayElapsed();\n }\n\n /**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */\n cancel(reason?: string): void {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n this.deferred.reject(\n new FirestoreError(\n Code.CANCELLED,\n 'Operation cancelled' + (reason ? ': ' + reason : '')\n )\n );\n }\n }\n\n then = this.deferred.promise.then.bind(this.deferred.promise);\n\n private handleDelayElapsed(): void {\n this.asyncQueue.enqueueAndForget(() => {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n return this.op().then(result => {\n return this.deferred.resolve(result);\n });\n } else {\n return Promise.resolve();\n }\n });\n }\n\n private clearTimeout(): void {\n if (this.timerHandle !== null) {\n this.removalCallback(this);\n clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n }\n}\n\nexport interface AsyncQueue {\n // Is this AsyncQueue being shut down? If true, this instance will not enqueue\n // any new operations, Promises from enqueue requests will not resolve.\n readonly isShuttingDown: boolean;\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget<T extends unknown>(op: () => Promise<T>): void;\n\n /**\n * Regardless if the queue has initialized shutdown, adds a new operation to the\n * queue without waiting for it to complete (i.e. we ignore the Promise result).\n */\n enqueueAndForgetEvenWhileRestricted<T extends unknown>(\n op: () => Promise<T>\n ): void;\n\n /**\n * Initialize the shutdown of this queue. Once this method is called, the\n * only possible way to request running an operation is through\n * `enqueueEvenWhileRestricted()`.\n *\n * @param purgeExistingTasks Whether already enqueued tasked should be\n * rejected (unless enqueued wih `enqueueEvenWhileRestricted()`). Defaults\n * to false.\n */\n enterRestrictedMode(purgeExistingTasks?: boolean): void;\n\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n */\n enqueue<T extends unknown>(op: () => Promise<T>): Promise<T>;\n\n /**\n * Enqueue a retryable operation.\n *\n * A retryable operation is rescheduled with backoff if it fails with a\n * IndexedDbTransactionError (the error type used by SimpleDb). All\n * retryable operations are executed in order and only run if all prior\n * operations were retried successfully.\n */\n enqueueRetryable(op: () => Promise<void>): void;\n\n /**\n * Schedules an operation to be queued on the AsyncQueue once the specified\n * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel\n * or fast-forward the operation prior to its running.\n */\n enqueueAfterDelay<T extends unknown>(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise<T>\n ): DelayedOperation<T>;\n\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n verifyOperationInProgress(): void;\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */\nexport function wrapInUserErrorIfRecoverable(\n e: Error,\n msg: string\n): FirestoreError {\n logError(LOG_TAG, `${msg}: ${e}`);\n if (isIndexedDbTransactionError(e)) {\n return new FirestoreError(Code.UNAVAILABLE, `${msg}: ${e}`);\n } else {\n throw e;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap } from '../util/sorted_map';\n\nimport { documentMap } from './collections';\nimport { Document } from './document';\nimport { DocumentComparator } from './document_comparator';\nimport { DocumentKey } from './document_key';\n\n/**\n * DocumentSet is an immutable (copy-on-write) collection that holds documents\n * in order specified by the provided comparator. We always add a document key\n * comparator on top of what is provided to guarantee document equality based on\n * the key.\n */\n\nexport class DocumentSet {\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */\n static emptySet(oldSet: DocumentSet): DocumentSet {\n return new DocumentSet(oldSet.comparator);\n }\n\n private comparator: DocumentComparator;\n private keyedMap: SortedMap<DocumentKey, Document>;\n private sortedSet: SortedMap<Document, null>;\n\n /** The default ordering is by key if the comparator is omitted */\n constructor(comp?: DocumentComparator) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n if (comp) {\n this.comparator = (d1: Document, d2: Document) =>\n comp(d1, d2) || DocumentKey.comparator(d1.key, d2.key);\n } else {\n this.comparator = (d1: Document, d2: Document) =>\n DocumentKey.comparator(d1.key, d2.key);\n }\n\n this.keyedMap = documentMap();\n this.sortedSet = new SortedMap<Document, null>(this.comparator);\n }\n\n has(key: DocumentKey): boolean {\n return this.keyedMap.get(key) != null;\n }\n\n get(key: DocumentKey): Document | null {\n return this.keyedMap.get(key);\n }\n\n first(): Document | null {\n return this.sortedSet.minKey();\n }\n\n last(): Document | null {\n return this.sortedSet.maxKey();\n }\n\n isEmpty(): boolean {\n return this.sortedSet.isEmpty();\n }\n\n /**\n * Returns the index of the provided key in the document set, or -1 if the\n * document key is not present in the set;\n */\n indexOf(key: DocumentKey): number {\n const doc = this.keyedMap.get(key);\n return doc ? this.sortedSet.indexOf(doc) : -1;\n }\n\n get size(): number {\n return this.sortedSet.size;\n }\n\n /** Iterates documents in order defined by \"comparator\" */\n forEach(cb: (doc: Document) => void): void {\n this.sortedSet.inorderTraversal((k, v) => {\n cb(k);\n return false;\n });\n }\n\n /** Inserts or updates a document with the same key */\n add(doc: Document): DocumentSet {\n // First remove the element if we have it.\n const set = this.delete(doc.key);\n return set.copy(\n set.keyedMap.insert(doc.key, doc),\n set.sortedSet.insert(doc, null)\n );\n }\n\n /** Deletes a document with a given key */\n delete(key: DocumentKey): DocumentSet {\n const doc = this.get(key);\n if (!doc) {\n return this;\n }\n\n return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc));\n }\n\n isEqual(other: DocumentSet | null | undefined): boolean {\n if (!(other instanceof DocumentSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.sortedSet.getIterator();\n const otherIt = other.sortedSet.getIterator();\n while (thisIt.hasNext()) {\n const thisDoc = thisIt.getNext().key;\n const otherDoc = otherIt.getNext().key;\n if (!thisDoc.isEqual(otherDoc)) {\n return false;\n }\n }\n return true;\n }\n\n toString(): string {\n const docStrings: string[] = [];\n this.forEach(doc => {\n docStrings.push(doc.toString());\n });\n if (docStrings.length === 0) {\n return 'DocumentSet ()';\n } else {\n return 'DocumentSet (\\n ' + docStrings.join(' \\n') + '\\n)';\n }\n }\n\n private copy(\n keyedMap: SortedMap<DocumentKey, Document>,\n sortedSet: SortedMap<Document, null>\n ): DocumentSet {\n const newSet = new DocumentSet();\n newSet.comparator = this.comparator;\n newSet.keyedMap = keyedMap;\n newSet.sortedSet = sortedSet;\n return newSet;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKeySet } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { fail } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { Query, queryEquals } from './query';\n\nexport const enum ChangeType {\n Added,\n Removed,\n Modified,\n Metadata\n}\n\nexport interface DocumentViewChange {\n type: ChangeType;\n doc: Document;\n}\n\nexport const enum SyncState {\n Local,\n Synced\n}\n\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */\nexport class DocumentChangeSet {\n private changeMap = new SortedMap<DocumentKey, DocumentViewChange>(\n DocumentKey.comparator\n );\n\n track(change: DocumentViewChange): void {\n const key = change.doc.key;\n const oldChange = this.changeMap.get(key);\n if (!oldChange) {\n this.changeMap = this.changeMap.insert(key, change);\n return;\n }\n\n // Merge the new change with the existing change.\n if (\n change.type !== ChangeType.Added &&\n oldChange.type === ChangeType.Metadata\n ) {\n this.changeMap = this.changeMap.insert(key, change);\n } else if (\n change.type === ChangeType.Metadata &&\n oldChange.type !== ChangeType.Removed\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: oldChange.type,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Modified\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Added\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Added,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Added\n ) {\n this.changeMap = this.changeMap.remove(key);\n } else if (\n change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Modified\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Removed,\n doc: oldChange.doc\n });\n } else if (\n change.type === ChangeType.Added &&\n oldChange.type === ChangeType.Removed\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n } else {\n // This includes these cases, which don't make sense:\n // Added->Added\n // Removed->Removed\n // Modified->Added\n // Removed->Modified\n // Metadata->Added\n // Removed->Metadata\n fail(\n 'unsupported combination of changes: ' +\n JSON.stringify(change) +\n ' after ' +\n JSON.stringify(oldChange)\n );\n }\n }\n\n getChanges(): DocumentViewChange[] {\n const changes: DocumentViewChange[] = [];\n this.changeMap.inorderTraversal(\n (key: DocumentKey, change: DocumentViewChange) => {\n changes.push(change);\n }\n );\n return changes;\n }\n}\n\nexport class ViewSnapshot {\n constructor(\n readonly query: Query,\n readonly docs: DocumentSet,\n readonly oldDocs: DocumentSet,\n readonly docChanges: DocumentViewChange[],\n readonly mutatedKeys: DocumentKeySet,\n readonly fromCache: boolean,\n readonly syncStateChanged: boolean,\n readonly excludesMetadataChanges: boolean,\n readonly hasCachedResults: boolean\n ) {}\n\n /** Returns a view snapshot as if all documents in the snapshot were added. */\n static fromInitialDocuments(\n query: Query,\n documents: DocumentSet,\n mutatedKeys: DocumentKeySet,\n fromCache: boolean,\n hasCachedResults: boolean\n ): ViewSnapshot {\n const changes: DocumentViewChange[] = [];\n documents.forEach(doc => {\n changes.push({ type: ChangeType.Added, doc });\n });\n\n return new ViewSnapshot(\n query,\n documents,\n DocumentSet.emptySet(documents),\n changes,\n mutatedKeys,\n fromCache,\n /* syncStateChanged= */ true,\n /* excludesMetadataChanges= */ false,\n hasCachedResults\n );\n }\n\n get hasPendingWrites(): boolean {\n return !this.mutatedKeys.isEmpty();\n }\n\n isEqual(other: ViewSnapshot): boolean {\n if (\n this.fromCache !== other.fromCache ||\n this.hasCachedResults !== other.hasCachedResults ||\n this.syncStateChanged !== other.syncStateChanged ||\n !this.mutatedKeys.isEqual(other.mutatedKeys) ||\n !queryEquals(this.query, other.query) ||\n !this.docs.isEqual(other.docs) ||\n !this.oldDocs.isEqual(other.oldDocs)\n ) {\n return false;\n }\n const changes: DocumentViewChange[] = this.docChanges;\n const otherChanges: DocumentViewChange[] = other.docChanges;\n if (changes.length !== otherChanges.length) {\n return false;\n }\n for (let i = 0; i < changes.length; i++) {\n if (\n changes[i].type !== otherChanges[i].type ||\n !changes[i].doc.isEqual(otherChanges[i].doc)\n ) {\n return false;\n }\n }\n return true;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, debugCast } from '../util/assert';\nimport { wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { EventHandler } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { canonifyQuery, Query, queryEquals, stringifyQuery } from './query';\nimport { OnlineState } from './types';\nimport { ChangeType, DocumentViewChange, ViewSnapshot } from './view_snapshot';\n\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */\nclass QueryListenersInfo {\n viewSnap: ViewSnapshot | undefined = undefined;\n listeners: QueryListener[] = [];\n}\n\n/**\n * Interface for handling events from the EventManager.\n */\nexport interface Observer<T> {\n next: EventHandler<T>;\n error: EventHandler<FirestoreError>;\n}\n\n/**\n * EventManager is responsible for mapping queries to query event emitters.\n * It handles \"fan-out\". -- Identical queries will re-use the same watch on the\n * backend.\n *\n * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be\n * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This\n * allows users to tree-shake the Watch logic.\n */\nexport interface EventManager {\n onListen?: (query: Query) => Promise<ViewSnapshot>;\n onUnlisten?: (query: Query) => Promise<void>;\n}\n\nexport function newEventManager(): EventManager {\n return new EventManagerImpl();\n}\n\nexport class EventManagerImpl implements EventManager {\n queries = new ObjectMap<Query, QueryListenersInfo>(\n q => canonifyQuery(q),\n queryEquals\n );\n\n onlineState = OnlineState.Unknown;\n\n snapshotsInSyncListeners: Set<Observer<void>> = new Set();\n\n /** Callback invoked when a Query is first listen to. */\n onListen?: (query: Query) => Promise<ViewSnapshot>;\n /** Callback invoked once all listeners to a Query are removed. */\n onUnlisten?: (query: Query) => Promise<void>;\n}\n\nexport async function eventManagerListen(\n eventManager: EventManager,\n listener: QueryListener\n): Promise<void> {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n debugAssert(!!eventManagerImpl.onListen, 'onListen not set');\n const query = listener.query;\n let firstListen = false;\n\n let queryInfo = eventManagerImpl.queries.get(query);\n if (!queryInfo) {\n firstListen = true;\n queryInfo = new QueryListenersInfo();\n }\n\n if (firstListen) {\n try {\n queryInfo.viewSnap = await eventManagerImpl.onListen(query);\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Initialization of query '${stringifyQuery(listener.query)}' failed`\n );\n listener.onError(firestoreError);\n return;\n }\n }\n\n eventManagerImpl.queries.set(query, queryInfo);\n queryInfo.listeners.push(listener);\n\n // Run global snapshot listeners if a consistent snapshot has been emitted.\n const raisedEvent = listener.applyOnlineStateChange(\n eventManagerImpl.onlineState\n );\n debugAssert(\n !raisedEvent,\n \"applyOnlineStateChange() shouldn't raise an event for brand-new listeners.\"\n );\n\n if (queryInfo.viewSnap) {\n const raisedEvent = listener.onViewSnapshot(queryInfo.viewSnap);\n if (raisedEvent) {\n raiseSnapshotsInSyncEvent(eventManagerImpl);\n }\n }\n}\n\nexport async function eventManagerUnlisten(\n eventManager: EventManager,\n listener: QueryListener\n): Promise<void> {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n debugAssert(!!eventManagerImpl.onUnlisten, 'onUnlisten not set');\n const query = listener.query;\n let lastListen = false;\n\n const queryInfo = eventManagerImpl.queries.get(query);\n if (queryInfo) {\n const i = queryInfo.listeners.indexOf(listener);\n if (i >= 0) {\n queryInfo.listeners.splice(i, 1);\n lastListen = queryInfo.listeners.length === 0;\n }\n }\n\n if (lastListen) {\n eventManagerImpl.queries.delete(query);\n return eventManagerImpl.onUnlisten(query);\n }\n}\n\nexport function eventManagerOnWatchChange(\n eventManager: EventManager,\n viewSnaps: ViewSnapshot[]\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n let raisedEvent = false;\n for (const viewSnap of viewSnaps) {\n const query = viewSnap.query;\n const queryInfo = eventManagerImpl.queries.get(query);\n if (queryInfo) {\n for (const listener of queryInfo.listeners) {\n if (listener.onViewSnapshot(viewSnap)) {\n raisedEvent = true;\n }\n }\n queryInfo.viewSnap = viewSnap;\n }\n }\n if (raisedEvent) {\n raiseSnapshotsInSyncEvent(eventManagerImpl);\n }\n}\n\nexport function eventManagerOnWatchError(\n eventManager: EventManager,\n query: Query,\n error: FirestoreError\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n const queryInfo = eventManagerImpl.queries.get(query);\n if (queryInfo) {\n for (const listener of queryInfo.listeners) {\n listener.onError(error);\n }\n }\n\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n eventManagerImpl.queries.delete(query);\n}\n\nexport function eventManagerOnOnlineStateChange(\n eventManager: EventManager,\n onlineState: OnlineState\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n eventManagerImpl.onlineState = onlineState;\n let raisedEvent = false;\n eventManagerImpl.queries.forEach((_, queryInfo) => {\n for (const listener of queryInfo.listeners) {\n // Run global snapshot listeners if a consistent snapshot has been emitted.\n if (listener.applyOnlineStateChange(onlineState)) {\n raisedEvent = true;\n }\n }\n });\n if (raisedEvent) {\n raiseSnapshotsInSyncEvent(eventManagerImpl);\n }\n}\n\nexport function addSnapshotsInSyncListener(\n eventManager: EventManager,\n observer: Observer<void>\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n eventManagerImpl.snapshotsInSyncListeners.add(observer);\n // Immediately fire an initial event, indicating all existing listeners\n // are in-sync.\n observer.next();\n}\n\nexport function removeSnapshotsInSyncListener(\n eventManager: EventManager,\n observer: Observer<void>\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n eventManagerImpl.snapshotsInSyncListeners.delete(observer);\n}\n\n// Call all global snapshot listeners that have been set.\nfunction raiseSnapshotsInSyncEvent(eventManagerImpl: EventManagerImpl): void {\n eventManagerImpl.snapshotsInSyncListeners.forEach(observer => {\n observer.next();\n });\n}\n\nexport interface ListenOptions {\n /** Raise events even when only the metadata changes */\n readonly includeMetadataChanges?: boolean;\n\n /**\n * Wait for a sync with the server when online, but still raise events while\n * offline.\n */\n readonly waitForSyncWhenOnline?: boolean;\n}\n\n/**\n * QueryListener takes a series of internal view snapshots and determines\n * when to raise the event.\n *\n * It uses an Observer to dispatch events.\n */\nexport class QueryListener {\n /**\n * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\n * observer. This flag is set to true once we've actually raised an event.\n */\n private raisedInitialEvent = false;\n\n private options: ListenOptions;\n\n private snap: ViewSnapshot | null = null;\n\n private onlineState = OnlineState.Unknown;\n\n constructor(\n readonly query: Query,\n private queryObserver: Observer<ViewSnapshot>,\n options?: ListenOptions\n ) {\n this.options = options || {};\n }\n\n /**\n * Applies the new ViewSnapshot to this listener, raising a user-facing event\n * if applicable (depending on what changed, whether the user has opted into\n * metadata-only changes, etc.). Returns true if a user-facing event was\n * indeed raised.\n */\n onViewSnapshot(snap: ViewSnapshot): boolean {\n debugAssert(\n snap.docChanges.length > 0 || snap.syncStateChanged,\n 'We got a new snapshot with no changes?'\n );\n\n if (!this.options.includeMetadataChanges) {\n // Remove the metadata only changes.\n const docChanges: DocumentViewChange[] = [];\n for (const docChange of snap.docChanges) {\n if (docChange.type !== ChangeType.Metadata) {\n docChanges.push(docChange);\n }\n }\n snap = new ViewSnapshot(\n snap.query,\n snap.docs,\n snap.oldDocs,\n docChanges,\n snap.mutatedKeys,\n snap.fromCache,\n snap.syncStateChanged,\n /* excludesMetadataChanges= */ true,\n snap.hasCachedResults\n );\n }\n let raisedEvent = false;\n if (!this.raisedInitialEvent) {\n if (this.shouldRaiseInitialEvent(snap, this.onlineState)) {\n this.raiseInitialEvent(snap);\n raisedEvent = true;\n }\n } else if (this.shouldRaiseEvent(snap)) {\n this.queryObserver.next(snap);\n raisedEvent = true;\n }\n\n this.snap = snap;\n return raisedEvent;\n }\n\n onError(error: FirestoreError): void {\n this.queryObserver.error(error);\n }\n\n /** Returns whether a snapshot was raised. */\n applyOnlineStateChange(onlineState: OnlineState): boolean {\n this.onlineState = onlineState;\n let raisedEvent = false;\n if (\n this.snap &&\n !this.raisedInitialEvent &&\n this.shouldRaiseInitialEvent(this.snap, onlineState)\n ) {\n this.raiseInitialEvent(this.snap);\n raisedEvent = true;\n }\n return raisedEvent;\n }\n\n private shouldRaiseInitialEvent(\n snap: ViewSnapshot,\n onlineState: OnlineState\n ): boolean {\n debugAssert(\n !this.raisedInitialEvent,\n 'Determining whether to raise first event but already had first event'\n );\n\n // Always raise the first event when we're synced\n if (!snap.fromCache) {\n return true;\n }\n\n // NOTE: We consider OnlineState.Unknown as online (it should become Offline\n // or Online if we wait long enough).\n const maybeOnline = onlineState !== OnlineState.Offline;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n if (this.options.waitForSyncWhenOnline && maybeOnline) {\n debugAssert(\n snap.fromCache,\n 'Waiting for sync, but snapshot is not from cache'\n );\n return false;\n }\n\n // Raise data from cache if we have any documents, have cached results before,\n // or we are offline.\n return (\n !snap.docs.isEmpty() ||\n snap.hasCachedResults ||\n onlineState === OnlineState.Offline\n );\n }\n\n private shouldRaiseEvent(snap: ViewSnapshot): boolean {\n // We don't need to handle includeDocumentMetadataChanges here because\n // the Metadata only changes have already been stripped out if needed.\n // At this point the only changes we will see are the ones we should\n // propagate.\n if (snap.docChanges.length > 0) {\n return true;\n }\n\n const hasPendingWritesChanged =\n this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites;\n if (snap.syncStateChanged || hasPendingWritesChanged) {\n return this.options.includeMetadataChanges === true;\n }\n\n // Generally we should have hit one of the cases above, but it's possible\n // to get here if there were only metadata docChanges and they got\n // stripped out.\n return false;\n }\n\n private raiseInitialEvent(snap: ViewSnapshot): void {\n debugAssert(\n !this.raisedInitialEvent,\n 'Trying to raise initial events for second time'\n );\n snap = ViewSnapshot.fromInitialDocuments(\n snap.query,\n snap.docs,\n snap.mutatedKeys,\n snap.fromCache,\n snap.hasCachedResults\n );\n this.raisedInitialEvent = true;\n this.queryObserver.next(snap);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryResult } from '../local/local_store_impl';\nimport {\n documentKeySet,\n DocumentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { TargetChange } from '../remote/remote_event';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { LimitType, newQueryComparator, Query, queryMatches } from './query';\nimport { OnlineState } from './types';\nimport {\n ChangeType,\n DocumentChangeSet,\n SyncState,\n ViewSnapshot\n} from './view_snapshot';\n\nexport type LimboDocumentChange = AddedLimboDocument | RemovedLimboDocument;\nexport class AddedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\nexport class RemovedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\n\n/** The result of applying a set of doc changes to a view. */\nexport interface ViewDocumentChanges {\n /** The new set of docs that should be in the view. */\n documentSet: DocumentSet;\n /** The diff of these docs with the previous set of docs. */\n changeSet: DocumentChangeSet;\n /**\n * Whether the set of documents passed in was not sufficient to calculate the\n * new state of the view and there needs to be another pass based on the\n * local cache.\n */\n needsRefill: boolean;\n\n mutatedKeys: DocumentKeySet;\n}\n\nexport interface ViewChange {\n snapshot?: ViewSnapshot;\n limboChanges: LimboDocumentChange[];\n}\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */\nexport class View {\n private syncState: SyncState | null = null;\n private hasCachedResults: boolean = false;\n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n private current = false;\n private documentSet: DocumentSet;\n /** Documents in the view but not in the remote target */\n private limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n private mutatedKeys = documentKeySet();\n /** Query comparator that defines the document order in this view. */\n private docComparator: (d1: Document, d2: Document) => number;\n\n constructor(\n private query: Query,\n /** Documents included in the remote target */\n private _syncedDocuments: DocumentKeySet\n ) {\n this.docComparator = newQueryComparator(query);\n this.documentSet = new DocumentSet(this.docComparator);\n }\n\n /**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */\n get syncedDocuments(): DocumentKeySet {\n return this._syncedDocuments;\n }\n\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges - The doc changes to apply to this view.\n * @param previousChanges - If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @returns a new set of docs, changes, and refill flag.\n */\n computeDocChanges(\n docChanges: DocumentMap,\n previousChanges?: ViewDocumentChanges\n ): ViewDocumentChanges {\n const changeSet = previousChanges\n ? previousChanges.changeSet\n : new DocumentChangeSet();\n const oldDocumentSet = previousChanges\n ? previousChanges.documentSet\n : this.documentSet;\n let newMutatedKeys = previousChanges\n ? previousChanges.mutatedKeys\n : this.mutatedKeys;\n let newDocumentSet = oldDocumentSet;\n let needsRefill = false;\n\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n //\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n const lastDocInLimit =\n this.query.limitType === LimitType.First &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n const firstDocInLimit =\n this.query.limitType === LimitType.Last &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.first()\n : null;\n\n docChanges.inorderTraversal((key, entry) => {\n const oldDoc = oldDocumentSet.get(key);\n const newDoc = queryMatches(this.query, entry) ? entry : null;\n\n const oldDocHadPendingMutations = oldDoc\n ? this.mutatedKeys.has(oldDoc.key)\n : false;\n const newDocHasPendingMutations = newDoc\n ? newDoc.hasLocalMutations ||\n // We only consider committed mutations for documents that were\n // mutated during the lifetime of the view.\n (this.mutatedKeys.has(newDoc.key) && newDoc.hasCommittedMutations)\n : false;\n\n let changeApplied = false;\n\n // Calculate change\n if (oldDoc && newDoc) {\n const docsEqual = oldDoc.data.isEqual(newDoc.data);\n if (!docsEqual) {\n if (!this.shouldWaitForSyncedDocument(oldDoc, newDoc)) {\n changeSet.track({\n type: ChangeType.Modified,\n doc: newDoc\n });\n changeApplied = true;\n\n if (\n (lastDocInLimit &&\n this.docComparator(newDoc, lastDocInLimit) > 0) ||\n (firstDocInLimit &&\n this.docComparator(newDoc, firstDocInLimit) < 0)\n ) {\n // This doc moved from inside the limit to outside the limit.\n // That means there may be some other doc in the local cache\n // that should be included instead.\n needsRefill = true;\n }\n }\n } else if (oldDocHadPendingMutations !== newDocHasPendingMutations) {\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\n changeApplied = true;\n }\n } else if (!oldDoc && newDoc) {\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\n changeApplied = true;\n } else if (oldDoc && !newDoc) {\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n changeApplied = true;\n\n if (lastDocInLimit || firstDocInLimit) {\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n needsRefill = true;\n }\n }\n\n if (changeApplied) {\n if (newDoc) {\n newDocumentSet = newDocumentSet.add(newDoc);\n if (newDocHasPendingMutations) {\n newMutatedKeys = newMutatedKeys.add(key);\n } else {\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n } else {\n newDocumentSet = newDocumentSet.delete(key);\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n }\n });\n\n // Drop documents out to meet limit/limitToLast requirement.\n if (this.query.limit !== null) {\n while (newDocumentSet.size > this.query.limit!) {\n const oldDoc =\n this.query.limitType === LimitType.First\n ? newDocumentSet.last()\n : newDocumentSet.first();\n newDocumentSet = newDocumentSet.delete(oldDoc!.key);\n newMutatedKeys = newMutatedKeys.delete(oldDoc!.key);\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc! });\n }\n }\n\n debugAssert(\n !needsRefill || !previousChanges,\n 'View was refilled using docs that themselves needed refilling.'\n );\n return {\n documentSet: newDocumentSet,\n changeSet,\n needsRefill,\n mutatedKeys: newMutatedKeys\n };\n }\n\n private shouldWaitForSyncedDocument(\n oldDoc: Document,\n newDoc: Document\n ): boolean {\n // We suppress the initial change event for documents that were modified as\n // part of a write acknowledgment (e.g. when the value of a server transform\n // is applied) as Watch will send us the same document again.\n // By suppressing the event, we only raise two user visible events (one with\n // `hasPendingWrites` and the final state of the document) instead of three\n // (one with `hasPendingWrites`, the modified document with\n // `hasPendingWrites` and the final state of the document).\n return (\n oldDoc.hasLocalMutations &&\n newDoc.hasCommittedMutations &&\n !newDoc.hasLocalMutations\n );\n }\n\n /**\n * Updates the view with the given ViewDocumentChanges and optionally updates\n * limbo docs and sync state from the provided target change.\n * @param docChanges - The set of changes to make to the view's docs.\n * @param updateLimboDocuments - Whether to update limbo documents based on\n * this change.\n * @param targetChange - A target change to apply for computing limbo docs and\n * sync state.\n * @returns A new ViewChange with the given docs, changes, and sync state.\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n applyChanges(\n docChanges: ViewDocumentChanges,\n updateLimboDocuments: boolean,\n targetChange?: TargetChange\n ): ViewChange {\n debugAssert(\n !docChanges.needsRefill,\n 'Cannot apply changes that need a refill'\n );\n const oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys;\n // Sort changes based on type and query comparator\n const changes = docChanges.changeSet.getChanges();\n changes.sort((c1, c2) => {\n return (\n compareChangeType(c1.type, c2.type) ||\n this.docComparator(c1.doc, c2.doc)\n );\n });\n\n this.applyTargetChange(targetChange);\n const limboChanges = updateLimboDocuments\n ? this.updateLimboDocuments()\n : [];\n const synced = this.limboDocuments.size === 0 && this.current;\n const newSyncState = synced ? SyncState.Synced : SyncState.Local;\n const syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return { limboChanges };\n } else {\n const snap: ViewSnapshot = new ViewSnapshot(\n this.query,\n docChanges.documentSet,\n oldDocs,\n changes,\n docChanges.mutatedKeys,\n newSyncState === SyncState.Local,\n syncStateChanged,\n /* excludesMetadataChanges= */ false,\n targetChange\n ? targetChange.resumeToken.approximateByteSize() > 0\n : false\n );\n return {\n snapshot: snap,\n limboChanges\n };\n }\n }\n\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */\n applyOnlineStateChange(onlineState: OnlineState): ViewChange {\n if (this.current && onlineState === OnlineState.Offline) {\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = false;\n return this.applyChanges(\n {\n documentSet: this.documentSet,\n changeSet: new DocumentChangeSet(),\n mutatedKeys: this.mutatedKeys,\n needsRefill: false\n },\n /* updateLimboDocuments= */ false\n );\n } else {\n // No effect, just return a no-op ViewChange.\n return { limboChanges: [] };\n }\n }\n\n /**\n * Returns whether the doc for the given key should be in limbo.\n */\n private shouldBeInLimbo(key: DocumentKey): boolean {\n // If the remote end says it's part of this query, it's not in limbo.\n if (this._syncedDocuments.has(key)) {\n return false;\n }\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n if (!this.documentSet.has(key)) {\n return false;\n }\n // If there are local changes to the doc, they might explain why the server\n // doesn't know that it's part of the query. So don't put it in limbo.\n // TODO(klimt): Ideally, we would only consider changes that might actually\n // affect this specific query.\n if (this.documentSet.get(key)!.hasLocalMutations) {\n return false;\n }\n // Everything else is in limbo.\n return true;\n }\n\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */\n private applyTargetChange(targetChange?: TargetChange): void {\n if (targetChange) {\n targetChange.addedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.add(key))\n );\n targetChange.modifiedDocuments.forEach(key => {\n debugAssert(\n this._syncedDocuments.has(key),\n `Modified document ${key} not found in view.`\n );\n });\n targetChange.removedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.delete(key))\n );\n this.current = targetChange.current;\n }\n }\n\n private updateLimboDocuments(): LimboDocumentChange[] {\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) {\n return [];\n }\n\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n const oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n this.documentSet.forEach(doc => {\n if (this.shouldBeInLimbo(doc.key)) {\n this.limboDocuments = this.limboDocuments.add(doc.key);\n }\n });\n\n // Diff the new limbo docs with the old limbo docs.\n const changes: LimboDocumentChange[] = [];\n oldLimboDocuments.forEach(key => {\n if (!this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(key => {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n }\n\n /**\n * Update the in-memory state of the current view with the state read from\n * persistence.\n *\n * We update the query view whenever a client's primary status changes:\n * - When a client transitions from primary to secondary, it can miss\n * LocalStorage updates and its query views may temporarily not be\n * synchronized with the state on disk.\n * - For secondary to primary transitions, the client needs to update the list\n * of `syncedDocuments` since secondary clients update their query views\n * based purely on synthesized RemoteEvents.\n *\n * @param queryResult.documents - The documents that match the query according\n * to the LocalStore.\n * @param queryResult.remoteKeys - The keys of the documents that match the\n * query according to the backend.\n *\n * @returns The ViewChange that resulted from this synchronization.\n */\n // PORTING NOTE: Multi-tab only.\n synchronizeWithPersistedState(queryResult: QueryResult): ViewChange {\n this._syncedDocuments = queryResult.remoteKeys;\n this.limboDocuments = documentKeySet();\n const docChanges = this.computeDocChanges(queryResult.documents);\n return this.applyChanges(docChanges, /*updateLimboDocuments=*/ true);\n }\n\n /**\n * Returns a view snapshot as if this query was just listened to. Contains\n * a document add for every existing document and the `fromCache` and\n * `hasPendingWrites` status of the already established view.\n */\n // PORTING NOTE: Multi-tab only.\n computeInitialSnapshot(): ViewSnapshot {\n return ViewSnapshot.fromInitialDocuments(\n this.query,\n this.documentSet,\n this.mutatedKeys,\n this.syncState === SyncState.Local,\n this.hasCachedResults\n );\n }\n}\n\nfunction compareChangeType(c1: ChangeType, c2: ChangeType): number {\n const order = (change: ChangeType): 0 | 1 | 2 => {\n switch (change) {\n case ChangeType.Added:\n return 1;\n case ChangeType.Modified:\n return 2;\n case ChangeType.Metadata:\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n case ChangeType.Removed:\n return 0;\n default:\n return fail('Unknown ChangeType: ' + change);\n }\n };\n\n return order(c1) - order(c2);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LoadBundleTask } from '../api/bundle';\nimport { User } from '../auth/user';\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from '../local/local_store';\nimport {\n localStoreAcknowledgeBatch,\n localStoreAllocateTarget,\n localStoreApplyRemoteEventToLocalCache,\n localStoreExecuteQuery,\n localStoreGetActiveClients,\n localStoreGetCachedTarget,\n localStoreGetHighestUnacknowledgedBatchId,\n localStoreGetNewDocumentChanges,\n localStoreHandleUserChange,\n localStoreHasNewerBundle,\n localStoreLookupMutationDocuments,\n localStoreNotifyLocalViewChanges,\n localStoreRejectBatch,\n localStoreReleaseTarget,\n localStoreRemoveCachedMutationBatchMetadata,\n localStoreSaveBundle,\n localStoreWriteLocally\n} from '../local/local_store_impl';\nimport { LocalViewChanges } from '../local/local_view_changes';\nimport { ReferenceSet } from '../local/reference_set';\nimport { ClientId, SharedClientState } from '../local/shared_client_state';\nimport { QueryTargetState } from '../local/shared_client_state_syncer';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport {\n DocumentKeySet,\n documentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatchResult } from '../model/mutation_batch';\nimport { ResourcePath } from '../model/path';\nimport { RemoteEvent, TargetChange } from '../remote/remote_event';\nimport {\n canUseNetwork,\n fillWritePipeline,\n RemoteStore,\n remoteStoreApplyPrimaryState,\n remoteStoreListen,\n remoteStoreUnlisten\n} from '../remote/remote_store';\nimport { debugAssert, debugCast, fail, hardAssert } from '../util/assert';\nimport { wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { BundleReader } from '../util/bundle_reader';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { Deferred } from '../util/promise';\nimport { SortedMap } from '../util/sorted_map';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport {\n bundleInitialProgress,\n BundleLoader,\n bundleSuccessProgress\n} from './bundle_impl';\nimport {\n EventManager,\n eventManagerOnOnlineStateChange,\n eventManagerOnWatchChange,\n eventManagerOnWatchError\n} from './event_manager';\nimport { ListenSequence } from './listen_sequence';\nimport {\n canonifyQuery,\n LimitType,\n newQuery,\n newQueryForPath,\n Query,\n queryEquals,\n queryCollectionGroup,\n queryToTarget,\n stringifyQuery\n} from './query';\nimport { SnapshotVersion } from './snapshot_version';\nimport { SyncEngine } from './sync_engine';\nimport { Target } from './target';\nimport { TargetIdGenerator } from './target_id_generator';\nimport {\n BatchId,\n MutationBatchState,\n OnlineState,\n OnlineStateSource,\n TargetId\n} from './types';\nimport {\n AddedLimboDocument,\n LimboDocumentChange,\n RemovedLimboDocument,\n View,\n ViewChange\n} from './view';\nimport { ViewSnapshot } from './view_snapshot';\n\nconst LOG_TAG = 'SyncEngine';\n\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nclass QueryView {\n constructor(\n /**\n * The query itself.\n */\n public query: Query,\n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n public targetId: TargetId,\n /**\n * The view is responsible for computing the final merged truth of what\n * docs are in the query. It gets notified of local and remote changes,\n * and applies the query filters and limits to determine the most correct\n * possible results.\n */\n public view: View\n ) {}\n}\n\n/** Tracks a limbo resolution. */\nclass LimboResolution {\n constructor(public key: DocumentKey) {}\n\n /**\n * Set to true once we've received a document. This is used in\n * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to\n * decide whether it needs to manufacture a delete event for the target once\n * the target is CURRENT.\n */\n receivedDocument: boolean = false;\n}\n\n/**\n * A function that updates a QueryView with a set of document changes (and a\n * remote event if applicable).\n */\ntype ApplyDocChangesHandler = (\n queryView: QueryView,\n changes: DocumentMap,\n remoteEvent?: RemoteEvent\n) => Promise<ViewSnapshot | undefined>;\n\n/**\n * Callbacks implemented by EventManager to handle notifications from\n * SyncEngine.\n */\ninterface SyncEngineListener {\n /** Handles new view snapshots. */\n onWatchChange?(snapshots: ViewSnapshot[]): void;\n\n /** Handles the failure of a query. */\n onWatchError?(query: Query, error: FirestoreError): void;\n}\n\n/**\n * An implementation of `SyncEngine` coordinating with other parts of SDK.\n *\n * The parts of SyncEngine that act as a callback to RemoteStore need to be\n * registered individually. This is done in `syncEngineWrite()` and\n * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods\n * serve as entry points to RemoteStore's functionality.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass SyncEngineImpl implements SyncEngine {\n syncEngineListener: SyncEngineListener = {};\n\n /**\n * A callback that updates the QueryView based on the provided change.\n *\n * PORTING NOTE: On other platforms, this logic lives in\n * `emitNewSnapshotsAndNotifyLocalStore()`, but on Web it is extracted to\n * ensure that all view logic only exists in bundles that include views.\n */\n applyDocChanges?: ApplyDocChangesHandler;\n\n queryViewsByQuery = new ObjectMap<Query, QueryView>(\n q => canonifyQuery(q),\n queryEquals\n );\n queriesByTarget = new Map<TargetId, Query[]>();\n /**\n * The keys of documents that are in limbo for which we haven't yet started a\n * limbo resolution query. The strings in this set are the result of calling\n * `key.path.canonicalString()` where `key` is a `DocumentKey` object.\n *\n * The `Set` type was chosen because it provides efficient lookup and removal\n * of arbitrary elements and it also maintains insertion order, providing the\n * desired queue-like FIFO semantics.\n */\n enqueuedLimboResolutions = new Set<string>();\n /**\n * Keeps track of the target ID for each document that is in limbo with an\n * active target.\n */\n activeLimboTargetsByKey = new SortedMap<DocumentKey, TargetId>(\n DocumentKey.comparator\n );\n /**\n * Keeps track of the information about an active limbo resolution for each\n * active target ID that was started for the purpose of limbo resolution.\n */\n activeLimboResolutionsByTarget = new Map<TargetId, LimboResolution>();\n limboDocumentRefs = new ReferenceSet();\n /** Stores user completion handlers, indexed by User and BatchId. */\n mutationUserCallbacks = {} as {\n [uidKey: string]: SortedMap<BatchId, Deferred<void>>;\n };\n /** Stores user callbacks waiting for all pending writes to be acknowledged. */\n pendingWritesCallbacks = new Map<BatchId, Array<Deferred<void>>>();\n limboTargetIdGenerator = TargetIdGenerator.forSyncEngine();\n\n onlineState = OnlineState.Unknown;\n\n // The primary state is set to `true` or `false` immediately after Firestore\n // startup. In the interim, a client should only be considered primary if\n // `isPrimary` is true.\n _isPrimaryClient: undefined | boolean = undefined;\n\n constructor(\n readonly localStore: LocalStore,\n readonly remoteStore: RemoteStore,\n readonly eventManager: EventManager,\n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n readonly sharedClientState: SharedClientState,\n public currentUser: User,\n readonly maxConcurrentLimboResolutions: number\n ) {}\n\n get isPrimaryClient(): boolean {\n return this._isPrimaryClient === true;\n }\n}\n\nexport function newSyncEngine(\n localStore: LocalStore,\n remoteStore: RemoteStore,\n eventManager: EventManager,\n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n sharedClientState: SharedClientState,\n currentUser: User,\n maxConcurrentLimboResolutions: number,\n isPrimary: boolean\n): SyncEngine {\n const syncEngine = new SyncEngineImpl(\n localStore,\n remoteStore,\n eventManager,\n sharedClientState,\n currentUser,\n maxConcurrentLimboResolutions\n );\n if (isPrimary) {\n syncEngine._isPrimaryClient = true;\n }\n return syncEngine;\n}\n\n/**\n * Initiates the new listen, resolves promise when listen enqueued to the\n * server. All the subsequent view snapshots or errors are sent to the\n * subscribed handlers. Returns the initial snapshot.\n */\nexport async function syncEngineListen(\n syncEngine: SyncEngine,\n query: Query\n): Promise<ViewSnapshot> {\n const syncEngineImpl = ensureWatchCallbacks(syncEngine);\n\n let targetId;\n let viewSnapshot;\n\n const queryView = syncEngineImpl.queryViewsByQuery.get(query);\n if (queryView) {\n // PORTING NOTE: With Multi-Tab Web, it is possible that a query view\n // already exists when EventManager calls us for the first time. This\n // happens when the primary tab is already listening to this query on\n // behalf of another tab and the user of the primary also starts listening\n // to the query. EventManager will not have an assigned target ID in this\n // case and calls `listen` to obtain this ID.\n targetId = queryView.targetId;\n syncEngineImpl.sharedClientState.addLocalQueryTarget(targetId);\n viewSnapshot = queryView.view.computeInitialSnapshot();\n } else {\n const targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n queryToTarget(query)\n );\n\n const status = syncEngineImpl.sharedClientState.addLocalQueryTarget(\n targetData.targetId\n );\n targetId = targetData.targetId;\n viewSnapshot = await initializeViewAndComputeSnapshot(\n syncEngineImpl,\n query,\n targetId,\n status === 'current',\n targetData.resumeToken\n );\n\n if (syncEngineImpl.isPrimaryClient) {\n remoteStoreListen(syncEngineImpl.remoteStore, targetData);\n }\n }\n\n return viewSnapshot;\n}\n\n/**\n * Registers a view for a previously unknown query and computes its initial\n * snapshot.\n */\nasync function initializeViewAndComputeSnapshot(\n syncEngineImpl: SyncEngineImpl,\n query: Query,\n targetId: TargetId,\n current: boolean,\n resumeToken: ByteString\n): Promise<ViewSnapshot> {\n // PORTING NOTE: On Web only, we inject the code that registers new Limbo\n // targets based on view changes. This allows us to only depend on Limbo\n // changes when user code includes queries.\n syncEngineImpl.applyDocChanges = (queryView, changes, remoteEvent) =>\n applyDocChanges(syncEngineImpl, queryView, changes, remoteEvent);\n\n const queryResult = await localStoreExecuteQuery(\n syncEngineImpl.localStore,\n query,\n /* usePreviousResults= */ true\n );\n const view = new View(query, queryResult.remoteKeys);\n const viewDocChanges = view.computeDocChanges(queryResult.documents);\n const synthesizedTargetChange =\n TargetChange.createSynthesizedTargetChangeForCurrentChange(\n targetId,\n current && syncEngineImpl.onlineState !== OnlineState.Offline,\n resumeToken\n );\n const viewChange = view.applyChanges(\n viewDocChanges,\n /* updateLimboDocuments= */ syncEngineImpl.isPrimaryClient,\n synthesizedTargetChange\n );\n updateTrackedLimbos(syncEngineImpl, targetId, viewChange.limboChanges);\n\n debugAssert(\n !!viewChange.snapshot,\n 'applyChanges for new view should always return a snapshot'\n );\n\n const data = new QueryView(query, targetId, view);\n\n syncEngineImpl.queryViewsByQuery.set(query, data);\n if (syncEngineImpl.queriesByTarget.has(targetId)) {\n syncEngineImpl.queriesByTarget.get(targetId)!.push(query);\n } else {\n syncEngineImpl.queriesByTarget.set(targetId, [query]);\n }\n\n return viewChange.snapshot;\n}\n\n/** Stops listening to the query. */\nexport async function syncEngineUnlisten(\n syncEngine: SyncEngine,\n query: Query\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const queryView = syncEngineImpl.queryViewsByQuery.get(query)!;\n debugAssert(\n !!queryView,\n 'Trying to unlisten on query not found:' + stringifyQuery(query)\n );\n\n // Only clean up the query view and target if this is the only query mapped\n // to the target.\n const queries = syncEngineImpl.queriesByTarget.get(queryView.targetId)!;\n if (queries.length > 1) {\n syncEngineImpl.queriesByTarget.set(\n queryView.targetId,\n queries.filter(q => !queryEquals(q, query))\n );\n syncEngineImpl.queryViewsByQuery.delete(query);\n return;\n }\n\n // No other queries are mapped to the target, clean up the query and the target.\n if (syncEngineImpl.isPrimaryClient) {\n // We need to remove the local query target first to allow us to verify\n // whether any other client is still interested in this target.\n syncEngineImpl.sharedClientState.removeLocalQueryTarget(queryView.targetId);\n const targetRemainsActive =\n syncEngineImpl.sharedClientState.isActiveQueryTarget(queryView.targetId);\n\n if (!targetRemainsActive) {\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n queryView.targetId,\n /*keepPersistedTargetData=*/ false\n )\n .then(() => {\n syncEngineImpl.sharedClientState.clearQueryState(queryView.targetId);\n remoteStoreUnlisten(syncEngineImpl.remoteStore, queryView.targetId);\n removeAndCleanupTarget(syncEngineImpl, queryView.targetId);\n })\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n } else {\n removeAndCleanupTarget(syncEngineImpl, queryView.targetId);\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n queryView.targetId,\n /*keepPersistedTargetData=*/ true\n );\n }\n}\n\n/**\n * Initiates the write of local mutation batch which involves adding the\n * writes to the mutation queue, notifying the remote store about new\n * mutations and raising events for any changes this write caused.\n *\n * The promise returned by this call is resolved when the above steps\n * have completed, *not* when the write was acked by the backend. The\n * userCallback is resolved once the write was acked/rejected by the\n * backend (or failed locally for any other reason).\n */\nexport async function syncEngineWrite(\n syncEngine: SyncEngine,\n batch: Mutation[],\n userCallback: Deferred<void>\n): Promise<void> {\n const syncEngineImpl = syncEngineEnsureWriteCallbacks(syncEngine);\n\n try {\n const result = await localStoreWriteLocally(\n syncEngineImpl.localStore,\n batch\n );\n syncEngineImpl.sharedClientState.addPendingMutation(result.batchId);\n addMutationCallback(syncEngineImpl, result.batchId, userCallback);\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n result.changes\n );\n await fillWritePipeline(syncEngineImpl.remoteStore);\n } catch (e) {\n // If we can't persist the mutation, we reject the user callback and\n // don't send the mutation. The user can then retry the write.\n const error = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to persist write`\n );\n userCallback.reject(error);\n }\n}\n\n/**\n * Applies one remote event to the sync engine, notifying any views of the\n * changes, and releasing any pending mutation batches that would become\n * visible because of the snapshot version the remote event contains.\n */\nexport async function syncEngineApplyRemoteEvent(\n syncEngine: SyncEngine,\n remoteEvent: RemoteEvent\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n try {\n const changes = await localStoreApplyRemoteEventToLocalCache(\n syncEngineImpl.localStore,\n remoteEvent\n );\n // Update `receivedDocument` as appropriate for any limbo targets.\n remoteEvent.targetChanges.forEach((targetChange, targetId) => {\n const limboResolution =\n syncEngineImpl.activeLimboResolutionsByTarget.get(targetId);\n if (limboResolution) {\n // Since this is a limbo resolution lookup, it's for a single document\n // and it could be added, modified, or removed, but not a combination.\n hardAssert(\n targetChange.addedDocuments.size +\n targetChange.modifiedDocuments.size +\n targetChange.removedDocuments.size <=\n 1,\n 'Limbo resolution for single document contains multiple changes.'\n );\n if (targetChange.addedDocuments.size > 0) {\n limboResolution.receivedDocument = true;\n } else if (targetChange.modifiedDocuments.size > 0) {\n hardAssert(\n limboResolution.receivedDocument,\n 'Received change for limbo target document without add.'\n );\n } else if (targetChange.removedDocuments.size > 0) {\n hardAssert(\n limboResolution.receivedDocument,\n 'Received remove for limbo target document without add.'\n );\n limboResolution.receivedDocument = false;\n } else {\n // This was probably just a CURRENT targetChange or similar.\n }\n }\n });\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n changes,\n remoteEvent\n );\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error as FirestoreError);\n }\n}\n\n/**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */\nexport function syncEngineApplyOnlineStateChange(\n syncEngine: SyncEngine,\n onlineState: OnlineState,\n source: OnlineStateSource\n): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n // If we are the secondary client, we explicitly ignore the remote store's\n // online state (the local client may go offline, even though the primary\n // tab remains online) and only apply the primary tab's online state from\n // SharedClientState.\n if (\n (syncEngineImpl.isPrimaryClient &&\n source === OnlineStateSource.RemoteStore) ||\n (!syncEngineImpl.isPrimaryClient &&\n source === OnlineStateSource.SharedClientState)\n ) {\n const newViewSnapshots = [] as ViewSnapshot[];\n syncEngineImpl.queryViewsByQuery.forEach((query, queryView) => {\n const viewChange = queryView.view.applyOnlineStateChange(onlineState);\n debugAssert(\n viewChange.limboChanges.length === 0,\n 'OnlineState should not affect limbo documents.'\n );\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n });\n\n eventManagerOnOnlineStateChange(syncEngineImpl.eventManager, onlineState);\n\n if (newViewSnapshots.length) {\n debugAssert(\n !!syncEngineImpl.syncEngineListener.onWatchChange,\n 'Active views but EventManager callbacks are not assigned'\n );\n syncEngineImpl.syncEngineListener.onWatchChange(newViewSnapshots);\n }\n\n syncEngineImpl.onlineState = onlineState;\n if (syncEngineImpl.isPrimaryClient) {\n syncEngineImpl.sharedClientState.setOnlineState(onlineState);\n }\n }\n}\n\n/**\n * Rejects the listen for the given targetID. This can be triggered by the\n * backend for any active target.\n *\n * @param syncEngine - The sync engine implementation.\n * @param targetId - The targetID corresponds to one previously initiated by the\n * user as part of TargetData passed to listen() on RemoteStore.\n * @param err - A description of the condition that has forced the rejection.\n * Nearly always this will be an indication that the user is no longer\n * authorized to see the data matching the target.\n */\nexport async function syncEngineRejectListen(\n syncEngine: SyncEngine,\n targetId: TargetId,\n err: FirestoreError\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n // PORTING NOTE: Multi-tab only.\n syncEngineImpl.sharedClientState.updateQueryState(targetId, 'rejected', err);\n\n const limboResolution =\n syncEngineImpl.activeLimboResolutionsByTarget.get(targetId);\n const limboKey = limboResolution && limboResolution.key;\n if (limboKey) {\n // TODO(klimt): We really only should do the following on permission\n // denied errors, but we don't have the cause code here.\n\n // It's a limbo doc. Create a synthetic event saying it was deleted.\n // This is kind of a hack. Ideally, we would have a method in the local\n // store to purge a document. However, it would be tricky to keep all of\n // the local store's invariants with another method.\n let documentUpdates = new SortedMap<DocumentKey, MutableDocument>(\n DocumentKey.comparator\n );\n // TODO(b/217189216): This limbo document should ideally have a read time,\n // so that it is picked up by any read-time based scans. The backend,\n // however, does not send a read time for target removals.\n documentUpdates = documentUpdates.insert(\n limboKey,\n MutableDocument.newNoDocument(limboKey, SnapshotVersion.min())\n );\n const resolvedLimboDocuments = documentKeySet().add(limboKey);\n const event = new RemoteEvent(\n SnapshotVersion.min(),\n /* targetChanges= */ new Map<TargetId, TargetChange>(),\n /* targetMismatches= */ new SortedMap<TargetId, TargetPurpose>(\n primitiveComparator\n ),\n documentUpdates,\n resolvedLimboDocuments\n );\n\n await syncEngineApplyRemoteEvent(syncEngineImpl, event);\n\n // Since this query failed, we won't want to manually unlisten to it.\n // We only remove it from bookkeeping after we successfully applied the\n // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to\n // this query when the RemoteStore restarts the Watch stream, which should\n // re-trigger the target failure.\n syncEngineImpl.activeLimboTargetsByKey =\n syncEngineImpl.activeLimboTargetsByKey.remove(limboKey);\n syncEngineImpl.activeLimboResolutionsByTarget.delete(targetId);\n pumpEnqueuedLimboResolutions(syncEngineImpl);\n } else {\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /* keepPersistedTargetData */ false\n )\n .then(() => removeAndCleanupTarget(syncEngineImpl, targetId, err))\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n}\n\nexport async function syncEngineApplySuccessfulWrite(\n syncEngine: SyncEngine,\n mutationBatchResult: MutationBatchResult\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const batchId = mutationBatchResult.batch.batchId;\n\n try {\n const changes = await localStoreAcknowledgeBatch(\n syncEngineImpl.localStore,\n mutationBatchResult\n );\n\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught\n // up), so we raise user callbacks first so that they consistently happen\n // before listen events.\n processUserCallback(syncEngineImpl, batchId, /*error=*/ null);\n triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n\n syncEngineImpl.sharedClientState.updateMutationState(\n batchId,\n 'acknowledged'\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes);\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error as FirestoreError);\n }\n}\n\nexport async function syncEngineRejectFailedWrite(\n syncEngine: SyncEngine,\n batchId: BatchId,\n error: FirestoreError\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n try {\n const changes = await localStoreRejectBatch(\n syncEngineImpl.localStore,\n batchId\n );\n\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught up),\n // so we raise user callbacks first so that they consistently happen before\n // listen events.\n processUserCallback(syncEngineImpl, batchId, error);\n triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n\n syncEngineImpl.sharedClientState.updateMutationState(\n batchId,\n 'rejected',\n error\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes);\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error as FirestoreError);\n }\n}\n\n/**\n * Registers a user callback that resolves when all pending mutations at the moment of calling\n * are acknowledged .\n */\nexport async function syncEngineRegisterPendingWritesCallback(\n syncEngine: SyncEngine,\n callback: Deferred<void>\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n if (!canUseNetwork(syncEngineImpl.remoteStore)) {\n logDebug(\n LOG_TAG,\n 'The network is disabled. The task returned by ' +\n \"'awaitPendingWrites()' will not complete until the network is enabled.\"\n );\n }\n\n try {\n const highestBatchId = await localStoreGetHighestUnacknowledgedBatchId(\n syncEngineImpl.localStore\n );\n if (highestBatchId === BATCHID_UNKNOWN) {\n // Trigger the callback right away if there is no pending writes at the moment.\n callback.resolve();\n return;\n }\n\n const callbacks =\n syncEngineImpl.pendingWritesCallbacks.get(highestBatchId) || [];\n callbacks.push(callback);\n syncEngineImpl.pendingWritesCallbacks.set(highestBatchId, callbacks);\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n 'Initialization of waitForPendingWrites() operation failed'\n );\n callback.reject(firestoreError);\n }\n}\n\n/**\n * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,\n * if there are any.\n */\nfunction triggerPendingWritesCallbacks(\n syncEngineImpl: SyncEngineImpl,\n batchId: BatchId\n): void {\n (syncEngineImpl.pendingWritesCallbacks.get(batchId) || []).forEach(\n callback => {\n callback.resolve();\n }\n );\n\n syncEngineImpl.pendingWritesCallbacks.delete(batchId);\n}\n\n/** Reject all outstanding callbacks waiting for pending writes to complete. */\nfunction rejectOutstandingPendingWritesCallbacks(\n syncEngineImpl: SyncEngineImpl,\n errorMessage: string\n): void {\n syncEngineImpl.pendingWritesCallbacks.forEach(callbacks => {\n callbacks.forEach(callback => {\n callback.reject(new FirestoreError(Code.CANCELLED, errorMessage));\n });\n });\n\n syncEngineImpl.pendingWritesCallbacks.clear();\n}\n\nfunction addMutationCallback(\n syncEngineImpl: SyncEngineImpl,\n batchId: BatchId,\n callback: Deferred<void>\n): void {\n let newCallbacks =\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()];\n if (!newCallbacks) {\n newCallbacks = new SortedMap<BatchId, Deferred<void>>(primitiveComparator);\n }\n newCallbacks = newCallbacks.insert(batchId, callback);\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()] =\n newCallbacks;\n}\n\n/**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */\nfunction processUserCallback(\n syncEngine: SyncEngine,\n batchId: BatchId,\n error: FirestoreError | null\n): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n let newCallbacks =\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()];\n\n // NOTE: Mutations restored from persistence won't have callbacks, so it's\n // okay for there to be no callback for this ID.\n if (newCallbacks) {\n const callback = newCallbacks.get(batchId);\n if (callback) {\n debugAssert(\n batchId === newCallbacks.minKey(),\n 'Mutation callbacks processed out-of-order?'\n );\n if (error) {\n callback.reject(error);\n } else {\n callback.resolve();\n }\n newCallbacks = newCallbacks.remove(batchId);\n }\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()] =\n newCallbacks;\n }\n}\n\nfunction removeAndCleanupTarget(\n syncEngineImpl: SyncEngineImpl,\n targetId: number,\n error: FirestoreError | null = null\n): void {\n syncEngineImpl.sharedClientState.removeLocalQueryTarget(targetId);\n\n debugAssert(\n syncEngineImpl.queriesByTarget.has(targetId) &&\n syncEngineImpl.queriesByTarget.get(targetId)!.length !== 0,\n `There are no queries mapped to target id ${targetId}`\n );\n\n for (const query of syncEngineImpl.queriesByTarget.get(targetId)!) {\n syncEngineImpl.queryViewsByQuery.delete(query);\n if (error) {\n syncEngineImpl.syncEngineListener.onWatchError!(query, error);\n }\n }\n\n syncEngineImpl.queriesByTarget.delete(targetId);\n\n if (syncEngineImpl.isPrimaryClient) {\n const limboKeys =\n syncEngineImpl.limboDocumentRefs.removeReferencesForId(targetId);\n limboKeys.forEach(limboKey => {\n const isReferenced =\n syncEngineImpl.limboDocumentRefs.containsKey(limboKey);\n if (!isReferenced) {\n // We removed the last reference for this key\n removeLimboTarget(syncEngineImpl, limboKey);\n }\n });\n }\n}\n\nfunction removeLimboTarget(\n syncEngineImpl: SyncEngineImpl,\n key: DocumentKey\n): void {\n syncEngineImpl.enqueuedLimboResolutions.delete(key.path.canonicalString());\n\n // It's possible that the target already got removed because the query failed. In that case,\n // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.\n const limboTargetId = syncEngineImpl.activeLimboTargetsByKey.get(key);\n if (limboTargetId === null) {\n // This target already got removed, because the query failed.\n return;\n }\n\n remoteStoreUnlisten(syncEngineImpl.remoteStore, limboTargetId);\n syncEngineImpl.activeLimboTargetsByKey =\n syncEngineImpl.activeLimboTargetsByKey.remove(key);\n syncEngineImpl.activeLimboResolutionsByTarget.delete(limboTargetId);\n pumpEnqueuedLimboResolutions(syncEngineImpl);\n}\n\nfunction updateTrackedLimbos(\n syncEngineImpl: SyncEngineImpl,\n targetId: TargetId,\n limboChanges: LimboDocumentChange[]\n): void {\n for (const limboChange of limboChanges) {\n if (limboChange instanceof AddedLimboDocument) {\n syncEngineImpl.limboDocumentRefs.addReference(limboChange.key, targetId);\n trackLimboChange(syncEngineImpl, limboChange);\n } else if (limboChange instanceof RemovedLimboDocument) {\n logDebug(LOG_TAG, 'Document no longer in limbo: ' + limboChange.key);\n syncEngineImpl.limboDocumentRefs.removeReference(\n limboChange.key,\n targetId\n );\n const isReferenced = syncEngineImpl.limboDocumentRefs.containsKey(\n limboChange.key\n );\n if (!isReferenced) {\n // We removed the last reference for this key\n removeLimboTarget(syncEngineImpl, limboChange.key);\n }\n } else {\n fail('Unknown limbo change: ' + JSON.stringify(limboChange));\n }\n }\n}\n\nfunction trackLimboChange(\n syncEngineImpl: SyncEngineImpl,\n limboChange: AddedLimboDocument\n): void {\n const key = limboChange.key;\n const keyString = key.path.canonicalString();\n if (\n !syncEngineImpl.activeLimboTargetsByKey.get(key) &&\n !syncEngineImpl.enqueuedLimboResolutions.has(keyString)\n ) {\n logDebug(LOG_TAG, 'New document in limbo: ' + key);\n syncEngineImpl.enqueuedLimboResolutions.add(keyString);\n pumpEnqueuedLimboResolutions(syncEngineImpl);\n }\n}\n\n/**\n * Starts listens for documents in limbo that are enqueued for resolution,\n * subject to a maximum number of concurrent resolutions.\n *\n * Without bounding the number of concurrent resolutions, the server can fail\n * with \"resource exhausted\" errors which can lead to pathological client\n * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.\n */\nfunction pumpEnqueuedLimboResolutions(syncEngineImpl: SyncEngineImpl): void {\n while (\n syncEngineImpl.enqueuedLimboResolutions.size > 0 &&\n syncEngineImpl.activeLimboTargetsByKey.size <\n syncEngineImpl.maxConcurrentLimboResolutions\n ) {\n const keyString = syncEngineImpl.enqueuedLimboResolutions\n .values()\n .next().value;\n syncEngineImpl.enqueuedLimboResolutions.delete(keyString);\n const key = new DocumentKey(ResourcePath.fromString(keyString));\n const limboTargetId = syncEngineImpl.limboTargetIdGenerator.next();\n syncEngineImpl.activeLimboResolutionsByTarget.set(\n limboTargetId,\n new LimboResolution(key)\n );\n syncEngineImpl.activeLimboTargetsByKey =\n syncEngineImpl.activeLimboTargetsByKey.insert(key, limboTargetId);\n remoteStoreListen(\n syncEngineImpl.remoteStore,\n new TargetData(\n queryToTarget(newQueryForPath(key.path)),\n limboTargetId,\n TargetPurpose.LimboResolution,\n ListenSequence.INVALID\n )\n );\n }\n}\n\n// Visible for testing\nexport function syncEngineGetActiveLimboDocumentResolutions(\n syncEngine: SyncEngine\n): SortedMap<DocumentKey, TargetId> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n return syncEngineImpl.activeLimboTargetsByKey;\n}\n\n// Visible for testing\nexport function syncEngineGetEnqueuedLimboDocumentResolutions(\n syncEngine: SyncEngine\n): Set<string> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n return syncEngineImpl.enqueuedLimboResolutions;\n}\n\nexport async function syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngine: SyncEngine,\n changes: DocumentMap,\n remoteEvent?: RemoteEvent\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const newSnaps: ViewSnapshot[] = [];\n const docChangesInAllViews: LocalViewChanges[] = [];\n const queriesProcessed: Array<Promise<void>> = [];\n\n if (syncEngineImpl.queryViewsByQuery.isEmpty()) {\n // Return early since `onWatchChange()` might not have been assigned yet.\n return;\n }\n\n syncEngineImpl.queryViewsByQuery.forEach((_, queryView) => {\n debugAssert(\n !!syncEngineImpl.applyDocChanges,\n 'ApplyDocChangesHandler not set'\n );\n queriesProcessed.push(\n syncEngineImpl\n .applyDocChanges(queryView, changes, remoteEvent)\n .then(viewSnapshot => {\n // If there are changes, or we are handling a global snapshot, notify\n // secondary clients to update query state.\n if (viewSnapshot || remoteEvent) {\n if (syncEngineImpl.isPrimaryClient) {\n syncEngineImpl.sharedClientState.updateQueryState(\n queryView.targetId,\n viewSnapshot?.fromCache ? 'not-current' : 'current'\n );\n }\n }\n\n // Update views if there are actual changes.\n if (!!viewSnapshot) {\n newSnaps.push(viewSnapshot);\n const docChanges = LocalViewChanges.fromSnapshot(\n queryView.targetId,\n viewSnapshot\n );\n docChangesInAllViews.push(docChanges);\n }\n })\n );\n });\n\n await Promise.all(queriesProcessed);\n syncEngineImpl.syncEngineListener.onWatchChange!(newSnaps);\n await localStoreNotifyLocalViewChanges(\n syncEngineImpl.localStore,\n docChangesInAllViews\n );\n}\n\nasync function applyDocChanges(\n syncEngineImpl: SyncEngineImpl,\n queryView: QueryView,\n changes: DocumentMap,\n remoteEvent?: RemoteEvent\n): Promise<ViewSnapshot | undefined> {\n let viewDocChanges = queryView.view.computeDocChanges(changes);\n if (viewDocChanges.needsRefill) {\n // The query has a limit and some docs were removed, so we need\n // to re-run the query against the local store to make sure we\n // didn't lose any good docs that had been past the limit.\n viewDocChanges = await localStoreExecuteQuery(\n syncEngineImpl.localStore,\n queryView.query,\n /* usePreviousResults= */ false\n ).then(({ documents }) => {\n return queryView.view.computeDocChanges(documents, viewDocChanges);\n });\n }\n\n const targetChange =\n remoteEvent && remoteEvent.targetChanges.get(queryView.targetId);\n const viewChange = queryView.view.applyChanges(\n viewDocChanges,\n /* updateLimboDocuments= */ syncEngineImpl.isPrimaryClient,\n targetChange\n );\n updateTrackedLimbos(\n syncEngineImpl,\n queryView.targetId,\n viewChange.limboChanges\n );\n return viewChange.snapshot;\n}\n\nexport async function syncEngineHandleCredentialChange(\n syncEngine: SyncEngine,\n user: User\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const userChanged = !syncEngineImpl.currentUser.isEqual(user);\n\n if (userChanged) {\n logDebug(LOG_TAG, 'User change. New user:', user.toKey());\n\n const result = await localStoreHandleUserChange(\n syncEngineImpl.localStore,\n user\n );\n syncEngineImpl.currentUser = user;\n\n // Fails tasks waiting for pending writes requested by previous user.\n rejectOutstandingPendingWritesCallbacks(\n syncEngineImpl,\n \"'waitForPendingWrites' promise is rejected due to a user change.\"\n );\n // TODO(b/114226417): Consider calling this only in the primary tab.\n syncEngineImpl.sharedClientState.handleUserChange(\n user,\n result.removedBatchIds,\n result.addedBatchIds\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n result.affectedDocuments\n );\n }\n}\n\nexport function syncEngineGetRemoteKeysForTarget(\n syncEngine: SyncEngine,\n targetId: TargetId\n): DocumentKeySet {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const limboResolution =\n syncEngineImpl.activeLimboResolutionsByTarget.get(targetId);\n if (limboResolution && limboResolution.receivedDocument) {\n return documentKeySet().add(limboResolution.key);\n } else {\n let keySet = documentKeySet();\n const queries = syncEngineImpl.queriesByTarget.get(targetId);\n if (!queries) {\n return keySet;\n }\n for (const query of queries) {\n const queryView = syncEngineImpl.queryViewsByQuery.get(query);\n debugAssert(\n !!queryView,\n `No query view found for ${stringifyQuery(query)}`\n );\n keySet = keySet.unionWith(queryView.view.syncedDocuments);\n }\n return keySet;\n }\n}\n\n/**\n * Reconcile the list of synced documents in an existing view with those\n * from persistence.\n */\nasync function synchronizeViewAndComputeSnapshot(\n syncEngine: SyncEngine,\n queryView: QueryView\n): Promise<ViewChange> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const queryResult = await localStoreExecuteQuery(\n syncEngineImpl.localStore,\n queryView.query,\n /* usePreviousResults= */ true\n );\n const viewSnapshot =\n queryView.view.synchronizeWithPersistedState(queryResult);\n if (syncEngineImpl.isPrimaryClient) {\n updateTrackedLimbos(\n syncEngineImpl,\n queryView.targetId,\n viewSnapshot.limboChanges\n );\n }\n return viewSnapshot;\n}\n\n/**\n * Retrieves newly changed documents from remote document cache and raises\n * snapshots if needed.\n */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineSynchronizeWithChangedDocuments(\n syncEngine: SyncEngine,\n collectionGroup: string\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n return localStoreGetNewDocumentChanges(\n syncEngineImpl.localStore,\n collectionGroup\n ).then(changes =>\n syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes)\n );\n}\n\n/** Applies a mutation state to an existing batch. */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineApplyBatchState(\n syncEngine: SyncEngine,\n batchId: BatchId,\n batchState: MutationBatchState,\n error?: FirestoreError\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const documents = await localStoreLookupMutationDocuments(\n syncEngineImpl.localStore,\n batchId\n );\n\n if (documents === null) {\n // A throttled tab may not have seen the mutation before it was completed\n // and removed from the mutation queue, in which case we won't have cached\n // the affected documents. In this case we can safely ignore the update\n // since that means we didn't apply the mutation locally at all (if we\n // had, we would have cached the affected documents), and so we will just\n // see any resulting document changes via normal remote document updates\n // as applicable.\n logDebug(LOG_TAG, 'Cannot apply mutation batch with id: ' + batchId);\n return;\n }\n\n if (batchState === 'pending') {\n // If we are the primary client, we need to send this write to the\n // backend. Secondary clients will ignore these writes since their remote\n // connection is disabled.\n await fillWritePipeline(syncEngineImpl.remoteStore);\n } else if (batchState === 'acknowledged' || batchState === 'rejected') {\n // NOTE: Both these methods are no-ops for batches that originated from\n // other clients.\n processUserCallback(syncEngineImpl, batchId, error ? error : null);\n triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n localStoreRemoveCachedMutationBatchMetadata(\n syncEngineImpl.localStore,\n batchId\n );\n } else {\n fail(`Unknown batchState: ${batchState}`);\n }\n\n await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, documents);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineApplyPrimaryState(\n syncEngine: SyncEngine,\n isPrimary: boolean\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n ensureWatchCallbacks(syncEngineImpl);\n syncEngineEnsureWriteCallbacks(syncEngineImpl);\n if (isPrimary === true && syncEngineImpl._isPrimaryClient !== true) {\n // Secondary tabs only maintain Views for their local listeners and the\n // Views internal state may not be 100% populated (in particular\n // secondary tabs don't track syncedDocuments, the set of documents the\n // server considers to be in the target). So when a secondary becomes\n // primary, we need to need to make sure that all views for all targets\n // match the state on disk.\n const activeTargets =\n syncEngineImpl.sharedClientState.getAllActiveQueryTargets();\n const activeQueries = await synchronizeQueryViewsAndRaiseSnapshots(\n syncEngineImpl,\n activeTargets.toArray(),\n /*transitionToPrimary=*/ true\n );\n syncEngineImpl._isPrimaryClient = true;\n await remoteStoreApplyPrimaryState(syncEngineImpl.remoteStore, true);\n for (const targetData of activeQueries) {\n remoteStoreListen(syncEngineImpl.remoteStore, targetData);\n }\n } else if (isPrimary === false && syncEngineImpl._isPrimaryClient !== false) {\n const activeTargets: TargetId[] = [];\n\n let p = Promise.resolve();\n syncEngineImpl.queriesByTarget.forEach((_, targetId) => {\n if (syncEngineImpl.sharedClientState.isLocalQueryTarget(targetId)) {\n activeTargets.push(targetId);\n } else {\n p = p.then(() => {\n removeAndCleanupTarget(syncEngineImpl, targetId);\n return localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /*keepPersistedTargetData=*/ true\n );\n });\n }\n remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId);\n });\n await p;\n\n await synchronizeQueryViewsAndRaiseSnapshots(\n syncEngineImpl,\n activeTargets,\n /*transitionToPrimary=*/ false\n );\n resetLimboDocuments(syncEngineImpl);\n syncEngineImpl._isPrimaryClient = false;\n await remoteStoreApplyPrimaryState(syncEngineImpl.remoteStore, false);\n }\n}\n\n// PORTING NOTE: Multi-Tab only.\nfunction resetLimboDocuments(syncEngine: SyncEngine): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n syncEngineImpl.activeLimboResolutionsByTarget.forEach((_, targetId) => {\n remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId);\n });\n syncEngineImpl.limboDocumentRefs.removeAllReferences();\n syncEngineImpl.activeLimboResolutionsByTarget = new Map<\n TargetId,\n LimboResolution\n >();\n syncEngineImpl.activeLimboTargetsByKey = new SortedMap<DocumentKey, TargetId>(\n DocumentKey.comparator\n );\n}\n\n/**\n * Reconcile the query views of the provided query targets with the state from\n * persistence. Raises snapshots for any changes that affect the local\n * client and returns the updated state of all target's query data.\n *\n * @param syncEngine - The sync engine implementation\n * @param targets - the list of targets with views that need to be recomputed\n * @param transitionToPrimary - `true` iff the tab transitions from a secondary\n * tab to a primary tab\n */\n// PORTING NOTE: Multi-Tab only.\nasync function synchronizeQueryViewsAndRaiseSnapshots(\n syncEngine: SyncEngine,\n targets: TargetId[],\n transitionToPrimary: boolean\n): Promise<TargetData[]> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const activeQueries: TargetData[] = [];\n const newViewSnapshots: ViewSnapshot[] = [];\n for (const targetId of targets) {\n let targetData: TargetData;\n const queries = syncEngineImpl.queriesByTarget.get(targetId);\n\n if (queries && queries.length !== 0) {\n // For queries that have a local View, we fetch their current state\n // from LocalStore (as the resume token and the snapshot version\n // might have changed) and reconcile their views with the persisted\n // state (the list of syncedDocuments may have gotten out of sync).\n targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n queryToTarget(queries[0])\n );\n\n for (const query of queries) {\n const queryView = syncEngineImpl.queryViewsByQuery.get(query);\n debugAssert(\n !!queryView,\n `No query view found for ${stringifyQuery(query)}`\n );\n\n const viewChange = await synchronizeViewAndComputeSnapshot(\n syncEngineImpl,\n queryView\n );\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n }\n } else {\n debugAssert(\n transitionToPrimary,\n 'A secondary tab should never have an active view without an active target.'\n );\n // For queries that never executed on this client, we need to\n // allocate the target in LocalStore and initialize a new View.\n const target = await localStoreGetCachedTarget(\n syncEngineImpl.localStore,\n targetId\n );\n debugAssert(!!target, `Target for id ${targetId} not found`);\n targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n target\n );\n await initializeViewAndComputeSnapshot(\n syncEngineImpl,\n synthesizeTargetToQuery(target!),\n targetId,\n /*current=*/ false,\n targetData.resumeToken\n );\n }\n\n activeQueries.push(targetData!);\n }\n\n syncEngineImpl.syncEngineListener.onWatchChange!(newViewSnapshots);\n return activeQueries;\n}\n\n/**\n * Creates a `Query` object from the specified `Target`. There is no way to\n * obtain the original `Query`, so we synthesize a `Query` from the `Target`\n * object.\n *\n * The synthesized result might be different from the original `Query`, but\n * since the synthesized `Query` should return the same results as the\n * original one (only the presentation of results might differ), the potential\n * difference will not cause issues.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction synthesizeTargetToQuery(target: Target): Query {\n return newQuery(\n target.path,\n target.collectionGroup,\n target.orderBy,\n target.filters,\n target.limit,\n LimitType.First,\n target.startAt,\n target.endAt\n );\n}\n\n/** Returns the IDs of the clients that are currently active. */\n// PORTING NOTE: Multi-Tab only.\nexport function syncEngineGetActiveClients(\n syncEngine: SyncEngine\n): Promise<ClientId[]> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n return localStoreGetActiveClients(syncEngineImpl.localStore);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineApplyTargetState(\n syncEngine: SyncEngine,\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n if (syncEngineImpl._isPrimaryClient) {\n // If we receive a target state notification via WebStorage, we are\n // either already secondary or another tab has taken the primary lease.\n logDebug(LOG_TAG, 'Ignoring unexpected query state notification.');\n return;\n }\n\n const query = syncEngineImpl.queriesByTarget.get(targetId);\n if (query && query.length > 0) {\n switch (state) {\n case 'current':\n case 'not-current': {\n const changes = await localStoreGetNewDocumentChanges(\n syncEngineImpl.localStore,\n queryCollectionGroup(query[0])\n );\n const synthesizedRemoteEvent =\n RemoteEvent.createSynthesizedRemoteEventForCurrentChange(\n targetId,\n state === 'current',\n ByteString.EMPTY_BYTE_STRING\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n changes,\n synthesizedRemoteEvent\n );\n break;\n }\n case 'rejected': {\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /* keepPersistedTargetData */ true\n );\n removeAndCleanupTarget(syncEngineImpl, targetId, error);\n break;\n }\n default:\n fail('Unexpected target state: ' + state);\n }\n }\n}\n\n/** Adds or removes Watch targets for queries from different tabs. */\nexport async function syncEngineApplyActiveTargetsChange(\n syncEngine: SyncEngine,\n added: TargetId[],\n removed: TargetId[]\n): Promise<void> {\n const syncEngineImpl = ensureWatchCallbacks(syncEngine);\n if (!syncEngineImpl._isPrimaryClient) {\n return;\n }\n\n for (const targetId of added) {\n if (syncEngineImpl.queriesByTarget.has(targetId)) {\n // A target might have been added in a previous attempt\n logDebug(LOG_TAG, 'Adding an already active target ' + targetId);\n continue;\n }\n\n const target = await localStoreGetCachedTarget(\n syncEngineImpl.localStore,\n targetId\n );\n debugAssert(!!target, `Query data for active target ${targetId} not found`);\n const targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n target\n );\n await initializeViewAndComputeSnapshot(\n syncEngineImpl,\n synthesizeTargetToQuery(target),\n targetData.targetId,\n /*current=*/ false,\n targetData.resumeToken\n );\n remoteStoreListen(syncEngineImpl.remoteStore, targetData);\n }\n\n for (const targetId of removed) {\n // Check that the target is still active since the target might have been\n // removed if it has been rejected by the backend.\n if (!syncEngineImpl.queriesByTarget.has(targetId)) {\n continue;\n }\n\n // Release queries that are still active.\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /* keepPersistedTargetData */ false\n )\n .then(() => {\n remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId);\n removeAndCleanupTarget(syncEngineImpl, targetId);\n })\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n}\n\nfunction ensureWatchCallbacks(syncEngine: SyncEngine): SyncEngineImpl {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.applyRemoteEvent =\n syncEngineApplyRemoteEvent.bind(null, syncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.getRemoteKeysForTarget =\n syncEngineGetRemoteKeysForTarget.bind(null, syncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.rejectListen =\n syncEngineRejectListen.bind(null, syncEngineImpl);\n syncEngineImpl.syncEngineListener.onWatchChange =\n eventManagerOnWatchChange.bind(null, syncEngineImpl.eventManager);\n syncEngineImpl.syncEngineListener.onWatchError =\n eventManagerOnWatchError.bind(null, syncEngineImpl.eventManager);\n return syncEngineImpl;\n}\n\nexport function syncEngineEnsureWriteCallbacks(\n syncEngine: SyncEngine\n): SyncEngineImpl {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.applySuccessfulWrite =\n syncEngineApplySuccessfulWrite.bind(null, syncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.rejectFailedWrite =\n syncEngineRejectFailedWrite.bind(null, syncEngineImpl);\n return syncEngineImpl;\n}\n\n/**\n * Loads a Firestore bundle into the SDK. The returned promise resolves when\n * the bundle finished loading.\n *\n * @param syncEngine - SyncEngine to use.\n * @param bundleReader - Bundle to load into the SDK.\n * @param task - LoadBundleTask used to update the loading progress to public API.\n */\nexport function syncEngineLoadBundle(\n syncEngine: SyncEngine,\n bundleReader: BundleReader,\n task: LoadBundleTask\n): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n loadBundleImpl(syncEngineImpl, bundleReader, task).then(collectionGroups => {\n syncEngineImpl.sharedClientState.notifyBundleLoaded(collectionGroups);\n });\n}\n\n/** Loads a bundle and returns the list of affected collection groups. */\nasync function loadBundleImpl(\n syncEngine: SyncEngineImpl,\n reader: BundleReader,\n task: LoadBundleTask\n): Promise<Set<string>> {\n try {\n const metadata = await reader.getMetadata();\n const skip = await localStoreHasNewerBundle(\n syncEngine.localStore,\n metadata\n );\n if (skip) {\n await reader.close();\n task._completeWith(bundleSuccessProgress(metadata));\n return Promise.resolve(new Set<string>());\n }\n\n task._updateProgress(bundleInitialProgress(metadata));\n\n const loader = new BundleLoader(\n metadata,\n syncEngine.localStore,\n reader.serializer\n );\n let element = await reader.nextElement();\n while (element) {\n debugAssert(\n !element.payload.metadata,\n 'Unexpected BundleMetadata element.'\n );\n const progress = await loader.addSizedElement(element);\n if (progress) {\n task._updateProgress(progress);\n }\n\n element = await reader.nextElement();\n }\n\n const result = await loader.complete();\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngine,\n result.changedDocs,\n /* remoteEvent */ undefined\n );\n\n // Save metadata, so loading the same bundle will skip.\n await localStoreSaveBundle(syncEngine.localStore, metadata);\n task._completeWith(result.progress);\n return Promise.resolve(result.changedCollectionGroups);\n } catch (e) {\n logWarn(LOG_TAG, `Loading bundle failed with ${e}`);\n task._failWith(e as FirestoreError);\n return Promise.resolve(new Set<string>());\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport {\n IndexBackfiller,\n IndexBackfillerScheduler\n} from '../local/index_backfiller';\nimport {\n indexedDbStoragePrefix,\n IndexedDbPersistence\n} from '../local/indexeddb_persistence';\nimport { LocalStore } from '../local/local_store';\nimport { newLocalStore } from '../local/local_store_impl';\nimport { LruParams } from '../local/lru_garbage_collector';\nimport { LruScheduler } from '../local/lru_garbage_collector_impl';\nimport {\n MemoryEagerDelegate,\n MemoryLruDelegate,\n MemoryPersistence\n} from '../local/memory_persistence';\nimport { Scheduler, Persistence } from '../local/persistence';\nimport { QueryEngine } from '../local/query_engine';\nimport {\n ClientId,\n MemorySharedClientState,\n SharedClientState,\n WebStorageSharedClientState\n} from '../local/shared_client_state';\nimport { newConnection, newConnectivityMonitor } from '../platform/connection';\nimport { getDocument, getWindow } from '../platform/dom';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport {\n fillWritePipeline,\n newRemoteStore,\n RemoteStore,\n remoteStoreApplyPrimaryState,\n remoteStoreShutdown\n} from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { DatabaseInfo } from './database_info';\nimport { EventManager, newEventManager } from './event_manager';\nimport { SyncEngine } from './sync_engine';\nimport {\n newSyncEngine,\n syncEngineApplyActiveTargetsChange,\n syncEngineApplyBatchState,\n syncEngineApplyOnlineStateChange,\n syncEngineApplyPrimaryState,\n syncEngineApplyTargetState,\n syncEngineEnsureWriteCallbacks,\n syncEngineGetActiveClients,\n syncEngineHandleCredentialChange,\n syncEngineSynchronizeWithChangedDocuments\n} from './sync_engine_impl';\nimport { OnlineStateSource } from './types';\n\nexport interface ComponentConfiguration {\n asyncQueue: AsyncQueue;\n databaseInfo: DatabaseInfo;\n authCredentials: CredentialsProvider<User>;\n appCheckCredentials: CredentialsProvider<string>;\n clientId: ClientId;\n initialUser: User;\n maxConcurrentLimboResolutions: number;\n}\n\n/**\n * Initializes and wires components that are needed to interface with the local\n * cache. Implementations override `initialize()` to provide all components.\n */\nexport interface OfflineComponentProvider {\n persistence: Persistence;\n sharedClientState: SharedClientState;\n localStore: LocalStore;\n gcScheduler: Scheduler | null;\n indexBackfillerScheduler: Scheduler | null;\n synchronizeTabs: boolean;\n\n initialize(cfg: ComponentConfiguration): Promise<void>;\n\n terminate(): Promise<void>;\n}\n\n/**\n * Provides all components needed for Firestore with in-memory persistence.\n * Uses EagerGC garbage collection.\n */\nexport class MemoryOfflineComponentProvider\n implements OfflineComponentProvider\n{\n persistence!: Persistence;\n sharedClientState!: SharedClientState;\n localStore!: LocalStore;\n gcScheduler!: Scheduler | null;\n indexBackfillerScheduler!: Scheduler | null;\n synchronizeTabs = false;\n\n serializer!: JsonProtoSerializer;\n\n async initialize(cfg: ComponentConfiguration): Promise<void> {\n this.serializer = newSerializer(cfg.databaseInfo.databaseId);\n this.sharedClientState = this.createSharedClientState(cfg);\n this.persistence = this.createPersistence(cfg);\n await this.persistence.start();\n this.localStore = this.createLocalStore(cfg);\n this.gcScheduler = this.createGarbageCollectionScheduler(\n cfg,\n this.localStore\n );\n this.indexBackfillerScheduler = this.createIndexBackfillerScheduler(\n cfg,\n this.localStore\n );\n }\n\n createGarbageCollectionScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n return null;\n }\n\n createIndexBackfillerScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n return null;\n }\n\n createLocalStore(cfg: ComponentConfiguration): LocalStore {\n return newLocalStore(\n this.persistence,\n new QueryEngine(),\n cfg.initialUser,\n this.serializer\n );\n }\n\n createPersistence(cfg: ComponentConfiguration): Persistence {\n return new MemoryPersistence(MemoryEagerDelegate.factory, this.serializer);\n }\n\n createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n return new MemorySharedClientState();\n }\n\n async terminate(): Promise<void> {\n if (this.gcScheduler) {\n this.gcScheduler.stop();\n }\n await this.sharedClientState.shutdown();\n await this.persistence.shutdown();\n }\n}\n\nexport class LruGcMemoryOfflineComponentProvider extends MemoryOfflineComponentProvider {\n constructor(protected readonly cacheSizeBytes: number | undefined) {\n super();\n }\n\n createGarbageCollectionScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n hardAssert(\n this.persistence.referenceDelegate instanceof MemoryLruDelegate,\n 'referenceDelegate is expected to be an instance of MemoryLruDelegate.'\n );\n\n const garbageCollector =\n this.persistence.referenceDelegate.garbageCollector;\n return new LruScheduler(garbageCollector, cfg.asyncQueue, localStore);\n }\n\n createPersistence(cfg: ComponentConfiguration): Persistence {\n const lruParams =\n this.cacheSizeBytes !== undefined\n ? LruParams.withCacheSize(this.cacheSizeBytes)\n : LruParams.DEFAULT;\n return new MemoryPersistence(\n p => MemoryLruDelegate.factory(p, lruParams),\n this.serializer\n );\n }\n}\n\n/**\n * Provides all components needed for Firestore with IndexedDB persistence.\n */\nexport class IndexedDbOfflineComponentProvider extends MemoryOfflineComponentProvider {\n persistence!: IndexedDbPersistence;\n sharedClientState!: SharedClientState;\n localStore!: LocalStore;\n gcScheduler!: Scheduler | null;\n indexBackfillerScheduler!: Scheduler | null;\n synchronizeTabs = false;\n\n constructor(\n protected readonly onlineComponentProvider: OnlineComponentProvider,\n protected readonly cacheSizeBytes: number | undefined,\n protected readonly forceOwnership: boolean | undefined\n ) {\n super();\n }\n\n async initialize(cfg: ComponentConfiguration): Promise<void> {\n await super.initialize(cfg);\n\n await this.onlineComponentProvider.initialize(this, cfg);\n\n // Enqueue writes from a previous session\n await syncEngineEnsureWriteCallbacks(\n this.onlineComponentProvider.syncEngine\n );\n await fillWritePipeline(this.onlineComponentProvider.remoteStore);\n\n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.setPrimaryStateListener(() => {\n if (this.gcScheduler && !this.gcScheduler.started) {\n this.gcScheduler.start();\n }\n if (\n this.indexBackfillerScheduler &&\n !this.indexBackfillerScheduler.started\n ) {\n this.indexBackfillerScheduler.start();\n }\n return Promise.resolve();\n });\n }\n\n createLocalStore(cfg: ComponentConfiguration): LocalStore {\n return newLocalStore(\n this.persistence,\n new QueryEngine(),\n cfg.initialUser,\n this.serializer\n );\n }\n\n createGarbageCollectionScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n const garbageCollector =\n this.persistence.referenceDelegate.garbageCollector;\n return new LruScheduler(garbageCollector, cfg.asyncQueue, localStore);\n }\n\n createIndexBackfillerScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n const indexBackfiller = new IndexBackfiller(localStore, this.persistence);\n return new IndexBackfillerScheduler(cfg.asyncQueue, indexBackfiller);\n }\n\n createPersistence(cfg: ComponentConfiguration): IndexedDbPersistence {\n const persistenceKey = indexedDbStoragePrefix(\n cfg.databaseInfo.databaseId,\n cfg.databaseInfo.persistenceKey\n );\n const lruParams =\n this.cacheSizeBytes !== undefined\n ? LruParams.withCacheSize(this.cacheSizeBytes)\n : LruParams.DEFAULT;\n\n return new IndexedDbPersistence(\n this.synchronizeTabs,\n persistenceKey,\n cfg.clientId,\n lruParams,\n cfg.asyncQueue,\n getWindow(),\n getDocument(),\n this.serializer,\n this.sharedClientState,\n !!this.forceOwnership\n );\n }\n\n createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n return new MemorySharedClientState();\n }\n}\n\n/**\n * Provides all components needed for Firestore with multi-tab IndexedDB\n * persistence.\n *\n * In the legacy client, this provider is used to provide both multi-tab and\n * non-multi-tab persistence since we cannot tell at build time whether\n * `synchronizeTabs` will be enabled.\n */\nexport class MultiTabOfflineComponentProvider extends IndexedDbOfflineComponentProvider {\n synchronizeTabs = true;\n\n constructor(\n protected readonly onlineComponentProvider: OnlineComponentProvider,\n protected readonly cacheSizeBytes: number | undefined\n ) {\n super(onlineComponentProvider, cacheSizeBytes, /* forceOwnership= */ false);\n }\n\n async initialize(cfg: ComponentConfiguration): Promise<void> {\n await super.initialize(cfg);\n\n const syncEngine = this.onlineComponentProvider.syncEngine;\n\n if (this.sharedClientState instanceof WebStorageSharedClientState) {\n this.sharedClientState.syncEngine = {\n applyBatchState: syncEngineApplyBatchState.bind(null, syncEngine),\n applyTargetState: syncEngineApplyTargetState.bind(null, syncEngine),\n applyActiveTargetsChange: syncEngineApplyActiveTargetsChange.bind(\n null,\n syncEngine\n ),\n getActiveClients: syncEngineGetActiveClients.bind(null, syncEngine),\n synchronizeWithChangedDocuments:\n syncEngineSynchronizeWithChangedDocuments.bind(null, syncEngine)\n };\n await this.sharedClientState.start();\n }\n\n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.setPrimaryStateListener(async isPrimary => {\n await syncEngineApplyPrimaryState(\n this.onlineComponentProvider.syncEngine,\n isPrimary\n );\n if (this.gcScheduler) {\n if (isPrimary && !this.gcScheduler.started) {\n this.gcScheduler.start();\n } else if (!isPrimary) {\n this.gcScheduler.stop();\n }\n }\n if (this.indexBackfillerScheduler) {\n if (isPrimary && !this.indexBackfillerScheduler.started) {\n this.indexBackfillerScheduler.start();\n } else if (!isPrimary) {\n this.indexBackfillerScheduler.stop();\n }\n }\n });\n }\n\n createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n const window = getWindow();\n if (!WebStorageSharedClientState.isAvailable(window)) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'IndexedDB persistence is only available on platforms that support LocalStorage.'\n );\n }\n const persistenceKey = indexedDbStoragePrefix(\n cfg.databaseInfo.databaseId,\n cfg.databaseInfo.persistenceKey\n );\n return new WebStorageSharedClientState(\n window,\n cfg.asyncQueue,\n persistenceKey,\n cfg.clientId,\n cfg.initialUser\n );\n }\n}\n\n/**\n * Initializes and wires the components that are needed to interface with the\n * network.\n */\nexport class OnlineComponentProvider {\n protected localStore!: LocalStore;\n protected sharedClientState!: SharedClientState;\n datastore!: Datastore;\n eventManager!: EventManager;\n remoteStore!: RemoteStore;\n syncEngine!: SyncEngine;\n\n async initialize(\n offlineComponentProvider: OfflineComponentProvider,\n cfg: ComponentConfiguration\n ): Promise<void> {\n if (this.localStore) {\n // OnlineComponentProvider may get initialized multiple times if\n // multi-tab persistence is used.\n return;\n }\n\n this.localStore = offlineComponentProvider.localStore;\n this.sharedClientState = offlineComponentProvider.sharedClientState;\n this.datastore = this.createDatastore(cfg);\n this.remoteStore = this.createRemoteStore(cfg);\n this.eventManager = this.createEventManager(cfg);\n this.syncEngine = this.createSyncEngine(\n cfg,\n /* startAsPrimary=*/ !offlineComponentProvider.synchronizeTabs\n );\n\n this.sharedClientState.onlineStateHandler = onlineState =>\n syncEngineApplyOnlineStateChange(\n this.syncEngine,\n onlineState,\n OnlineStateSource.SharedClientState\n );\n\n this.remoteStore.remoteSyncer.handleCredentialChange =\n syncEngineHandleCredentialChange.bind(null, this.syncEngine);\n\n await remoteStoreApplyPrimaryState(\n this.remoteStore,\n this.syncEngine.isPrimaryClient\n );\n }\n\n createEventManager(cfg: ComponentConfiguration): EventManager {\n return newEventManager();\n }\n\n createDatastore(cfg: ComponentConfiguration): Datastore {\n const serializer = newSerializer(cfg.databaseInfo.databaseId);\n const connection = newConnection(cfg.databaseInfo);\n return newDatastore(\n cfg.authCredentials,\n cfg.appCheckCredentials,\n connection,\n serializer\n );\n }\n\n createRemoteStore(cfg: ComponentConfiguration): RemoteStore {\n return newRemoteStore(\n this.localStore,\n this.datastore,\n cfg.asyncQueue,\n onlineState =>\n syncEngineApplyOnlineStateChange(\n this.syncEngine,\n onlineState,\n OnlineStateSource.RemoteStore\n ),\n newConnectivityMonitor()\n );\n }\n\n createSyncEngine(\n cfg: ComponentConfiguration,\n startAsPrimary: boolean\n ): SyncEngine {\n return newSyncEngine(\n this.localStore,\n this.remoteStore,\n this.eventManager,\n this.sharedClientState,\n cfg.initialUser,\n cfg.maxConcurrentLimboResolutions,\n startAsPrimary\n );\n }\n\n terminate(): Promise<void> {\n return remoteStoreShutdown(this.remoteStore);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseInfo } from '../../core/database_info';\nimport { Connection } from '../../remote/connection';\nimport { ConnectivityMonitor } from '../../remote/connectivity_monitor';\nimport { NoopConnectivityMonitor } from '../../remote/connectivity_monitor_noop';\n\nimport { BrowserConnectivityMonitor } from './connectivity_monitor';\nimport { WebChannelConnection } from './webchannel_connection';\n\n/** Initializes the WebChannelConnection for the browser. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n return new WebChannelConnection(databaseInfo);\n}\n\n/** Return the Platform-specific connectivity monitor. */\nexport function newConnectivityMonitor(): ConnectivityMonitor {\n if (BrowserConnectivityMonitor.isAvailable()) {\n return new BrowserConnectivityMonitor();\n } else {\n return new NoopConnectivityMonitor();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Observer } from '../core/event_manager';\n\nimport { FirestoreError } from './error';\nimport { logError } from './log';\nimport { EventHandler } from './misc';\n\n/*\n * A wrapper implementation of Observer<T> that will dispatch events\n * asynchronously. To allow immediate silencing, a mute call is added which\n * causes events scheduled to no longer be raised.\n */\nexport class AsyncObserver<T> implements Observer<T> {\n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n private muted = false;\n\n constructor(private observer: Partial<Observer<T>>) {}\n\n next(value: T): void {\n if (this.observer.next) {\n this.scheduleEvent(this.observer.next, value);\n }\n }\n\n error(error: FirestoreError): void {\n if (this.observer.error) {\n this.scheduleEvent(this.observer.error, error);\n } else {\n logError('Uncaught Error in snapshot listener:', error.toString());\n }\n }\n\n mute(): void {\n this.muted = true;\n }\n\n private scheduleEvent<E>(eventHandler: EventHandler<E>, event: E): void {\n if (!this.muted) {\n setTimeout(() => {\n if (!this.muted) {\n eventHandler(event);\n }\n }, 0);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GetOptions } from '@firebase/firestore-types';\n\nimport { LoadBundleTask } from '../api/bundle';\nimport {\n CredentialChangeListener,\n CredentialsProvider\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreConfigureFieldIndexes,\n localStoreDeleteAllFieldIndexes,\n localStoreExecuteQuery,\n localStoreGetNamedQuery,\n localStoreHandleUserChange,\n localStoreReadDocument,\n localStoreSetIndexAutoCreationEnabled\n} from '../local/local_store_impl';\nimport { Persistence } from '../local/persistence';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex } from '../model/field_index';\nimport { Mutation } from '../model/mutation';\nimport { toByteStreamReader } from '../platform/byte_stream_reader';\nimport { newSerializer } from '../platform/serializer';\nimport { newTextEncoder } from '../platform/text_serializer';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { Datastore, invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport {\n RemoteStore,\n remoteStoreDisableNetwork,\n remoteStoreEnableNetwork,\n remoteStoreHandleCredentialChange\n} from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncObserver } from '../util/async_observer';\nimport { AsyncQueue, wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { BundleReader } from '../util/bundle_reader';\nimport { newBundleReader } from '../util/bundle_reader_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { AutoId } from '../util/misc';\nimport { Deferred } from '../util/promise';\n\nimport { Aggregate } from './aggregate';\nimport { NamedQuery } from './bundle';\nimport {\n ComponentConfiguration,\n MemoryOfflineComponentProvider,\n OfflineComponentProvider,\n OnlineComponentProvider\n} from './component_provider';\nimport { DatabaseId, DatabaseInfo } from './database_info';\nimport {\n addSnapshotsInSyncListener,\n EventManager,\n eventManagerListen,\n eventManagerUnlisten,\n ListenOptions,\n Observer,\n QueryListener,\n removeSnapshotsInSyncListener\n} from './event_manager';\nimport { newQueryForPath, Query } from './query';\nimport { SyncEngine } from './sync_engine';\nimport {\n syncEngineListen,\n syncEngineLoadBundle,\n syncEngineRegisterPendingWritesCallback,\n syncEngineUnlisten,\n syncEngineWrite\n} from './sync_engine_impl';\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\nimport { TransactionRunner } from './transaction_runner';\nimport { View } from './view';\nimport { ViewSnapshot } from './view_snapshot';\n\nconst LOG_TAG = 'FirestoreClient';\nexport const MAX_CONCURRENT_LIMBO_RESOLUTIONS = 100;\n\n/** DOMException error code constants. */\nconst DOM_EXCEPTION_INVALID_STATE = 11;\nconst DOM_EXCEPTION_ABORTED = 20;\nconst DOM_EXCEPTION_QUOTA_EXCEEDED = 22;\n\n/**\n * FirestoreClient is a top-level class that constructs and owns all of the //\n * pieces of the client SDK architecture. It is responsible for creating the //\n * async queue that is shared by all of the other components in the system. //\n */\nexport class FirestoreClient {\n private user = User.UNAUTHENTICATED;\n private readonly clientId = AutoId.newId();\n private authCredentialListener: CredentialChangeListener<User> = () =>\n Promise.resolve();\n private appCheckCredentialListener: (\n appCheckToken: string,\n user: User\n ) => Promise<void> = () => Promise.resolve();\n _uninitializedComponentsProvider?: {\n _offline: OfflineComponentProvider;\n _offlineKind: 'memory' | 'persistent';\n _online: OnlineComponentProvider;\n };\n\n _offlineComponents?: OfflineComponentProvider;\n _onlineComponents?: OnlineComponentProvider;\n\n constructor(\n private authCredentials: CredentialsProvider<User>,\n private appCheckCredentials: CredentialsProvider<string>,\n /**\n * Asynchronous queue responsible for all of our internal processing. When\n * we get incoming work from the user (via public API) or the network\n * (incoming GRPC messages), we should always schedule onto this queue.\n * This ensures all of our work is properly serialized (e.g. we don't\n * start processing a new operation while the previous one is waiting for\n * an async I/O to complete).\n */\n public asyncQueue: AsyncQueue,\n private databaseInfo: DatabaseInfo\n ) {\n this.authCredentials.start(asyncQueue, async user => {\n logDebug(LOG_TAG, 'Received user=', user.uid);\n await this.authCredentialListener(user);\n this.user = user;\n });\n this.appCheckCredentials.start(asyncQueue, newAppCheckToken => {\n logDebug(LOG_TAG, 'Received new app check token=', newAppCheckToken);\n return this.appCheckCredentialListener(newAppCheckToken, this.user);\n });\n }\n\n async getConfiguration(): Promise<ComponentConfiguration> {\n return {\n asyncQueue: this.asyncQueue,\n databaseInfo: this.databaseInfo,\n clientId: this.clientId,\n authCredentials: this.authCredentials,\n appCheckCredentials: this.appCheckCredentials,\n initialUser: this.user,\n maxConcurrentLimboResolutions: MAX_CONCURRENT_LIMBO_RESOLUTIONS\n };\n }\n\n setCredentialChangeListener(listener: (user: User) => Promise<void>): void {\n this.authCredentialListener = listener;\n }\n\n setAppCheckTokenChangeListener(\n listener: (appCheckToken: string, user: User) => Promise<void>\n ): void {\n this.appCheckCredentialListener = listener;\n }\n\n /**\n * Checks that the client has not been terminated. Ensures that other methods on //\n * this class cannot be called after the client is terminated. //\n */\n verifyNotTerminated(): void {\n if (this.asyncQueue.isShuttingDown) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n terminate(): Promise<void> {\n this.asyncQueue.enterRestrictedMode();\n const deferred = new Deferred();\n this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async () => {\n try {\n if (this._onlineComponents) {\n await this._onlineComponents.terminate();\n }\n if (this._offlineComponents) {\n await this._offlineComponents.terminate();\n }\n\n // The credentials provider must be terminated after shutting down the\n // RemoteStore as it will prevent the RemoteStore from retrieving auth\n // tokens.\n this.authCredentials.shutdown();\n this.appCheckCredentials.shutdown();\n deferred.resolve();\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to shutdown persistence`\n );\n deferred.reject(firestoreError);\n }\n });\n return deferred.promise;\n }\n}\n\nexport async function setOfflineComponentProvider(\n client: FirestoreClient,\n offlineComponentProvider: OfflineComponentProvider\n): Promise<void> {\n client.asyncQueue.verifyOperationInProgress();\n\n logDebug(LOG_TAG, 'Initializing OfflineComponentProvider');\n const configuration = await client.getConfiguration();\n await offlineComponentProvider.initialize(configuration);\n\n let currentUser = configuration.initialUser;\n client.setCredentialChangeListener(async user => {\n if (!currentUser.isEqual(user)) {\n await localStoreHandleUserChange(\n offlineComponentProvider.localStore,\n user\n );\n currentUser = user;\n }\n });\n\n // When a user calls clearPersistence() in one client, all other clients\n // need to be terminated to allow the delete to succeed.\n offlineComponentProvider.persistence.setDatabaseDeletedListener(() =>\n client.terminate()\n );\n\n client._offlineComponents = offlineComponentProvider;\n}\n\nexport async function setOnlineComponentProvider(\n client: FirestoreClient,\n onlineComponentProvider: OnlineComponentProvider\n): Promise<void> {\n client.asyncQueue.verifyOperationInProgress();\n\n const offlineComponentProvider = await ensureOfflineComponents(client);\n\n logDebug(LOG_TAG, 'Initializing OnlineComponentProvider');\n const configuration = await client.getConfiguration();\n await onlineComponentProvider.initialize(\n offlineComponentProvider,\n configuration\n );\n // The CredentialChangeListener of the online component provider takes\n // precedence over the offline component provider.\n client.setCredentialChangeListener(user =>\n remoteStoreHandleCredentialChange(onlineComponentProvider.remoteStore, user)\n );\n client.setAppCheckTokenChangeListener((_, user) =>\n remoteStoreHandleCredentialChange(onlineComponentProvider.remoteStore, user)\n );\n client._onlineComponents = onlineComponentProvider;\n}\n\n/**\n * Decides whether the provided error allows us to gracefully disable\n * persistence (as opposed to crashing the client).\n */\nexport function canFallbackFromIndexedDbError(\n error: FirestoreError | DOMException\n): boolean {\n if (error.name === 'FirebaseError') {\n return (\n error.code === Code.FAILED_PRECONDITION ||\n error.code === Code.UNIMPLEMENTED\n );\n } else if (\n typeof DOMException !== 'undefined' &&\n error instanceof DOMException\n ) {\n // There are a few known circumstances where we can open IndexedDb but\n // trying to read/write will fail (e.g. quota exceeded). For\n // well-understood cases, we attempt to detect these and then gracefully\n // fall back to memory persistence.\n // NOTE: Rather than continue to add to this list, we could decide to\n // always fall back, with the risk that we might accidentally hide errors\n // representing actual SDK bugs.\n return (\n // When the browser is out of quota we could get either quota exceeded\n // or an aborted error depending on whether the error happened during\n // schema migration.\n error.code === DOM_EXCEPTION_QUOTA_EXCEEDED ||\n error.code === DOM_EXCEPTION_ABORTED ||\n // Firefox Private Browsing mode disables IndexedDb and returns\n // INVALID_STATE for any usage.\n error.code === DOM_EXCEPTION_INVALID_STATE\n );\n }\n\n return true;\n}\n\nasync function ensureOfflineComponents(\n client: FirestoreClient\n): Promise<OfflineComponentProvider> {\n if (!client._offlineComponents) {\n if (client._uninitializedComponentsProvider) {\n logDebug(LOG_TAG, 'Using user provided OfflineComponentProvider');\n try {\n await setOfflineComponentProvider(\n client,\n client._uninitializedComponentsProvider._offline\n );\n } catch (e) {\n const error = e as FirestoreError | DOMException;\n if (!canFallbackFromIndexedDbError(error)) {\n throw error;\n }\n logWarn(\n 'Error using user provided cache. Falling back to ' +\n 'memory cache: ' +\n error\n );\n await setOfflineComponentProvider(\n client,\n new MemoryOfflineComponentProvider()\n );\n }\n } else {\n logDebug(LOG_TAG, 'Using default OfflineComponentProvider');\n await setOfflineComponentProvider(\n client,\n new MemoryOfflineComponentProvider()\n );\n }\n }\n\n return client._offlineComponents!;\n}\n\nasync function ensureOnlineComponents(\n client: FirestoreClient\n): Promise<OnlineComponentProvider> {\n if (!client._onlineComponents) {\n if (client._uninitializedComponentsProvider) {\n logDebug(LOG_TAG, 'Using user provided OnlineComponentProvider');\n await setOnlineComponentProvider(\n client,\n client._uninitializedComponentsProvider._online\n );\n } else {\n logDebug(LOG_TAG, 'Using default OnlineComponentProvider');\n await setOnlineComponentProvider(client, new OnlineComponentProvider());\n }\n }\n\n return client._onlineComponents!;\n}\n\nfunction getPersistence(client: FirestoreClient): Promise<Persistence> {\n return ensureOfflineComponents(client).then(c => c.persistence);\n}\n\nexport function getLocalStore(client: FirestoreClient): Promise<LocalStore> {\n return ensureOfflineComponents(client).then(c => c.localStore);\n}\n\nfunction getRemoteStore(client: FirestoreClient): Promise<RemoteStore> {\n return ensureOnlineComponents(client).then(c => c.remoteStore);\n}\n\nexport function getSyncEngine(client: FirestoreClient): Promise<SyncEngine> {\n return ensureOnlineComponents(client).then(c => c.syncEngine);\n}\n\nfunction getDatastore(client: FirestoreClient): Promise<Datastore> {\n return ensureOnlineComponents(client).then(c => c.datastore);\n}\n\nexport async function getEventManager(\n client: FirestoreClient\n): Promise<EventManager> {\n const onlineComponentProvider = await ensureOnlineComponents(client);\n const eventManager = onlineComponentProvider.eventManager;\n eventManager.onListen = syncEngineListen.bind(\n null,\n onlineComponentProvider.syncEngine\n );\n eventManager.onUnlisten = syncEngineUnlisten.bind(\n null,\n onlineComponentProvider.syncEngine\n );\n return eventManager;\n}\n\n/** Enables the network connection and re-enqueues all pending operations. */\nexport function firestoreClientEnableNetwork(\n client: FirestoreClient\n): Promise<void> {\n return client.asyncQueue.enqueue(async () => {\n const persistence = await getPersistence(client);\n const remoteStore = await getRemoteStore(client);\n persistence.setNetworkEnabled(true);\n return remoteStoreEnableNetwork(remoteStore);\n });\n}\n\n/** Disables the network connection. Pending operations will not complete. */\nexport function firestoreClientDisableNetwork(\n client: FirestoreClient\n): Promise<void> {\n return client.asyncQueue.enqueue(async () => {\n const persistence = await getPersistence(client);\n const remoteStore = await getRemoteStore(client);\n persistence.setNetworkEnabled(false);\n return remoteStoreDisableNetwork(remoteStore);\n });\n}\n\n/**\n * Returns a Promise that resolves when all writes that were pending at the time\n * this method was called received server acknowledgement. An acknowledgement\n * can be either acceptance or rejection.\n */\nexport function firestoreClientWaitForPendingWrites(\n client: FirestoreClient\n): Promise<void> {\n const deferred = new Deferred<void>();\n client.asyncQueue.enqueueAndForget(async () => {\n const syncEngine = await getSyncEngine(client);\n return syncEngineRegisterPendingWritesCallback(syncEngine, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientListen(\n client: FirestoreClient,\n query: Query,\n options: ListenOptions,\n observer: Partial<Observer<ViewSnapshot>>\n): () => void {\n const wrappedObserver = new AsyncObserver(observer);\n const listener = new QueryListener(query, wrappedObserver, options);\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return eventManagerListen(eventManager, listener);\n });\n return () => {\n wrappedObserver.mute();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return eventManagerUnlisten(eventManager, listener);\n });\n };\n}\n\nexport function firestoreClientGetDocumentFromLocalCache(\n client: FirestoreClient,\n docKey: DocumentKey\n): Promise<Document | null> {\n const deferred = new Deferred<Document | null>();\n client.asyncQueue.enqueueAndForget(async () => {\n const localStore = await getLocalStore(client);\n return readDocumentFromCache(localStore, docKey, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentViaSnapshotListener(\n client: FirestoreClient,\n key: DocumentKey,\n options: GetOptions = {}\n): Promise<ViewSnapshot> {\n const deferred = new Deferred<ViewSnapshot>();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return readDocumentViaSnapshotListener(\n eventManager,\n client.asyncQueue,\n key,\n options,\n deferred\n );\n });\n return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentsFromLocalCache(\n client: FirestoreClient,\n query: Query\n): Promise<ViewSnapshot> {\n const deferred = new Deferred<ViewSnapshot>();\n client.asyncQueue.enqueueAndForget(async () => {\n const localStore = await getLocalStore(client);\n return executeQueryFromCache(localStore, query, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentsViaSnapshotListener(\n client: FirestoreClient,\n query: Query,\n options: GetOptions = {}\n): Promise<ViewSnapshot> {\n const deferred = new Deferred<ViewSnapshot>();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return executeQueryViaSnapshotListener(\n eventManager,\n client.asyncQueue,\n query,\n options,\n deferred\n );\n });\n return deferred.promise;\n}\n\nexport function firestoreClientRunAggregateQuery(\n client: FirestoreClient,\n query: Query,\n aggregates: Aggregate[]\n): Promise<ApiClientObjectMap<Value>> {\n const deferred = new Deferred<ApiClientObjectMap<Value>>();\n\n client.asyncQueue.enqueueAndForget(async () => {\n // Implement and call executeAggregateQueryViaSnapshotListener, similar\n // to the implementation in firestoreClientGetDocumentsViaSnapshotListener\n // above\n try {\n // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab.\n const datastore = await getDatastore(client);\n deferred.resolve(\n invokeRunAggregationQueryRpc(datastore, query, aggregates)\n );\n } catch (e) {\n deferred.reject(e as Error);\n }\n });\n return deferred.promise;\n}\n\nexport function firestoreClientWrite(\n client: FirestoreClient,\n mutations: Mutation[]\n): Promise<void> {\n const deferred = new Deferred<void>();\n client.asyncQueue.enqueueAndForget(async () => {\n const syncEngine = await getSyncEngine(client);\n return syncEngineWrite(syncEngine, mutations, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientAddSnapshotsInSyncListener(\n client: FirestoreClient,\n observer: Partial<Observer<void>>\n): () => void {\n const wrappedObserver = new AsyncObserver(observer);\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return addSnapshotsInSyncListener(eventManager, wrappedObserver);\n });\n return () => {\n wrappedObserver.mute();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return removeSnapshotsInSyncListener(eventManager, wrappedObserver);\n });\n };\n}\n\n/**\n * Takes an updateFunction in which a set of reads and writes can be performed\n * atomically. In the updateFunction, the client can read and write values\n * using the supplied transaction object. After the updateFunction, all\n * changes will be committed. If a retryable error occurs (ex: some other\n * client has changed any of the data referenced), then the updateFunction\n * will be called again after a backoff. If the updateFunction still fails\n * after all retries, then the transaction will be rejected.\n *\n * The transaction object passed to the updateFunction contains methods for\n * accessing documents and collections. Unlike other datastore access, data\n * accessed with the transaction will not reflect local changes that have not\n * been committed. For this reason, it is required that all reads are\n * performed before any writes. Transactions must be performed while online.\n */\nexport function firestoreClientTransaction<T>(\n client: FirestoreClient,\n updateFunction: (transaction: Transaction) => Promise<T>,\n options: TransactionOptions\n): Promise<T> {\n const deferred = new Deferred<T>();\n client.asyncQueue.enqueueAndForget(async () => {\n const datastore = await getDatastore(client);\n new TransactionRunner<T>(\n client.asyncQueue,\n datastore,\n options,\n updateFunction,\n deferred\n ).run();\n });\n return deferred.promise;\n}\n\nasync function readDocumentFromCache(\n localStore: LocalStore,\n docKey: DocumentKey,\n result: Deferred<Document | null>\n): Promise<void> {\n try {\n const document = await localStoreReadDocument(localStore, docKey);\n if (document.isFoundDocument()) {\n result.resolve(document);\n } else if (document.isNoDocument()) {\n result.resolve(null);\n } else {\n result.reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document from cache. (However, this document may ' +\n \"exist on the server. Run again without setting 'source' in \" +\n 'the GetOptions to attempt to retrieve the document from the ' +\n 'server.)'\n )\n );\n }\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to get document '${docKey} from cache`\n );\n result.reject(firestoreError);\n }\n}\n\n/**\n * Retrieves a latency-compensated document from the backend via a\n * SnapshotListener.\n */\nfunction readDocumentViaSnapshotListener(\n eventManager: EventManager,\n asyncQueue: AsyncQueue,\n key: DocumentKey,\n options: GetOptions,\n result: Deferred<ViewSnapshot>\n): Promise<void> {\n const wrappedObserver = new AsyncObserver({\n next: (snap: ViewSnapshot) => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n asyncQueue.enqueueAndForget(() =>\n eventManagerUnlisten(eventManager, listener)\n );\n\n const exists = snap.docs.has(key);\n if (!exists && snap.fromCache) {\n // TODO(dimond): If we're online and the document doesn't\n // exist then we resolve with a doc.exists set to false. If\n // we're offline however, we reject the Promise in this\n // case. Two options: 1) Cache the negative response from\n // the server so we can deliver that even when you're\n // offline 2) Actually reject the Promise in the online case\n // if the document doesn't exist.\n result.reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document because the client is offline.'\n )\n );\n } else if (\n exists &&\n snap.fromCache &&\n options &&\n options.source === 'server'\n ) {\n result.reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document from server. (However, this ' +\n 'document does exist in the local cache. Run again ' +\n 'without setting source to \"server\" to ' +\n 'retrieve the cached document.)'\n )\n );\n } else {\n debugAssert(\n snap.docs.size <= 1,\n 'Expected zero or a single result on a document-only query'\n );\n result.resolve(snap);\n }\n },\n error: e => result.reject(e)\n });\n\n const listener = new QueryListener(\n newQueryForPath(key.path),\n wrappedObserver,\n {\n includeMetadataChanges: true,\n waitForSyncWhenOnline: true\n }\n );\n return eventManagerListen(eventManager, listener);\n}\n\nasync function executeQueryFromCache(\n localStore: LocalStore,\n query: Query,\n result: Deferred<ViewSnapshot>\n): Promise<void> {\n try {\n const queryResult = await localStoreExecuteQuery(\n localStore,\n query,\n /* usePreviousResults= */ true\n );\n const view = new View(query, queryResult.remoteKeys);\n const viewDocChanges = view.computeDocChanges(queryResult.documents);\n const viewChange = view.applyChanges(\n viewDocChanges,\n /* updateLimboDocuments= */ false\n );\n result.resolve(viewChange.snapshot!);\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to execute query '${query} against cache`\n );\n result.reject(firestoreError);\n }\n}\n\n/**\n * Retrieves a latency-compensated query snapshot from the backend via a\n * SnapshotListener.\n */\nfunction executeQueryViaSnapshotListener(\n eventManager: EventManager,\n asyncQueue: AsyncQueue,\n query: Query,\n options: GetOptions,\n result: Deferred<ViewSnapshot>\n): Promise<void> {\n const wrappedObserver = new AsyncObserver<ViewSnapshot>({\n next: snapshot => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n asyncQueue.enqueueAndForget(() =>\n eventManagerUnlisten(eventManager, listener)\n );\n\n if (snapshot.fromCache && options.source === 'server') {\n result.reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get documents from server. (However, these ' +\n 'documents may exist in the local cache. Run again ' +\n 'without setting source to \"server\" to ' +\n 'retrieve the cached documents.)'\n )\n );\n } else {\n result.resolve(snapshot);\n }\n },\n error: e => result.reject(e)\n });\n\n const listener = new QueryListener(query, wrappedObserver, {\n includeMetadataChanges: true,\n waitForSyncWhenOnline: true\n });\n return eventManagerListen(eventManager, listener);\n}\n\nexport function firestoreClientLoadBundle(\n client: FirestoreClient,\n databaseId: DatabaseId,\n data: ReadableStream<Uint8Array> | ArrayBuffer | string,\n resultTask: LoadBundleTask\n): void {\n const reader = createBundleReader(data, newSerializer(databaseId));\n client.asyncQueue.enqueueAndForget(async () => {\n syncEngineLoadBundle(await getSyncEngine(client), reader, resultTask);\n });\n}\n\nexport function firestoreClientGetNamedQuery(\n client: FirestoreClient,\n queryName: string\n): Promise<NamedQuery | undefined> {\n return client.asyncQueue.enqueue(async () =>\n localStoreGetNamedQuery(await getLocalStore(client), queryName)\n );\n}\n\nfunction createBundleReader(\n data: ReadableStream<Uint8Array> | ArrayBuffer | string,\n serializer: JsonProtoSerializer\n): BundleReader {\n let content: ReadableStream<Uint8Array> | ArrayBuffer;\n if (typeof data === 'string') {\n content = newTextEncoder().encode(data);\n } else {\n content = data;\n }\n return newBundleReader(toByteStreamReader(content), serializer);\n}\n\nexport function firestoreClientSetIndexConfiguration(\n client: FirestoreClient,\n indexes: FieldIndex[]\n): Promise<void> {\n return client.asyncQueue.enqueue(async () => {\n return localStoreConfigureFieldIndexes(\n await getLocalStore(client),\n indexes\n );\n });\n}\n\nexport function firestoreClientSetPersistentCacheIndexAutoCreationEnabled(\n client: FirestoreClient,\n isEnabled: boolean\n): Promise<void> {\n return client.asyncQueue.enqueue(async () => {\n return localStoreSetIndexAutoCreationEnabled(\n await getLocalStore(client),\n isEnabled\n );\n });\n}\n\nexport function firestoreClientDeleteAllFieldIndexes(\n client: FirestoreClient\n): Promise<void> {\n return client.asyncQueue.enqueue(async () => {\n return localStoreDeleteAllFieldIndexes(await getLocalStore(client));\n });\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Options that configure the SDK’s underlying network transport (WebChannel)\n * when long-polling is used.\n *\n * Note: This interface is \"experimental\" and is subject to change.\n *\n * See `FirestoreSettings.experimentalAutoDetectLongPolling`,\n * `FirestoreSettings.experimentalForceLongPolling`, and\n * `FirestoreSettings.experimentalLongPollingOptions`.\n */\nexport interface ExperimentalLongPollingOptions {\n /**\n * The desired maximum timeout interval, in seconds, to complete a\n * long-polling GET response. Valid values are between 5 and 30, inclusive.\n * Floating point values are allowed and will be rounded to the nearest\n * millisecond.\n *\n * By default, when long-polling is used the \"hanging GET\" request sent by\n * the client times out after 30 seconds. To request a different timeout\n * from the server, set this setting with the desired timeout.\n *\n * Changing the default timeout may be useful, for example, if the buffering\n * proxy that necessitated enabling long-polling in the first place has a\n * shorter timeout for hanging GET requests, in which case setting the\n * long-polling timeout to a shorter value, such as 25 seconds, may fix\n * prematurely-closed hanging GET requests.\n * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987.\n */\n timeoutSeconds?: number;\n}\n\n/**\n * Compares two `ExperimentalLongPollingOptions` objects for equality.\n */\nexport function longPollingOptionsEqual(\n options1: ExperimentalLongPollingOptions,\n options2: ExperimentalLongPollingOptions\n): boolean {\n return options1.timeoutSeconds === options2.timeoutSeconds;\n}\n\n/**\n * Creates and returns a new `ExperimentalLongPollingOptions` with the same\n * option values as the given instance.\n */\nexport function cloneLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): ExperimentalLongPollingOptions {\n const clone: ExperimentalLongPollingOptions = {};\n\n if (options.timeoutSeconds !== undefined) {\n clone.timeoutSeconds = options.timeoutSeconds;\n }\n\n return clone;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { _FirebaseService } from '@firebase/app';\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { cloneLongPollingOptions } from '../api/long_polling_options';\nimport { User } from '../auth/user';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { newConnection } from '../platform/connection';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { FirestoreSettingsImpl } from './settings';\n\nexport const LOG_TAG = 'ComponentProvider';\n\n// The components module manages the lifetime of dependencies of the Firestore\n// client. Dependencies can be lazily constructed and only one exists per\n// Firestore instance.\n\n/**\n * An interface implemented by FirebaseFirestore that provides compatibility\n * with the usage in this file.\n *\n * This interface mainly exists to remove a cyclic dependency.\n */\nexport interface FirestoreService extends _FirebaseService {\n _authCredentials: CredentialsProvider<User>;\n _appCheckCredentials: CredentialsProvider<string>;\n _persistenceKey: string;\n _databaseId: DatabaseId;\n _terminated: boolean;\n\n _freezeSettings(): FirestoreSettingsImpl;\n}\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\nconst datastoreInstances = new Map<FirestoreService, Datastore>();\n\n/**\n * Returns an initialized and started Datastore for the given Firestore\n * instance. Callers must invoke removeComponents() when the Firestore\n * instance is terminated.\n */\nexport function getDatastore(firestore: FirestoreService): Datastore {\n if (firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n if (!datastoreInstances.has(firestore)) {\n logDebug(LOG_TAG, 'Initializing Datastore');\n const databaseInfo = makeDatabaseInfo(\n firestore._databaseId,\n firestore.app.options.appId || '',\n firestore._persistenceKey,\n firestore._freezeSettings()\n );\n const connection = newConnection(databaseInfo);\n const serializer = newSerializer(firestore._databaseId);\n const datastore = newDatastore(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n connection,\n serializer\n );\n\n datastoreInstances.set(firestore, datastore);\n }\n return datastoreInstances.get(firestore)!;\n}\n\n/**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\nexport function removeComponents(firestore: FirestoreService): void {\n const datastore = datastoreInstances.get(firestore);\n if (datastore) {\n logDebug(LOG_TAG, 'Removing Datastore');\n datastoreInstances.delete(firestore);\n datastore.terminate();\n }\n}\n\nexport function makeDatabaseInfo(\n databaseId: DatabaseId,\n appId: string,\n persistenceKey: string,\n settings: FirestoreSettingsImpl\n): DatabaseInfo {\n return new DatabaseInfo(\n databaseId,\n appId,\n persistenceKey,\n settings.host,\n settings.ssl,\n settings.experimentalForceLongPolling,\n settings.experimentalAutoDetectLongPolling,\n cloneLongPollingOptions(settings.experimentalLongPollingOptions),\n settings.useFetchStreams\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\n\nimport { fail } from './assert';\nimport { Code, FirestoreError } from './error';\n\n/** Types accepted by validateType() and related methods for validation. */\nexport type ValidationType =\n | 'undefined'\n | 'object'\n | 'function'\n | 'boolean'\n | 'number'\n | 'string'\n | 'non-empty string';\n\nexport function validateNonEmptyArgument(\n functionName: string,\n argumentName: string,\n argument?: string\n): asserts argument is string {\n if (!argument) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() cannot be called with an empty ${argumentName}.`\n );\n }\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */\nexport function validateIsNotUsedTogether(\n optionName1: string,\n argument1: boolean | undefined,\n optionName2: string,\n argument2: boolean | undefined\n): void {\n if (argument1 === true && argument2 === true) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `${optionName1} and ${optionName2} cannot be used together.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */\nexport function validateDocumentPath(path: ResourcePath): void {\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */\nexport function validateCollectionPath(path: ResourcePath): void {\n if (DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nexport function isPlainObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n (Object.getPrototypeOf(input) === Object.prototype ||\n Object.getPrototypeOf(input) === null)\n );\n}\n\n/** Returns a string describing the type / value of the provided input. */\nexport function valueDescription(input: unknown): string {\n if (input === undefined) {\n return 'undefined';\n } else if (input === null) {\n return 'null';\n } else if (typeof input === 'string') {\n if (input.length > 20) {\n input = `${input.substring(0, 20)}...`;\n }\n return JSON.stringify(input);\n } else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n } else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n } else {\n const customObjectName = tryGetCustomObjectType(input!);\n if (customObjectName) {\n return `a custom ${customObjectName} object`;\n } else {\n return 'an object';\n }\n }\n } else if (typeof input === 'function') {\n return 'a function';\n } else {\n return fail('Unknown wrong type: ' + typeof input);\n }\n}\n\n/** try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input: object): string | null {\n if (input.constructor) {\n return input.constructor.name;\n }\n return null;\n}\n\n/**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */\nexport function cast<T>(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n if ('_delegate' in obj) {\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj = (obj as any)._delegate;\n }\n\n if (!(obj instanceof constructor)) {\n if (constructor.name === obj.constructor.name) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Type does not match the expected instance. Did you pass a ' +\n `reference from a different Firestore SDK?`\n );\n } else {\n const description = valueDescription(obj);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Expected type '${constructor.name}', but it was: ${description}`\n );\n }\n }\n return obj as T;\n}\n\nexport function validatePositiveNumber(functionName: string, n: number): void {\n if (n <= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires a positive number, but it was: ${n}.`\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreLocalCache } from '../api/cache_config';\nimport { CredentialsSettings } from '../api/credentials';\nimport {\n ExperimentalLongPollingOptions,\n cloneLongPollingOptions,\n longPollingOptionsEqual\n} from '../api/long_polling_options';\nimport {\n LRU_COLLECTION_DISABLED,\n LRU_DEFAULT_CACHE_SIZE_BYTES\n} from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { validateIsNotUsedTogether } from '../util/input_validation';\n\n// settings() defaults:\nexport const DEFAULT_HOST = 'firestore.googleapis.com';\nexport const DEFAULT_SSL = true;\n\n// The minimum long-polling timeout is hardcoded on the server. The value here\n// should be kept in sync with the value used by the server, as the server will\n// silently ignore a value below the minimum and fall back to the default.\n// Googlers see b/266868871 for relevant discussion.\nconst MIN_LONG_POLLING_TIMEOUT_SECONDS = 5;\n\n// No maximum long-polling timeout is configured in the server, and defaults to\n// 30 seconds, which is what Watch appears to use.\n// Googlers see b/266868871 for relevant discussion.\nconst MAX_LONG_POLLING_TIMEOUT_SECONDS = 30;\n\n// Whether long-polling auto-detected is enabled by default.\nconst DEFAULT_AUTO_DETECT_LONG_POLLING = true;\n\n/**\n * Specifies custom configurations for your Cloud Firestore instance.\n * You must set these before invoking any other methods.\n */\nexport interface FirestoreSettings {\n /** The hostname to connect to. */\n host?: string;\n\n /** Whether to use SSL when connecting. */\n ssl?: boolean;\n\n /**\n * Whether to skip nested properties that are set to `undefined` during\n * object serialization. If set to `true`, these properties are skipped\n * and not written to Firestore. If set to `false` or omitted, the SDK\n * throws an exception when it encounters properties of type `undefined`.\n */\n ignoreUndefinedProperties?: boolean;\n}\n\n/**\n * @internal\n * Undocumented, private additional settings not exposed in our public API.\n */\nexport interface PrivateSettings extends FirestoreSettings {\n // Can be a google-auth-library or gapi client.\n credentials?: CredentialsSettings;\n cacheSizeBytes?: number;\n experimentalForceLongPolling?: boolean;\n experimentalAutoDetectLongPolling?: boolean;\n experimentalLongPollingOptions?: ExperimentalLongPollingOptions;\n useFetchStreams?: boolean;\n\n localCache?: FirestoreLocalCache;\n}\n\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nexport class FirestoreSettingsImpl {\n /** The hostname to connect to. */\n readonly host: string;\n\n /** Whether to use SSL when connecting. */\n readonly ssl: boolean;\n\n readonly cacheSizeBytes: number;\n\n readonly experimentalForceLongPolling: boolean;\n\n readonly experimentalAutoDetectLongPolling: boolean;\n\n readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions;\n\n readonly ignoreUndefinedProperties: boolean;\n\n readonly useFetchStreams: boolean;\n readonly localCache?: FirestoreLocalCache;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '../api';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport {\n ActiveTargets,\n GC_DID_NOT_RUN,\n LRU_COLLECTION_DISABLED,\n LruDelegate,\n LruGarbageCollector,\n LruParams,\n LruResults\n} from './lru_garbage_collector';\nimport { Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'LruGarbageCollector';\n\nexport const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\n\nfunction bufferEntryComparator(\n [aSequence, aIndex]: BufferEntry,\n [bSequence, bIndex]: BufferEntry\n): number {\n const seqCmp = primitiveComparator(aSequence, bSequence);\n if (seqCmp === 0) {\n // This order doesn't matter, but we can bias against churn by sorting\n // entries created earlier as less than newer entries.\n return primitiveComparator(aIndex, bIndex);\n } else {\n return seqCmp;\n }\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */\nclass RollingSequenceNumberBuffer {\n private buffer: SortedSet<BufferEntry> = new SortedSet<BufferEntry>(\n bufferEntryComparator\n );\n\n private previousIndex = 0;\n\n constructor(private readonly maxElements: number) {}\n\n private nextIndex(): number {\n return ++this.previousIndex;\n }\n\n addElement(sequenceNumber: ListenSequenceNumber): void {\n const entry: BufferEntry = [sequenceNumber, this.nextIndex()];\n if (this.buffer.size < this.maxElements) {\n this.buffer = this.buffer.add(entry);\n } else {\n const highestValue = this.buffer.last()!;\n if (bufferEntryComparator(entry, highestValue) < 0) {\n this.buffer = this.buffer.delete(highestValue).add(entry);\n }\n }\n }\n\n get maxValue(): ListenSequenceNumber {\n // Guaranteed to be non-empty. If we decide we are not collecting any\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\n // decided that we are collecting n sequence numbers, it's because n is some\n // percentage of the existing sequence numbers. That means we should never\n // be in a situation where we are collecting sequence numbers but don't\n // actually have any.\n return this.buffer.last()![0];\n }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */\nexport class LruScheduler implements Scheduler {\n private gcTask: DelayedOperation<void> | null;\n\n constructor(\n private readonly garbageCollector: LruGarbageCollector,\n private readonly asyncQueue: AsyncQueue,\n private readonly localStore: LocalStore\n ) {\n this.gcTask = null;\n }\n\n start(): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot start an already started LruScheduler'\n );\n if (\n this.garbageCollector.params.cacheSizeCollectionThreshold !==\n LRU_COLLECTION_DISABLED\n ) {\n this.scheduleGC(INITIAL_GC_DELAY_MS);\n }\n }\n\n stop(): void {\n if (this.gcTask) {\n this.gcTask.cancel();\n this.gcTask = null;\n }\n }\n\n get started(): boolean {\n return this.gcTask !== null;\n }\n\n private scheduleGC(delay: number): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot schedule GC while a task is pending'\n );\n logDebug(LOG_TAG, `Garbage collection scheduled in ${delay}ms`);\n this.gcTask = this.asyncQueue.enqueueAfterDelay(\n TimerId.LruGarbageCollection,\n delay,\n async () => {\n this.gcTask = null;\n try {\n await this.localStore.collectGarbage(this.garbageCollector);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during garbage collection: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.scheduleGC(REGULAR_GC_DELAY_MS);\n }\n );\n }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */\nclass LruGarbageCollectorImpl implements LruGarbageCollector {\n constructor(\n private readonly delegate: LruDelegate,\n readonly params: LruParams\n ) {}\n\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise<number> {\n return this.delegate.getSequenceNumberCount(txn).next(targetCount => {\n return Math.floor((percentile / 100.0) * targetCount);\n });\n }\n\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise<ListenSequenceNumber> {\n if (n === 0) {\n return PersistencePromise.resolve(ListenSequence.INVALID);\n }\n\n const buffer = new RollingSequenceNumberBuffer(n);\n return this.delegate\n .forEachTarget(txn, target => buffer.addElement(target.sequenceNumber))\n .next(() => {\n return this.delegate.forEachOrphanedDocumentSequenceNumber(\n txn,\n sequenceNumber => buffer.addElement(sequenceNumber)\n );\n })\n .next(() => buffer.maxValue);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number> {\n return this.delegate.removeOrphanedDocuments(txn, upperBound);\n }\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<LruResults> {\n if (this.params.cacheSizeCollectionThreshold === LRU_COLLECTION_DISABLED) {\n logDebug('LruGarbageCollector', 'Garbage collection skipped; disabled');\n return PersistencePromise.resolve(GC_DID_NOT_RUN);\n }\n\n return this.getCacheSize(txn).next(cacheSize => {\n if (cacheSize < this.params.cacheSizeCollectionThreshold) {\n logDebug(\n 'LruGarbageCollector',\n `Garbage collection skipped; Cache size ${cacheSize} ` +\n `is lower than threshold ${this.params.cacheSizeCollectionThreshold}`\n );\n return GC_DID_NOT_RUN;\n } else {\n return this.runGarbageCollection(txn, activeTargetIds);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return this.delegate.getCacheSize(txn);\n }\n\n private runGarbageCollection(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<LruResults> {\n let upperBoundSequenceNumber: number;\n let sequenceNumbersToCollect: number, targetsRemoved: number;\n // Timestamps for various pieces of the process\n let countedTargetsTs: number,\n foundUpperBoundTs: number,\n removedTargetsTs: number,\n removedDocumentsTs: number;\n const startTs = Date.now();\n return this.calculateTargetCount(txn, this.params.percentileToCollect)\n .next(sequenceNumbers => {\n // Cap at the configured max\n if (sequenceNumbers > this.params.maximumSequenceNumbersToCollect) {\n logDebug(\n 'LruGarbageCollector',\n 'Capping sequence numbers to collect down ' +\n `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` +\n `from ${sequenceNumbers}`\n );\n sequenceNumbersToCollect =\n this.params.maximumSequenceNumbersToCollect;\n } else {\n sequenceNumbersToCollect = sequenceNumbers;\n }\n countedTargetsTs = Date.now();\n\n return this.nthSequenceNumber(txn, sequenceNumbersToCollect);\n })\n .next(upperBound => {\n upperBoundSequenceNumber = upperBound;\n foundUpperBoundTs = Date.now();\n\n return this.removeTargets(\n txn,\n upperBoundSequenceNumber,\n activeTargetIds\n );\n })\n .next(numTargetsRemoved => {\n targetsRemoved = numTargetsRemoved;\n removedTargetsTs = Date.now();\n\n return this.removeOrphanedDocuments(txn, upperBoundSequenceNumber);\n })\n .next(documentsRemoved => {\n removedDocumentsTs = Date.now();\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n const desc =\n 'LRU Garbage Collection\\n' +\n `\\tCounted targets in ${countedTargetsTs - startTs}ms\\n` +\n `\\tDetermined least recently used ${sequenceNumbersToCollect} in ` +\n `${foundUpperBoundTs - countedTargetsTs}ms\\n` +\n `\\tRemoved ${targetsRemoved} targets in ` +\n `${removedTargetsTs - foundUpperBoundTs}ms\\n` +\n `\\tRemoved ${documentsRemoved} documents in ` +\n `${removedDocumentsTs - removedTargetsTs}ms\\n` +\n `Total Duration: ${removedDocumentsTs - startTs}ms`;\n logDebug('LruGarbageCollector', desc);\n }\n\n return PersistencePromise.resolve<LruResults>({\n didRun: true,\n sequenceNumbersCollected: sequenceNumbersToCollect,\n targetsRemoved,\n documentsRemoved\n });\n });\n }\n}\n\nexport function newLruGarbageCollector(\n delegate: LruDelegate,\n params: LruParams\n): LruGarbageCollector {\n return new LruGarbageCollectorImpl(delegate, params);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort\n} from '@firebase/util';\n\nimport {\n CredentialsProvider,\n EmulatorAuthCredentialsProvider,\n makeAuthCredentialsProvider,\n OAuthToken\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { FirestoreService, removeComponents } from './components';\nimport {\n DEFAULT_HOST,\n FirestoreSettingsImpl,\n PrivateSettings,\n FirestoreSettings\n} from './settings';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore implements FirestoreService {\n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n type: 'firestore-lite' | 'firestore' = 'firestore-lite';\n\n readonly _persistenceKey: string = '(lite)';\n\n private _settings = new FirestoreSettingsImpl({});\n private _settingsFrozen = false;\n\n // A task that is assigned when the terminate() is invoked and resolved when\n // all components have shut down.\n private _terminateTask?: Promise<void>;\n\n /** @hideconstructor */\n constructor(\n public _authCredentials: CredentialsProvider<User>,\n public _appCheckCredentials: CredentialsProvider<string>,\n readonly _databaseId: DatabaseId,\n readonly _app?: FirebaseApp\n ) {}\n\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */\n get app(): FirebaseApp {\n if (!this._app) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available'\n );\n }\n return this._app;\n }\n\n get _initialized(): boolean {\n return this._settingsFrozen;\n }\n\n get _terminated(): boolean {\n return this._terminateTask !== undefined;\n }\n\n _setSettings(settings: PrivateSettings): void {\n if (this._settingsFrozen) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only modify settings before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\n this._settings = new FirestoreSettingsImpl(settings);\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _freezeSettings(): FirestoreSettingsImpl {\n this._settingsFrozen = true;\n return this._settings;\n }\n\n _delete(): Promise<void> {\n if (!this._terminateTask) {\n this._terminateTask = this._terminate();\n }\n return this._terminateTask;\n }\n\n /** Returns a JSON-serializable representation of this `Firestore` instance. */\n toJSON(): object {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\n }\n\n /**\n * Terminates all components used by this client. Subclasses can override\n * this method to clean up their own dependencies, but must also call this\n * method.\n *\n * Only ever called once.\n */\n protected _terminate(): Promise<void> {\n removeComponents(this);\n return Promise.resolve();\n }\n}\n\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @returns A newly initialized `Firestore` instance.\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings\n): Firestore;\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized `Firestore` instance.\n * @beta\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore;\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore {\n if (!databaseId) {\n databaseId = DEFAULT_DATABASE_NAME;\n }\n const provider = _getProvider(app, 'firestore/lite');\n\n if (provider.isInitialized(databaseId)) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore can only be initialized once per app.'\n );\n }\n\n return provider.initialize({\n options: settings,\n instanceIdentifier: databaseId\n });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n appOrDatabaseId?: FirebaseApp | string,\n optionalDatabaseId?: string\n): Firestore {\n const app: FirebaseApp =\n typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n const databaseId =\n typeof appOrDatabaseId === 'string'\n ? appOrDatabaseId\n : optionalDatabaseId || '(default)';\n const db = _getProvider(app, 'firestore/lite').getImmediate({\n identifier: databaseId\n }) as Firestore;\n if (!db._initialized) {\n const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n if (emulator) {\n connectFirestoreEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */\nexport function connectFirestoreEmulator(\n firestore: Firestore,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n firestore = cast(firestore, Firestore);\n const settings = firestore._getSettings();\n const newHostSetting = `${host}:${port}`;\n\n if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) {\n logWarn(\n 'Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' +\n 'will be used.'\n );\n }\n\n firestore._setSettings({\n ...settings,\n host: newHostSetting,\n ssl: false\n });\n\n if (options.mockUserToken) {\n let token: string;\n let user: User;\n if (typeof options.mockUserToken === 'string') {\n token = options.mockUserToken;\n user = User.MOCK_USER;\n } else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n token = createMockUserToken(\n options.mockUserToken,\n firestore._app?.options.projectId\n );\n const uid = options.mockUserToken.sub || options.mockUserToken.user_id;\n if (!uid) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"mockUserToken must contain 'sub' or 'user_id' field!\"\n );\n }\n user = new User(uid);\n }\n\n firestore._authCredentials = new EmulatorAuthCredentialsProvider(\n new OAuthToken(token, user)\n );\n }\n}\n\n/**\n * Terminates the provided `Firestore` instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` functions\n * may be used. Any other function will throw a `FirestoreError`. Termination\n * does not cancel any pending writes, and any promises that are awaiting a\n * response from the server will not be resolved.\n *\n * To restart after termination, create a new instance of `Firestore` with\n * {@link (getFirestore:1)}.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all of\n * its resources or in combination with {@link clearIndexedDbPersistence} to\n * ensure that all local state is destroyed between test runs.\n *\n * @param firestore - The `Firestore` instance to terminate.\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise<void> {\n firestore = cast(firestore, Firestore);\n _removeServiceInstance(firestore.app, 'firestore/lite');\n return firestore._delete();\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64urlEncodeWithoutPadding } from './crypt';\n\n// Firebase Auth tokens contain snake_case claims following the JWT standard / convention.\n/* eslint-disable camelcase */\n\nexport type FirebaseSignInProvider =\n | 'custom'\n | 'email'\n | 'password'\n | 'phone'\n | 'anonymous'\n | 'google.com'\n | 'facebook.com'\n | 'github.com'\n | 'twitter.com'\n | 'microsoft.com'\n | 'apple.com';\n\ninterface FirebaseIdToken {\n // Always set to https://securetoken.google.com/PROJECT_ID\n iss: string;\n\n // Always set to PROJECT_ID\n aud: string;\n\n // The user's unique ID\n sub: string;\n\n // The token issue time, in seconds since epoch\n iat: number;\n\n // The token expiry time, normally 'iat' + 3600\n exp: number;\n\n // The user's unique ID. Must be equal to 'sub'\n user_id: string;\n\n // The time the user authenticated, normally 'iat'\n auth_time: number;\n\n // The sign in provider, only set when the provider is 'anonymous'\n provider_id?: 'anonymous';\n\n // The user's primary email\n email?: string;\n\n // The user's email verification status\n email_verified?: boolean;\n\n // The user's primary phone number\n phone_number?: string;\n\n // The user's display name\n name?: string;\n\n // The user's profile photo URL\n picture?: string;\n\n // Information on all identities linked to this user\n firebase: {\n // The primary sign-in provider\n sign_in_provider: FirebaseSignInProvider;\n\n // A map of providers to the user's list of unique identifiers from\n // each provider\n identities?: { [provider in FirebaseSignInProvider]?: string[] };\n };\n\n // Custom claims set by the developer\n [claim: string]: unknown;\n\n uid?: never; // Try to catch a common mistake of \"uid\" (should be \"sub\" instead).\n}\n\nexport type EmulatorMockTokenOptions = ({ user_id: string } | { sub: string }) &\n Partial<FirebaseIdToken>;\n\nexport function createMockUserToken(\n token: EmulatorMockTokenOptions,\n projectId?: string\n): string {\n if (token.uid) {\n throw new Error(\n 'The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.'\n );\n }\n // Unsecured JWTs use \"none\" as the algorithm.\n const header = {\n alg: 'none',\n type: 'JWT'\n };\n\n const project = projectId || 'demo-project';\n const iat = token.iat || 0;\n const sub = token.sub || token.user_id;\n if (!sub) {\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\n }\n\n const payload: FirebaseIdToken = {\n // Set all required fields to decent defaults\n iss: `https://securetoken.google.com/${project}`,\n aud: project,\n iat,\n exp: iat + 3600,\n auth_time: iat,\n sub,\n user_id: sub,\n firebase: {\n sign_in_provider: 'custom',\n identities: {}\n },\n\n // Override with user options\n ...token\n };\n\n // Unsecured JWTs use the empty string as a signature.\n const signature = '';\n return [\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\n signature\n ].join('.');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport {\n newQueryForCollectionGroup,\n newQueryForPath,\n Query as InternalQuery,\n queryEquals\n} from '../core/query';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n cast,\n validateCollectionPath,\n validateDocumentPath,\n validateNonEmptyArgument\n} from '../util/input_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { FirestoreDataConverter } from './snapshot';\nimport { NestedUpdateFields, Primitive } from './types';\n\n/**\n * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to\n * values.\n */\nexport interface DocumentData {\n /** A mapping between a field and its value. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [field: string]: any;\n}\n\n/**\n * Similar to Typescript's `Partial<T>`, but allows nested fields to be\n * omitted and FieldValues to be passed in as property values.\n */\nexport type PartialWithFieldValue<T> =\n | Partial<T>\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: PartialWithFieldValue<T[K]> | FieldValue }\n : never);\n\n/**\n * Allows FieldValues to be passed in as a property value while maintaining\n * type safety.\n */\nexport type WithFieldValue<T> =\n | T\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]: WithFieldValue<T[K]> | FieldValue }\n : never);\n\n/**\n * Update data (for use with {@link (updateDoc:1)}) that consists of field paths\n * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots\n * reference nested fields within the document. FieldValues can be passed in\n * as property values.\n */\nexport type UpdateData<T> = T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: UpdateData<T[K]> | FieldValue } & NestedUpdateFields<T>\n : Partial<T>;\n/**\n * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link\n * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be\n * configured to perform granular merges instead of overwriting the target\n * documents in their entirety by providing a `SetOptions` with `merge: true`.\n *\n * @param merge - Changes the behavior of a `setDoc()` call to only replace the\n * values specified in its data argument. Fields omitted from the `setDoc()`\n * call remain untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace\n * the specified field paths. Any field path that is not specified is ignored\n * and remains untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n */\nexport type SetOptions =\n | {\n readonly merge?: boolean;\n }\n | {\n readonly mergeFields?: Array<string | FieldPath>;\n };\n\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */\nexport class Query<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type: 'query' | 'collection' = 'query';\n\n /**\n * The `Firestore` instance for the Firestore database (useful for performing\n * transactions, etc.).\n */\n readonly firestore: Firestore;\n\n // This is the lite version of the Query class in the main SDK.\n\n /** @hideconstructor protected */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _query: InternalQuery\n ) {\n this.firestore = firestore;\n }\n\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `Query<DocumentData, DocumentData>` that does not use a\n * converter.\n */\n withConverter(converter: null): Query<DocumentData, DocumentData>;\n /**\n * Applies a custom data converter to this query, allowing you to use your own\n * custom model objects with Firestore. When you call {@link getDocs} with\n * the returned query, the provided converter will convert between Firestore\n * data of type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `Query` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n ): Query<NewAppModelType, NewDbModelType>;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n ): Query<NewAppModelType, NewDbModelType> {\n return new Query<NewAppModelType, NewDbModelType>(\n this.firestore,\n converter,\n this._query\n );\n }\n}\n\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */\nexport class DocumentReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type = 'document';\n\n /**\n * The {@link Firestore} instance the document is in.\n * This is useful for performing transactions, for example.\n */\n readonly firestore: Firestore;\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _key: DocumentKey\n ) {\n this.firestore = firestore;\n }\n\n get _path(): ResourcePath {\n return this._key.path;\n }\n\n /**\n * The document's identifier within its collection.\n */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */\n get path(): string {\n return this._key.path.canonicalString();\n }\n\n /**\n * The collection this `DocumentReference` belongs to.\n */\n get parent(): CollectionReference<AppModelType, DbModelType> {\n return new CollectionReference<AppModelType, DbModelType>(\n this.firestore,\n this.converter,\n this._key.path.popLast()\n );\n }\n\n /**\n * Applies a custom data converter to this `DocumentReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`\n * instance, the provided converter will convert between Firestore data of\n * type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `DocumentReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n ): DocumentReference<NewAppModelType, NewDbModelType>;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `DocumentReference<DocumentData, DocumentData>` that does not\n * use a converter.\n */\n withConverter(converter: null): DocumentReference<DocumentData, DocumentData>;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n ): DocumentReference<NewAppModelType, NewDbModelType> {\n return new DocumentReference<NewAppModelType, NewDbModelType>(\n this.firestore,\n converter,\n this._key\n );\n }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link (query:1)}).\n */\nexport class CollectionReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends Query<AppModelType, DbModelType> {\n /** The type of this Firestore reference. */\n readonly type = 'collection';\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n converter: FirestoreDataConverter<AppModelType, DbModelType> | null,\n readonly _path: ResourcePath\n ) {\n super(firestore, converter, newQueryForPath(_path));\n }\n\n /** The collection's identifier. */\n get id(): string {\n return this._query.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */\n get path(): string {\n return this._query.path.canonicalString();\n }\n\n /**\n * A reference to the containing `DocumentReference` if this is a\n * subcollection. If this isn't a subcollection, the reference is null.\n */\n get parent(): DocumentReference<DocumentData, DocumentData> | null {\n const parentPath = this._path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n } else {\n return new DocumentReference(\n this.firestore,\n /* converter= */ null,\n new DocumentKey(parentPath)\n );\n }\n }\n\n /**\n * Applies a custom data converter to this `CollectionReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * addDoc} with the returned `CollectionReference` instance, the provided\n * converter will convert between Firestore data of type `NewDbModelType` and\n * your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `CollectionReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n ): CollectionReference<NewAppModelType, NewDbModelType>;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `CollectionReference<DocumentData, DocumentData>` that does not\n * use a converter.\n */\n withConverter(\n converter: null\n ): CollectionReference<DocumentData, DocumentData>;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n ): CollectionReference<NewAppModelType, NewDbModelType> {\n return new CollectionReference<NewAppModelType, NewDbModelType>(\n this.firestore,\n converter,\n this._path\n );\n }\n}\n\n/**\n * Gets a `CollectionReference` instance that refers to the collection at\n * the specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the the specified relative path.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n reference: CollectionReference<AppModelType, DbModelType>,\n path: string,\n ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n path: string,\n ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n parent:\n | Firestore\n | DocumentReference<AppModelType, DbModelType>\n | CollectionReference<AppModelType, DbModelType>,\n path: string,\n ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData> {\n parent = getModularInstance(parent);\n\n validateNonEmptyArgument('collection', 'path', path);\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateCollectionPath(absolutePath);\n return new CollectionReference(parent, /* converter= */ null, absolutePath);\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateCollectionPath(absolutePath);\n return new CollectionReference(\n parent.firestore,\n /* converter= */ null,\n absolutePath\n );\n }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */\nexport function collectionGroup(\n firestore: Firestore,\n collectionId: string\n): Query<DocumentData, DocumentData> {\n firestore = cast(firestore, Firestore);\n\n validateNonEmptyArgument('collectionGroup', 'collection id', collectionId);\n if (collectionId.indexOf('/') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection ID '${collectionId}' passed to function ` +\n `collectionGroup(). Collection IDs must not contain '/'.`\n );\n }\n\n return new Query(\n firestore,\n /* converter= */ null,\n newQueryForCollectionGroup(collectionId)\n );\n}\n\n/**\n * Gets a `DocumentReference` instance that refers to the document at the\n * specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): DocumentReference<DocumentData, DocumentData>;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path. If no path is specified, an\n * automatically-generated unique ID will be used for the returned\n * `DocumentReference`.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a document. Has to be omitted to use\n * auto-genrated IDs.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc<AppModelType, DbModelType extends DocumentData>(\n reference: CollectionReference<AppModelType, DbModelType>,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference<AppModelType, DbModelType>;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n path: string,\n ...pathSegments: string[]\n): DocumentReference<DocumentData, DocumentData>;\nexport function doc<AppModelType, DbModelType extends DocumentData>(\n parent:\n | Firestore\n | CollectionReference<AppModelType, DbModelType>\n | DocumentReference<AppModelType, DbModelType>,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference<AppModelType, DbModelType> {\n parent = getModularInstance(parent);\n\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 1) {\n path = AutoId.newId();\n }\n validateNonEmptyArgument('doc', 'path', path);\n\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent,\n /* converter= */ null,\n new DocumentKey(absolutePath)\n );\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateDocumentPath(absolutePath);\n return new DocumentReference<AppModelType, DbModelType>(\n parent.firestore,\n parent instanceof CollectionReference ? parent.converter : null,\n new DocumentKey(absolutePath)\n );\n }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function refEqual<AppModelType, DbModelType extends DocumentData>(\n left:\n | DocumentReference<AppModelType, DbModelType>\n | CollectionReference<AppModelType, DbModelType>,\n right:\n | DocumentReference<AppModelType, DbModelType>\n | CollectionReference<AppModelType, DbModelType>\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (\n (left instanceof DocumentReference ||\n left instanceof CollectionReference) &&\n (right instanceof DocumentReference || right instanceof CollectionReference)\n ) {\n return (\n left.firestore === right.firestore &&\n left.path === right.path &&\n left.converter === right.converter\n );\n }\n return false;\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function queryEqual<AppModelType, DbModelType extends DocumentData>(\n left: Query<AppModelType, DbModelType>,\n right: Query<AppModelType, DbModelType>\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof Query && right instanceof Query) {\n return (\n left.firestore === right.firestore &&\n queryEquals(left._query, right._query) &&\n left.converter === right.converter\n );\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\nimport { getDocument } from '../platform/dom';\nimport { ExponentialBackoff } from '../remote/backoff';\n\nimport { debugAssert, fail } from './assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from './async_queue';\nimport { FirestoreError } from './error';\nimport { logDebug, logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\nexport class AsyncQueueImpl implements AsyncQueue {\n // The last promise in the queue.\n private tail: Promise<unknown> = Promise.resolve();\n\n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n private retryableOps: Array<() => Promise<void>> = [];\n\n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n private _isShuttingDown: boolean = false;\n\n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n private delayedOperations: Array<DelayedOperation<unknown>> = [];\n\n // visible for testing\n failure: FirestoreError | null = null;\n\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n private operationInProgress = false;\n\n // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n private skipNonRestrictedTasks = false;\n\n // List of TimerIds to fast-forward delays for.\n private timerIdsToSkip: TimerId[] = [];\n\n // Backoff timer used to schedule retries for retryable operations\n private backoff = new ExponentialBackoff(this, TimerId.AsyncQueueRetry);\n\n // Visibility handler that triggers an immediate retry of all retryable\n // operations. Meant to speed up recovery when we regain file system access\n // after page comes into foreground.\n private visibilityHandler: () => void = () => {\n const document = getDocument();\n if (document) {\n logDebug(\n LOG_TAG,\n 'Visibility state changed to ' + document.visibilityState\n );\n }\n this.backoff.skipBackoff();\n };\n\n constructor() {\n const document = getDocument();\n if (document && typeof document.addEventListener === 'function') {\n document.addEventListener('visibilitychange', this.visibilityHandler);\n }\n }\n\n get isShuttingDown(): boolean {\n return this._isShuttingDown;\n }\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget<T extends unknown>(op: () => Promise<T>): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(op);\n }\n\n enqueueAndForgetEvenWhileRestricted<T extends unknown>(\n op: () => Promise<T>\n ): void {\n this.verifyNotFailed();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueueInternal(op);\n }\n\n enterRestrictedMode(purgeExistingTasks?: boolean): void {\n if (!this._isShuttingDown) {\n this._isShuttingDown = true;\n this.skipNonRestrictedTasks = purgeExistingTasks || false;\n const document = getDocument();\n if (document && typeof document.removeEventListener === 'function') {\n document.removeEventListener(\n 'visibilitychange',\n this.visibilityHandler\n );\n }\n }\n }\n\n enqueue<T extends unknown>(op: () => Promise<T>): Promise<T> {\n this.verifyNotFailed();\n if (this._isShuttingDown) {\n // Return a Promise which never resolves.\n return new Promise<T>(() => {});\n }\n\n // Create a deferred Promise that we can return to the callee. This\n // allows us to return a \"hanging Promise\" only to the callee and still\n // advance the queue even when the operation is not run.\n const task = new Deferred<T>();\n return this.enqueueInternal<unknown>(() => {\n if (this._isShuttingDown && this.skipNonRestrictedTasks) {\n // We do not resolve 'task'\n return Promise.resolve();\n }\n\n op().then(task.resolve, task.reject);\n return task.promise;\n }).then(() => task.promise);\n }\n\n enqueueRetryable(op: () => Promise<void>): void {\n this.enqueueAndForget(() => {\n this.retryableOps.push(op);\n return this.retryNextOp();\n });\n }\n\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */\n private async retryNextOp(): Promise<void> {\n if (this.retryableOps.length === 0) {\n return;\n }\n\n try {\n await this.retryableOps[0]();\n this.retryableOps.shift();\n this.backoff.reset();\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e);\n } else {\n throw e; // Failure will be handled by AsyncQueue\n }\n }\n\n if (this.retryableOps.length > 0) {\n // If there are additional operations, we re-schedule `retryNextOp()`.\n // This is necessary to run retryable operations that failed during\n // their initial attempt since we don't know whether they are already\n // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n // needs to be re-run, we will run `op1`, `op1`, `op2` using the\n // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n // call scheduled here.\n // Since `backoffAndRun()` cancels an existing backoff and schedules a\n // new backoff on every call, there is only ever a single additional\n // operation in the queue.\n this.backoff.backoffAndRun(() => this.retryNextOp());\n }\n }\n\n private enqueueInternal<T extends unknown>(op: () => Promise<T>): Promise<T> {\n const newTail = this.tail.then(() => {\n this.operationInProgress = true;\n return op()\n .catch((error: FirestoreError) => {\n this.failure = error;\n this.operationInProgress = false;\n const message = getMessageOrStack(error);\n logError('INTERNAL UNHANDLED ERROR: ', message);\n\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw error;\n })\n .then(result => {\n this.operationInProgress = false;\n return result;\n });\n });\n this.tail = newTail;\n return newTail;\n }\n\n enqueueAfterDelay<T extends unknown>(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise<T>\n ): DelayedOperation<T> {\n this.verifyNotFailed();\n\n debugAssert(\n delayMs >= 0,\n `Attempted to schedule an operation with a negative delay of ${delayMs}`\n );\n\n // Fast-forward delays for timerIds that have been overriden.\n if (this.timerIdsToSkip.indexOf(timerId) > -1) {\n delayMs = 0;\n }\n\n const delayedOp = DelayedOperation.createAndSchedule<T>(\n this,\n timerId,\n delayMs,\n op,\n removedOp =>\n this.removeDelayedOperation(removedOp as DelayedOperation<unknown>)\n );\n this.delayedOperations.push(delayedOp as DelayedOperation<unknown>);\n return delayedOp;\n }\n\n private verifyNotFailed(): void {\n if (this.failure) {\n fail('AsyncQueue is already failed: ' + getMessageOrStack(this.failure));\n }\n }\n\n verifyOperationInProgress(): void {\n debugAssert(\n this.operationInProgress,\n 'verifyOpInProgress() called when no op in progress on this queue.'\n );\n }\n\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */\n async drain(): Promise<void> {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let currentTail: Promise<unknown>;\n do {\n currentTail = this.tail;\n await currentTail;\n } while (currentTail !== this.tail);\n }\n\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */\n containsDelayedOperation(timerId: TimerId): boolean {\n for (const op of this.delayedOperations) {\n if (op.timerId === timerId) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId - Delayed operations up to and including this TimerId\n * will be drained. Pass TimerId.All to run all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */\n runAllDelayedOperationsUntil(lastTimerId: TimerId): Promise<void> {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.drain().then(() => {\n // Run ops in the same order they'd run if they ran naturally.\n this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs);\n\n for (const op of this.delayedOperations) {\n op.skipDelay();\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\n break;\n }\n }\n\n return this.drain();\n });\n }\n\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */\n skipDelaysForTimerId(timerId: TimerId): void {\n this.timerIdsToSkip.push(timerId);\n }\n\n /** Called once a DelayedOperation is run or canceled. */\n private removeDelayedOperation(op: DelayedOperation<unknown>): void {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const index = this.delayedOperations.indexOf(op);\n debugAssert(index >= 0, 'Delayed operation not found.');\n this.delayedOperations.splice(index, 1);\n }\n}\n\nexport function newAsyncQueue(): AsyncQueue {\n return new AsyncQueueImpl();\n}\n\n/**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\nfunction getMessageOrStack(error: Error): string {\n let message = error.message || '';\n if (error.stack) {\n if (error.stack.includes(error.message)) {\n message = error.stack;\n } else {\n message = error.message + '\\n' + error.stack;\n }\n }\n return message;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport { deepEqual, getDefaultEmulatorHostnameAndPort } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport {\n IndexedDbOfflineComponentProvider,\n MultiTabOfflineComponentProvider,\n OfflineComponentProvider,\n OnlineComponentProvider\n} from '../core/component_provider';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport {\n canFallbackFromIndexedDbError,\n FirestoreClient,\n firestoreClientDisableNetwork,\n firestoreClientEnableNetwork,\n firestoreClientGetNamedQuery,\n firestoreClientLoadBundle,\n firestoreClientWaitForPendingWrites,\n setOfflineComponentProvider,\n setOnlineComponentProvider\n} from '../core/firestore_client';\nimport { makeDatabaseInfo } from '../lite-api/components';\nimport {\n Firestore as LiteFirestore,\n connectFirestoreEmulator\n} from '../lite-api/database';\nimport { Query } from '../lite-api/reference';\nimport {\n indexedDbClearPersistence,\n indexedDbStoragePrefix\n} from '../local/indexeddb_persistence';\nimport { LRU_COLLECTION_DISABLED } from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\nimport { Deferred } from '../util/promise';\n\nimport { LoadBundleTask } from './bundle';\nimport { CredentialsProvider } from './credentials';\nimport { PersistenceSettings, FirestoreSettings } from './settings';\nexport {\n connectFirestoreEmulator,\n EmulatorMockTokenOptions\n} from '../lite-api/database';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore': Firestore;\n }\n}\n\n/**\n * Constant used to indicate the LRU garbage collection should be disabled.\n * Set this value as the `cacheSizeBytes` on the settings passed to the\n * {@link Firestore} instance.\n */\nexport const CACHE_SIZE_UNLIMITED = LRU_COLLECTION_DISABLED;\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore extends LiteFirestore {\n /**\n * Whether it's a {@link Firestore} or Firestore Lite instance.\n */\n type: 'firestore-lite' | 'firestore' = 'firestore';\n\n readonly _queue: AsyncQueue = newAsyncQueue();\n readonly _persistenceKey: string;\n\n _firestoreClient: FirestoreClient | undefined;\n\n /** @hideconstructor */\n constructor(\n authCredentialsProvider: CredentialsProvider<User>,\n appCheckCredentialsProvider: CredentialsProvider<string>,\n databaseId: DatabaseId,\n app?: FirebaseApp\n ) {\n super(\n authCredentialsProvider,\n appCheckCredentialsProvider,\n databaseId,\n app\n );\n this._persistenceKey = app?.name || '[DEFAULT]';\n }\n\n _terminate(): Promise<void> {\n if (!this._firestoreClient) {\n // The client must be initialized to ensure that all subsequent API\n // usage throws an exception.\n configureFirestore(this);\n }\n return this._firestoreClient!.terminate();\n }\n}\n\n/**\n * Initializes a new instance of {@link Firestore} with the provided settings.\n * Can only be called before any other function, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will\n * be associated.\n * @param settings - A settings object to configure the {@link Firestore} instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized {@link Firestore} instance.\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore {\n if (!databaseId) {\n databaseId = DEFAULT_DATABASE_NAME;\n }\n const provider = _getProvider(app, 'firestore');\n\n if (provider.isInitialized(databaseId)) {\n const existingInstance = provider.getImmediate({\n identifier: databaseId\n });\n const initialSettings = provider.getOptions(\n databaseId\n ) as FirestoreSettings;\n if (deepEqual(initialSettings, settings)) {\n return existingInstance;\n } else {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'initializeFirestore() has already been called with ' +\n 'different options. To avoid this error, call initializeFirestore() with the ' +\n 'same options as when it was originally called, or call getFirestore() to return the' +\n ' already initialized instance.'\n );\n }\n }\n\n if (\n settings.cacheSizeBytes !== undefined &&\n settings.localCache !== undefined\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes will` +\n `be deprecated. Instead, specify the cache size in the cache object`\n );\n }\n\n if (\n settings.cacheSizeBytes !== undefined &&\n settings.cacheSizeBytes !== CACHE_SIZE_UNLIMITED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n }\n\n return provider.initialize({\n options: settings,\n instanceIdentifier: databaseId\n });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The default {@link Firestore} instance of the default app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The default {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing named {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The named {@link Firestore} instance of the default app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing named {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The named {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n appOrDatabaseId?: FirebaseApp | string,\n optionalDatabaseId?: string\n): Firestore {\n const app: FirebaseApp =\n typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n const databaseId =\n typeof appOrDatabaseId === 'string'\n ? appOrDatabaseId\n : optionalDatabaseId || DEFAULT_DATABASE_NAME;\n const db = _getProvider(app, 'firestore').getImmediate({\n identifier: databaseId\n }) as Firestore;\n if (!db._initialized) {\n const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n if (emulator) {\n connectFirestoreEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * @internal\n */\nexport function ensureFirestoreConfigured(\n firestore: Firestore\n): FirestoreClient {\n if (!firestore._firestoreClient) {\n configureFirestore(firestore);\n }\n firestore._firestoreClient!.verifyNotTerminated();\n return firestore._firestoreClient as FirestoreClient;\n}\n\nexport function configureFirestore(firestore: Firestore): void {\n const settings = firestore._freezeSettings();\n debugAssert(!!settings.host, 'FirestoreSettings.host is not set');\n debugAssert(\n !firestore._firestoreClient,\n 'configureFirestore() called multiple times'\n );\n\n const databaseInfo = makeDatabaseInfo(\n firestore._databaseId,\n firestore._app?.options.appId || '',\n firestore._persistenceKey,\n settings\n );\n firestore._firestoreClient = new FirestoreClient(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n firestore._queue,\n databaseInfo\n );\n if (\n settings.localCache?._offlineComponentProvider &&\n settings.localCache?._onlineComponentProvider\n ) {\n firestore._firestoreClient._uninitializedComponentsProvider = {\n _offlineKind: settings.localCache.kind,\n _offline: settings.localCache._offlineComponentProvider,\n _online: settings.localCache._onlineComponentProvider\n };\n }\n}\n\n/**\n * Attempts to enable persistent storage, if possible.\n *\n * Must be called before any other functions (other than\n * {@link initializeFirestore}, {@link (getFirestore:1)} or\n * {@link clearIndexedDbPersistence}.\n *\n * If this fails, `enableIndexedDbPersistence()` will reject the promise it\n * returns. Note that even after this failure, the {@link Firestore} instance will\n * remain usable, however offline persistence will be disabled.\n *\n * There are several reasons why this can fail, which can be identified by\n * the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab.\n * * unimplemented: The browser is incompatible with the offline\n * persistence implementation.\n *\n * Persistence cannot be used in a Node.js environment.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @param persistenceSettings - Optional settings object to configure\n * persistence.\n * @returns A `Promise` that represents successfully enabling persistent storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to\n * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache`\n * is already specified will throw an exception.\n */\nexport function enableIndexedDbPersistence(\n firestore: Firestore,\n persistenceSettings?: PersistenceSettings\n): Promise<void> {\n firestore = cast(firestore, Firestore);\n verifyNotInitialized(firestore);\n\n const client = ensureFirestoreConfigured(firestore);\n if (client._uninitializedComponentsProvider) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'SDK cache is already specified.'\n );\n }\n\n logWarn(\n 'enableIndexedDbPersistence() will be deprecated in the future, ' +\n 'you can use `FirestoreSettings.cache` instead.'\n );\n const settings = firestore._freezeSettings();\n\n const onlineComponentProvider = new OnlineComponentProvider();\n const offlineComponentProvider = new IndexedDbOfflineComponentProvider(\n onlineComponentProvider,\n settings.cacheSizeBytes,\n persistenceSettings?.forceOwnership\n );\n return setPersistenceProviders(\n client,\n onlineComponentProvider,\n offlineComponentProvider\n );\n}\n\n/**\n * Attempts to enable multi-tab persistent storage, if possible. If enabled\n * across all tabs, all operations share access to local persistence, including\n * shared execution of queries and latency-compensated local document updates\n * across all connected instances.\n *\n * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise\n * it returns. Note that even after this failure, the {@link Firestore} instance will\n * remain usable, however offline persistence will be disabled.\n *\n * There are several reasons why this can fail, which can be identified by\n * the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab and\n * multi-tab is not enabled.\n * * unimplemented: The browser is incompatible with the offline\n * persistence implementation.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @returns A `Promise` that represents successfully enabling persistent\n * storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to\n * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache`\n * is already specified will throw an exception.\n */\nexport function enableMultiTabIndexedDbPersistence(\n firestore: Firestore\n): Promise<void> {\n firestore = cast(firestore, Firestore);\n verifyNotInitialized(firestore);\n\n const client = ensureFirestoreConfigured(firestore);\n if (client._uninitializedComponentsProvider) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'SDK cache is already specified.'\n );\n }\n\n logWarn(\n 'enableMultiTabIndexedDbPersistence() will be deprecated in the future, ' +\n 'you can use `FirestoreSettings.cache` instead.'\n );\n const settings = firestore._freezeSettings();\n\n const onlineComponentProvider = new OnlineComponentProvider();\n const offlineComponentProvider = new MultiTabOfflineComponentProvider(\n onlineComponentProvider,\n settings.cacheSizeBytes\n );\n return setPersistenceProviders(\n client,\n onlineComponentProvider,\n offlineComponentProvider\n );\n}\n\n/**\n * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.\n * If the operation fails with a recoverable error (see\n * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected\n * but the client remains usable.\n */\nfunction setPersistenceProviders(\n client: FirestoreClient,\n onlineComponentProvider: OnlineComponentProvider,\n offlineComponentProvider: OfflineComponentProvider\n): Promise<void> {\n const persistenceResult = new Deferred();\n return client.asyncQueue\n .enqueue(async () => {\n try {\n await setOfflineComponentProvider(client, offlineComponentProvider);\n await setOnlineComponentProvider(client, onlineComponentProvider);\n persistenceResult.resolve();\n } catch (e) {\n const error = e as FirestoreError | DOMException;\n if (!canFallbackFromIndexedDbError(error)) {\n throw error;\n }\n logWarn(\n 'Error enabling indexeddb cache. Falling back to ' +\n 'memory cache: ' +\n error\n );\n persistenceResult.reject(error);\n }\n })\n .then(() => persistenceResult.promise);\n}\n\n/**\n * Clears the persistent storage. This includes pending writes and cached\n * documents.\n *\n * Must be called while the {@link Firestore} instance is not started (after the app is\n * terminated or when the app is first initialized). On startup, this function\n * must be called before other functions (other than {@link\n * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}\n * instance is still running, the promise will be rejected with the error code\n * of `failed-precondition`.\n *\n * Note: `clearIndexedDbPersistence()` is primarily intended to help write\n * reliable tests that use Cloud Firestore. It uses an efficient mechanism for\n * dropping existing data but does not attempt to securely overwrite or\n * otherwise make cached data unrecoverable. For applications that are sensitive\n * to the disclosure of cached data in between user sessions, we strongly\n * recommend not enabling persistence at all.\n *\n * @param firestore - The {@link Firestore} instance to clear persistence for.\n * @returns A `Promise` that is resolved when the persistent storage is\n * cleared. Otherwise, the promise is rejected with an error.\n */\nexport function clearIndexedDbPersistence(firestore: Firestore): Promise<void> {\n if (firestore._initialized && !firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Persistence can only be cleared before a Firestore instance is ' +\n 'initialized or after it is terminated.'\n );\n }\n\n const deferred = new Deferred<void>();\n firestore._queue.enqueueAndForgetEvenWhileRestricted(async () => {\n try {\n await indexedDbClearPersistence(\n indexedDbStoragePrefix(firestore._databaseId, firestore._persistenceKey)\n );\n deferred.resolve();\n } catch (e) {\n deferred.reject(e as Error | undefined);\n }\n });\n return deferred.promise;\n}\n\n/**\n * Waits until all currently pending writes for the active user have been\n * acknowledged by the backend.\n *\n * The returned promise resolves immediately if there are no outstanding writes.\n * Otherwise, the promise waits for all previously issued writes (including\n * those written in a previous app session), but it does not wait for writes\n * that were added after the function is called. If you want to wait for\n * additional writes, call `waitForPendingWrites()` again.\n *\n * Any outstanding `waitForPendingWrites()` promises are rejected during user\n * changes.\n *\n * @returns A `Promise` which resolves when all currently pending writes have been\n * acknowledged by the backend.\n */\nexport function waitForPendingWrites(firestore: Firestore): Promise<void> {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientWaitForPendingWrites(client);\n}\n\n/**\n * Re-enables use of the network for this {@link Firestore} instance after a prior\n * call to {@link disableNetwork}.\n *\n * @returns A `Promise` that is resolved once the network has been enabled.\n */\nexport function enableNetwork(firestore: Firestore): Promise<void> {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientEnableNetwork(client);\n}\n\n/**\n * Disables network usage for this instance. It can be re-enabled via {@link\n * enableNetwork}. While the network is disabled, any snapshot listeners,\n * `getDoc()` or `getDocs()` calls will return results from cache, and any write\n * operations will be queued until the network is restored.\n *\n * @returns A `Promise` that is resolved once the network has been disabled.\n */\nexport function disableNetwork(firestore: Firestore): Promise<void> {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientDisableNetwork(client);\n}\n\n/**\n * Terminates the provided {@link Firestore} instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` function\n * may be used. Any other function will throw a `FirestoreError`.\n *\n * To restart after termination, create a new instance of FirebaseFirestore with\n * {@link (getFirestore:1)}.\n *\n * Termination does not cancel any pending writes, and any promises that are\n * awaiting a response from the server will not be resolved. If you have\n * persistence enabled, the next time you start this instance, it will resume\n * sending these writes to the server.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all\n * of its resources or in combination with `clearIndexedDbPersistence()` to\n * ensure that all local state is destroyed between test runs.\n *\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise<void> {\n _removeServiceInstance(\n firestore.app,\n 'firestore',\n firestore._databaseId.database\n );\n return firestore._delete();\n}\n\n/**\n * Loads a Firestore bundle into the local cache.\n *\n * @param firestore - The {@link Firestore} instance to load bundles for.\n * @param bundleData - An object representing the bundle to be loaded. Valid\n * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.\n *\n * @returns A `LoadBundleTask` object, which notifies callers with progress\n * updates, and completion or error events. It can be used as a\n * `Promise<LoadBundleTaskProgress>`.\n */\nexport function loadBundle(\n firestore: Firestore,\n bundleData: ReadableStream<Uint8Array> | ArrayBuffer | string\n): LoadBundleTask {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const resultTask = new LoadBundleTask();\n firestoreClientLoadBundle(\n client,\n firestore._databaseId,\n bundleData,\n resultTask\n );\n return resultTask;\n}\n\n/**\n * Reads a Firestore {@link Query} from local cache, identified by the given\n * name.\n *\n * The named queries are packaged into bundles on the server side (along\n * with resulting documents), and loaded to local cache using `loadBundle`. Once\n * in local cache, use this method to extract a {@link Query} by name.\n *\n * @param firestore - The {@link Firestore} instance to read the query from.\n * @param name - The name of the query.\n * @returns A `Promise` that is resolved with the Query or `null`.\n */\nexport function namedQuery(\n firestore: Firestore,\n name: string\n): Promise<Query | null> {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientGetNamedQuery(client, name).then(namedQuery => {\n if (!namedQuery) {\n return null;\n }\n\n return new Query(firestore, null, namedQuery.query);\n });\n}\n\nfunction verifyNotInitialized(firestore: Firestore): void {\n if (firestore._initialized || firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and persistence can no longer be ' +\n 'enabled. You can only enable persistence before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * An immutable object representing an array of bytes.\n */\nexport class Bytes {\n _byteString: ByteString;\n\n /** @hideconstructor */\n constructor(byteString: ByteString) {\n this._byteString = byteString;\n }\n\n /**\n * Creates a new `Bytes` object from the given Base64 string, converting it to\n * bytes.\n *\n * @param base64 - The Base64 string used to create the `Bytes` object.\n */\n static fromBase64String(base64: string): Bytes {\n try {\n return new Bytes(ByteString.fromBase64String(base64));\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to construct data from Base64 string: ' + e\n );\n }\n }\n\n /**\n * Creates a new `Bytes` object from the given Uint8Array.\n *\n * @param array - The Uint8Array used to create the `Bytes` object.\n */\n static fromUint8Array(array: Uint8Array): Bytes {\n return new Bytes(ByteString.fromUint8Array(array));\n }\n\n /**\n * Returns the underlying bytes as a Base64-encoded string.\n *\n * @returns The Base64-encoded string created from the `Bytes` object.\n */\n toBase64(): string {\n return this._byteString.toBase64();\n }\n\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */\n toUint8Array(): Uint8Array {\n return this._byteString.toUint8Array();\n }\n\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */\n toString(): string {\n return 'Bytes(base64: ' + this.toBase64() + ')';\n }\n\n /**\n * Returns true if this `Bytes` object is equal to the provided one.\n *\n * @param other - The `Bytes` object to compare against.\n * @returns true if this `Bytes` object is equal to the provided one.\n */\n isEqual(other: Bytes): boolean {\n return this._byteString.isEqual(other._byteString);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DOCUMENT_KEY_NAME,\n FieldPath as InternalFieldPath\n} from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */\nexport class FieldPath {\n /** Internal representation of a Firestore field path. */\n readonly _internalPath: InternalFieldPath;\n\n /**\n * Creates a `FieldPath` from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...fieldNames: string[]) {\n for (let i = 0; i < fieldNames.length; ++i) {\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field name at argument $(i + 1). ` +\n 'Field names must not be empty.'\n );\n }\n }\n\n this._internalPath = new InternalFieldPath(fieldNames);\n }\n\n /**\n * Returns true if this `FieldPath` is equal to the provided one.\n *\n * @param other - The `FieldPath` to compare against.\n * @returns true if this `FieldPath` is equal to the provided one.\n */\n isEqual(other: FieldPath): boolean {\n return this._internalPath.isEqual(other._internalPath);\n }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */\nexport function documentId(): FieldPath {\n return new FieldPath(DOCUMENT_KEY_NAME);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParseContext } from '../api/parse_context';\nimport { FieldTransform } from '../model/mutation';\n\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */\nexport abstract class FieldValue {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(public _methodName: string) {}\n\n /** Compares `FieldValue`s for equality. */\n abstract isEqual(other: FieldValue): boolean;\n abstract _toFieldTransform(context: ParseContext): FieldTransform | null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\nimport { primitiveComparator } from '../util/misc';\n\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */\nexport class GeoPoint {\n // Prefix with underscore to signal this is a private variable in JS and\n // prevent it showing up for autocompletion when typing latitude or longitude.\n private _lat: number;\n private _long: number;\n\n /**\n * Creates a new immutable `GeoPoint` object with the provided latitude and\n * longitude values.\n * @param latitude - The latitude as number between -90 and 90.\n * @param longitude - The longitude as number between -180 and 180.\n */\n constructor(latitude: number, longitude: number) {\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Latitude must be a number between -90 and 90, but was: ' + latitude\n );\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Longitude must be a number between -180 and 180, but was: ' + longitude\n );\n }\n\n this._lat = latitude;\n this._long = longitude;\n }\n\n /**\n * The latitude of this `GeoPoint` instance.\n */\n get latitude(): number {\n return this._lat;\n }\n\n /**\n * The longitude of this `GeoPoint` instance.\n */\n get longitude(): number {\n return this._long;\n }\n\n /**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other - The `GeoPoint` to compare against.\n * @returns true if this `GeoPoint` is equal to the provided one.\n */\n isEqual(other: GeoPoint): boolean {\n return this._lat === other._lat && this._long === other._long;\n }\n\n /** Returns a JSON-serializable representation of this GeoPoint. */\n toJSON(): { latitude: number; longitude: number } {\n return { latitude: this._lat, longitude: this._long };\n }\n\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n _compareTo(other: GeoPoint): number {\n return (\n primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport { newSerializer } from '../platform/serializer';\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { toNumber } from '../remote/number_serializer';\nimport {\n JsonProtoSerializer,\n toBytes,\n toResourceName,\n toTimestamp\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { Dict, forEach, isEmpty } from '../util/obj';\n\nimport { Bytes } from './bytes';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { GeoPoint } from './geo_point';\nimport {\n DocumentReference,\n PartialWithFieldValue,\n WithFieldValue\n} from './reference';\nimport { Timestamp } from './timestamp';\n\nconst RESERVED_FIELD_REGEX = /^__.*__$/;\n\n/**\n * An untyped Firestore Data Converter interface that is shared between the\n * lite, firestore-exp and classic SDK.\n */\nexport interface UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n toFirestore(\n modelObject: WithFieldValue<AppModelType>\n ): WithFieldValue<DbModelType>;\n toFirestore(\n modelObject: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n ): PartialWithFieldValue<DbModelType>;\n fromFirestore(snapshot: unknown, options?: unknown): AppModelType;\n}\n\n/** The result of parsing document data (e.g. for a setData call). */\nexport class ParsedSetData {\n constructor(\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask | null,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n if (this.fieldMask !== null) {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n } else {\n return new SetMutation(\n key,\n this.data,\n precondition,\n this.fieldTransforms\n );\n }\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nexport class ParsedUpdateData {\n constructor(\n readonly data: ObjectValue,\n // The fieldMask does not include document transforms.\n readonly fieldMask: FieldMask,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n }\n}\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nexport const enum UserDataSource {\n Set,\n Update,\n MergeSet,\n /**\n * Indicates the source is a where clause, cursor bound, arrayUnion()\n * element, etc. Of note, isWrite(source) will return false.\n */\n Argument,\n /**\n * Indicates that the source is an Argument that may directly contain nested\n * arrays (e.g. the operand of an `in` query).\n */\n ArrayArgument\n}\n\nfunction isWrite(dataSource: UserDataSource): boolean {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.Argument:\n case UserDataSource.ArrayArgument:\n return false;\n default:\n throw fail(`Unexpected case for UserDataSource: ${dataSource}`);\n }\n}\n\n/** Contains the settings that are mutated as we parse user data. */\ninterface ContextSettings {\n /** Indicates what kind of API method this data came from. */\n readonly dataSource: UserDataSource;\n /** The name of the method the user called to create the ParseContext. */\n readonly methodName: string;\n /** The document the user is attempting to modify, if that applies. */\n readonly targetDoc?: DocumentKey;\n /**\n * A path within the object being parsed. This could be an empty path (in\n * which case the context represents the root of the data being parsed), or a\n * nonempty path (indicating the context represents a nested location within\n * the data).\n */\n readonly path?: InternalFieldPath;\n /**\n * Whether or not this context corresponds to an element of an array.\n * If not set, elements are treated as if they were outside of arrays.\n */\n readonly arrayElement?: boolean;\n /**\n * Whether or not a converter was specified in this context. If true, error\n * messages will reference the converter when invalid data is provided.\n */\n readonly hasConverter?: boolean;\n}\n\n/** A \"context\" object passed around while parsing user data. */\nclass ParseContextImpl implements ParseContext {\n readonly fieldTransforms: FieldTransform[];\n readonly fieldMask: InternalFieldPath[];\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings - The settings for the parser.\n * @param databaseId - The database ID of the Firestore instance.\n * @param serializer - The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms - A mutable list of field transforms encountered\n * while parsing the data.\n * @param fieldMask - A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(\n readonly settings: ContextSettings,\n readonly databaseId: DatabaseId,\n readonly serializer: JsonProtoSerializer,\n readonly ignoreUndefinedProperties: boolean,\n fieldTransforms?: FieldTransform[],\n fieldMask?: InternalFieldPath[]\n ) {\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n\n get path(): InternalFieldPath | undefined {\n return this.settings.path;\n }\n\n get dataSource(): UserDataSource {\n return this.settings.dataSource;\n }\n\n /** Returns a new context with the specified settings overwritten. */\n contextWith(configuration: Partial<ContextSettings>): ParseContextImpl {\n return new ParseContextImpl(\n { ...this.settings, ...configuration },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties,\n this.fieldTransforms,\n this.fieldMask\n );\n }\n\n childContextForField(field: string): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePathSegment(field);\n return context;\n }\n\n childContextForFieldPath(field: InternalFieldPath): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePath();\n return context;\n }\n\n childContextForArray(index: number): ParseContextImpl {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.contextWith({ path: undefined, arrayElement: true });\n }\n\n createError(reason: string): FirestoreError {\n return createError(\n reason,\n this.settings.methodName,\n this.settings.hasConverter || false,\n this.path,\n this.settings.targetDoc\n );\n }\n\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\n contains(fieldPath: InternalFieldPath): boolean {\n return (\n this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined ||\n this.fieldTransforms.find(transform =>\n fieldPath.isPrefixOf(transform.field)\n ) !== undefined\n );\n }\n\n private validatePath(): void {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (!this.path) {\n return;\n }\n for (let i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n }\n\n private validatePathSegment(segment: string): void {\n if (segment.length === 0) {\n throw this.createError('Document fields must not be empty');\n }\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with \"__\"');\n }\n }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nexport class UserDataReader {\n private readonly serializer: JsonProtoSerializer;\n\n constructor(\n private readonly databaseId: DatabaseId,\n private readonly ignoreUndefinedProperties: boolean,\n serializer?: JsonProtoSerializer\n ) {\n this.serializer = serializer || newSerializer(databaseId);\n }\n\n /** Creates a new top-level parse context. */\n createContext(\n dataSource: UserDataSource,\n methodName: string,\n targetDoc?: DocumentKey,\n hasConverter = false\n ): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource,\n methodName,\n targetDoc,\n path: InternalFieldPath.emptyPath(),\n arrayElement: false,\n hasConverter\n },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties\n );\n }\n}\n\nexport function newUserDataReader(firestore: Firestore): UserDataReader {\n const settings = firestore._freezeSettings();\n const serializer = newSerializer(firestore._databaseId);\n return new UserDataReader(\n firestore._databaseId,\n !!settings.ignoreUndefinedProperties,\n serializer\n );\n}\n\n/** Parse document data from a set() call. */\nexport function parseSetData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown,\n hasConverter: boolean,\n options: SetOptions = {}\n): ParsedSetData {\n const context = userDataReader.createContext(\n options.merge || options.mergeFields\n ? UserDataSource.MergeSet\n : UserDataSource.Set,\n methodName,\n targetDoc,\n hasConverter\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n const updateData = parseObject(input, context)!;\n\n let fieldMask: FieldMask | null;\n let fieldTransforms: FieldTransform[];\n\n if (options.merge) {\n fieldMask = new FieldMask(context.fieldMask);\n fieldTransforms = context.fieldTransforms;\n } else if (options.mergeFields) {\n const validatedFieldPaths: InternalFieldPath[] = [];\n\n for (const stringOrFieldPath of options.mergeFields) {\n const fieldPath = fieldPathFromArgument(\n methodName,\n stringOrFieldPath,\n targetDoc\n );\n if (!context.contains(fieldPath)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Field '${fieldPath}' is specified in your field mask but missing from your input data.`\n );\n }\n\n if (!fieldMaskContains(validatedFieldPaths, fieldPath)) {\n validatedFieldPaths.push(fieldPath);\n }\n }\n\n fieldMask = new FieldMask(validatedFieldPaths);\n fieldTransforms = context.fieldTransforms.filter(transform =>\n fieldMask!.covers(transform.field)\n );\n } else {\n fieldMask = null;\n fieldTransforms = context.fieldTransforms;\n }\n\n return new ParsedSetData(\n new ObjectValue(updateData),\n fieldMask,\n fieldTransforms\n );\n}\n\nexport class DeleteFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): null {\n if (context.dataSource === UserDataSource.MergeSet) {\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n context.fieldMask.push(context.path!);\n } else if (context.dataSource === UserDataSource.Update) {\n debugAssert(\n context.path!.length > 0,\n `${this._methodName}() at the top level should have already ` +\n 'been handled.'\n );\n throw context.createError(\n `${this._methodName}() can only appear at the top level ` +\n 'of your update data'\n );\n } else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError(\n `${this._methodName}() cannot be used with set() unless you pass ` +\n '{merge:true}'\n );\n }\n return null;\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof DeleteFieldValueImpl;\n }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n * context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */\nfunction createSentinelChildContext(\n fieldValue: FieldValue,\n context: ParseContextImpl,\n arrayElement: boolean\n): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource: UserDataSource.Argument,\n targetDoc: context.settings.targetDoc,\n methodName: fieldValue._methodName,\n arrayElement\n },\n context.databaseId,\n context.serializer,\n context.ignoreUndefinedProperties\n );\n}\n\nexport class ServerTimestampFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n return new FieldTransform(context.path!, new ServerTimestampTransform());\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof ServerTimestampFieldValueImpl;\n }\n}\n\nexport class ArrayUnionFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayUnionTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n // TODO(mrschmidt): Implement isEquals\n return this === other;\n }\n}\n\nexport class ArrayRemoveFieldValueImpl extends FieldValue {\n constructor(methodName: string, readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayRemoveTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n // TODO(mrschmidt): Implement isEquals\n return this === other;\n }\n}\n\nexport class NumericIncrementFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _operand: number) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const numericIncrement = new NumericIncrementTransformOperation(\n context.serializer,\n toNumber(context.serializer, this._operand)\n );\n return new FieldTransform(context.path!, numericIncrement);\n }\n\n isEqual(other: FieldValue): boolean {\n // TODO(mrschmidt): Implement isEquals\n return this === other;\n }\n}\n\n/** Parse update data from an update() call. */\nexport function parseUpdateData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n forEach(input as Dict<unknown>, (key, value) => {\n const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n });\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */\nexport function parseUpdateVarargs(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n field: string | PublicFieldPath | Compat<PublicFieldPath>,\n value: unknown,\n moreFieldsAndValues: unknown[]\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n const keys = [fieldPathFromArgument(methodName, field, targetDoc)];\n const values = [value];\n\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${methodName}() needs to be called with an even number ` +\n 'of arguments that alternate between field names and values.'\n );\n }\n\n for (let i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(\n fieldPathFromArgument(\n methodName,\n moreFieldsAndValues[i] as string | PublicFieldPath\n )\n );\n values.push(moreFieldsAndValues[i + 1]);\n }\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n\n // We iterate in reverse order to pick the last value for a field if the\n // user specified the field multiple times.\n for (let i = keys.length - 1; i >= 0; --i) {\n if (!fieldMaskContains(fieldMaskPaths, keys[i])) {\n const path = keys[i];\n let value = values[i];\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n }\n }\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */\nexport function parseQueryValue(\n userDataReader: UserDataReader,\n methodName: string,\n input: unknown,\n allowArrays = false\n): ProtoValue {\n const context = userDataReader.createContext(\n allowArrays ? UserDataSource.ArrayArgument : UserDataSource.Argument,\n methodName\n );\n const parsed = parseData(input, context);\n debugAssert(parsed != null, 'Parsed data should not be null.');\n debugAssert(\n context.fieldTransforms.length === 0,\n 'Field transforms should have been disallowed.'\n );\n return parsed;\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\nexport function parseData(\n input: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n input = getModularInstance(input);\n\n if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return parseObject(input, context);\n } else if (input instanceof FieldValue) {\n // FieldValues usually parse into transforms (except deleteField())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n parseSentinelFieldValue(input, context);\n return null;\n } else if (input === undefined && context.ignoreUndefinedProperties) {\n // If the input is undefined it can never participate in the fieldMask, so\n // don't handle this below. If `ignoreUndefinedProperties` is false,\n // `parseScalarValue` will reject an undefined value.\n return null;\n } else {\n // If context.path is null we are inside an array and we don't support\n // field mask paths more granular than the top-level array.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n\n if (input instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n // In the case of IN queries, the parsed data is an array (representing\n // the set of values to be included for the IN query) that may directly\n // contain additional arrays (each representing an individual field\n // value), so we disable this validation.\n if (\n context.settings.arrayElement &&\n context.dataSource !== UserDataSource.ArrayArgument\n ) {\n throw context.createError('Nested arrays are not supported');\n }\n return parseArray(input as unknown[], context);\n } else {\n return parseScalarValue(input, context);\n }\n }\n}\n\nfunction parseObject(\n obj: Dict<unknown>,\n context: ParseContextImpl\n): { mapValue: ProtoMapValue } {\n const fields: Dict<ProtoValue> = {};\n\n if (isEmpty(obj)) {\n // If we encounter an empty object, we explicitly add it to the update\n // mask to ensure that the server creates a map entry.\n if (context.path && context.path.length > 0) {\n context.fieldMask.push(context.path);\n }\n } else {\n forEach(obj, (key: string, val: unknown) => {\n const parsedValue = parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n fields[key] = parsedValue;\n }\n });\n }\n\n return { mapValue: { fields } };\n}\n\nfunction parseArray(array: unknown[], context: ParseContextImpl): ProtoValue {\n const values: ProtoValue[] = [];\n let entryIndex = 0;\n for (const entry of array) {\n let parsedEntry = parseData(\n entry,\n context.childContextForArray(entryIndex)\n );\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = { nullValue: 'NULL_VALUE' };\n }\n values.push(parsedEntry);\n entryIndex++;\n }\n return { arrayValue: { values } };\n}\n\n/**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\nfunction parseSentinelFieldValue(\n value: FieldValue,\n context: ParseContextImpl\n): void {\n // Sentinels are only supported with writes, and not within arrays.\n if (!isWrite(context.dataSource)) {\n throw context.createError(\n `${value._methodName}() can only be used with update() and set()`\n );\n }\n if (!context.path) {\n throw context.createError(\n `${value._methodName}() is not currently supported inside arrays`\n );\n }\n\n const fieldTransform = value._toFieldTransform(context);\n if (fieldTransform) {\n context.fieldTransforms.push(fieldTransform);\n }\n}\n\n/**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */\nfunction parseScalarValue(\n value: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n value = getModularInstance(value);\n\n if (value === null) {\n return { nullValue: 'NULL_VALUE' };\n } else if (typeof value === 'number') {\n return toNumber(context.serializer, value);\n } else if (typeof value === 'boolean') {\n return { booleanValue: value };\n } else if (typeof value === 'string') {\n return { stringValue: value };\n } else if (value instanceof Date) {\n const timestamp = Timestamp.fromDate(value);\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof Timestamp) {\n // Firestore backend truncates precision down to microseconds. To ensure\n // offline mode works the same with regards to truncation, perform the\n // truncation immediately without waiting for the backend to do that.\n const timestamp = new Timestamp(\n value.seconds,\n Math.floor(value.nanoseconds / 1000) * 1000\n );\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof GeoPoint) {\n return {\n geoPointValue: {\n latitude: value.latitude,\n longitude: value.longitude\n }\n };\n } else if (value instanceof Bytes) {\n return { bytesValue: toBytes(context.serializer, value._byteString) };\n } else if (value instanceof DocumentReference) {\n const thisDb = context.databaseId;\n const otherDb = value.firestore._databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw context.createError(\n 'Document reference is for database ' +\n `${otherDb.projectId}/${otherDb.database} but should be ` +\n `for database ${thisDb.projectId}/${thisDb.database}`\n );\n }\n return {\n referenceValue: toResourceName(\n value.firestore._databaseId || context.databaseId,\n value._key.path\n )\n };\n } else {\n throw context.createError(\n `Unsupported field value: ${valueDescription(value)}`\n );\n }\n}\n\n/**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */\nfunction looksLikeJsonObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof Timestamp) &&\n !(input instanceof GeoPoint) &&\n !(input instanceof Bytes) &&\n !(input instanceof DocumentReference) &&\n !(input instanceof FieldValue)\n );\n}\n\nfunction validatePlainObject(\n message: string,\n context: ParseContextImpl,\n input: unknown\n): asserts input is Dict<unknown> {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n const description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n } else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n path: string | PublicFieldPath | Compat<PublicFieldPath>,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n // If required, replace the FieldPath Compat class with with the firestore-exp\n // FieldPath.\n path = getModularInstance(path);\n\n if (path instanceof FieldPath) {\n return path._internalPath;\n } else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n } else {\n const message = 'Field path arguments must be of type string or ';\n throw createError(\n message,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nconst FIELD_PATH_RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */\nexport function fieldPathFromDotSeparatedString(\n methodName: string,\n path: string,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n const found = path.search(FIELD_PATH_RESERVED);\n if (found >= 0) {\n throw createError(\n `Invalid field path (${path}). Paths must not contain ` +\n `'~', '*', '/', '[', or ']'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n\n try {\n return new FieldPath(...path.split('.'))._internalPath;\n } catch (e) {\n throw createError(\n `Invalid field path (${path}). Paths must not be empty, ` +\n `begin with '.', end with '.', or contain '..'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\nfunction createError(\n reason: string,\n methodName: string,\n hasConverter: boolean,\n path?: InternalFieldPath,\n targetDoc?: DocumentKey\n): FirestoreError {\n const hasPath = path && !path.isEmpty();\n const hasDocument = targetDoc !== undefined;\n let message = `Function ${methodName}() called with invalid data`;\n if (hasConverter) {\n message += ' (via `toFirestore()`)';\n }\n message += '. ';\n\n let description = '';\n if (hasPath || hasDocument) {\n description += ' (found';\n\n if (hasPath) {\n description += ` in field ${path}`;\n }\n if (hasDocument) {\n description += ` in document ${targetDoc}`;\n }\n description += ')';\n }\n\n return new FirestoreError(\n Code.INVALID_ARGUMENT,\n message + reason + description\n );\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */\nfunction fieldMaskContains(\n haystack: InternalFieldPath[],\n needle: InternalFieldPath\n): boolean {\n return haystack.some(v => v.isEqual(needle));\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { arrayEquals } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n queryEqual,\n SetOptions,\n WithFieldValue\n} from './reference';\nimport {\n fieldPathFromDotSeparatedString,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * @example\n * ```typescript\n * class Post {\n * constructor(readonly title: string, readonly author: string) {}\n *\n * toString(): string {\n * return this.title + ', by ' + this.author;\n * }\n * }\n *\n * interface PostDbModel {\n * title: string;\n * author: string;\n * }\n *\n * const postConverter = {\n * toFirestore(post: WithFieldValue<Post>): PostDbModel {\n * return {title: post.title, author: post.author};\n * },\n * fromFirestore(snapshot: QueryDocumentSnapshot): Post {\n * const data = snapshot.data(options) as PostDbModel;\n * return new Post(data.title, data.author);\n * }\n * };\n *\n * const postSnap = await firebase.firestore()\n * .collection('posts')\n * .withConverter(postConverter)\n * .doc().get();\n * const post = postSnap.data();\n * if (post !== undefined) {\n * post.title; // string\n * post.toString(); // Should be defined\n * post.someNonExistentProperty; // TS error\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain Javascript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)}.\n *\n * The `WithFieldValue<T>` type extends `T` to also allow FieldValues such as\n * {@link (deleteField:1)} to be used as property values.\n */\n toFirestore(\n modelObject: WithFieldValue<AppModelType>\n ): WithFieldValue<DbModelType>;\n\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain Javascript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true`\n * or `mergeFields`.\n *\n * The `PartialWithFieldValue<T>` type extends `Partial<T>` to allow\n * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n * It also supports nested `Partial` by allowing nested fields to be\n * omitted.\n */\n toFirestore(\n modelObject: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n ): PartialWithFieldValue<DbModelType>;\n\n /**\n * Called by the Firestore SDK to convert Firestore data into an object of\n * type `AppModelType`. You can access your data by calling:\n * `snapshot.data()`.\n *\n * Generally, the data returned from `snapshot.data()` can be cast to\n * `DbModelType`; however, this is not guaranteed as writes to the database\n * may have occurred without a type converter enforcing this specific layout.\n *\n * @param snapshot - A `QueryDocumentSnapshot` containing your data and\n * metadata.\n */\n fromFirestore(\n snapshot: QueryDocumentSnapshot<DocumentData, DocumentData>\n ): AppModelType;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get(<field>)` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n // Note: This class is stripped down version of the DocumentSnapshot in\n // the legacy SDK. The changes are:\n // - No support for SnapshotMetadata.\n // - No support for SnapshotOptions.\n\n /** @hideconstructor protected */\n constructor(\n public _firestore: Firestore,\n public _userDataWriter: AbstractUserDataWriter,\n public _key: DocumentKey,\n public _document: Document | null,\n public _converter: UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null\n ) {}\n\n /** Property of the `DocumentSnapshot` that provides the document's ID. */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */\n get ref(): DocumentReference<AppModelType, DbModelType> {\n return new DocumentReference<AppModelType, DbModelType>(\n this._firestore,\n this._converter,\n this._key\n );\n }\n\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */\n exists(): this is QueryDocumentSnapshot<AppModelType, DbModelType> {\n return this._document !== null;\n }\n\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * @returns An `Object` containing all fields in the document or `undefined`\n * if the document doesn't exist.\n */\n data(): AppModelType | undefined {\n if (!this._document) {\n return undefined;\n } else if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n this._key,\n this._document,\n /* converter= */ null\n );\n return this._converter.fromFirestore(snapshot);\n } else {\n return this._userDataWriter.convertValue(\n this._document.data.value\n ) as AppModelType;\n }\n }\n\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(fieldPath: string | FieldPath): any {\n if (this._document) {\n const value = this._document.data.field(\n fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n );\n if (value !== null) {\n return this._userDataWriter.convertValue(value);\n }\n }\n return undefined;\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get(<field>)` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot<AppModelType, DbModelType> {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * @override\n * @returns An `Object` containing all fields in the document.\n */\n data(): AppModelType {\n return super.data() as AppModelType;\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * The query on which you called {@link getDocs} in order to get this\n * `QuerySnapshot`.\n */\n readonly query: Query<AppModelType, DbModelType>;\n\n /** @hideconstructor */\n constructor(\n _query: Query<AppModelType, DbModelType>,\n readonly _docs: Array<QueryDocumentSnapshot<AppModelType, DbModelType>>\n ) {\n this.query = _query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array<QueryDocumentSnapshot<AppModelType, DbModelType>> {\n return [...this._docs];\n }\n\n /** The number of documents in the `QuerySnapshot`. */\n get size(): number {\n return this.docs.length;\n }\n\n /** True if there are no documents in the `QuerySnapshot`. */\n get empty(): boolean {\n return this.docs.length === 0;\n }\n\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */\n forEach(\n callback: (\n result: QueryDocumentSnapshot<AppModelType, DbModelType>\n ) => void,\n thisArg?: unknown\n ): void {\n this._docs.forEach(callback, thisArg);\n }\n}\n\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual<AppModelType, DbModelType extends DocumentData>(\n left:\n | DocumentSnapshot<AppModelType, DbModelType>\n | QuerySnapshot<AppModelType, DbModelType>,\n right:\n | DocumentSnapshot<AppModelType, DbModelType>\n | QuerySnapshot<AppModelType, DbModelType>\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n return (\n left._firestore === right._firestore &&\n left._key.isEqual(right._key) &&\n (left._document === null\n ? right._document === null\n : left._document.isEqual(right._document)) &&\n left._converter === right._converter\n );\n } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n return (\n queryEqual(left.query, right.query) &&\n arrayEquals(left.docs, right.docs, snapshotEqual)\n );\n }\n\n return false;\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n arg: string | FieldPath | Compat<FieldPath>\n): InternalFieldPath {\n if (typeof arg === 'string') {\n return fieldPathFromDotSeparatedString(methodName, arg);\n } else if (arg instanceof FieldPath) {\n return arg._internalPath;\n } else {\n return arg._delegate._internalPath;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n isCollectionGroupQuery,\n LimitType,\n Query as InternalQuery,\n queryNormalizedOrderBy,\n queryWithAddedFilter,\n queryWithAddedOrderBy,\n queryWithEndAt,\n queryWithLimit,\n queryWithStartAt\n} from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath, ResourcePath } from '../model/path';\nimport { isServerTimestamp } from '../model/server_timestamps';\nimport { refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n validatePositiveNumber,\n valueDescription\n} from '../util/input_validation';\n\nimport { FieldPath } from './field_path';\nimport { DocumentData, DocumentReference, Query } from './reference';\nimport { DocumentSnapshot, fieldPathFromArgument } from './snapshot';\nimport {\n newUserDataReader,\n parseQueryValue,\n UserDataReader\n} from './user_data_reader';\n\nexport function validateHasExplicitOrderByForLimitToLast(\n query: InternalQuery\n): void {\n if (\n query.limitType === LimitType.Last &&\n query.explicitOrderBy.length === 0\n ) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'limitToLast() queries require specifying at least one orderBy() clause'\n );\n }\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'where'\n | 'orderBy'\n | 'limit'\n | 'limitToLast'\n | 'startAt'\n | 'startAfter'\n | 'endAt'\n | 'endBefore';\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */\nexport abstract class AppliableConstraint {\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType>;\n}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link\n * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link (query:1)} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint extends AppliableConstraint {\n /** The type of this query constraint */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType>;\n}\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to\n * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or\n * {@link or}.\n * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to\n * apply (e.g. {@link orderBy}, {@link limit}).\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n compositeFilter: QueryCompositeFilterConstraint,\n ...queryConstraints: QueryNonFilterConstraint[]\n): Query<AppModelType, DbModelType>;\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param queryConstraints - The list of {@link QueryConstraint}s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n ...queryConstraints: QueryConstraint[]\n): Query<AppModelType, DbModelType>;\n\nexport function query<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n queryConstraint: QueryCompositeFilterConstraint | QueryConstraint | undefined,\n ...additionalQueryConstraints: Array<\n QueryConstraint | QueryNonFilterConstraint\n >\n): Query<AppModelType, DbModelType> {\n let queryConstraints: AppliableConstraint[] = [];\n\n if (queryConstraint instanceof AppliableConstraint) {\n queryConstraints.push(queryConstraint);\n }\n\n queryConstraints = queryConstraints.concat(additionalQueryConstraints);\n\n validateQueryConstraintArray(queryConstraints);\n\n for (const constraint of queryConstraints) {\n query = constraint._apply(query);\n }\n return query;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link (query:1)} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */\nexport class QueryFieldFilterConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'where';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _op: Operator,\n private _value: unknown\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _op: Operator,\n _value: unknown\n ): QueryFieldFilterConstraint {\n return new QueryFieldFilterConstraint(_field, _op, _value);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const filter = this._parse(query);\n validateNewFieldFilter(query._query, filter);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, filter)\n );\n }\n\n _parse<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): FieldFilter {\n const reader = newUserDataReader(query.firestore);\n const filter = newQueryFilter(\n query._query,\n 'where',\n reader,\n query.firestore._databaseId,\n this._field,\n this._op,\n this._value\n );\n return filter;\n }\n}\n\n/**\n * Filter conditions in a {@link where} clause are specified using the\n * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in',\n * 'array-contains-any', and 'not-in'.\n */\nexport type WhereFilterOp =\n | '<'\n | '<='\n | '=='\n | '!='\n | '>='\n | '>'\n | 'array-contains'\n | 'in'\n | 'array-contains-any'\n | 'not-in';\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"<\", \"<=\", \"==\", \"<\",\n * \"<=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */\nexport function where(\n fieldPath: string | FieldPath,\n opStr: WhereFilterOp,\n value: unknown\n): QueryFieldFilterConstraint {\n const op = opStr as Operator;\n const field = fieldPathFromArgument('where', fieldPath);\n return QueryFieldFilterConstraint._create(field, op, value);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n */\nexport class QueryCompositeFilterConstraint extends AppliableConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'or' | 'and',\n private readonly _queryConstraints: QueryFilterConstraint[]\n ) {\n super();\n }\n\n static _create(\n type: 'or' | 'and',\n _queryConstraints: QueryFilterConstraint[]\n ): QueryCompositeFilterConstraint {\n return new QueryCompositeFilterConstraint(type, _queryConstraints);\n }\n\n _parse<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Filter {\n const parsedFilters = this._queryConstraints\n .map(queryConstraint => {\n return queryConstraint._parse(query);\n })\n .filter(parsedFilter => parsedFilter.getFilters().length > 0);\n\n if (parsedFilters.length === 1) {\n return parsedFilters[0];\n }\n\n return CompositeFilter.create(parsedFilters, this._getOperator());\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const parsedFilter = this._parse(query);\n if (parsedFilter.getFilters().length === 0) {\n // Return the existing query if not adding any more filters (e.g. an empty\n // composite filter).\n return query;\n }\n validateNewFilter(query._query, parsedFilter);\n\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, parsedFilter)\n );\n }\n\n _getQueryConstraints(): readonly AppliableConstraint[] {\n return this._queryConstraints;\n }\n\n _getOperator(): CompositeOperator {\n return this.type === 'and' ? CompositeOperator.AND : CompositeOperator.OR;\n }\n}\n\n/**\n * `QueryNonFilterConstraint` is a helper union type that represents\n * QueryConstraints which are used to narrow or order the set of documents,\n * but that do not explicitly filter on a document field.\n * `QueryNonFilterConstraint`s are created by invoking {@link orderBy},\n * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)},\n * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)}\n * to create a new query instance that also contains the `QueryConstraint`.\n */\nexport type QueryNonFilterConstraint =\n | QueryOrderByConstraint\n | QueryLimitConstraint\n | QueryStartAtConstraint\n | QueryEndAtConstraint;\n\n/**\n * `QueryFilterConstraint` is a helper union type that represents\n * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}.\n */\nexport type QueryFilterConstraint =\n | QueryFieldFilterConstraint\n | QueryCompositeFilterConstraint;\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function or(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('or', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.OR,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function and(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('and', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.AND,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */\nexport class QueryOrderByConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'orderBy';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _direction: Direction\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _direction: Direction\n ): QueryOrderByConstraint {\n return new QueryOrderByConstraint(_field, _direction);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const orderBy = newQueryOrderBy(query._query, this._field, this._direction);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedOrderBy(query._query, orderBy)\n );\n }\n}\n\n/**\n * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc'\n * (descending or ascending).\n */\nexport type OrderByDirection = 'desc' | 'asc';\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */\nexport function orderBy(\n fieldPath: string | FieldPath,\n directionStr: OrderByDirection = 'asc'\n): QueryOrderByConstraint {\n const direction = directionStr as Direction;\n const path = fieldPathFromArgument('orderBy', fieldPath);\n return QueryOrderByConstraint._create(path, direction);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */\nexport class QueryLimitConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'limit' | 'limitToLast',\n private readonly _limit: number,\n private readonly _limitType: LimitType\n ) {\n super();\n }\n\n static _create(\n type: 'limit' | 'limitToLast',\n _limit: number,\n _limitType: LimitType\n ): QueryLimitConstraint {\n return new QueryLimitConstraint(type, _limit, _limitType);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n return new Query(\n query.firestore,\n query.converter,\n queryWithLimit(query._query, this._limit, this._limitType)\n );\n }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limit(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limit', limit);\n return QueryLimitConstraint._create('limit', limit, LimitType.First);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limitToLast(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limitToLast', limit);\n return QueryLimitConstraint._create('limitToLast', limit, LimitType.Last);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */\nexport class QueryStartAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'startAt' | 'startAfter',\n private readonly _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'startAt' | 'startAfter',\n _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n _inclusive: boolean\n ): QueryStartAtConstraint {\n return new QueryStartAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query<AppModelType, DbModelType>(\n query.firestore,\n query.converter,\n queryWithStartAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided document (inclusive). The starting position is relative\n * to the order of the query. The document must contain all of the fields\n * provided in the `orderBy` of this query.\n *\n * @param snapshot - The snapshot of the document to start at.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt<AppModelType, DbModelType extends DocumentData>(\n snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query at, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAt<AppModelType, DbModelType extends DocumentData>(\n ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided document (exclusive). The starting position is\n * relative to the order of the query. The document must contain all of the\n * fields provided in the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to start after.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter<AppModelType, DbModelType extends DocumentData>(\n snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided fields relative to the order of the query. The order\n * of the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query after, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAfter<AppModelType, DbModelType extends DocumentData>(\n ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAfter',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */\nexport class QueryEndAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'endBefore' | 'endAt',\n private readonly _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'endBefore' | 'endAt',\n _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n _inclusive: boolean\n ): QueryEndAtConstraint {\n return new QueryEndAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithEndAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided document (exclusive). The end position is relative to the\n * order of the query. The document must contain all of the fields provided in\n * the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end before.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore<AppModelType, DbModelType extends DocumentData>(\n snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query before, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endBefore<AppModelType, DbModelType extends DocumentData>(\n ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endBefore',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided document (inclusive). The end position is relative to the order\n * of the query. The document must contain all of the fields provided in the\n * orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end at.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt<AppModelType, DbModelType extends DocumentData>(\n snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided fields relative to the order of the query. The order of the field\n * values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query at, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endAt<AppModelType, DbModelType extends DocumentData>(\n ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/** Helper function to create a bound from a document or fields */\nfunction newQueryBoundFromDocOrFields<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query<AppModelType, DbModelType>,\n methodName: string,\n docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>,\n inclusive: boolean\n): Bound {\n docOrFields[0] = getModularInstance(docOrFields[0]);\n\n if (docOrFields[0] instanceof DocumentSnapshot) {\n return newQueryBoundFromDocument(\n query._query,\n query.firestore._databaseId,\n methodName,\n docOrFields[0]._document,\n inclusive\n );\n } else {\n const reader = newUserDataReader(query.firestore);\n return newQueryBoundFromFields(\n query._query,\n query.firestore._databaseId,\n reader,\n methodName,\n docOrFields,\n inclusive\n );\n }\n}\n\nexport function newQueryFilter(\n query: InternalQuery,\n methodName: string,\n dataReader: UserDataReader,\n databaseId: DatabaseId,\n fieldPath: InternalFieldPath,\n op: Operator,\n value: unknown\n): FieldFilter {\n let fieldValue: ProtoValue;\n if (fieldPath.isKeyField()) {\n if (op === Operator.ARRAY_CONTAINS || op === Operator.ARRAY_CONTAINS_ANY) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. You can't perform '${op}' queries on documentId().`\n );\n } else if (op === Operator.IN || op === Operator.NOT_IN) {\n validateDisjunctiveFilterElements(value, op);\n const referenceList: ProtoValue[] = [];\n for (const arrayValue of value as ProtoValue[]) {\n referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue));\n }\n fieldValue = { arrayValue: { values: referenceList } };\n } else {\n fieldValue = parseDocumentIdValue(databaseId, query, value);\n }\n } else {\n if (\n op === Operator.IN ||\n op === Operator.NOT_IN ||\n op === Operator.ARRAY_CONTAINS_ANY\n ) {\n validateDisjunctiveFilterElements(value, op);\n }\n fieldValue = parseQueryValue(\n dataReader,\n methodName,\n value,\n /* allowArrays= */ op === Operator.IN || op === Operator.NOT_IN\n );\n }\n const filter = FieldFilter.create(fieldPath, op, fieldValue);\n return filter;\n}\n\nexport function newQueryOrderBy(\n query: InternalQuery,\n fieldPath: InternalFieldPath,\n direction: Direction\n): OrderBy {\n if (query.startAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call startAt() or startAfter() before ' +\n 'calling orderBy().'\n );\n }\n if (query.endAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call endAt() or endBefore() before ' +\n 'calling orderBy().'\n );\n }\n const orderBy = new OrderBy(fieldPath, direction);\n return orderBy;\n}\n\n/**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */\nexport function newQueryBoundFromDocument(\n query: InternalQuery,\n databaseId: DatabaseId,\n methodName: string,\n doc: Document | null,\n inclusive: boolean\n): Bound {\n if (!doc) {\n throw new FirestoreError(\n Code.NOT_FOUND,\n `Can't use a DocumentSnapshot that doesn't exist for ` +\n `${methodName}().`\n );\n }\n\n const components: ProtoValue[] = [];\n\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n if (orderBy.field.isKeyField()) {\n components.push(refValue(databaseId, doc.key));\n } else {\n const value = doc.data.field(orderBy.field);\n if (isServerTimestamp(value)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You are trying to start or end a query using a ' +\n 'document for which the field \"' +\n orderBy.field +\n '\" is an uncommitted server timestamp. (Since the value of ' +\n 'this field is unknown, you cannot start/end a query with it.)'\n );\n } else if (value !== null) {\n components.push(value);\n } else {\n const field = orderBy.field.canonicalString();\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You are trying to start or end a query using a ` +\n `document for which the field '${field}' (used as the ` +\n `orderBy) does not exist.`\n );\n }\n }\n }\n return new Bound(components, inclusive);\n}\n\n/**\n * Converts a list of field values to a `Bound` for the given query.\n */\nexport function newQueryBoundFromFields(\n query: InternalQuery,\n databaseId: DatabaseId,\n dataReader: UserDataReader,\n methodName: string,\n values: unknown[],\n inclusive: boolean\n): Bound {\n // Use explicit order by's because it has to match the query the user made\n const orderBy = query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Too many arguments provided to ${methodName}(). ` +\n `The number of arguments must be less than or equal to the ` +\n `number of orderBy() clauses`\n );\n }\n\n const components: ProtoValue[] = [];\n for (let i = 0; i < values.length; i++) {\n const rawValue = values[i];\n const orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. Expected a string for document ID in ` +\n `${methodName}(), but got a ${typeof rawValue}`\n );\n }\n if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection and ordering by documentId(), ` +\n `the value passed to ${methodName}() must be a plain document ID, but ` +\n `'${rawValue}' contains a slash.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(rawValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group and ordering by ` +\n `documentId(), the value passed to ${methodName}() must result in a ` +\n `valid document path, but '${path}' is not because it contains an odd number ` +\n `of segments.`\n );\n }\n const key = new DocumentKey(path);\n components.push(refValue(databaseId, key));\n } else {\n const wrapped = parseQueryValue(dataReader, methodName, rawValue);\n components.push(wrapped);\n }\n }\n\n return new Bound(components, inclusive);\n}\n\n/**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */\nfunction parseDocumentIdValue(\n databaseId: DatabaseId,\n query: InternalQuery,\n documentIdValue: unknown\n): ProtoValue {\n documentIdValue = getModularInstance(documentIdValue);\n\n if (typeof documentIdValue === 'string') {\n if (documentIdValue === '') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. When querying with documentId(), you ' +\n 'must provide a valid document ID, but it was an empty string.'\n );\n }\n if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection by ` +\n `documentId(), you must provide a plain document ID, but ` +\n `'${documentIdValue}' contains a '/' character.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(documentIdValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group by ` +\n `documentId(), the value provided must result in a valid document path, ` +\n `but '${path}' is not because it has an odd number of segments (${path.length}).`\n );\n }\n return refValue(databaseId, new DocumentKey(path));\n } else if (documentIdValue instanceof DocumentReference) {\n return refValue(databaseId, documentIdValue._key);\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying with documentId(), you must provide a valid ` +\n `string or a DocumentReference, but it was: ` +\n `${valueDescription(documentIdValue)}.`\n );\n }\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */\nfunction validateDisjunctiveFilterElements(\n value: unknown,\n operator: Operator\n): void {\n if (!Array.isArray(value) || value.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid Query. A non-empty array is required for ' +\n `'${operator.toString()}' filters.`\n );\n }\n}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * This is not a comprehensive check, and this function should be removed in the\n * long term. Validations should occur in the Firestore backend.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one inequality per query.\n * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n */\nfunction conflictingOps(op: Operator): Operator[] {\n switch (op) {\n case Operator.NOT_EQUAL:\n return [Operator.NOT_EQUAL, Operator.NOT_IN];\n case Operator.ARRAY_CONTAINS_ANY:\n case Operator.IN:\n return [Operator.NOT_IN];\n case Operator.NOT_IN:\n return [\n Operator.ARRAY_CONTAINS_ANY,\n Operator.IN,\n Operator.NOT_IN,\n Operator.NOT_EQUAL\n ];\n default:\n return [];\n }\n}\n\nfunction validateNewFieldFilter(\n query: InternalQuery,\n fieldFilter: FieldFilter\n): void {\n const conflictingOp = findOpInsideFilters(\n query.filters,\n conflictingOps(fieldFilter.op)\n );\n if (conflictingOp !== null) {\n // Special case when it's a duplicate op to give a slightly clearer error message.\n if (conflictingOp === fieldFilter.op) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You cannot use more than one ' +\n `'${fieldFilter.op.toString()}' filter.`\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` +\n `with '${conflictingOp.toString()}' filters.`\n );\n }\n }\n}\n\nfunction validateNewFilter(query: InternalQuery, filter: Filter): void {\n let testQuery = query;\n const subFilters = filter.getFlattenedFilters();\n for (const subFilter of subFilters) {\n validateNewFieldFilter(testQuery, subFilter);\n testQuery = queryWithAddedFilter(testQuery, subFilter);\n }\n}\n\n// Checks if any of the provided filter operators are included in the given list of filters and\n// returns the first one that is, or null if none are.\nfunction findOpInsideFilters(\n filters: Filter[],\n operators: Operator[]\n): Operator | null {\n for (const filter of filters) {\n for (const fieldFilter of filter.getFlattenedFilters()) {\n if (operators.indexOf(fieldFilter.op) >= 0) {\n return fieldFilter.op;\n }\n }\n }\n return null;\n}\n\nexport function validateQueryFilterConstraint(\n functionName: string,\n queryConstraint: AppliableConstraint\n): void {\n if (\n !(queryConstraint instanceof QueryFieldFilterConstraint) &&\n !(queryConstraint instanceof QueryCompositeFilterConstraint)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`\n );\n }\n}\n\nfunction validateQueryConstraintArray(\n queryConstraint: AppliableConstraint[]\n): void {\n const compositeFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryCompositeFilterConstraint\n ).length;\n const fieldFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryFieldFilterConstraint\n ).length;\n\n if (\n compositeFilterCount > 1 ||\n (compositeFilterCount > 0 && fieldFilterCount > 0)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'InvalidQuery. When using composite filters, you cannot use ' +\n 'more than one filter at the top level. Consider nesting the multiple ' +\n 'filters within an `and(...)` statement. For example: ' +\n 'change `query(query, where(...), or(...))` to ' +\n '`query(query, and(where(...), or(...)))`.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentData } from '@firebase/firestore-types';\n\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from '../model/normalize';\nimport { ResourcePath } from '../model/path';\nimport {\n getLocalWriteTime,\n getPreviousValue\n} from '../model/server_timestamps';\nimport { TypeOrder } from '../model/type_order';\nimport { typeOrder } from '../model/values';\nimport {\n ApiClientObjectMap,\n ArrayValue as ProtoArrayValue,\n LatLng as ProtoLatLng,\n MapValue as ProtoMapValue,\n Timestamp as ProtoTimestamp,\n Value,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { isValidResourceName } from '../remote/serializer';\nimport { fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logError } from '../util/log';\nimport { forEach } from '../util/obj';\n\nimport { GeoPoint } from './geo_point';\nimport { Timestamp } from './timestamp';\n\nexport type ServerTimestampBehavior = 'estimate' | 'previous' | 'none';\n\n/**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */\nexport abstract class AbstractUserDataWriter {\n convertValue(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): unknown {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return null;\n case TypeOrder.BooleanValue:\n return value.booleanValue!;\n case TypeOrder.NumberValue:\n return normalizeNumber(value.integerValue || value.doubleValue);\n case TypeOrder.TimestampValue:\n return this.convertTimestamp(value.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return this.convertServerTimestamp(value, serverTimestampBehavior);\n case TypeOrder.StringValue:\n return value.stringValue!;\n case TypeOrder.BlobValue:\n return this.convertBytes(normalizeByteString(value.bytesValue!));\n case TypeOrder.RefValue:\n return this.convertReference(value.referenceValue!);\n case TypeOrder.GeoPointValue:\n return this.convertGeoPoint(value.geoPointValue!);\n case TypeOrder.ArrayValue:\n return this.convertArray(value.arrayValue!, serverTimestampBehavior);\n case TypeOrder.ObjectValue:\n return this.convertObject(value.mapValue!, serverTimestampBehavior);\n default:\n throw fail('Invalid value type: ' + JSON.stringify(value));\n }\n }\n\n private convertObject(\n mapValue: ProtoMapValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): DocumentData {\n return this.convertObjectMap(mapValue.fields, serverTimestampBehavior);\n }\n\n /**\n * @internal\n */\n convertObjectMap(\n fields: ApiClientObjectMap<Value> | undefined,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): DocumentData {\n const result: DocumentData = {};\n forEach(fields, (key, value) => {\n result[key] = this.convertValue(value, serverTimestampBehavior);\n });\n return result;\n }\n\n private convertGeoPoint(value: ProtoLatLng): GeoPoint {\n return new GeoPoint(\n normalizeNumber(value.latitude),\n normalizeNumber(value.longitude)\n );\n }\n\n private convertArray(\n arrayValue: ProtoArrayValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown[] {\n return (arrayValue.values || []).map(value =>\n this.convertValue(value, serverTimestampBehavior)\n );\n }\n\n private convertServerTimestamp(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown {\n switch (serverTimestampBehavior) {\n case 'previous':\n const previousValue = getPreviousValue(value);\n if (previousValue == null) {\n return null;\n }\n return this.convertValue(previousValue, serverTimestampBehavior);\n case 'estimate':\n return this.convertTimestamp(getLocalWriteTime(value));\n default:\n return null;\n }\n }\n\n private convertTimestamp(value: ProtoTimestamp): Timestamp {\n const normalizedValue = normalizeTimestamp(value);\n return new Timestamp(normalizedValue.seconds, normalizedValue.nanos);\n }\n\n protected convertDocumentKey(\n name: string,\n expectedDatabaseId: DatabaseId\n ): DocumentKey {\n const resourcePath = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resourcePath),\n 'ReferenceValue is not valid ' + name\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter<T>(\n converter: UntypedFirestoreDataConverter<T> | null,\n value: WithFieldValue<T> | PartialWithFieldValue<T>,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue<T>);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(result.length === 1, 'Expected a single document result');\n const document = result[0];\n return new DocumentSnapshot<AppModelType, DbModelType>(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n query = cast<Query<AppModelType, DbModelType>>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot<AppModelType, DbModelType>(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot<AppModelType, DbModelType>(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n): Promise<void>;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n): Promise<void>;\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options?: SetOptions\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: UpdateData<DbModelType>\n): Promise<void>;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise<void>;\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n fieldOrUpdateData: string | FieldPath | UpdateData<DbModelType>,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc<AppModelType, DbModelType extends DocumentData>(\n reference: CollectionReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n): Promise<DocumentReference<AppModelType, DbModelType>> {\n reference = cast<CollectionReference<AppModelType, DbModelType>>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue<AppModelType>\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { newQueryComparator } from '../core/query';\nimport { ChangeType, ViewSnapshot } from '../core/view_snapshot';\nimport { FieldPath } from '../lite-api/field_path';\nimport {\n DocumentData,\n PartialWithFieldValue,\n Query,\n queryEqual,\n SetOptions,\n WithFieldValue\n} from '../lite-api/reference';\nimport {\n DocumentSnapshot as LiteDocumentSnapshot,\n fieldPathFromArgument,\n FirestoreDataConverter as LiteFirestoreDataConverter\n} from '../lite-api/snapshot';\nimport { UntypedFirestoreDataConverter } from '../lite-api/user_data_reader';\nimport { AbstractUserDataWriter } from '../lite-api/user_data_writer';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { Firestore } from './database';\nimport { SnapshotListenOptions } from './reference_impl';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * @example\n * ```typescript\n * class Post {\n * constructor(readonly title: string, readonly author: string) {}\n *\n * toString(): string {\n * return this.title + ', by ' + this.author;\n * }\n * }\n *\n * interface PostDbModel {\n * title: string;\n * author: string;\n * }\n *\n * const postConverter = {\n * toFirestore(post: WithFieldValue<Post>): PostDbModel {\n * return {title: post.title, author: post.author};\n * },\n * fromFirestore(\n * snapshot: QueryDocumentSnapshot,\n * options: SnapshotOptions\n * ): Post {\n * const data = snapshot.data(options) as PostDbModel;\n * return new Post(data.title, data.author);\n * }\n * };\n *\n * const postSnap = await firebase.firestore()\n * .collection('posts')\n * .withConverter(postConverter)\n * .doc().get();\n * const post = postSnap.data();\n * if (post !== undefined) {\n * post.title; // string\n * post.toString(); // Should be defined\n * post.someNonExistentProperty; // TS error\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> extends LiteFirestoreDataConverter<AppModelType, DbModelType> {\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. To use `set()`\n * with `merge` and `mergeFields`, `toFirestore()` must be defined with\n * `PartialWithFieldValue<AppModelType>`.\n *\n * The `WithFieldValue<T>` type extends `T` to also allow FieldValues such as\n * {@link (deleteField:1)} to be used as property values.\n */\n toFirestore(\n modelObject: WithFieldValue<AppModelType>\n ): WithFieldValue<DbModelType>;\n\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and\n * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`.\n *\n * The `PartialWithFieldValue<T>` type extends `Partial<T>` to allow\n * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n * It also supports nested `Partial` by allowing nested fields to be\n * omitted.\n */\n toFirestore(\n modelObject: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n ): PartialWithFieldValue<DbModelType>;\n\n /**\n * Called by the Firestore SDK to convert Firestore data into an object of\n * type `AppModelType`. You can access your data by calling:\n * `snapshot.data(options)`.\n *\n * Generally, the data returned from `snapshot.data()` can be cast to\n * `DbModelType`; however, this is not guaranteed as writes to the database\n * may have occurred without a type converter enforcing this specific layout.\n *\n * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata.\n * @param options - The `SnapshotOptions` from the initial call to `data()`.\n */\n fromFirestore(\n snapshot: QueryDocumentSnapshot<DocumentData, DocumentData>,\n options?: SnapshotOptions\n ): AppModelType;\n}\n\n/**\n * Options that configure how data is retrieved from a `DocumentSnapshot` (for\n * example the desired behavior for server timestamps that have not yet been set\n * to their final value).\n */\nexport interface SnapshotOptions {\n /**\n * If set, controls the return value for server timestamps that have not yet\n * been set to their final value.\n *\n * By specifying 'estimate', pending server timestamps return an estimate\n * based on the local clock. This estimate will differ from the final value\n * and cause these values to change once the server result becomes available.\n *\n * By specifying 'previous', pending timestamps will be ignored and return\n * their previous value instead.\n *\n * If omitted or set to 'none', `null` will be returned by default until the\n * server value becomes available.\n */\n readonly serverTimestamps?: 'estimate' | 'previous' | 'none';\n}\n\n/**\n * Metadata about a snapshot, describing the state of the snapshot.\n */\nexport class SnapshotMetadata {\n /**\n * True if the snapshot contains the result of local writes (for example\n * `set()` or `update()` calls) that have not yet been committed to the\n * backend. If your listener has opted into metadata updates (via\n * `SnapshotListenOptions`) you will receive another snapshot with\n * `hasPendingWrites` equal to false once the writes have been committed to\n * the backend.\n */\n readonly hasPendingWrites: boolean;\n\n /**\n * True if the snapshot was created from cached data rather than guaranteed\n * up-to-date server data. If your listener has opted into metadata updates\n * (via `SnapshotListenOptions`) you will receive another snapshot with\n * `fromCache` set to false once the client has received up-to-date data from\n * the backend.\n */\n readonly fromCache: boolean;\n\n /** @hideconstructor */\n constructor(hasPendingWrites: boolean, fromCache: boolean) {\n this.hasPendingWrites = hasPendingWrites;\n this.fromCache = fromCache;\n }\n\n /**\n * Returns true if this `SnapshotMetadata` is equal to the provided one.\n *\n * @param other - The `SnapshotMetadata` to compare against.\n * @returns true if this `SnapshotMetadata` is equal to the provided one.\n */\n isEqual(other: SnapshotMetadata): boolean {\n return (\n this.hasPendingWrites === other.hasPendingWrites &&\n this.fromCache === other.fromCache\n );\n }\n}\n\n/**\n * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'.\n */\nexport type DocumentChangeType = 'added' | 'removed' | 'modified';\n\n/**\n * A `DocumentChange` represents a change to the documents matching a query.\n * It contains the document affected and the type of change that occurred.\n */\nexport interface DocumentChange<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of change ('added', 'modified', or 'removed'). */\n readonly type: DocumentChangeType;\n\n /** The document affected by this change. */\n readonly doc: QueryDocumentSnapshot<AppModelType, DbModelType>;\n\n /**\n * The index of the changed document in the result set immediately prior to\n * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects\n * have been applied). Is `-1` for 'added' events.\n */\n readonly oldIndex: number;\n\n /**\n * The index of the changed document in the result set immediately after\n * this `DocumentChange` (i.e. supposing that all prior `DocumentChange`\n * objects and the current `DocumentChange` object have been applied).\n * Is -1 for 'removed' events.\n */\n readonly newIndex: number;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get(<field>)` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends LiteDocumentSnapshot<AppModelType, DbModelType> {\n private readonly _firestoreImpl: Firestore;\n\n /**\n * Metadata about the `DocumentSnapshot`, including information about its\n * source and local modifications.\n */\n readonly metadata: SnapshotMetadata;\n\n /** @hideconstructor protected */\n constructor(\n readonly _firestore: Firestore,\n userDataWriter: AbstractUserDataWriter,\n key: DocumentKey,\n document: Document | null,\n metadata: SnapshotMetadata,\n converter: UntypedFirestoreDataConverter<AppModelType, DbModelType> | null\n ) {\n super(_firestore, userDataWriter, key, document, converter);\n this._firestoreImpl = _firestore;\n this.metadata = metadata;\n }\n\n /**\n * Returns whether or not the data exists. True if the document exists.\n */\n exists(): this is QueryDocumentSnapshot<AppModelType, DbModelType> {\n return super.exists();\n }\n\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document or `undefined` if\n * the document doesn't exist.\n */\n data(options: SnapshotOptions = {}): AppModelType | undefined {\n if (!this._document) {\n return undefined;\n } else if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n this._key,\n this._document,\n this.metadata,\n /* converter= */ null\n );\n return this._converter.fromFirestore(snapshot, options);\n } else {\n return this._userDataWriter.convertValue(\n this._document.data.value,\n options.serverTimestamps\n ) as AppModelType;\n }\n }\n\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * By default, a `serverTimestamp()` that has not yet been set to\n * its final value will be returned as `null`. You can override this by\n * passing an options object.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @param options - An options object to configure how the field is retrieved\n * from the snapshot (for example the desired behavior for server timestamps\n * that have not yet been set to their final value).\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(fieldPath: string | FieldPath, options: SnapshotOptions = {}): any {\n if (this._document) {\n const value = this._document.data.field(\n fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n );\n if (value !== null) {\n return this._userDataWriter.convertValue(\n value,\n options.serverTimestamps\n );\n }\n }\n return undefined;\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get(<field>)` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot<AppModelType, DbModelType> {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @override\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document.\n */\n data(options: SnapshotOptions = {}): AppModelType {\n return super.data(options) as AppModelType;\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * Metadata about this snapshot, concerning its source and if it has local\n * modifications.\n */\n readonly metadata: SnapshotMetadata;\n\n /**\n * The query on which you called `get` or `onSnapshot` in order to get this\n * `QuerySnapshot`.\n */\n readonly query: Query<AppModelType, DbModelType>;\n\n private _cachedChanges?: Array<DocumentChange<AppModelType, DbModelType>>;\n private _cachedChangesIncludeMetadataChanges?: boolean;\n\n /** @hideconstructor */\n constructor(\n readonly _firestore: Firestore,\n readonly _userDataWriter: AbstractUserDataWriter,\n query: Query<AppModelType, DbModelType>,\n readonly _snapshot: ViewSnapshot\n ) {\n this.metadata = new SnapshotMetadata(\n _snapshot.hasPendingWrites,\n _snapshot.fromCache\n );\n this.query = query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array<QueryDocumentSnapshot<AppModelType, DbModelType>> {\n const result: Array<QueryDocumentSnapshot<AppModelType, DbModelType>> = [];\n this.forEach(doc => result.push(doc));\n return result;\n }\n\n /** The number of documents in the `QuerySnapshot`. */\n get size(): number {\n return this._snapshot.docs.size;\n }\n\n /** True if there are no documents in the `QuerySnapshot`. */\n get empty(): boolean {\n return this.size === 0;\n }\n\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */\n forEach(\n callback: (\n result: QueryDocumentSnapshot<AppModelType, DbModelType>\n ) => void,\n thisArg?: unknown\n ): void {\n this._snapshot.docs.forEach(doc => {\n callback.call(\n thisArg,\n new QueryDocumentSnapshot<AppModelType, DbModelType>(\n this._firestore,\n this._userDataWriter,\n doc.key,\n doc,\n new SnapshotMetadata(\n this._snapshot.mutatedKeys.has(doc.key),\n this._snapshot.fromCache\n ),\n this.query.converter\n )\n );\n });\n }\n\n /**\n * Returns an array of the documents changes since the last snapshot. If this\n * is the first snapshot, all documents will be in the list as 'added'\n * changes.\n *\n * @param options - `SnapshotListenOptions` that control whether metadata-only\n * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger\n * snapshot events.\n */\n docChanges(\n options: SnapshotListenOptions = {}\n ): Array<DocumentChange<AppModelType, DbModelType>> {\n const includeMetadataChanges = !!options.includeMetadataChanges;\n\n if (includeMetadataChanges && this._snapshot.excludesMetadataChanges) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'To include metadata changes with your document changes, you must ' +\n 'also pass { includeMetadataChanges:true } to onSnapshot().'\n );\n }\n\n if (\n !this._cachedChanges ||\n this._cachedChangesIncludeMetadataChanges !== includeMetadataChanges\n ) {\n this._cachedChanges = changesFromSnapshot(this, includeMetadataChanges);\n this._cachedChangesIncludeMetadataChanges = includeMetadataChanges;\n }\n\n return this._cachedChanges;\n }\n}\n\n/** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */\nexport function changesFromSnapshot<\n AppModelType,\n DbModelType extends DocumentData\n>(\n querySnapshot: QuerySnapshot<AppModelType, DbModelType>,\n includeMetadataChanges: boolean\n): Array<DocumentChange<AppModelType, DbModelType>> {\n if (querySnapshot._snapshot.oldDocs.isEmpty()) {\n // Special case the first snapshot because index calculation is easy and\n // fast\n let lastDoc: Document;\n let index = 0;\n return querySnapshot._snapshot.docChanges.map(change => {\n debugAssert(\n change.type === ChangeType.Added,\n 'Invalid event type for first snapshot'\n );\n debugAssert(\n !lastDoc ||\n newQueryComparator(querySnapshot._snapshot.query)(\n lastDoc,\n change.doc\n ) < 0,\n 'Got added events in wrong order'\n );\n const doc = new QueryDocumentSnapshot<AppModelType, DbModelType>(\n querySnapshot._firestore,\n querySnapshot._userDataWriter,\n change.doc.key,\n change.doc,\n new SnapshotMetadata(\n querySnapshot._snapshot.mutatedKeys.has(change.doc.key),\n querySnapshot._snapshot.fromCache\n ),\n querySnapshot.query.converter\n );\n lastDoc = change.doc;\n return {\n type: 'added' as DocumentChangeType,\n doc,\n oldIndex: -1,\n newIndex: index++\n };\n });\n } else {\n // A `DocumentSet` that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n let indexTracker = querySnapshot._snapshot.oldDocs;\n return querySnapshot._snapshot.docChanges\n .filter(\n change => includeMetadataChanges || change.type !== ChangeType.Metadata\n )\n .map(change => {\n const doc = new QueryDocumentSnapshot<AppModelType, DbModelType>(\n querySnapshot._firestore,\n querySnapshot._userDataWriter,\n change.doc.key,\n change.doc,\n new SnapshotMetadata(\n querySnapshot._snapshot.mutatedKeys.has(change.doc.key),\n querySnapshot._snapshot.fromCache\n ),\n querySnapshot.query.converter\n );\n let oldIndex = -1;\n let newIndex = -1;\n if (change.type !== ChangeType.Added) {\n oldIndex = indexTracker.indexOf(change.doc.key);\n debugAssert(oldIndex >= 0, 'Index for document not found');\n indexTracker = indexTracker.delete(change.doc.key);\n }\n if (change.type !== ChangeType.Removed) {\n indexTracker = indexTracker.add(change.doc);\n newIndex = indexTracker.indexOf(change.doc.key);\n }\n return {\n type: resultChangeType(change.type),\n doc,\n oldIndex,\n newIndex\n };\n });\n }\n}\n\nexport function resultChangeType(type: ChangeType): DocumentChangeType {\n switch (type) {\n case ChangeType.Added:\n return 'added';\n case ChangeType.Modified:\n case ChangeType.Metadata:\n return 'modified';\n case ChangeType.Removed:\n return 'removed';\n default:\n return fail('Unknown change type: ' + type);\n }\n}\n\n// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot\n// metadata\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual<AppModelType, DbModelType extends DocumentData>(\n left:\n | DocumentSnapshot<AppModelType, DbModelType>\n | QuerySnapshot<AppModelType, DbModelType>,\n right:\n | DocumentSnapshot<AppModelType, DbModelType>\n | QuerySnapshot<AppModelType, DbModelType>\n): boolean {\n if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n return (\n left._firestore === right._firestore &&\n left._key.isEqual(right._key) &&\n (left._document === null\n ? right._document === null\n : left._document.isEqual(right._document)) &&\n left._converter === right._converter\n );\n } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n return (\n left._firestore === right._firestore &&\n queryEqual(left.query, right.query) &&\n left.metadata.isEqual(right.metadata) &&\n left._snapshot.isEqual(right._snapshot)\n );\n }\n\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport {\n CompleteFn,\n ErrorFn,\n isPartialObserver,\n NextFn,\n PartialObserver\n} from '../api/observer';\nimport {\n firestoreClientAddSnapshotsInSyncListener,\n firestoreClientGetDocumentFromLocalCache,\n firestoreClientGetDocumentsFromLocalCache,\n firestoreClientGetDocumentsViaSnapshotListener,\n firestoreClientGetDocumentViaSnapshotListener,\n firestoreClientListen,\n firestoreClientWrite\n} from '../core/firestore_client';\nimport { newQueryForPath, Query as InternalQuery } from '../core/query';\nimport { ViewSnapshot } from '../core/view_snapshot';\nimport { Bytes } from '../lite-api/bytes';\nimport { FieldPath } from '../lite-api/field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from '../lite-api/query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from '../lite-api/reference';\nimport { applyFirestoreDataConverter } from '../lite-api/reference_impl';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs\n} from '../lite-api/user_data_reader';\nimport { AbstractUserDataWriter } from '../lite-api/user_data_writer';\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { DocumentSnapshot, QuerySnapshot, SnapshotMetadata } from './snapshot';\n\n/**\n * An options object that can be passed to {@link (onSnapshot:1)} and {@link\n * QuerySnapshot.docChanges} to control which types of changes to include in the\n * result set.\n */\nexport interface SnapshotListenOptions {\n /**\n * Include a change even if only the metadata of the query or of a document\n * changed. Default is false.\n */\n readonly includeMetadataChanges?: boolean;\n}\n\n/**\n * Reads the document referred to by this `DocumentReference`.\n *\n * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting\n * for data from the server, but it may return cached data or fail if you are\n * offline and the server cannot be reached. To specify this behavior, invoke\n * {@link getDocFromCache} or {@link getDocFromServer}.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */\nexport function getDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n\n return firestoreClientGetDocumentViaSnapshotListener(\n client,\n reference._key\n ).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot));\n}\n\nexport class ExpUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from cache.\n * Returns an error if the document is not currently cached.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */\nexport function getDocFromCache<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n return firestoreClientGetDocumentFromLocalCache(client, reference._key).then(\n doc =>\n new DocumentSnapshot<AppModelType, DbModelType>(\n firestore,\n userDataWriter,\n reference._key,\n doc,\n new SnapshotMetadata(\n doc !== null && doc.hasLocalMutations,\n /* fromCache= */ true\n ),\n reference.converter\n )\n );\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from the server.\n * Returns an error if the network is not available.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */\nexport function getDocFromServer<\n AppModelType,\n DbModelType extends DocumentData\n>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n\n return firestoreClientGetDocumentViaSnapshotListener(client, reference._key, {\n source: 'server'\n }).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot`.\n *\n * Note: `getDocs()` attempts to provide up-to-date data when possible by\n * waiting for data from the server, but it may return cached data or fail if\n * you are offline and the server cannot be reached. To specify this behavior,\n * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */\nexport function getDocs<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n query = cast<Query<AppModelType, DbModelType>>(query, Query);\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n validateHasExplicitOrderByForLimitToLast(query._query);\n return firestoreClientGetDocumentsViaSnapshotListener(\n client,\n query._query\n ).then(\n snapshot =>\n new QuerySnapshot<AppModelType, DbModelType>(\n firestore,\n userDataWriter,\n query,\n snapshot\n )\n );\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from cache.\n * Returns an empty result set if no documents matching the query are currently\n * cached.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */\nexport function getDocsFromCache<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n query = cast<Query<AppModelType, DbModelType>>(query, Query);\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n return firestoreClientGetDocumentsFromLocalCache(client, query._query).then(\n snapshot =>\n new QuerySnapshot<AppModelType, DbModelType>(\n firestore,\n userDataWriter,\n query,\n snapshot\n )\n );\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from the\n * server. Returns an error if the network is not available.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */\nexport function getDocsFromServer<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n query = cast<Query<AppModelType, DbModelType>>(query, Query);\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n return firestoreClientGetDocumentsViaSnapshotListener(client, query._query, {\n source: 'server'\n }).then(\n snapshot => new QuerySnapshot(firestore, userDataWriter, query, snapshot)\n );\n}\n\n/**\n * Writes to the document referred to by this `DocumentReference`. If the\n * document does not yet exist, it will be created.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n): Promise<void>;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @returns A Promise resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n): Promise<void>;\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options?: SetOptions\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as WithFieldValue<AppModelType>,\n options\n );\n const dataReader = newUserDataReader(firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const mutation = parsed.toMutation(reference._key, Precondition.none());\n return executeWrite(firestore, [mutation]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: UpdateData<DbModelType>\n): Promise<void>;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise<void>;\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<unknown>,\n fieldOrUpdateData: string | FieldPath | UpdateData<DbModelType>,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n\n const dataReader = newUserDataReader(firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const mutation = parsed.toMutation(reference._key, Precondition.exists(true));\n return executeWrite(firestore, [mutation]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * @param reference - A reference to the document to delete.\n * @returns A Promise resolved once the document has been successfully\n * deleted from the backend (note that it won't resolve while you're offline).\n */\nexport function deleteDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<void> {\n const firestore = cast(reference.firestore, Firestore);\n const mutations = [new DeleteMutation(reference._key, Precondition.none())];\n return executeWrite(firestore, mutations);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend (Note that it\n * won't resolve while you're offline).\n */\nexport function addDoc<AppModelType, DbModelType extends DocumentData>(\n reference: CollectionReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n): Promise<DocumentReference<AppModelType, DbModelType>> {\n const firestore = cast(reference.firestore, Firestore);\n\n const docRef = doc(reference);\n const convertedValue = applyFirestoreDataConverter(reference.converter, data);\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n reference.converter !== null,\n {}\n );\n\n const mutation = parsed.toMutation(docRef._key, Precondition.exists(false));\n return executeWrite(firestore, [mutation]).then(() => docRef);\n}\n\n/**\n * A function returned by `onSnapshot()` that removes the listener when invoked.\n */\nexport interface Unsubscribe {\n /** Removes the listener when invoked. */\n (): void;\n}\n\n// TODO(firestorexp): Make sure these overloads are tested via the Firestore\n// integration tests\n\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n observer: {\n next?: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n options: SnapshotListenOptions,\n observer: {\n next?: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot`\n * is available.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n onNext: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot`\n * is available.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n options: SnapshotListenOptions,\n onNext: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n observer: {\n next?: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n options: SnapshotListenOptions,\n observer: {\n next?: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param onNext - A callback to be called every time a new `QuerySnapshot`\n * is available.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n onNext: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `QuerySnapshot`\n * is available.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n options: SnapshotListenOptions,\n onNext: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n reference:\n | Query<AppModelType, DbModelType>\n | DocumentReference<AppModelType, DbModelType>,\n ...args: unknown[]\n): Unsubscribe {\n reference = getModularInstance(reference);\n\n let options: SnapshotListenOptions = {\n includeMetadataChanges: false\n };\n let currArg = 0;\n if (typeof args[currArg] === 'object' && !isPartialObserver(args[currArg])) {\n options = args[currArg] as SnapshotListenOptions;\n currArg++;\n }\n\n const internalOptions = {\n includeMetadataChanges: options.includeMetadataChanges\n };\n\n if (isPartialObserver(args[currArg])) {\n const userObserver = args[currArg] as PartialObserver<\n QuerySnapshot<AppModelType, DbModelType>\n >;\n args[currArg] = userObserver.next?.bind(userObserver);\n args[currArg + 1] = userObserver.error?.bind(userObserver);\n args[currArg + 2] = userObserver.complete?.bind(userObserver);\n }\n\n let observer: PartialObserver<ViewSnapshot>;\n let firestore: Firestore;\n let internalQuery: InternalQuery;\n\n if (reference instanceof DocumentReference) {\n firestore = cast(reference.firestore, Firestore);\n internalQuery = newQueryForPath(reference._key.path);\n\n observer = {\n next: snapshot => {\n if (args[currArg]) {\n (\n args[currArg] as NextFn<DocumentSnapshot<AppModelType, DbModelType>>\n )(\n convertToDocSnapshot(\n firestore,\n reference as DocumentReference<AppModelType, DbModelType>,\n snapshot\n )\n );\n }\n },\n error: args[currArg + 1] as ErrorFn,\n complete: args[currArg + 2] as CompleteFn\n };\n } else {\n const query = cast<Query<AppModelType, DbModelType>>(reference, Query);\n firestore = cast(query.firestore, Firestore);\n internalQuery = query._query;\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n observer = {\n next: snapshot => {\n if (args[currArg]) {\n (args[currArg] as NextFn<QuerySnapshot<AppModelType, DbModelType>>)(\n new QuerySnapshot(firestore, userDataWriter, query, snapshot)\n );\n }\n },\n error: args[currArg + 1] as ErrorFn,\n complete: args[currArg + 2] as CompleteFn\n };\n\n validateHasExplicitOrderByForLimitToLast(reference._query);\n }\n\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientListen(\n client,\n internalQuery,\n internalOptions,\n observer\n );\n}\n\n// TODO(firestorexp): Make sure these overloads are tested via the Firestore\n// integration tests\n\n/**\n * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync\n * event indicates that all listeners affected by a given change have fired,\n * even if a single server-generated change affects multiple listeners.\n *\n * NOTE: The snapshots-in-sync event only indicates that listeners are in sync\n * with each other, but does not relate to whether those snapshots are in sync\n * with the server. Use SnapshotMetadata in the individual listeners to\n * determine if a snapshot is from the cache or the server.\n *\n * @param firestore - The instance of Firestore for synchronizing snapshots.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n */\nexport function onSnapshotsInSync(\n firestore: Firestore,\n observer: {\n next?: (value: void) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync\n * event indicates that all listeners affected by a given change have fired,\n * even if a single server-generated change affects multiple listeners.\n *\n * NOTE: The snapshots-in-sync event only indicates that listeners are in sync\n * with each other, but does not relate to whether those snapshots are in sync\n * with the server. Use `SnapshotMetadata` in the individual listeners to\n * determine if a snapshot is from the cache or the server.\n *\n * @param firestore - The `Firestore` instance for synchronizing snapshots.\n * @param onSync - A callback to be called every time all snapshot listeners are\n * in sync with each other.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n */\nexport function onSnapshotsInSync(\n firestore: Firestore,\n onSync: () => void\n): Unsubscribe;\nexport function onSnapshotsInSync(\n firestore: Firestore,\n arg: unknown\n): Unsubscribe {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const observer = isPartialObserver(arg)\n ? (arg as PartialObserver<void>)\n : {\n next: arg as () => void\n };\n\n return firestoreClientAddSnapshotsInSyncListener(client, observer);\n}\n\n/**\n * Locally writes `mutations` on the async queue.\n * @internal\n */\nexport function executeWrite(\n firestore: Firestore,\n mutations: Mutation[]\n): Promise<void> {\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientWrite(client, mutations);\n}\n\n/**\n * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`\n * to a {@link DocumentSnapshot}.\n */\nfunction convertToDocSnapshot<AppModelType, DbModelType extends DocumentData>(\n firestore: Firestore,\n ref: DocumentReference<AppModelType, DbModelType>,\n snapshot: ViewSnapshot\n): DocumentSnapshot<AppModelType, DbModelType> {\n debugAssert(\n snapshot.docs.size <= 1,\n 'Expected zero or a single result on a document-only query'\n );\n const doc = snapshot.docs.get(ref._key);\n\n const userDataWriter = new ExpUserDataWriter(firestore);\n return new DocumentSnapshot<AppModelType, DbModelType>(\n firestore,\n userDataWriter,\n ref._key,\n doc,\n new SnapshotMetadata(snapshot.hasPendingWrites, snapshot.fromCache),\n ref.converter\n );\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n firestoreClientDeleteAllFieldIndexes,\n firestoreClientSetPersistentCacheIndexAutoCreationEnabled,\n FirestoreClient\n} from '../core/firestore_client';\nimport { cast } from '../util/input_validation';\nimport { logDebug, logWarn } from '../util/log';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\n\n/**\n * A `PersistentCacheIndexManager` for configuring persistent cache indexes used\n * for local query execution.\n *\n * To use, call `getPersistentCacheIndexManager()` to get an instance.\n */\nexport class PersistentCacheIndexManager {\n /** A type string to uniquely identify instances of this class. */\n readonly type: 'PersistentCacheIndexManager' = 'PersistentCacheIndexManager';\n\n /** @hideconstructor */\n constructor(readonly _client: FirestoreClient) {}\n}\n\n/**\n * Returns the PersistentCache Index Manager used by the given `Firestore`\n * object.\n *\n * @return The `PersistentCacheIndexManager` instance, or `null` if local\n * persistent storage is not in use.\n */\nexport function getPersistentCacheIndexManager(\n firestore: Firestore\n): PersistentCacheIndexManager | null {\n firestore = cast(firestore, Firestore);\n\n const cachedInstance = persistentCacheIndexManagerByFirestore.get(firestore);\n if (cachedInstance) {\n return cachedInstance;\n }\n\n const client = ensureFirestoreConfigured(firestore);\n if (client._uninitializedComponentsProvider?._offlineKind !== 'persistent') {\n return null;\n }\n\n const instance = new PersistentCacheIndexManager(client);\n persistentCacheIndexManagerByFirestore.set(firestore, instance);\n return instance;\n}\n\n/**\n * Enables the SDK to create persistent cache indexes automatically for local\n * query execution when the SDK believes cache indexes can help improve\n * performance.\n *\n * This feature is disabled by default.\n */\nexport function enablePersistentCacheIndexAutoCreation(\n indexManager: PersistentCacheIndexManager\n): void {\n setPersistentCacheIndexAutoCreationEnabled(indexManager, true);\n}\n\n/**\n * Stops creating persistent cache indexes automatically for local query\n * execution. The indexes which have been created by calling\n * `enablePersistentCacheIndexAutoCreation()` still take effect.\n */\nexport function disablePersistentCacheIndexAutoCreation(\n indexManager: PersistentCacheIndexManager\n): void {\n setPersistentCacheIndexAutoCreationEnabled(indexManager, false);\n}\n\n/**\n * Removes all persistent cache indexes.\n *\n * Please note this function will also deletes indexes generated by\n * `setIndexConfiguration()`, which is deprecated.\n */\nexport function deleteAllPersistentCacheIndexes(\n indexManager: PersistentCacheIndexManager\n): void {\n indexManager._client.verifyNotTerminated();\n\n const promise = firestoreClientDeleteAllFieldIndexes(indexManager._client);\n\n promise\n .then(_ => logDebug('deleting all persistent cache indexes succeeded'))\n .catch(error =>\n logWarn('deleting all persistent cache indexes failed', error)\n );\n}\n\nfunction setPersistentCacheIndexAutoCreationEnabled(\n indexManager: PersistentCacheIndexManager,\n isEnabled: boolean\n): void {\n indexManager._client.verifyNotTerminated();\n\n const promise = firestoreClientSetPersistentCacheIndexAutoCreationEnabled(\n indexManager._client,\n isEnabled\n );\n\n promise\n .then(_ =>\n logDebug(\n `setting persistent cache index auto creation ` +\n `isEnabled=${isEnabled} succeeded`\n )\n )\n .catch(error =>\n logWarn(\n `setting persistent cache index auto creation ` +\n `isEnabled=${isEnabled} failed`,\n error\n )\n );\n}\n\n/**\n * Maps `Firestore` instances to their corresponding\n * `PersistentCacheIndexManager` instances.\n *\n * Use a `WeakMap` so that the mapping will be automatically dropped when the\n * `Firestore` instance is garbage collected. This emulates a private member\n * as described in https://goo.gle/454yvug.\n */\nconst persistentCacheIndexManagerByFirestore = new WeakMap<\n Firestore,\n PersistentCacheIndexManager\n>();\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { name, version } from '../package.json';\nimport {\n FirebaseAppCheckTokenProvider,\n FirebaseAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { setSDKVersion } from '../src/core/version';\n\nimport { Firestore } from './api/database';\nimport { databaseIdFromApp } from './core/database_info';\n\nexport function registerFirestore(\n variant?: string,\n useFetchStreams = true\n): void {\n setSDKVersion(SDK_VERSION);\n _registerComponent(\n new Component(\n 'firestore',\n (container, { instanceIdentifier: databaseId, options: settings }) => {\n const app = container.getProvider('app').getImmediate()!;\n const firestoreInstance = new Firestore(\n new FirebaseAuthCredentialsProvider(\n container.getProvider('auth-internal')\n ),\n new FirebaseAppCheckTokenProvider(\n container.getProvider('app-check-internal')\n ),\n databaseIdFromApp(app, databaseId),\n app\n );\n settings = { useFetchStreams, ...settings };\n firestoreInstance._setSettings(settings);\n return firestoreInstance;\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * Cloud Firestore\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Firestore } from './api/database';\nimport { registerFirestore } from './register';\n\nregisterFirestore();\n\nexport * from './api';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore': Firestore;\n }\n}\n","// Import the functions you need from the SDKs you need\nimport { initializeApp } from \"firebase/app\";\nimport { getAnalytics } from \"firebase/analytics\";\nimport { getAuth} from \"firebase/auth\"\nimport { getFirestore } from \"firebase/firestore\"\n// TODO: Add SDKs for Firebase products that you want to use\n// https://firebase.google.com/docs/web/setup#available-libraries\n\n// Your web app's Firebase configuration\n// For Firebase JS SDK v7.20.0 and later, measurementId is optional\nconst firebaseConfig = {\n apiKey: \"AIzaSyDZjgosQcTQgNfvwAaFC_W6R5Sv0JjjxkM\",\n authDomain: \"friendly-betting-fb47e.firebaseapp.com\",\n projectId: \"friendly-betting-fb47e\",\n storageBucket: \"friendly-betting-fb47e.appspot.com\",\n messagingSenderId: \"897713635691\",\n appId: \"1:897713635691:web:70b530052a319f77e14c2e\",\n measurementId: \"G-74305KF5X4\"\n};\n\n// Initialize Firebase\nconst app = initializeApp(firebaseConfig);\nconst analytics = getAnalytics(app);\n\n\nexport const auth = getAuth(app);\nexport const db = getFirestore(app);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\nimport {\n Auth,\n NextOrObserver,\n Persistence,\n User,\n CompleteFn,\n ErrorFn,\n Unsubscribe,\n PasswordValidationStatus\n} from '../model/public_types';\nimport { _initializeRecaptchaConfig } from '../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { _castAuth } from '../core/auth/auth_impl';\n\nexport {\n debugErrorMap,\n prodErrorMap,\n AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as AuthErrorCodes\n} from './errors';\n\n// Non-optional auth methods.\n/**\n * Changes the type of persistence on the {@link Auth} instance for the currently saved\n * `Auth` session and applies this type of persistence for future sign-in requests, including\n * sign-in with redirect requests.\n *\n * @remarks\n * This makes it easy for a user signing in to specify whether their session should be\n * remembered or not. It also makes it easier to never persist the `Auth` state for applications\n * that are shared by other users or have sensitive data.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * setPersistence(auth, browserSessionPersistence);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param persistence - The {@link Persistence} to use.\n * @returns A `Promise` that resolves once the persistence change has completed\n *\n * @public\n */\nexport function setPersistence(\n auth: Auth,\n persistence: Persistence\n): Promise<void> {\n return getModularInstance(auth).setPersistence(persistence);\n}\n\n/**\n * Loads the reCAPTCHA configuration into the `Auth` instance.\n *\n * @remarks\n * This will load the reCAPTCHA config, which indicates whether the reCAPTCHA\n * verification flow should be triggered for each auth provider, into the\n * current Auth session.\n *\n * If initializeRecaptchaConfig() is not invoked, the auth flow will always start\n * without reCAPTCHA verification. If the provider is configured to require reCAPTCHA\n * verification, the SDK will transparently load the reCAPTCHA config and restart the\n * auth flows.\n *\n * Thus, by calling this optional method, you will reduce the latency of future auth flows.\n * Loading the reCAPTCHA config early will also enhance the signal collected by reCAPTCHA.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * initializeRecaptchaConfig(auth);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport function initializeRecaptchaConfig(auth: Auth): Promise<void> {\n return _initializeRecaptchaConfig(auth);\n}\n\n/**\n * Validates the password against the password policy configured for the project or tenant.\n *\n * @remarks\n * If no tenant ID is set on the `Auth` instance, then this method will use the password\n * policy configured for the project. Otherwise, this method will use the policy configured\n * for the tenant. If a password policy has not been configured, then the default policy\n * configured for all projects will be used.\n *\n * If an auth flow fails because a submitted password does not meet the password policy\n * requirements and this method has previously been called, then this method will use the\n * most recent policy available when called again.\n *\n * @example\n * ```javascript\n * validatePassword(auth, 'some-password');\n * ```\n *\n * @param auth The {@link Auth} instance.\n * @param password The password to validate.\n *\n * @public\n */\nexport async function validatePassword(\n auth: Auth,\n password: string\n): Promise<PasswordValidationStatus> {\n const authInternal = _castAuth(auth);\n return authInternal.validatePassword(password);\n}\n\n/**\n * Adds an observer for changes to the signed-in user's ID token.\n *\n * @remarks\n * This includes sign-in, sign-out, and token refresh events.\n * This will not be triggered automatically upon ID token expiration. Use {@link User.getIdToken} to refresh the ID token.\n *\n * @param auth - The {@link Auth} instance.\n * @param nextOrObserver - callback triggered on change.\n * @param error - Deprecated. This callback is never triggered. Errors\n * on signing in/out can be caught in promises returned from\n * sign-in/sign-out functions.\n * @param completed - Deprecated. This callback is never triggered.\n *\n * @public\n */\nexport function onIdTokenChanged(\n auth: Auth,\n nextOrObserver: NextOrObserver<User>,\n error?: ErrorFn,\n completed?: CompleteFn\n): Unsubscribe {\n return getModularInstance(auth).onIdTokenChanged(\n nextOrObserver,\n error,\n completed\n );\n}\n/**\n * Adds a blocking callback that runs before an auth state change\n * sets a new user.\n *\n * @param auth - The {@link Auth} instance.\n * @param callback - callback triggered before new user value is set.\n * If this throws, it blocks the user from being set.\n * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`\n * callback throws, allowing you to undo any side effects.\n */\nexport function beforeAuthStateChanged(\n auth: Auth,\n callback: (user: User | null) => void | Promise<void>,\n onAbort?: () => void\n): Unsubscribe {\n return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);\n}\n/**\n * Adds an observer for changes to the user's sign-in state.\n *\n * @remarks\n * To keep the old behavior, see {@link onIdTokenChanged}.\n *\n * @param auth - The {@link Auth} instance.\n * @param nextOrObserver - callback triggered on change.\n * @param error - Deprecated. This callback is never triggered. Errors\n * on signing in/out can be caught in promises returned from\n * sign-in/sign-out functions.\n * @param completed - Deprecated. This callback is never triggered.\n *\n * @public\n */\nexport function onAuthStateChanged(\n auth: Auth,\n nextOrObserver: NextOrObserver<User>,\n error?: ErrorFn,\n completed?: CompleteFn\n): Unsubscribe {\n return getModularInstance(auth).onAuthStateChanged(\n nextOrObserver,\n error,\n completed\n );\n}\n/**\n * Sets the current language to the default device/browser preference.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport function useDeviceLanguage(auth: Auth): void {\n getModularInstance(auth).useDeviceLanguage();\n}\n/**\n * Asynchronously sets the provided user as {@link Auth.currentUser} on the\n * {@link Auth} instance.\n *\n * @remarks\n * A new instance copy of the user provided will be made and set as currentUser.\n *\n * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners\n * like other sign in methods.\n *\n * The operation fails with an error if the user to be updated belongs to a different Firebase\n * project.\n *\n * @param auth - The {@link Auth} instance.\n * @param user - The new {@link User}.\n *\n * @public\n */\nexport function updateCurrentUser(\n auth: Auth,\n user: User | null\n): Promise<void> {\n return getModularInstance(auth).updateCurrentUser(user);\n}\n/**\n * Signs out the current user.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport function signOut(auth: Auth): Promise<void> {\n return getModularInstance(auth).signOut();\n}\n\n/**\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\n *\n * @param auth - The {@link Auth} instance.\n * @param token - The Apple OAuth access token.\n *\n * @public\n */\nexport function revokeAccessToken(auth: Auth, token: string): Promise<void> {\n const authInternal = _castAuth(auth);\n return authInternal.revokeAccessToken(token);\n}\n\nexport { initializeAuth } from './auth/initialize';\nexport { connectAuthEmulator } from './auth/emulator';\n\n// credentials\nexport { AuthCredential } from './credentials';\nexport { EmailAuthCredential } from './credentials/email';\nexport { OAuthCredential } from './credentials/oauth';\nexport { PhoneAuthCredential } from './credentials/phone';\n\n// persistence\nexport { inMemoryPersistence } from './persistence/in_memory';\n\n// providers\nexport { EmailAuthProvider } from './providers/email';\nexport { FacebookAuthProvider } from './providers/facebook';\nexport { CustomParameters } from './providers/federated';\nexport { GoogleAuthProvider } from './providers/google';\nexport { GithubAuthProvider } from './providers/github';\nexport { OAuthProvider, OAuthCredentialOptions } from './providers/oauth';\nexport { SAMLAuthProvider } from './providers/saml';\nexport { TwitterAuthProvider } from './providers/twitter';\n\n// strategies\nexport { signInAnonymously } from './strategies/anonymous';\nexport {\n signInWithCredential,\n linkWithCredential,\n reauthenticateWithCredential\n} from './strategies/credential';\nexport { signInWithCustomToken } from './strategies/custom_token';\nexport {\n sendPasswordResetEmail,\n confirmPasswordReset,\n applyActionCode,\n checkActionCode,\n verifyPasswordResetCode,\n createUserWithEmailAndPassword,\n signInWithEmailAndPassword\n} from './strategies/email_and_password';\nexport {\n sendSignInLinkToEmail,\n isSignInWithEmailLink,\n signInWithEmailLink\n} from './strategies/email_link';\nexport {\n fetchSignInMethodsForEmail,\n sendEmailVerification,\n verifyBeforeUpdateEmail\n} from './strategies/email';\n\n// core\nexport { ActionCodeURL, parseActionCodeURL } from './action_code_url';\n\n// user\nexport {\n updateProfile,\n updateEmail,\n updatePassword\n} from './user/account_info';\nexport { getIdToken, getIdTokenResult } from './user/id_token_result';\nexport { unlink } from './user/link_unlink';\nexport { getAdditionalUserInfo } from './user/additional_user_info';\n\n// Non-optional user methods.\nexport { reload } from './user/reload';\n/**\n * Deletes and signs out the user.\n *\n * @remarks\n * Important: this is a security-sensitive operation that requires the user to have recently\n * signed in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n *\n * @public\n */\nexport async function deleteUser(user: User): Promise<void> {\n return getModularInstance(user).delete();\n}\n","////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location<State = any> extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: State;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n\n /**\n * The delta between this location and the former location in the history stack\n */\n delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial<Path>;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n /**\n * The last action that modified the current location. This will always be\n * Action.Pop when a history instance is first created. This value is mutable.\n */\n readonly action: Action;\n\n /**\n * The current location. This value is mutable.\n */\n readonly location: Location;\n\n /**\n * Returns a valid href for the given `to` value that may be used as\n * the value of an <a href> attribute.\n *\n * @param to - The destination URL\n */\n createHref(to: To): string;\n\n /**\n * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial<Location>;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 1 });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route (<Route path=\"*\">) since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant<T>(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\nexport function warning(cond: any, message: string) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly<Location> {\n let location: Readonly<Location> = {\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\",\n ...(typeof to === \"string\" ? parsePath(to) : to),\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: (to && (to as Location).key) || key || createKey(),\n };\n return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial<Path>) {\n if (search && search !== \"?\")\n pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\")\n pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial<Path> {\n let parsedPath: Partial<Path> = {};\n\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n window?: Window;\n v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n createHref: (window: Window, to: To) => string,\n validateLocation: ((location: Location, to: To) => void) | null,\n options: UrlHistoryOptions = {}\n): UrlHistory {\n let { window = document.defaultView!, v5Compat = false } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 1 });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n deferred = \"deferred\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: any;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n type: ResultType.deferred;\n deferredData: DeferredData;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n status: number;\n location: string;\n revalidate: boolean;\n reloadDocument?: boolean;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n type: ResultType.error;\n error: any;\n headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n | SuccessResult\n | DeferredResult\n | RedirectResult\n | ErrorResult;\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;\n\n/**\n * Users can specify either lowercase or uppercase form methods on `<Form>`,\n * useSubmit(), `<fetcher.Form>`, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude<FormMethod, \"get\">;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude<V7_FormMethod, \"GET\">;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"application/json\"\n | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: undefined;\n text: string;\n };\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs<Context> {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs<Context = any>\n extends DataFunctionArgs<Context> {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs<Context = any>\n extends DataFunctionArgs<Context> {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable<unknown> | null;\n\n/**\n * Route loader function signature\n */\nexport interface LoaderFunction<Context = any> {\n (args: LoaderFunctionArgs<Context>):\n | Promise<DataFunctionValue>\n | DataFunctionValue;\n}\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction<Context = any> {\n (args: ActionFunctionArgs<Context>):\n | Promise<DataFunctionValue>\n | DataFunctionValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n text?: Submission[\"text\"];\n formData?: Submission[\"formData\"];\n json?: Submission[\"json\"];\n actionResult?: any;\n defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record<string, any>;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set<ImmutableRouteKey>([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne<T, Key = keyof T> = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit<T, K> & Required<Pick<T, K>> : never;\n }[keyof T],\n undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction<R extends AgnosticRouteObject> {\n (): Promise<RequireOne<Omit<R, ImmutableRouteKey>>>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n caseSensitive?: boolean;\n path?: string;\n id?: string;\n loader?: LoaderFunction;\n action?: ActionFunction;\n hasErrorBoundary?: boolean;\n shouldRevalidate?: ShouldRevalidateFunction;\n handle?: any;\n lazy?: LazyRouteFunction<AgnosticBaseRouteObject>;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record<string, AgnosticDataRouteObject | undefined>;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam<Path extends string> =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam<L> | _PathParam<R>\n : // find params after `:`\n Path extends `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\n : Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam<Path extends string> =\n // check if path is just a wildcard\n Path extends \"*\" | \"/*\"\n ? \"*\"\n : // look for wildcard at the end of the path\n Path extends `${infer Rest}/*`\n ? \"*\" | _PathParam<Rest>\n : // look for params in the absence of wildcards\n _PathParam<Path>;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise, return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey<Segment extends string> =\n // if you could not find path params, fallback to `string`\n [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params<Key extends string = string> = {\n readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params<ParamKey>;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The route object that was used to match.\n */\n route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {}\n\nfunction isIndexRoute(\n route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n routes: AgnosticRouteObject[],\n mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: number[] = [],\n manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, index];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(\n route.index !== true || !route.children,\n `Cannot specify children on an index route`\n );\n invariant(\n !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\n\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial<Location> | string,\n basename = \"/\"\n): AgnosticRouteMatch<string, RouteObjectType>[] | null {\n let location =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n let pathname = stripBasename(location.pathname || \"/\", basename);\n\n if (pathname == null) {\n return null;\n }\n\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n\n let matches = null;\n for (let i = 0; matches == null && i < branches.length; ++i) {\n matches = matchRouteBranch<string, RouteObjectType>(\n branches[i],\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n safelyDecodeURI(pathname)\n );\n }\n\n return matches;\n}\n\nexport interface UIMatch<Data = unknown, Handle = unknown> {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: Data;\n handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UIMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle,\n };\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta<RouteObjectType>[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch<RouteObjectType>[] = [],\n parentsMeta: RouteMeta<RouteObjectType>[] = [],\n parentPath = \"\"\n): RouteBranch<RouteObjectType>[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta<RouteObjectType> = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:\\w+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch<RouteObjectType>,\n pathname: string\n): AgnosticRouteMatch<ParamKey, RouteObjectType>[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch<ParamKey, RouteObjectType>[] = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname =\n matchedPathname === \"/\"\n ? pathname\n : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath(\n { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n remainingPathname\n );\n\n if (!match) return null;\n\n Object.assign(matchedParams, match.params);\n\n let route = meta.route;\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params<ParamKey>,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(\n joinPaths([matchedPathname, match.pathnameBase])\n ),\n route,\n });\n\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n\n return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/utils/generate-path\n */\nexport function generatePath<Path extends string>(\n originalPath: Path,\n params: {\n [key in PathParam<Path>]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const stringify = (p: any) =>\n p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam<Path>;\n // Apply the splat\n return stringify(params[star]);\n }\n\n const keyMatch = segment.match(/^:(\\w+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam<Path>];\n invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n return stringify(param);\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern<Path extends string = string> {\n /**\n * A string to match against a URL pathname. May contain `:id`-style segments\n * to indicate placeholders for dynamic parameters. May also end with `/*` to\n * indicate matching the rest of the URL pathname.\n */\n path: Path;\n /**\n * Should be `true` if the static portions of the `path` should be matched in\n * the same case.\n */\n caseSensitive?: boolean;\n /**\n * Should be `true` if this pattern should match the entire URL pathname.\n */\n end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch<ParamKey extends string = string> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params<ParamKey>;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The pattern that was used to match.\n */\n pattern: PathPattern;\n}\n\ntype Mutable<T> = {\n -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey<Path>,\n Path extends string\n>(\n pattern: PathPattern<Path> | Path,\n pathname: string\n): PathMatch<ParamKey> | null {\n if (typeof pattern === \"string\") {\n pattern = { path: pattern, caseSensitive: false, end: true };\n }\n\n let [matcher, compiledParams] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = compiledParams.reduce<Mutable<Params>>(\n (memo, { paramName, isOptional }, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = safelyDecodeURIComponent(value || \"\", paramName);\n }\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, CompiledPathParam[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let params: CompiledPathParam[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(/\\/:(\\w+)(\\?)?/g, (_: string, paramName: string, isOptional) => {\n params.push({ paramName, isOptional: isOptional != null });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n });\n\n if (path.endsWith(\"*\")) {\n params.push({ paramName: \"*\" });\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, params];\n}\n\nfunction safelyDecodeURI(value: string) {\n try {\n return decodeURI(value);\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\n}\n\nfunction safelyDecodeURIComponent(value: string, paramName: string) {\n try {\n return decodeURIComponent(value);\n } catch (error) {\n warning(\n false,\n `The value for the URL param \"${paramName}\" will not be decoded because` +\n ` the string \"${value}\" is a malformed URL segment. This is probably` +\n ` due to a bad percent encoding (${error}).`\n );\n\n return value;\n }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n pathname: string,\n basename: string\n): string | null {\n if (basename === \"/\") return pathname;\n\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\")\n ? basename.length - 1\n : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n\n return pathname.slice(startIndex) || \"/\";\n}\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\",\n } = typeof to === \"string\" ? parsePath(to) : to;\n\n let pathname = toPathname\n ? toPathname.startsWith(\"/\")\n ? toPathname\n : resolvePathname(toPathname, fromPathname)\n : fromPathname;\n\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash),\n };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n\n relativeSegments.forEach((segment) => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n char: string,\n field: string,\n dest: string,\n path: Partial<Path>\n) {\n return (\n `Cannot include a '${char}' character in a manually specified ` +\n `\\`to.${field}\\` field [${JSON.stringify(\n path\n )}]. Please separate it out to the ` +\n `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n `a string in <Link to=\"...\"> and the router will parse it for you.`\n );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * <Route path=\"/\">\n * <Route path=\"accounts\" element={<Link to=\"..\"}>\n * </Route>\n *\n * <Route path=\"/\">\n * <Route path=\"accounts\">\n * <Route element={<AccountsLayout />}> // <-- Does not contribute\n * <Route index element={<Link to=\"..\"} /> // <-- Does not contribute\n * </Route\n * </Route>\n * </Route>\n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\n );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n // Use the full pathname for the leaf match so we include splat values for \".\" links\n return getPathContributingMatches(matches).map((match, idx) =>\n idx === matches.length - 1 ? match.pathname : match.pathnameBase\n );\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial<Path>;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = { ...toArg };\n\n invariant(\n !to.pathname || !to.pathname.includes(\"?\"),\n getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n );\n invariant(\n !to.pathname || !to.pathname.includes(\"#\"),\n getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n );\n invariant(\n !to.search || !to.search.includes(\"#\"),\n getInvalidPathError(\"#\", \"search\", \"hash\", to)\n );\n }\n\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n let from: string;\n\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `<Link to>` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (toPathname == null) {\n from = locationPathname;\n } else if (isPathRelative) {\n let fromSegments = routePathnames[routePathnames.length - 1]\n .replace(/^\\//, \"\")\n .split(\"/\");\n\n if (toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n // With relative=\"path\", each leading .. segment means \"go up one URL segment\"\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n fromSegments.pop();\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n from = \"/\" + fromSegments.join(\"/\");\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n if (toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how <a href> works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n // If there are more \"..\" segments than parent routes, resolve relative to\n // the root / URL.\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\n}\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n !search || search === \"?\"\n ? \"\"\n : search.startsWith(\"?\")\n ? search\n : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = <Data>(\n data: Data,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n\n return new Response(JSON.stringify(data), {\n ...responseInit,\n headers,\n });\n};\n\nexport interface TrackedPromise extends Promise<any> {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeysSet: Set<string> = new Set<string>();\n private controller: AbortController;\n private abortPromise: Promise<void>;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record<string, unknown>;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record<string, unknown>, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise<unknown> | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record<string, unknown>,\n init?: number | ResponseInit\n) => DeferredData;\n\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n\nexport type ErrorResponse = {\n status: number;\n statusText: string;\n data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n private error?: Error;\n private internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n ActionFunction,\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n AgnosticRouteObject,\n DataResult,\n DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n ImmutableRouteKey,\n LoaderFunction,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\n} from \"./utils\";\nimport {\n ErrorResponseImpl,\n ResultType,\n convertRouteMatchToUiMatch,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n getResolveToMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n resolveTo,\n stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record<string, number>,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): Promise<void>;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher<TData = any>(key: string): Fetcher<TData>;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete the fetcher for a given key\n * @param key\n */\n deleteFetcher(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map<string, AbortController>;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map<string, DeferredData>;\n}\n\n/**\n * State maintained internally by the router. During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n /**\n * The action of the most recent navigation\n */\n historyAction: HistoryAction;\n\n /**\n * The current location reflected by the router\n */\n location: Location;\n\n /**\n * The current set of route matches\n */\n matches: AgnosticDataRouteMatch[];\n\n /**\n * Tracks whether we've completed our initial data load\n */\n initialized: boolean;\n\n /**\n * Current scroll position we should start at for a new view\n * - number -> scroll position to restore to\n * - false -> do not restore scroll at all (used during submissions)\n * - null -> don't have a saved position, scroll to hash or top of page\n */\n restoreScrollPosition: number | false | null;\n\n /**\n * Indicate whether this navigation should skip resetting the scroll position\n * if we are unable to restore the scroll position\n */\n preventScrollReset: boolean;\n\n /**\n * Tracks the state of the current navigation\n */\n navigation: Navigation;\n\n /**\n * Tracks any in-progress revalidations\n */\n revalidation: RevalidationState;\n\n /**\n * Data from the loaders for the current matches\n */\n loaderData: RouteData;\n\n /**\n * Data from the action for the current matches\n */\n actionData: RouteData | null;\n\n /**\n * Errors caught from loaders for the current matches\n */\n errors: RouteData | null;\n\n /**\n * Map of current fetchers\n */\n fetchers: Map<string, Fetcher>;\n\n /**\n * Map of current blockers\n */\n blockers: Map<string, Blocker>;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick<RouterState, \"loaderData\" | \"actionData\" | \"errors\">\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_prependBasename: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial<FutureConfig>;\n hydrationData?: HydrationState;\n window?: Window;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record<string, Headers>;\n actionHeaders: Record<string, Headers>;\n activeDeferreds: Record<string, DeferredData> | null;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(\n request: Request,\n opts?: { requestContext?: unknown }\n ): Promise<StaticHandlerContext | Response>;\n queryRoute(\n request: Request,\n opts?: { routeId?: string; requestContext?: unknown }\n ): Promise<any>;\n}\n\ntype ViewTransitionOpts = {\n currentLocation: Location;\n nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (\n state: RouterState,\n opts: {\n deletedFetchers: string[];\n unstable_viewTransitionOpts?: ViewTransitionOpts;\n unstable_flushSync: boolean;\n }\n ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n unstable_viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n} & (\n | { formData: FormData; body?: undefined }\n | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n json: undefined;\n text: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n text: Submission[\"text\"] | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n text: Submission[\"text\"];\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates<TData = any> = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n text: Submission[\"text\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n text: Submission[\"text\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n data: TData | undefined;\n };\n};\n\nexport type Fetcher<TData = any> =\n FetcherStates<TData>[keyof FetcherStates<TData>];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\ninterface HandleActionResult extends ShortCircuitable {\n /**\n * Error thrown from the current action, keyed by the route containing the\n * error boundary to render the error. To be committed to the state after\n * loaders have completed\n */\n pendingActionError?: RouteData;\n /**\n * Data returned from the current action, keyed by the route owning the action.\n * To be committed to the state after loaders have completed\n */\n pendingActionData?: RouteData;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n /**\n * loaderData returned from the current set of loaders\n */\n loaderData?: RouterState[\"loaderData\"];\n /**\n * errors thrown from the current set of loaders\n */\n errors?: RouterState[\"errors\"];\n}\n\n/**\n * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\n/**\n * Wrapper object to allow us to throw any response out from callLoaderOrAction\n * for queryRouter while preserving whether or not it was thrown or returned\n * from the loader/action\n */\ninterface QueryRouteResponse {\n type: ResultType.data | ResultType.error;\n response: Response;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\nconst validMutationMethods = new Set<MutationFormMethod>(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set<FormMethod>(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n const routerWindow = init.window\n ? init.window\n : typeof window !== \"undefined\"\n ? window\n : undefined;\n const isBrowser =\n typeof routerWindow !== \"undefined\" &&\n typeof routerWindow.document !== \"undefined\" &&\n typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_prependBasename: false,\n ...init.future,\n };\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set<RouterSubscriber>();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record<string, number> | null = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition: GetScrollPositionFunction | null = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from <ScrollRestoration /> until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialErrors: RouteData | null = null;\n\n if (initialMatches == null) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n let initialized =\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n !initialMatches.some((m) => m.route.lazy) &&\n // And we have to either have no loaders or have been provided hydrationData\n (!initialMatches.some((m) => m.route.loader) || init.hydrationData != null);\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n blockers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: HistoryAction = HistoryAction.Pop;\n\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions: Map<string, Set<string>> = new Map<\n string,\n Set<string>\n >();\n\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener: (() => void) | null = null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map<string, AbortController>();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map<string, number>();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set<string>();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map<string, FetchLoadMatch>();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map<string, number>();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set<string>();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map<string, DeferredData>();\n\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map<string, BlockerFunction>();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let ignoreNextHistoryUpdate = false;\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n ignoreNextHistoryUpdate = true;\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked\n init.history.go(delta);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () =>\n persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () =>\n routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location);\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(\n newState: Partial<RouterState>,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach((subscriber) =>\n subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n unstable_viewTransitionOpts: opts.viewTransitionOpts,\n unstable_flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n }\n }\n\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(\n location: Location,\n newState: Partial<Omit<RouterState, \"action\" | \"location\" | \"navigation\">>,\n { flushSync }: { flushSync?: boolean } = {}\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.Replace) {\n init.history.replace(location, location.state);\n }\n\n let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === HistoryAction.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location,\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set<string>([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n }\n\n updateState(\n {\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers,\n },\n {\n viewTransitionOpts,\n flushSync: flushSync === true,\n }\n );\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\n }\n\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(\n to: number | To | null,\n opts?: RouterNavigateOptions\n ): Promise<void> {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n to,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.unstable_viewTransition,\n flushSync,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n { overrideNavigation: state.navigation }\n );\n }\n\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(\n historyAction: HistoryAction,\n location: Location,\n opts?: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponseImpl;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n enableViewTransition?: boolean;\n flushSync?: boolean;\n }\n ): Promise<void> {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n completeNavigation(\n location,\n {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n },\n { flushSync }\n );\n return;\n }\n\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial load will always\n // be \"same hash\". For example, on /page#hash and submit a <Form method=\"post\">\n // which will default to a navigation to /page\n if (\n state.initialized &&\n !isRevalidationRequired &&\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches }, { flushSync });\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let pendingActionData: RouteData | undefined;\n let pendingError: RouteData | undefined;\n\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingError = {\n [findNearestBoundary(matches).route.id]: opts.pendingError,\n };\n } else if (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\n // Call action if we received an action submission\n let actionOutput = await handleAction(\n request,\n location,\n opts.submission,\n matches,\n { replace: opts.replace, flushSync }\n );\n\n if (actionOutput.shortCircuited) {\n return;\n }\n\n pendingActionData = actionOutput.pendingActionData;\n pendingError = actionOutput.pendingActionError;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n\n // Create a GET request for the loaders\n request = new Request(request.url, { signal: request.signal });\n }\n\n // Call loaders\n let { shortCircuited, loaderData, errors } = await handleLoaders(\n request,\n location,\n matches,\n loadingNavigation,\n opts && opts.submission,\n opts && opts.fetcherSubmission,\n opts && opts.replace,\n flushSync,\n pendingActionData,\n pendingError\n );\n\n if (shortCircuited) {\n return;\n }\n\n // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches,\n ...(pendingActionData ? { actionData: pendingActionData } : {}),\n loaderData,\n errors,\n });\n }\n\n // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n async function handleAction(\n request: Request,\n location: Location,\n submission: Submission,\n matches: AgnosticDataRouteMatch[],\n opts: { replace?: boolean; flushSync?: boolean } = {}\n ): Promise<HandleActionResult> {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n replace =\n result.location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(state, result, { submission, replace });\n return { shortCircuited: true };\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n // By default, all submissions are REPLACE navigations, but if the\n // action threw an error that'll be rendered in an errorElement, we fall\n // back to PUSH so that the user can use the back button to get back to\n // the pre-submission form location to try again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n // Send back an empty object we can use to clear out any prior actionData\n pendingActionData: {},\n pendingActionError: { [boundaryMatch.route.id]: result.error },\n };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n return {\n pendingActionData: { [actionMatch.route.id]: result.data },\n };\n }\n\n // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n async function handleLoaders(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n overrideNavigation?: Navigation,\n submission?: Submission,\n fetcherSubmission?: Submission,\n replace?: boolean,\n flushSync?: boolean,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n ): Promise<HandleLoadersResult> {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation =\n overrideNavigation || getLoadingNavigation(location, submission);\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission ||\n fetcherSubmission ||\n getSubmissionFromNavigation(loadingNavigation);\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionData,\n pendingError\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n );\n\n pendingNavigationLoadId = ++incrementingLoadId;\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(\n location,\n {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors: pendingError || null,\n ...(pendingActionData ? { actionData: pendingActionData } : {}),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n },\n { flushSync }\n );\n return { shortCircuited: true };\n }\n\n // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n if (!isUninterruptedRevalidation) {\n revalidatingFetchers.forEach((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n fetcher ? fetcher.data : undefined\n );\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n let actionData = pendingActionData || state.actionData;\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData\n ? Object.keys(actionData).length === 0\n ? { actionData: null }\n : { actionData }\n : {}),\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n revalidatingFetchers.forEach((rf) => {\n if (fetchControllers.has(rf.key)) {\n abortFetcher(rf.key);\n }\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n await startRedirectNavigation(state, redirect.result, { replace });\n return { shortCircuited: true };\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n matchesToLoad,\n loaderResults,\n pendingError,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe((aborted) => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n if (fetchControllers.has(key)) abortFetcher(key);\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath }),\n { flushSync }\n );\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n true,\n normalizedPath,\n opts\n );\n\n if (error) {\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n let match = getTargetMatch(matches, path);\n\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\n submission\n );\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, { routeId, path });\n handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\n submission\n );\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n requestMatches: AgnosticDataRouteMatch[],\n flushSync: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action && !match.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync,\n });\n\n // Call the action for the fetcher\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResult = await callLoaderOrAction(\n \"action\",\n fetchRequest,\n match,\n requestMatches,\n manifest,\n mapRouteProperties,\n basename\n );\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(state, actionResult, {\n fetcherSubmission: submission,\n });\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(\n init.history,\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n { [match.route.id]: actionResult.data },\n undefined // No need to send through errors since we short circuit above\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(staleKey, revalidatingFetcher);\n if (fetchControllers.has(staleKey)) {\n abortFetcher(staleKey);\n }\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n return startRedirectNavigation(state, redirect.result);\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n state.matches,\n matchesToLoad,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n\n abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n fetchers: new Map(state.fetchers),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n flushSync: boolean,\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(\n key,\n getLoadingFetcher(\n submission,\n existingFetcher ? existingFetcher.data : undefined\n ),\n { flushSync }\n );\n\n // Call the loader for this fetcher route match\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let result: DataResult = await callLoaderOrAction(\n \"loader\",\n fetchRequest,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename\n );\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\n\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(state, result);\n return;\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n state: RouterState,\n redirect: RedirectResult,\n {\n submission,\n fetcherSubmission,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n replace?: boolean;\n } = {}\n ) {\n if (redirect.revalidate) {\n isRevalidationRequired = true;\n }\n\n let redirectLocation = createLocation(state.location, redirect.location, {\n _isRedirect: true,\n });\n invariant(\n redirectLocation,\n \"Expected a location on the redirect navigation\"\n );\n\n if (isBrowser) {\n let isDocumentReload = false;\n\n if (redirect.reloadDocument) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(redirect.location)) {\n const url = init.history.createURL(redirect.location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(redirect.location);\n } else {\n routerWindow.location.assign(redirect.location);\n }\n return;\n }\n }\n\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectHistoryAction =\n replace === true ? HistoryAction.Replace : HistoryAction.Push;\n\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let { formMethod, formAction, formEncType } = state.navigation;\n if (\n !submission &&\n !fetcherSubmission &&\n formMethod &&\n formAction &&\n formEncType\n ) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (\n redirectPreserveMethodStatusCodes.has(redirect.status) &&\n activeSubmission &&\n isMutationMethod(activeSubmission.formMethod)\n ) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: redirect.location,\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(\n redirectLocation,\n submission\n );\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n }\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n // Call all navigation loaders and revalidating fetcher loaders in parallel,\n // then slice off the results into separate arrays so we can handle them\n // accordingly\n let results = await Promise.all([\n ...matchesToLoad.map((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename\n )\n ),\n ...fetchersToLoad.map((f) => {\n if (f.matches && f.match && f.controller) {\n return callLoaderOrAction(\n \"loader\",\n createClientSideRequest(init.history, f.path, f.controller.signal),\n f.match,\n f.matches,\n manifest,\n mapRouteProperties,\n basename\n );\n } else {\n let error: ErrorResult = {\n type: ResultType.error,\n error: getInternalRouterError(404, { pathname: f.path }),\n };\n return error;\n }\n }),\n ]);\n let loaderResults = results.slice(0, matchesToLoad.length);\n let fetcherResults = results.slice(matchesToLoad.length);\n\n await Promise.all([\n resolveDeferredResults(\n currentMatches,\n matchesToLoad,\n loaderResults,\n loaderResults.map(() => request.signal),\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map((f) => f.match),\n fetcherResults,\n fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)),\n true\n ),\n ]);\n\n return { results, loaderResults, fetcherResults };\n }\n\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true;\n\n // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.push(key);\n abortFetcher(key);\n }\n });\n }\n\n function updateFetcherState(\n key: string,\n fetcher: Fetcher,\n opts: { flushSync?: boolean } = {}\n ) {\n state.fetchers.set(key, fetcher);\n updateState(\n { fetchers: new Map(state.fetchers) },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function setFetcherError(\n key: string,\n routeId: string,\n error: any,\n opts: { flushSync?: boolean } = {}\n ) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState(\n {\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function getFetcher<TData = any>(key: string): Fetcher<TData> {\n if (future.v7_fetcherPersist) {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n function deleteFetcher(key: string): void {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (\n fetchControllers.has(key) &&\n !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n ) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n deletedFetchers.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n if (future.v7_fetcherPersist) {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n } else {\n activeFetchers.set(key, count);\n }\n } else {\n deleteFetcher(key);\n }\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n invariant(controller, `Expected fetch controller: ${key}`);\n controller.abort();\n fetchControllers.delete(key);\n }\n\n function markFetchersDone(keys: string[]) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({ blockers });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\n }\n\n function cancelActiveDeferreds(\n predicate?: (routeId: string) => boolean\n ): string[] {\n let cancelledRouteIds: string[] = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the <ScrollRestoration> component\n function enableScrollRestoration(\n positions: Record<string, number>,\n getPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || null;\n\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered <ScrollRestoration/>\n // and therefore have no savedScrollPositions available\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({ restoreScrollPosition: y });\n }\n }\n\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n\n function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(\n location,\n matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n );\n return key || location.key;\n }\n return location.key;\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\n );\n }\n\n router = {\n get basename() {\n return basename;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n */\n async function query(\n request: Request,\n { requestContext }: { requestContext?: unknown } = {}\n ): Promise<StaticHandlerContext | Response> {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(request, location, matches, requestContext);\n if (isResponse(result)) {\n return result;\n }\n\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n }: { requestContext?: unknown; routeId?: string } = {}\n ): Promise<any> {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n match\n );\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch\n ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction, we throw\n // it to bail out and then return or throw here based on whether the user\n // returned or threw\n if (isQueryRouteResponse(e)) {\n if (e.type === ResultType.error) {\n throw e.response;\n }\n return e.response;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n isRouteRequest: boolean\n ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n { isStaticRequest: true, isRouteRequest, requestContext }\n );\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(\n `${method}() call aborted: ${request.method} ${request.url}`\n );\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.status,\n headers: {\n Location: result.location,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n let context = await loadRouteData(\n request,\n matches,\n requestContext,\n undefined,\n {\n [boundaryMatch.route.id]: result.error,\n }\n );\n\n // action status codes take precedence over loader status codes\n return {\n ...context,\n statusCode: isRouteErrorResponse(result.error)\n ? result.error.status\n : 500,\n actionData: null,\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n let context = await loadRouteData(loaderRequest, matches, requestContext);\n\n return {\n ...context,\n // action status codes take precedence over loader status codes\n ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n actionData: {\n [actionMatch.route.id]: result.data,\n },\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n async function loadRouteData(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch,\n pendingActionError?: RouteData\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(pendingActionError || {})[0]\n );\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors: pendingActionError || null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let results = await Promise.all([\n ...matchesToLoad.map((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n { isStaticRequest: true, isRouteRequest, requestContext }\n )\n ),\n ]);\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(\n `${method}() call aborted: ${request.method} ${request.url}`\n );\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map<string, DeferredData>();\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionError,\n activeDeferreds\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set<string>(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\n };\n }\n\n return {\n dataRoutes,\n query,\n queryRoute,\n };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n routes: AgnosticDataRouteObject[],\n context: StaticHandlerContext,\n error: any\n) {\n let newContext: StaticHandlerContext = {\n ...context,\n statusCode: 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error,\n },\n };\n return newContext;\n}\n\nfunction isSubmissionNavigation(\n opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n return (\n opts != null &&\n ((\"formData\" in opts && opts.formData != null) ||\n (\"body\" in opts && opts.body !== undefined))\n );\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n prependBasename: boolean,\n to: To | null,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getResolveToMatches(contextualMatches),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Add an ?index param for matched index routes if we don't already have one\n if (\n (to == null || to === \"\" || to === \".\") &&\n activeRouteMatch &&\n activeRouteMatch.route.index &&\n !hasNakedIndexQuery(path.search)\n ) {\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n normalizeFormMethod: boolean,\n isFetcher: boolean,\n path: string,\n opts?: BaseNavigateOrFetchOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponseImpl;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, { type: \"invalid-body\" }),\n });\n\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() as FormMethod);\n let formAction = stripHashFromPath(path);\n\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n let text =\n typeof opts.body === \"string\"\n ? opts.body\n : opts.body instanceof FormData ||\n opts.body instanceof URLSearchParams\n ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce(\n (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n \"\"\n )\n : String(opts.body);\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text,\n },\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n try {\n let json =\n typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined,\n },\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n\n invariant(\n typeof FormData === \"function\",\n \"FormData is not available in this environment\"\n );\n\n let searchParams: URLSearchParams;\n let formData: FormData;\n\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n\n let submission: Submission = {\n formMethod,\n formAction,\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n matches: AgnosticDataRouteMatch[],\n boundaryId?: string\n) {\n let boundaryMatches = matches;\n if (boundaryId) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n boundaryMatches = matches.slice(0, index);\n }\n }\n return boundaryMatches;\n}\n\nfunction getMatchesToLoad(\n history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n deletedFetchers: Set<string>,\n fetchLoadMatches: Map<string, FetchLoadMatch>,\n fetchRedirectIds: Set<string>,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingError\n ? Object.values(pendingError)[0]\n : pendingActionData\n ? Object.values(pendingActionData)[0]\n : undefined;\n\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n\n let navigationMatches = boundaryMatches.filter((match, index) => {\n if (match.route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n if (match.route.loader == null) {\n return false;\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\n return true;\n }\n\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n defaultShouldRevalidate:\n // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n // Clicked the same link, resubmitted a GET form\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate if fetcher won't be present in the subsequent render\n if (\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.has(key)\n ) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.includes(key)) {\n // Always revalidate if the fetcher was cancelled\n shouldRevalidate = true;\n } else if (\n fetcher &&\n fetcher.state !== \"idle\" &&\n fetcher.data === undefined\n ) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n defaultShouldRevalidate: isRevalidationRequired,\n });\n }\n\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: ShouldRevalidateFunctionArgs\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record<string, any> = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n basename: string,\n opts: {\n isStaticRequest?: boolean;\n isRouteRequest?: boolean;\n requestContext?: unknown;\n } = {}\n): Promise<DataResult> {\n let resultType;\n let result;\n let onReject: (() => void) | undefined;\n\n let runHandler = (handler: ActionFunction | LoaderFunction) => {\n // Setup a promise we can race against so that abort signals short circuit\n let reject: () => void;\n let abortPromise = new Promise((_, r) => (reject = r));\n onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n return Promise.race([\n handler({\n request,\n params: match.params,\n context: opts.requestContext,\n }),\n abortPromise,\n ]);\n };\n\n try {\n let handler = match.route[type];\n\n if (match.route.lazy) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let values = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch((e) => {\n handlerError = e;\n }),\n loadLazyRouteModule(match.route, mapRouteProperties, manifest),\n ]);\n if (handlerError) {\n throw handlerError;\n }\n result = values[0];\n } else {\n // Load lazy route module, then run any returned handler\n await loadLazyRouteModule(match.route, mapRouteProperties, manifest);\n\n handler = match.route[type];\n if (handler) {\n // Handler still run even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, data: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n\n invariant(\n result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n resultType = ResultType.error;\n result = e;\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n if (isResponse(result)) {\n let status = result.status;\n\n // Process redirects\n if (redirectStatusCodes.has(status)) {\n let location = result.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n // Support relative routing in internal redirects\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n location = normalizeTo(\n new URL(request.url),\n matches.slice(0, matches.indexOf(match) + 1),\n basename,\n true,\n location\n );\n } else if (!opts.isStaticRequest) {\n // Strip off the protocol+origin for same-origin + same-basename absolute\n // redirects. If this is a static request, we can let it go back to the\n // browser as-is\n let currentUrl = new URL(request.url);\n let url = location.startsWith(\"//\")\n ? new URL(currentUrl.protocol + location)\n : new URL(location);\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n location = url.pathname + url.search + url.hash;\n }\n }\n\n // Don't process redirects in the router during static requests requests.\n // Instead, throw the Response and let the server handle it with an HTTP\n // redirect. We also update the Location header in place in this flow so\n // basename and relative routing is taken into account\n if (opts.isStaticRequest) {\n result.headers.set(\"Location\", location);\n throw result;\n }\n\n return {\n type: ResultType.redirect,\n status,\n location,\n revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null,\n reloadDocument: result.headers.get(\"X-Remix-Reload-Document\") !== null,\n };\n }\n\n // For SSR single-route requests, we want to hand Responses back directly\n // without unwrapping. We do this with the QueryRouteResponse wrapper\n // interface so we can know whether it was returned or thrown\n if (opts.isRouteRequest) {\n let queryRouteResponse: QueryRouteResponse = {\n type:\n resultType === ResultType.error ? ResultType.error : ResultType.data,\n response: result,\n };\n throw queryRouteResponse;\n }\n\n let data: any;\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n data = await result.json();\n } else {\n data = await result.text();\n }\n\n if (resultType === ResultType.error) {\n return {\n type: resultType,\n error: new ErrorResponseImpl(status, result.statusText, data),\n headers: result.headers,\n };\n }\n\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n if (resultType === ResultType.error) {\n return { type: resultType, error: result };\n }\n\n if (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n return { type: ResultType.data, data: result };\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n\n if (formEncType === \"application/json\") {\n init.headers = new Headers({ \"Content-Type\": formEncType });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (\n formEncType === \"application/x-www-form-urlencoded\" &&\n submission.formData\n ) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n\n return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n searchParams: URLSearchParams\n): FormData {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n activeDeferreds: Map<string, DeferredData>\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record<string, Headers>;\n} {\n // Fill in loaderData/errors from our loaders\n let loaderData: RouterState[\"loaderData\"] = {};\n let errors: RouterState[\"errors\"] | null = null;\n let statusCode: number | undefined;\n let foundError = false;\n let loaderHeaders: Record<string, Headers> = {};\n\n // Process loader results into state.loaderData/state.errors\n results.forEach((result, index) => {\n let id = matchesToLoad[index].route.id;\n invariant(\n !isRedirectResult(result),\n \"Cannot handle redirect results in processLoaderData\"\n );\n if (isErrorResult(result)) {\n // Look upwards from the matched route for the closest ancestor\n // error boundary, defaulting to the root match\n let boundaryMatch = findNearestBoundary(matches, id);\n let error = result.error;\n // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n if (pendingError) {\n error = Object.values(pendingError)[0];\n pendingError = undefined;\n }\n\n errors = errors || {};\n\n // Prefer higher error values if lower errors bubble to the same boundary\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n } else {\n loaderData[id] = result.data;\n }\n\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (\n result.statusCode != null &&\n result.statusCode !== 200 &&\n !foundError\n ) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n });\n\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here. Also clear out any loaderData for the\n // throwing route\n if (pendingError) {\n errors = pendingError;\n loaderData[Object.keys(pendingError)[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: DataResult[],\n activeDeferreds: Map<string, DeferredData>\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingError,\n activeDeferreds\n );\n\n // Process results from our revalidating fetchers\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let { key, match, controller } = revalidatingFetchers[index];\n invariant(\n fetcherResults !== undefined && fetcherResults[index] !== undefined,\n \"Did not find corresponding fetcher result\"\n );\n let result = fetcherResults[index];\n\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n continue;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[],\n errors: RouteData | null | undefined\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponseImpl(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n results: DataResult[]\n): { result: RedirectResult; idx: number } | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return { result, idx: i };\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\n}\n\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isQueryRouteResponse(obj: any): obj is QueryRouteResponse {\n return (\n obj &&\n isResponse(obj.response) &&\n (obj.type === ResultType.data || obj.type === ResultType.error)\n );\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: (AgnosticDataRouteMatch | null)[],\n results: DataResult[],\n signals: (AbortSignal | null)[],\n isFetcher: boolean,\n currentLoaderData?: RouteData\n) {\n for (let index = 0; index < results.length; index++) {\n let result = results[index];\n let match = matchesToLoad[index];\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n let signal = signals[index];\n invariant(\n signal,\n \"Expected an AbortSignal for revalidating fetcher deferred result\"\n );\n await resolveDeferredData(result, signal, isFetcher).then((result) => {\n if (result) {\n results[index] = result || results[index];\n }\n });\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise<SuccessResult | ErrorResult | undefined> {\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData,\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e,\n };\n }\n }\n\n return {\n type: ResultType.data,\n data: result.deferredData.data,\n };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n hasNakedIndexQuery(search || \"\")\n ) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n navigation: Navigation\n): Submission | undefined {\n let { formMethod, formAction, formEncType, text, formData, json } =\n navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text,\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined,\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined,\n };\n }\n}\n\nfunction getLoadingNavigation(\n location: Location,\n submission?: Submission\n): NavigationStates[\"Loading\"] {\n if (submission) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n } else {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n };\n return navigation;\n }\n}\n\nfunction getSubmittingNavigation(\n location: Location,\n submission: Submission\n): NavigationStates[\"Submitting\"] {\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n}\n\nfunction getLoadingFetcher(\n submission?: Submission,\n data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n if (submission) {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data,\n };\n return fetcher;\n } else {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n }\n}\n\nfunction getSubmittingFetcher(\n submission: Submission,\n existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined,\n };\n return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n let fetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n _window: Window,\n transitions: Map<string, Set<string>>\n) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(\n TRANSITIONS_STORAGE_KEY\n );\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\n\nfunction persistAppliedTransitions(\n _window: Window,\n transitions: Map<string, Set<string>>\n) {\n if (transitions.size > 0) {\n let json: Record<string, string[]> = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(\n TRANSITIONS_STORAGE_KEY,\n JSON.stringify(json)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save applied view transitions in sessionStorage (${error}).`\n );\n }\n }\n}\n\n//#endregion\n","import * as React from \"react\";\nimport type {\n AgnosticIndexRouteObject,\n AgnosticNonIndexRouteObject,\n AgnosticRouteMatch,\n History,\n LazyRouteFunction,\n Location,\n Action as NavigationType,\n RelativeRoutingType,\n Router,\n StaticHandlerContext,\n To,\n TrackedPromise,\n} from \"@remix-run/router\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticIndexRouteObject[\"path\"];\n id?: AgnosticIndexRouteObject[\"id\"];\n loader?: AgnosticIndexRouteObject[\"loader\"];\n action?: AgnosticIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticIndexRouteObject[\"handle\"];\n index: true;\n children?: undefined;\n element?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport interface NonIndexRouteObject {\n caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticNonIndexRouteObject[\"path\"];\n id?: AgnosticNonIndexRouteObject[\"id\"];\n loader?: AgnosticNonIndexRouteObject[\"loader\"];\n action?: AgnosticNonIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticNonIndexRouteObject[\"handle\"];\n index?: false;\n children?: RouteObject[];\n element?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n children?: DataRouteObject[];\n id: string;\n};\n\nexport interface RouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {}\n\nexport interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}\n\nexport interface DataRouterContextObject extends NavigationContextObject {\n router: Router;\n staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n React.createContext<DataRouterContextObject | null>(null);\nif (__DEV__) {\n DataRouterContext.displayName = \"DataRouter\";\n}\n\nexport const DataRouterStateContext = React.createContext<\n Router[\"state\"] | null\n>(null);\nif (__DEV__) {\n DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nexport const AwaitContext = React.createContext<TrackedPromise | null>(null);\nif (__DEV__) {\n AwaitContext.displayName = \"Await\";\n}\n\nexport interface NavigateOptions {\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n unstable_viewTransition?: boolean;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `<Router>` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n createHref: History[\"createHref\"];\n // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n encodeLocation?: History[\"encodeLocation\"];\n go: History[\"go\"];\n push(to: To, state?: any, opts?: NavigateOptions): void;\n replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n basename: string;\n navigator: Navigator;\n static: boolean;\n}\n\nexport const NavigationContext = React.createContext<NavigationContextObject>(\n null!\n);\n\nif (__DEV__) {\n NavigationContext.displayName = \"Navigation\";\n}\n\ninterface LocationContextObject {\n location: Location;\n navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext<LocationContextObject>(\n null!\n);\n\nif (__DEV__) {\n LocationContext.displayName = \"Location\";\n}\n\nexport interface RouteContextObject {\n outlet: React.ReactElement | null;\n matches: RouteMatch[];\n isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext<RouteContextObject>({\n outlet: null,\n matches: [],\n isDataRoute: false,\n});\n\nif (__DEV__) {\n RouteContext.displayName = \"Route\";\n}\n\nexport const RouteErrorContext = React.createContext<any>(null);\n\nif (__DEV__) {\n RouteErrorContext.displayName = \"RouteError\";\n}\n","import * as React from \"react\";\nimport type {\n Blocker,\n BlockerFunction,\n Location,\n ParamParseKey,\n Params,\n Path,\n PathMatch,\n PathPattern,\n RelativeRoutingType,\n Router as RemixRouter,\n RevalidationState,\n To,\n UIMatch,\n} from \"@remix-run/router\";\nimport {\n IDLE_BLOCKER,\n Action as NavigationType,\n UNSAFE_convertRouteMatchToUiMatch as convertRouteMatchToUiMatch,\n UNSAFE_getResolveToMatches as getResolveToMatches,\n UNSAFE_invariant as invariant,\n isRouteErrorResponse,\n joinPaths,\n matchPath,\n matchRoutes,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n DataRouteMatch,\n NavigateOptions,\n RouteContextObject,\n RouteMatch,\n RouteObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n RouteErrorContext,\n} from \"./context\";\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/hooks/use-href\n */\nexport function useHref(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useHref() may be used only in the context of a <Router> component.`\n );\n\n let { basename, navigator } = React.useContext(NavigationContext);\n let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n let joinedPathname = pathname;\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the href. If this is a root navigation, then just use the raw\n // basename which allows the basename to have full control over the presence\n // of a trailing slash on root links\n if (basename !== \"/\") {\n joinedPathname =\n pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n }\n\n return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a `<Router>`.\n *\n * @see https://reactrouter.com/hooks/use-in-router-context\n */\nexport function useInRouterContext(): boolean {\n return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/hooks/use-location\n */\nexport function useLocation(): Location {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useLocation() may be used only in the context of a <Router> component.`\n );\n\n return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/hooks/use-navigation-type\n */\nexport function useNavigationType(): NavigationType {\n return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * `<NavLink>`.\n *\n * @see https://reactrouter.com/hooks/use-match\n */\nexport function useMatch<\n ParamKey extends ParamParseKey<Path>,\n Path extends string\n>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useMatch() may be used only in the context of a <Router> component.`\n );\n\n let { pathname } = useLocation();\n return React.useMemo(\n () => matchPath<ParamKey, Path>(pattern, pathname),\n [pathname, pattern]\n );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n (to: To, options?: NavigateOptions): void;\n (delta: number): void;\n}\n\nconst navigateEffectWarning =\n `You should call navigate() in a React.useEffect(), not when ` +\n `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n cb: Parameters<typeof React.useLayoutEffect>[0]\n) {\n let isStatic = React.useContext(NavigationContext).static;\n if (!isStatic) {\n // We should be able to get rid of this once react 18.3 is released\n // See: https://github.com/facebook/react/pull/26395\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(cb);\n }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by `<Link>`s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/hooks/use-navigate\n */\nexport function useNavigate(): NavigateFunction {\n let { isDataRoute } = React.useContext(RouteContext);\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useNavigate() may be used only in the context of a <Router> component.`\n );\n\n let dataRouterContext = React.useContext(DataRouterContext);\n let { basename, navigator } = React.useContext(NavigationContext);\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n\n let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our history listener yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n navigator.go(to);\n return;\n }\n\n let path = resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n options.relative === \"path\"\n );\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to handing off to history (but only if we're not in a data router,\n // otherwise it'll prepend the basename inside of the router).\n // If this is a root navigation, then we navigate to the raw basename\n // which allows the basename to have full control over the presence of a\n // trailing slash on root links\n if (dataRouterContext == null && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\"\n ? basename\n : joinPaths([basename, path.pathname]);\n }\n\n (!!options.replace ? navigator.replace : navigator.push)(\n path,\n options.state,\n options\n );\n },\n [\n basename,\n navigator,\n routePathnamesJson,\n locationPathname,\n dataRouterContext,\n ]\n );\n\n return navigate;\n}\n\nconst OutletContext = React.createContext<unknown>(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/hooks/use-outlet-context\n */\nexport function useOutletContext<Context = unknown>(): Context {\n return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `<Outlet>` to render child routes.\n *\n * @see https://reactrouter.com/hooks/use-outlet\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n let outlet = React.useContext(RouteContext).outlet;\n if (outlet) {\n return (\n <OutletContext.Provider value={context}>{outlet}</OutletContext.Provider>\n );\n }\n return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/hooks/use-params\n */\nexport function useParams<\n ParamsOrKey extends string | Record<string, string | undefined> = string\n>(): Readonly<\n [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>\n> {\n let { matches } = React.useContext(RouteContext);\n let routeMatch = matches[matches.length - 1];\n return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/hooks/use-resolved-path\n */\nexport function useResolvedPath(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));\n\n return React.useMemo(\n () =>\n resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n relative === \"path\"\n ),\n [to, routePathnamesJson, locationPathname, relative]\n );\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `<Outlet>` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/hooks/use-routes\n */\nexport function useRoutes(\n routes: RouteObject[],\n locationArg?: Partial<Location> | string\n): React.ReactElement | null {\n return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nexport function useRoutesImpl(\n routes: RouteObject[],\n locationArg?: Partial<Location> | string,\n dataRouterState?: RemixRouter[\"state\"]\n): React.ReactElement | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useRoutes() may be used only in the context of a <Router> component.`\n );\n\n let { navigator } = React.useContext(NavigationContext);\n let { matches: parentMatches } = React.useContext(RouteContext);\n let routeMatch = parentMatches[parentMatches.length - 1];\n let parentParams = routeMatch ? routeMatch.params : {};\n let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n let parentRoute = routeMatch && routeMatch.route;\n\n if (__DEV__) {\n // You won't get a warning about 2 different <Routes> under a <Route>\n // without a trailing *, but this is a best-effort warning anyway since we\n // cannot even give the warning unless they land at the parent route.\n //\n // Example:\n //\n // <Routes>\n // {/* This route path MUST end with /* because otherwise\n // it will never match /blog/post/123 */}\n // <Route path=\"blog\" element={<Blog />} />\n // <Route path=\"blog/feed\" element={<BlogFeed />} />\n // </Routes>\n //\n // function Blog() {\n // return (\n // <Routes>\n // <Route path=\"post/:id\" element={<Post />} />\n // </Routes>\n // );\n // }\n let parentPath = (parentRoute && parentRoute.path) || \"\";\n warningOnce(\n parentPathname,\n !parentRoute || parentPath.endsWith(\"*\"),\n `You rendered descendant <Routes> (or called \\`useRoutes()\\`) at ` +\n `\"${parentPathname}\" (under <Route path=\"${parentPath}\">) but the ` +\n `parent route path has no trailing \"*\". This means if you navigate ` +\n `deeper, the parent won't match anymore and therefore the child ` +\n `routes will never render.\\n\\n` +\n `Please change the parent <Route path=\"${parentPath}\"> to <Route ` +\n `path=\"${parentPath === \"/\" ? \"*\" : `${parentPath}/*`}\">.`\n );\n }\n\n let locationFromContext = useLocation();\n\n let location;\n if (locationArg) {\n let parsedLocationArg =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n invariant(\n parentPathnameBase === \"/\" ||\n parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n `When overriding the location using \\`<Routes location>\\` or \\`useRoutes(routes, location)\\`, ` +\n `the location pathname must begin with the portion of the URL pathname that was ` +\n `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n );\n\n location = parsedLocationArg;\n } else {\n location = locationFromContext;\n }\n\n let pathname = location.pathname || \"/\";\n let remainingPathname =\n parentPathnameBase === \"/\"\n ? pathname\n : pathname.slice(parentPathnameBase.length) || \"/\";\n\n let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n if (__DEV__) {\n warning(\n parentRoute || matches != null,\n `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n );\n\n warning(\n matches == null ||\n matches[matches.length - 1].route.element !== undefined ||\n matches[matches.length - 1].route.Component !== undefined,\n `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n `does not have an element or Component. This means it will render an <Outlet /> with a ` +\n `null value by default resulting in an \"empty\" page.`\n );\n }\n\n let renderedMatches = _renderMatches(\n matches &&\n matches.map((match) =>\n Object.assign({}, match, {\n params: Object.assign({}, parentParams, match.params),\n pathname: joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathname).pathname\n : match.pathname,\n ]),\n pathnameBase:\n match.pathnameBase === \"/\"\n ? parentPathnameBase\n : joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathnameBase).pathname\n : match.pathnameBase,\n ]),\n })\n ),\n parentMatches,\n dataRouterState\n );\n\n // When a user passes in a `locationArg`, the associated routes need to\n // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n // to use the scoped location instead of the global location.\n if (locationArg && renderedMatches) {\n return (\n <LocationContext.Provider\n value={{\n location: {\n pathname: \"/\",\n search: \"\",\n hash: \"\",\n state: null,\n key: \"default\",\n ...location,\n },\n navigationType: NavigationType.Pop,\n }}\n >\n {renderedMatches}\n </LocationContext.Provider>\n );\n }\n\n return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n let error = useRouteError();\n let message = isRouteErrorResponse(error)\n ? `${error.status} ${error.statusText}`\n : error instanceof Error\n ? error.message\n : JSON.stringify(error);\n let stack = error instanceof Error ? error.stack : null;\n let lightgrey = \"rgba(200,200,200, 0.5)\";\n let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n let devInfo = null;\n if (__DEV__) {\n console.error(\n \"Error handled by React Router default ErrorBoundary:\",\n error\n );\n\n devInfo = (\n <>\n <p>💿 Hey developer 👋</p>\n <p>\n You can provide a way better UX than this when your app throws errors\n by providing your own <code style={codeStyles}>ErrorBoundary</code> or{\" \"}\n <code style={codeStyles}>errorElement</code> prop on your route.\n </p>\n </>\n );\n }\n\n return (\n <>\n <h2>Unexpected Application Error!</h2>\n <h3 style={{ fontStyle: \"italic\" }}>{message}</h3>\n {stack ? <pre style={preStyles}>{stack}</pre> : null}\n {devInfo}\n </>\n );\n}\n\nconst defaultErrorElement = <DefaultErrorComponent />;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n location: Location;\n revalidation: RevalidationState;\n error: any;\n component: React.ReactNode;\n routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n location: Location;\n revalidation: RevalidationState;\n error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n RenderErrorBoundaryProps,\n RenderErrorBoundaryState\n> {\n constructor(props: RenderErrorBoundaryProps) {\n super(props);\n this.state = {\n location: props.location,\n revalidation: props.revalidation,\n error: props.error,\n };\n }\n\n static getDerivedStateFromError(error: any) {\n return { error: error };\n }\n\n static getDerivedStateFromProps(\n props: RenderErrorBoundaryProps,\n state: RenderErrorBoundaryState\n ) {\n // When we get into an error state, the user will likely click \"back\" to the\n // previous page that didn't have an error. Because this wraps the entire\n // application, that will have no effect--the error page continues to display.\n // This gives us a mechanism to recover from the error when the location changes.\n //\n // Whether we're in an error state or not, we update the location in state\n // so that when we are in an error state, it gets reset when a new location\n // comes in and the user recovers from the error.\n if (\n state.location !== props.location ||\n (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n ) {\n return {\n error: props.error,\n location: props.location,\n revalidation: props.revalidation,\n };\n }\n\n // If we're not changing locations, preserve the location but still surface\n // any new errors that may come through. We retain the existing error, we do\n // this because the error provided from the app state may be cleared without\n // the location changing.\n return {\n error: props.error || state.error,\n location: state.location,\n revalidation: props.revalidation || state.revalidation,\n };\n }\n\n componentDidCatch(error: any, errorInfo: any) {\n console.error(\n \"React Router caught the following error during render\",\n error,\n errorInfo\n );\n }\n\n render() {\n return this.state.error ? (\n <RouteContext.Provider value={this.props.routeContext}>\n <RouteErrorContext.Provider\n value={this.state.error}\n children={this.props.component}\n />\n </RouteContext.Provider>\n ) : (\n this.props.children\n );\n }\n}\n\ninterface RenderedRouteProps {\n routeContext: RouteContextObject;\n match: RouteMatch<string, RouteObject>;\n children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n let dataRouterContext = React.useContext(DataRouterContext);\n\n // Track how deep we got in our render pass to emulate SSR componentDidCatch\n // in a DataStaticRouter\n if (\n dataRouterContext &&\n dataRouterContext.static &&\n dataRouterContext.staticContext &&\n (match.route.errorElement || match.route.ErrorBoundary)\n ) {\n dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n }\n\n return (\n <RouteContext.Provider value={routeContext}>\n {children}\n </RouteContext.Provider>\n );\n}\n\nexport function _renderMatches(\n matches: RouteMatch[] | null,\n parentMatches: RouteMatch[] = [],\n dataRouterState: RemixRouter[\"state\"] | null = null\n): React.ReactElement | null {\n if (matches == null) {\n if (dataRouterState?.errors) {\n // Don't bail if we have data router errors so we can render them in the\n // boundary. Use the pre-matched (or shimmed) matches\n matches = dataRouterState.matches as DataRouteMatch[];\n } else {\n return null;\n }\n }\n\n let renderedMatches = matches;\n\n // If we have data errors, trim matches to the highest error boundary\n let errors = dataRouterState?.errors;\n if (errors != null) {\n let errorIndex = renderedMatches.findIndex(\n (m) => m.route.id && errors?.[m.route.id]\n );\n invariant(\n errorIndex >= 0,\n `Could not find a matching route for errors on route IDs: ${Object.keys(\n errors\n ).join(\",\")}`\n );\n renderedMatches = renderedMatches.slice(\n 0,\n Math.min(renderedMatches.length, errorIndex + 1)\n );\n }\n\n return renderedMatches.reduceRight((outlet, match, index) => {\n let error = match.route.id ? errors?.[match.route.id] : null;\n // Only data routers handle errors\n let errorElement: React.ReactNode | null = null;\n if (dataRouterState) {\n errorElement = match.route.errorElement || defaultErrorElement;\n }\n let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n let getChildren = () => {\n let children: React.ReactNode;\n if (error) {\n children = errorElement;\n } else if (match.route.Component) {\n // Note: This is a de-optimized path since React won't re-use the\n // ReactElement since it's identity changes with each new\n // React.createElement call. We keep this so folks can use\n // `<Route Component={...}>` in `<Routes>` but generally `Component`\n // usage is only advised in `RouterProvider` when we can convert it to\n // `element` ahead of time.\n children = <match.route.Component />;\n } else if (match.route.element) {\n children = match.route.element;\n } else {\n children = outlet;\n }\n return (\n <RenderedRoute\n match={match}\n routeContext={{\n outlet,\n matches,\n isDataRoute: dataRouterState != null,\n }}\n children={children}\n />\n );\n };\n // Only wrap in an error boundary within data router usages when we have an\n // ErrorBoundary/errorElement on this route. Otherwise let it bubble up to\n // an ancestor ErrorBoundary/errorElement\n return dataRouterState &&\n (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n <RenderErrorBoundary\n location={dataRouterState.location}\n revalidation={dataRouterState.revalidation}\n component={errorElement}\n error={error}\n children={getChildren()}\n routeContext={{ outlet: null, matches, isDataRoute: true }}\n />\n ) : (\n getChildren()\n );\n }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n UseBlocker = \"useBlocker\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n UseBlocker = \"useBlocker\",\n UseLoaderData = \"useLoaderData\",\n UseActionData = \"useActionData\",\n UseRouteError = \"useRouteError\",\n UseNavigation = \"useNavigation\",\n UseRouteLoaderData = \"useRouteLoaderData\",\n UseMatches = \"useMatches\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n hookName: DataRouterHook | DataRouterStateHook\n) {\n return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n let ctx = React.useContext(DataRouterContext);\n invariant(ctx, getDataRouterConsoleError(hookName));\n return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n let state = React.useContext(DataRouterStateContext);\n invariant(state, getDataRouterConsoleError(hookName));\n return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n let route = React.useContext(RouteContext);\n invariant(route, getDataRouterConsoleError(hookName));\n return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n let route = useRouteContext(hookName);\n let thisRoute = route.matches[route.matches.length - 1];\n invariant(\n thisRoute.route.id,\n `${hookName} can only be used on routes that contain a unique \"id\"`\n );\n return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nexport function useNavigation() {\n let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nexport function useRevalidator() {\n let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n return React.useMemo(\n () => ({\n revalidate: dataRouterContext.router.revalidate,\n state: state.revalidation,\n }),\n [dataRouterContext.router.revalidate, state.revalidation]\n );\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nexport function useMatches(): UIMatch[] {\n let { matches, loaderData } = useDataRouterState(\n DataRouterStateHook.UseMatches\n );\n return React.useMemo(\n () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),\n [matches, loaderData]\n );\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nexport function useLoaderData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n if (state.errors && state.errors[routeId] != null) {\n console.error(\n `You cannot \\`useLoaderData\\` in an errorElement (routeId: ${routeId})`\n );\n return undefined;\n }\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nexport function useActionData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseActionData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error. This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nexport function useRouteError(): unknown {\n let error = React.useContext(RouteErrorContext);\n let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n // If this was a render error, we put it in a RouteError context inside\n // of RenderErrorBoundary\n if (error) {\n return error;\n }\n\n // Otherwise look for errors from our data router state\n return state.errors?.[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `<Await />` value\n */\nexport function useAsyncValue(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `<Await />` value\n */\nexport function useAsyncError(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation. Mostly used to avoid\n * using half-filled form data. This does not handle hard-reloads or\n * cross-origin navigations.\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);\n let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n\n let [blockerKey, setBlockerKey] = React.useState(\"\");\n let blockerFunction = React.useCallback<BlockerFunction>(\n (arg) => {\n if (typeof shouldBlock !== \"function\") {\n return !!shouldBlock;\n }\n if (basename === \"/\") {\n return shouldBlock(arg);\n }\n\n // If they provided us a function and we've got an active basename, strip\n // it from the locations we expose to the user to match the behavior of\n // useLocation\n let { currentLocation, nextLocation, historyAction } = arg;\n return shouldBlock({\n currentLocation: {\n ...currentLocation,\n pathname:\n stripBasename(currentLocation.pathname, basename) ||\n currentLocation.pathname,\n },\n nextLocation: {\n ...nextLocation,\n pathname:\n stripBasename(nextLocation.pathname, basename) ||\n nextLocation.pathname,\n },\n historyAction,\n });\n },\n [basename, shouldBlock]\n );\n\n // This effect is in charge of blocker key assignment and deletion (which is\n // tightly coupled to the key)\n React.useEffect(() => {\n let key = String(++blockerId);\n setBlockerKey(key);\n return () => router.deleteBlocker(key);\n }, [router]);\n\n // This effect handles assigning the blockerFunction. This is to handle\n // unstable blocker function identities, and happens only after the prior\n // effect so we don't get an orphaned blockerFunction in the router with a\n // key of \"\". Until then we just have the IDLE_BLOCKER.\n React.useEffect(() => {\n if (blockerKey !== \"\") {\n router.getBlocker(blockerKey, blockerFunction);\n }\n }, [router, blockerKey, blockerFunction]);\n\n // Prefer the blocker from `state` not `router.state` since DataRouterContext\n // is memoized so this ensures we update on blocker state updates\n return blockerKey && state.blockers.has(blockerKey)\n ? state.blockers.get(blockerKey)!\n : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable(): NavigateFunction {\n let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our router subscriber yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n router.navigate(to);\n } else {\n router.navigate(to, { fromRouteId: id, ...options });\n }\n },\n [router, id]\n );\n\n return navigate;\n}\n\nconst alreadyWarned: Record<string, boolean> = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n if (!cond && !alreadyWarned[key]) {\n alreadyWarned[key] = true;\n warning(false, message);\n }\n}\n","import type {\n InitialEntry,\n LazyRouteFunction,\n Location,\n MemoryHistory,\n RelativeRoutingType,\n Router as RemixRouter,\n RouterState,\n RouterSubscriber,\n To,\n TrackedPromise,\n} from \"@remix-run/router\";\nimport {\n AbortedDeferredError,\n Action as NavigationType,\n createMemoryHistory,\n UNSAFE_getResolveToMatches as getResolveToMatches,\n UNSAFE_invariant as invariant,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\nimport * as React from \"react\";\n\nimport type {\n DataRouteObject,\n IndexRouteObject,\n Navigator,\n NonIndexRouteObject,\n RouteMatch,\n RouteObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n} from \"./context\";\nimport {\n _renderMatches,\n useAsyncValue,\n useInRouterContext,\n useLocation,\n useNavigate,\n useOutlet,\n useRoutes,\n useRoutesImpl,\n} from \"./hooks\";\n\nexport interface FutureConfig {\n v7_startTransition: boolean;\n}\n\nexport interface RouterProviderProps {\n fallbackElement?: React.ReactNode;\n router: RemixRouter;\n future?: Partial<FutureConfig>;\n}\n\n/**\n Webpack + React 17 fails to compile on any of the following because webpack\n complains that `startTransition` doesn't exist in `React`:\n * import { startTransition } from \"react\"\n * import * as React from from \"react\";\n \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n * import * as React from from \"react\";\n \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n Moving it to a constant such as the following solves the Webpack/React 17 issue:\n * import * as React from from \"react\";\n const START_TRANSITION = \"startTransition\";\n START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n However, that introduces webpack/terser minification issues in production builds\n in React 18 where minification/obfuscation ends up removing the call of\n React.startTransition entirely from the first half of the ternary. Grabbing\n this exported reference once up front resolves that issue.\n\n See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n fallbackElement,\n router,\n future,\n}: RouterProviderProps): React.ReactElement {\n let [state, setStateImpl] = React.useState(router.state);\n let { v7_startTransition } = future || {};\n\n let setState = React.useCallback<RouterSubscriber>(\n (newState: RouterState) => {\n if (v7_startTransition && startTransitionImpl) {\n startTransitionImpl(() => setStateImpl(newState));\n } else {\n setStateImpl(newState);\n }\n },\n [setStateImpl, v7_startTransition]\n );\n\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n let navigator = React.useMemo((): Navigator => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: (n) => router.navigate(n),\n push: (to, state, opts) =>\n router.navigate(to, {\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n replace: (to, state, opts) =>\n router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n };\n }, [router]);\n\n let basename = router.basename || \"/\";\n\n let dataRouterContext = React.useMemo(\n () => ({\n router,\n navigator,\n static: false,\n basename,\n }),\n [router, navigator, basename]\n );\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a <script> here\n // containing the hydrated server-side staticContext (from StaticRouterProvider).\n // useId relies on the component tree structure to generate deterministic id's\n // so we need to ensure it remains the same on the client even though\n // we don't need the <script> tag\n return (\n <>\n <DataRouterContext.Provider value={dataRouterContext}>\n <DataRouterStateContext.Provider value={state}>\n <Router\n basename={basename}\n location={state.location}\n navigationType={state.historyAction}\n navigator={navigator}\n >\n {state.initialized ? (\n <DataRoutes routes={router.routes} state={state} />\n ) : (\n fallbackElement\n )}\n </Router>\n </DataRouterStateContext.Provider>\n </DataRouterContext.Provider>\n {null}\n </>\n );\n}\n\nfunction DataRoutes({\n routes,\n state,\n}: {\n routes: DataRouteObject[];\n state: RouterState;\n}): React.ReactElement | null {\n return useRoutesImpl(routes, undefined, state);\n}\n\nexport interface MemoryRouterProps {\n basename?: string;\n children?: React.ReactNode;\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n future?: Partial<FutureConfig>;\n}\n\n/**\n * A `<Router>` that stores all entries in memory.\n *\n * @see https://reactrouter.com/router-components/memory-router\n */\nexport function MemoryRouter({\n basename,\n children,\n initialEntries,\n initialIndex,\n future,\n}: MemoryRouterProps): React.ReactElement {\n let historyRef = React.useRef<MemoryHistory>();\n if (historyRef.current == null) {\n historyRef.current = createMemoryHistory({\n initialEntries,\n initialIndex,\n v5Compat: true,\n });\n }\n\n let history = historyRef.current;\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n />\n );\n}\n\nexport interface NavigateProps {\n to: To;\n replace?: boolean;\n state?: any;\n relative?: RelativeRoutingType;\n}\n\n/**\n * Changes the current location.\n *\n * Note: This API is mostly useful in React.Component subclasses that are not\n * able to use hooks. In functional components, we recommend you use the\n * `useNavigate` hook instead.\n *\n * @see https://reactrouter.com/components/navigate\n */\nexport function Navigate({\n to,\n replace,\n state,\n relative,\n}: NavigateProps): null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of\n // the router loaded. We can help them understand how to avoid that.\n `<Navigate> may be used only in the context of a <Router> component.`\n );\n\n warning(\n !React.useContext(NavigationContext).static,\n `<Navigate> must not be used on the initial render in a <StaticRouter>. ` +\n `This is a no-op, but you should modify your code so the <Navigate> is ` +\n `only ever rendered in response to some user interaction or state change.`\n );\n\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n let navigate = useNavigate();\n\n // Resolve the path outside of the effect so that when effects run twice in\n // StrictMode they navigate to the same place\n let path = resolveTo(\n to,\n getResolveToMatches(matches),\n locationPathname,\n relative === \"path\"\n );\n let jsonPath = JSON.stringify(path);\n\n React.useEffect(\n () => navigate(JSON.parse(jsonPath), { replace, state, relative }),\n [navigate, jsonPath, relative, replace, state]\n );\n\n return null;\n}\n\nexport interface OutletProps {\n context?: unknown;\n}\n\n/**\n * Renders the child route's element, if there is one.\n *\n * @see https://reactrouter.com/components/outlet\n */\nexport function Outlet(props: OutletProps): React.ReactElement | null {\n return useOutlet(props.context);\n}\n\nexport interface PathRouteProps {\n caseSensitive?: NonIndexRouteObject[\"caseSensitive\"];\n path?: NonIndexRouteObject[\"path\"];\n id?: NonIndexRouteObject[\"id\"];\n lazy?: LazyRouteFunction<NonIndexRouteObject>;\n loader?: NonIndexRouteObject[\"loader\"];\n action?: NonIndexRouteObject[\"action\"];\n hasErrorBoundary?: NonIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: NonIndexRouteObject[\"shouldRevalidate\"];\n handle?: NonIndexRouteObject[\"handle\"];\n index?: false;\n children?: React.ReactNode;\n element?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n}\n\nexport interface LayoutRouteProps extends PathRouteProps {}\n\nexport interface IndexRouteProps {\n caseSensitive?: IndexRouteObject[\"caseSensitive\"];\n path?: IndexRouteObject[\"path\"];\n id?: IndexRouteObject[\"id\"];\n lazy?: LazyRouteFunction<IndexRouteObject>;\n loader?: IndexRouteObject[\"loader\"];\n action?: IndexRouteObject[\"action\"];\n hasErrorBoundary?: IndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: IndexRouteObject[\"shouldRevalidate\"];\n handle?: IndexRouteObject[\"handle\"];\n index: true;\n children?: undefined;\n element?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n}\n\nexport type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;\n\n/**\n * Declares an element that should be rendered at a certain URL path.\n *\n * @see https://reactrouter.com/components/route\n */\nexport function Route(_props: RouteProps): React.ReactElement | null {\n invariant(\n false,\n `A <Route> is only ever to be used as the child of <Routes> element, ` +\n `never rendered directly. Please wrap your <Route> in a <Routes>.`\n );\n}\n\nexport interface RouterProps {\n basename?: string;\n children?: React.ReactNode;\n location: Partial<Location> | string;\n navigationType?: NavigationType;\n navigator: Navigator;\n static?: boolean;\n}\n\n/**\n * Provides location context for the rest of the app.\n *\n * Note: You usually won't render a `<Router>` directly. Instead, you'll render a\n * router that is more specific to your environment such as a `<BrowserRouter>`\n * in web browsers or a `<StaticRouter>` for server rendering.\n *\n * @see https://reactrouter.com/router-components/router\n */\nexport function Router({\n basename: basenameProp = \"/\",\n children = null,\n location: locationProp,\n navigationType = NavigationType.Pop,\n navigator,\n static: staticProp = false,\n}: RouterProps): React.ReactElement | null {\n invariant(\n !useInRouterContext(),\n `You cannot render a <Router> inside another <Router>.` +\n ` You should never have more than one in your app.`\n );\n\n // Preserve trailing slashes on basename, so we can let the user control\n // the enforcement of trailing slashes throughout the app\n let basename = basenameProp.replace(/^\\/*/, \"/\");\n let navigationContext = React.useMemo(\n () => ({ basename, navigator, static: staticProp }),\n [basename, navigator, staticProp]\n );\n\n if (typeof locationProp === \"string\") {\n locationProp = parsePath(locationProp);\n }\n\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n state = null,\n key = \"default\",\n } = locationProp;\n\n let locationContext = React.useMemo(() => {\n let trailingPathname = stripBasename(pathname, basename);\n\n if (trailingPathname == null) {\n return null;\n }\n\n return {\n location: {\n pathname: trailingPathname,\n search,\n hash,\n state,\n key,\n },\n navigationType,\n };\n }, [basename, pathname, search, hash, state, key, navigationType]);\n\n warning(\n locationContext != null,\n `<Router basename=\"${basename}\"> is not able to match the URL ` +\n `\"${pathname}${search}${hash}\" because it does not start with the ` +\n `basename, so the <Router> won't render anything.`\n );\n\n if (locationContext == null) {\n return null;\n }\n\n return (\n <NavigationContext.Provider value={navigationContext}>\n <LocationContext.Provider children={children} value={locationContext} />\n </NavigationContext.Provider>\n );\n}\n\nexport interface RoutesProps {\n children?: React.ReactNode;\n location?: Partial<Location> | string;\n}\n\n/**\n * A container for a nested tree of `<Route>` elements that renders the branch\n * that best matches the current location.\n *\n * @see https://reactrouter.com/components/routes\n */\nexport function Routes({\n children,\n location,\n}: RoutesProps): React.ReactElement | null {\n return useRoutes(createRoutesFromChildren(children), location);\n}\n\nexport interface AwaitResolveRenderFunction {\n (data: Awaited<any>): React.ReactNode;\n}\n\nexport interface AwaitProps {\n children: React.ReactNode | AwaitResolveRenderFunction;\n errorElement?: React.ReactNode;\n resolve: TrackedPromise | any;\n}\n\n/**\n * Component to use for rendering lazily loaded data from returning defer()\n * in a loader function\n */\nexport function Await({ children, errorElement, resolve }: AwaitProps) {\n return (\n <AwaitErrorBoundary resolve={resolve} errorElement={errorElement}>\n <ResolveAwait>{children}</ResolveAwait>\n </AwaitErrorBoundary>\n );\n}\n\ntype AwaitErrorBoundaryProps = React.PropsWithChildren<{\n errorElement?: React.ReactNode;\n resolve: TrackedPromise | any;\n}>;\n\ntype AwaitErrorBoundaryState = {\n error: any;\n};\n\nenum AwaitRenderStatus {\n pending,\n success,\n error,\n}\n\nconst neverSettledPromise = new Promise(() => {});\n\nclass AwaitErrorBoundary extends React.Component<\n AwaitErrorBoundaryProps,\n AwaitErrorBoundaryState\n> {\n constructor(props: AwaitErrorBoundaryProps) {\n super(props);\n this.state = { error: null };\n }\n\n static getDerivedStateFromError(error: any) {\n return { error };\n }\n\n componentDidCatch(error: any, errorInfo: any) {\n console.error(\n \"<Await> caught the following error during render\",\n error,\n errorInfo\n );\n }\n\n render() {\n let { children, errorElement, resolve } = this.props;\n\n let promise: TrackedPromise | null = null;\n let status: AwaitRenderStatus = AwaitRenderStatus.pending;\n\n if (!(resolve instanceof Promise)) {\n // Didn't get a promise - provide as a resolved promise\n status = AwaitRenderStatus.success;\n promise = Promise.resolve();\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n Object.defineProperty(promise, \"_data\", { get: () => resolve });\n } else if (this.state.error) {\n // Caught a render error, provide it as a rejected promise\n status = AwaitRenderStatus.error;\n let renderError = this.state.error;\n promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n Object.defineProperty(promise, \"_error\", { get: () => renderError });\n } else if ((resolve as TrackedPromise)._tracked) {\n // Already tracked promise - check contents\n promise = resolve;\n status =\n promise._error !== undefined\n ? AwaitRenderStatus.error\n : promise._data !== undefined\n ? AwaitRenderStatus.success\n : AwaitRenderStatus.pending;\n } else {\n // Raw (untracked) promise - track it\n status = AwaitRenderStatus.pending;\n Object.defineProperty(resolve, \"_tracked\", { get: () => true });\n promise = resolve.then(\n (data: any) =>\n Object.defineProperty(resolve, \"_data\", { get: () => data }),\n (error: any) =>\n Object.defineProperty(resolve, \"_error\", { get: () => error })\n );\n }\n\n if (\n status === AwaitRenderStatus.error &&\n promise._error instanceof AbortedDeferredError\n ) {\n // Freeze the UI by throwing a never resolved promise\n throw neverSettledPromise;\n }\n\n if (status === AwaitRenderStatus.error && !errorElement) {\n // No errorElement, throw to the nearest route-level error boundary\n throw promise._error;\n }\n\n if (status === AwaitRenderStatus.error) {\n // Render via our errorElement\n return <AwaitContext.Provider value={promise} children={errorElement} />;\n }\n\n if (status === AwaitRenderStatus.success) {\n // Render children with resolved value\n return <AwaitContext.Provider value={promise} children={children} />;\n }\n\n // Throw to the suspense boundary\n throw promise;\n }\n}\n\n/**\n * @private\n * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`\n */\nfunction ResolveAwait({\n children,\n}: {\n children: React.ReactNode | AwaitResolveRenderFunction;\n}) {\n let data = useAsyncValue();\n let toRender = typeof children === \"function\" ? children(data) : children;\n return <>{toRender}</>;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// UTILS\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Creates a route config from a React \"children\" object, which is usually\n * either a `<Route>` element or an array of them. Used internally by\n * `<Routes>` to create a route config from its children.\n *\n * @see https://reactrouter.com/utils/create-routes-from-children\n */\nexport function createRoutesFromChildren(\n children: React.ReactNode,\n parentPath: number[] = []\n): RouteObject[] {\n let routes: RouteObject[] = [];\n\n React.Children.forEach(children, (element, index) => {\n if (!React.isValidElement(element)) {\n // Ignore non-elements. This allows people to more easily inline\n // conditionals in their route config.\n return;\n }\n\n let treePath = [...parentPath, index];\n\n if (element.type === React.Fragment) {\n // Transparently support React.Fragment and its children.\n routes.push.apply(\n routes,\n createRoutesFromChildren(element.props.children, treePath)\n );\n return;\n }\n\n invariant(\n element.type === Route,\n `[${\n typeof element.type === \"string\" ? element.type : element.type.name\n }] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`\n );\n\n invariant(\n !element.props.index || !element.props.children,\n \"An index route cannot have child routes.\"\n );\n\n let route: RouteObject = {\n id: element.props.id || treePath.join(\"-\"),\n caseSensitive: element.props.caseSensitive,\n element: element.props.element,\n Component: element.props.Component,\n index: element.props.index,\n path: element.props.path,\n loader: element.props.loader,\n action: element.props.action,\n errorElement: element.props.errorElement,\n ErrorBoundary: element.props.ErrorBoundary,\n hasErrorBoundary:\n element.props.ErrorBoundary != null ||\n element.props.errorElement != null,\n shouldRevalidate: element.props.shouldRevalidate,\n handle: element.props.handle,\n lazy: element.props.lazy,\n };\n\n if (element.props.children) {\n route.children = createRoutesFromChildren(\n element.props.children,\n treePath\n );\n }\n\n routes.push(route);\n });\n\n return routes;\n}\n\n/**\n * Renders the result of `matchRoutes()` into a React element.\n */\nexport function renderMatches(\n matches: RouteMatch[] | null\n): React.ReactElement | null {\n return _renderMatches(matches);\n}\n","// extracted by mini-css-extract-plugin\nexport default {\"signIn\":\"SignIn_signIn__3t4GY\",\"signInTransition\":\"SignIn_signInTransition__DVaCC\",\"signInLabel\":\"SignIn_signInLabel__6itNQ\",\"swapSignIn\":\"SignIn_swapSignIn__WlTGP\"};","import { useEffect, useState } from \"react\";\nimport { auth } from \"../../Config/firebase-config\";\nimport { createUserWithEmailAndPassword, signOut } from \"firebase/auth\";\nimport {useNavigate} from \"react-router-dom\";\nimport css from \"./SignIn.module.css\";\n\n\n\n\nconst SignIn = () => {\n\n const [email, setEmail] = useState(\"\");\n const [password, setPassword] = useState(\"\");\n const [signInTransition, setSignInTransition] = useState(false);\n\n console.log(auth?.currentUser?.email)\n\n const singInUser = async () => {\n try{\n await createUserWithEmailAndPassword(auth, email, password);\n } catch (err){\n console.error(err);\n }\n }\n\n const logOut = async () => {\n try{\n await signOut(auth)\n } catch (err){\n console.error(err);\n }\n }\n\n const navigate = useNavigate();\n const toCreateAccount = () => {\n navigate(\"/Friendly-Betting/CreateAccount\");\n }\n\n\n \n\n useEffect(() => {\n const timeout = setTimeout(() => {\n setSignInTransition(true);\n }, 2);\n\n return () => clearTimeout(timeout);\n }, []);\n \n\n return (\n \n <div className={`${css.signIn} ${signInTransition ? \"\" : css.signInTransition}`}>\n <div className={css.signInLabel}>Sign in</div>\n <input \n type=\"text\" \n placeholder=\"Email or Number\" \n onChange={(e) => setEmail(e.target.value)}\n />\n <input \n type=\"password\" \n placeholder=\"password\" \n id=\"\" \n onChange={(e) => setPassword(e.target.value)}\n />\n <button onClick={singInUser}>Sign In</button>\n <div>\n <div onClick={toCreateAccount} className={css.swapSignIn} >Don't have account? Create One!</div>\n </div>\n <br />\n <br />\n <button onClick={logOut}>Log Out</button>\n </div>\n \n\n )\n}\n\nexport default SignIn;","import { Link, useNavigate} from \"react-router-dom\";\nimport { useEffect, useState} from \"react\";\n\nimport css from \"./SignIn.module.css\";\n\n\n\n\n\nconst CreateAccount = () => {\n\n const [signInTransition, setSignInTransition] = useState(false);\n const navigate = useNavigate();\n const toSignIn = () => {\n navigate(\"/Friendly-Betting/SignIn\");\n }\n\nuseEffect(() => {\n const timeout = setTimeout(() => {\n setSignInTransition(true);\n }, 2);\n\n return () => clearTimeout(timeout);\n }, []);\n return (\n <div className={`${css.signIn} ${signInTransition ? \"\" : css.signInTransition}`}>\n <div className={css.signInLabel}>Create Account</div>\n <input type=\"text\" placeholder=\"Email\" />\n <input type=\"text\" placeholder=\"Phone\" />\n <br />\n <input type=\"password\" placeholder=\"password\" name=\"\" id=\"\" />\n <input type=\"password\" placeholder=\"confirm password\" name=\"\" id=\"\" />\n <button>Create Account</button>\n <div>\n <div onClick={toSignIn} className={css.swapSignIn} >Already have account? Sign in!</div>\n </div>\n </div>\n )\n}\n\nexport default CreateAccount;","import type {\n FormEncType,\n HTMLFormMethod,\n RelativeRoutingType,\n} from \"@remix-run/router\";\nimport { stripBasename, UNSAFE_warning as warning } from \"@remix-run/router\";\n\nexport const defaultMethod: HTMLFormMethod = \"get\";\nconst defaultEncType: FormEncType = \"application/x-www-form-urlencoded\";\n\nexport function isHtmlElement(object: any): object is HTMLElement {\n return object != null && typeof object.tagName === \"string\";\n}\n\nexport function isButtonElement(object: any): object is HTMLButtonElement {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"button\";\n}\n\nexport function isFormElement(object: any): object is HTMLFormElement {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"form\";\n}\n\nexport function isInputElement(object: any): object is HTMLInputElement {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"input\";\n}\n\ntype LimitedMouseEvent = Pick<\n MouseEvent,\n \"button\" | \"metaKey\" | \"altKey\" | \"ctrlKey\" | \"shiftKey\"\n>;\n\nfunction isModifiedEvent(event: LimitedMouseEvent) {\n return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);\n}\n\nexport function shouldProcessLinkClick(\n event: LimitedMouseEvent,\n target?: string\n) {\n return (\n event.button === 0 && // Ignore everything but left clicks\n (!target || target === \"_self\") && // Let browser handle \"target=_blank\" etc.\n !isModifiedEvent(event) // Ignore clicks with modifier keys\n );\n}\n\nexport type ParamKeyValuePair = [string, string];\n\nexport type URLSearchParamsInit =\n | string\n | ParamKeyValuePair[]\n | Record<string, string | string[]>\n | URLSearchParams;\n\n/**\n * Creates a URLSearchParams object using the given initializer.\n *\n * This is identical to `new URLSearchParams(init)` except it also\n * supports arrays as values in the object form of the initializer\n * instead of just strings. This is convenient when you need multiple\n * values for a given key, but don't want to use an array initializer.\n *\n * For example, instead of:\n *\n * let searchParams = new URLSearchParams([\n * ['sort', 'name'],\n * ['sort', 'price']\n * ]);\n *\n * you can do:\n *\n * let searchParams = createSearchParams({\n * sort: ['name', 'price']\n * });\n */\nexport function createSearchParams(\n init: URLSearchParamsInit = \"\"\n): URLSearchParams {\n return new URLSearchParams(\n typeof init === \"string\" ||\n Array.isArray(init) ||\n init instanceof URLSearchParams\n ? init\n : Object.keys(init).reduce((memo, key) => {\n let value = init[key];\n return memo.concat(\n Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]\n );\n }, [] as ParamKeyValuePair[])\n );\n}\n\nexport function getSearchParamsForLocation(\n locationSearch: string,\n defaultSearchParams: URLSearchParams | null\n) {\n let searchParams = createSearchParams(locationSearch);\n\n if (defaultSearchParams) {\n // Use `defaultSearchParams.forEach(...)` here instead of iterating of\n // `defaultSearchParams.keys()` to work-around a bug in Firefox related to\n // web extensions. Relevant Bugzilla tickets:\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984\n defaultSearchParams.forEach((_, key) => {\n if (!searchParams.has(key)) {\n defaultSearchParams.getAll(key).forEach((value) => {\n searchParams.append(key, value);\n });\n }\n });\n }\n\n return searchParams;\n}\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\nexport type SubmitTarget =\n | HTMLFormElement\n | HTMLButtonElement\n | HTMLInputElement\n | FormData\n | URLSearchParams\n | JsonValue\n | null;\n\n// One-time check for submitter support\nlet _formDataSupportsSubmitter: boolean | null = null;\n\nfunction isFormDataSubmitterSupported() {\n if (_formDataSupportsSubmitter === null) {\n try {\n new FormData(\n document.createElement(\"form\"),\n // @ts-expect-error if FormData supports the submitter parameter, this will throw\n 0\n );\n _formDataSupportsSubmitter = false;\n } catch (e) {\n _formDataSupportsSubmitter = true;\n }\n }\n return _formDataSupportsSubmitter;\n}\n\nexport interface SubmitOptions {\n /**\n * The HTTP method used to submit the form. Overrides `<form method>`.\n * Defaults to \"GET\".\n */\n method?: HTMLFormMethod;\n\n /**\n * The action URL path used to submit the form. Overrides `<form action>`.\n * Defaults to the path of the current route.\n */\n action?: string;\n\n /**\n * The encoding used to submit the form. Overrides `<form encType>`.\n * Defaults to \"application/x-www-form-urlencoded\".\n */\n encType?: FormEncType;\n\n /**\n * Indicate a specific fetcherKey to use when using navigate=false\n */\n fetcherKey?: string;\n\n /**\n * navigate=false will use a fetcher instead of a navigation\n */\n navigate?: boolean;\n\n /**\n * Set `true` to replace the current entry in the browser's history stack\n * instead of creating a new one (i.e. stay on \"the same page\"). Defaults\n * to `false`.\n */\n replace?: boolean;\n\n /**\n * State object to add to the history stack entry for this navigation\n */\n state?: any;\n\n /**\n * Determines whether the form action is relative to the route hierarchy or\n * the pathname. Use this if you want to opt out of navigating the route\n * hierarchy and want to instead route based on /-delimited URL segments\n */\n relative?: RelativeRoutingType;\n\n /**\n * In browser-based environments, prevent resetting scroll after this\n * navigation when using the <ScrollRestoration> component\n */\n preventScrollReset?: boolean;\n\n /**\n * Enable flushSync for this navigation's state updates\n */\n unstable_flushSync?: boolean;\n\n /**\n * Enable view transitions on this submission navigation\n */\n unstable_viewTransition?: boolean;\n}\n\nconst supportedFormEncTypes: Set<FormEncType> = new Set([\n \"application/x-www-form-urlencoded\",\n \"multipart/form-data\",\n \"text/plain\",\n]);\n\nfunction getFormEncType(encType: string | null) {\n if (encType != null && !supportedFormEncTypes.has(encType as FormEncType)) {\n warning(\n false,\n `\"${encType}\" is not a valid \\`encType\\` for \\`<Form>\\`/\\`<fetcher.Form>\\` ` +\n `and will default to \"${defaultEncType}\"`\n );\n\n return null;\n }\n return encType;\n}\n\nexport function getFormSubmissionInfo(\n target: SubmitTarget,\n basename: string\n): {\n action: string | null;\n method: string;\n encType: string;\n formData: FormData | undefined;\n body: any;\n} {\n let method: string;\n let action: string | null;\n let encType: string;\n let formData: FormData | undefined;\n let body: any;\n\n if (isFormElement(target)) {\n // When grabbing the action from the element, it will have had the basename\n // prefixed to ensure non-JS scenarios work, so strip it since we'll\n // re-prefix in the router\n let attr = target.getAttribute(\"action\");\n action = attr ? stripBasename(attr, basename) : null;\n method = target.getAttribute(\"method\") || defaultMethod;\n encType = getFormEncType(target.getAttribute(\"enctype\")) || defaultEncType;\n\n formData = new FormData(target);\n } else if (\n isButtonElement(target) ||\n (isInputElement(target) &&\n (target.type === \"submit\" || target.type === \"image\"))\n ) {\n let form = target.form;\n\n if (form == null) {\n throw new Error(\n `Cannot submit a <button> or <input type=\"submit\"> without a <form>`\n );\n }\n\n // <button>/<input type=\"submit\"> may override attributes of <form>\n\n // When grabbing the action from the element, it will have had the basename\n // prefixed to ensure non-JS scenarios work, so strip it since we'll\n // re-prefix in the router\n let attr = target.getAttribute(\"formaction\") || form.getAttribute(\"action\");\n action = attr ? stripBasename(attr, basename) : null;\n\n method =\n target.getAttribute(\"formmethod\") ||\n form.getAttribute(\"method\") ||\n defaultMethod;\n encType =\n getFormEncType(target.getAttribute(\"formenctype\")) ||\n getFormEncType(form.getAttribute(\"enctype\")) ||\n defaultEncType;\n\n // Build a FormData object populated from a form and submitter\n formData = new FormData(form, target);\n\n // If this browser doesn't support the `FormData(el, submitter)` format,\n // then tack on the submitter value at the end. This is a lightweight\n // solution that is not 100% spec compliant. For complete support in older\n // browsers, consider using the `formdata-submitter-polyfill` package\n if (!isFormDataSubmitterSupported()) {\n let { name, type, value } = target;\n if (type === \"image\") {\n let prefix = name ? `${name}.` : \"\";\n formData.append(`${prefix}x`, \"0\");\n formData.append(`${prefix}y`, \"0\");\n } else if (name) {\n formData.append(name, value);\n }\n }\n } else if (isHtmlElement(target)) {\n throw new Error(\n `Cannot submit element that is not <form>, <button>, or ` +\n `<input type=\"submit|image\">`\n );\n } else {\n method = defaultMethod;\n action = null;\n encType = defaultEncType;\n body = target;\n }\n\n // Send body for <Form encType=\"text/plain\" so we encode it into text\n if (formData && encType === \"text/plain\") {\n body = formData;\n formData = undefined;\n }\n\n return { action, method: method.toLowerCase(), encType, formData, body };\n}\n","/**\n * NOTE: If you refactor this to split up the modules into separate files,\n * you'll need to update the rollup config for react-router-dom-v5-compat.\n */\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport type {\n DataRouteObject,\n FutureConfig,\n Location,\n NavigateOptions,\n NavigationType,\n Navigator,\n RelativeRoutingType,\n RouteObject,\n RouterProviderProps,\n To,\n} from \"react-router\";\nimport {\n Router,\n createPath,\n useHref,\n useLocation,\n useMatches,\n useNavigate,\n useNavigation,\n useResolvedPath,\n useBlocker,\n UNSAFE_DataRouterContext as DataRouterContext,\n UNSAFE_DataRouterStateContext as DataRouterStateContext,\n UNSAFE_NavigationContext as NavigationContext,\n UNSAFE_RouteContext as RouteContext,\n UNSAFE_mapRouteProperties as mapRouteProperties,\n UNSAFE_useRouteId as useRouteId,\n UNSAFE_useRoutesImpl as useRoutesImpl,\n} from \"react-router\";\nimport type {\n BrowserHistory,\n Fetcher,\n FormEncType,\n FormMethod,\n FutureConfig as RouterFutureConfig,\n GetScrollRestorationKeyFunction,\n HashHistory,\n History,\n HTMLFormMethod,\n HydrationState,\n Router as RemixRouter,\n V7_FormMethod,\n RouterState,\n RouterSubscriber,\n BlockerFunction,\n} from \"@remix-run/router\";\nimport {\n createRouter,\n createBrowserHistory,\n createHashHistory,\n joinPaths,\n stripBasename,\n UNSAFE_ErrorResponseImpl as ErrorResponseImpl,\n UNSAFE_invariant as invariant,\n UNSAFE_warning as warning,\n matchPath,\n IDLE_FETCHER,\n} from \"@remix-run/router\";\n\nimport type {\n SubmitOptions,\n ParamKeyValuePair,\n URLSearchParamsInit,\n SubmitTarget,\n} from \"./dom\";\nimport {\n createSearchParams,\n defaultMethod,\n getFormSubmissionInfo,\n getSearchParamsForLocation,\n shouldProcessLinkClick,\n} from \"./dom\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Re-exports\n////////////////////////////////////////////////////////////////////////////////\n\nexport type {\n FormEncType,\n FormMethod,\n GetScrollRestorationKeyFunction,\n ParamKeyValuePair,\n SubmitOptions,\n URLSearchParamsInit,\n V7_FormMethod,\n};\nexport { createSearchParams };\n\n// Note: Keep in sync with react-router exports!\nexport type {\n ActionFunction,\n ActionFunctionArgs,\n AwaitProps,\n unstable_Blocker,\n unstable_BlockerFunction,\n DataRouteMatch,\n DataRouteObject,\n ErrorResponse,\n Fetcher,\n Hash,\n IndexRouteObject,\n IndexRouteProps,\n JsonFunction,\n LazyRouteFunction,\n LayoutRouteProps,\n LoaderFunction,\n LoaderFunctionArgs,\n Location,\n MemoryRouterProps,\n NavigateFunction,\n NavigateOptions,\n NavigateProps,\n Navigation,\n Navigator,\n NonIndexRouteObject,\n OutletProps,\n Params,\n ParamParseKey,\n Path,\n PathMatch,\n Pathname,\n PathParam,\n PathPattern,\n PathRouteProps,\n RedirectFunction,\n RelativeRoutingType,\n RouteMatch,\n RouteObject,\n RouteProps,\n RouterProps,\n RouterProviderProps,\n RoutesProps,\n Search,\n ShouldRevalidateFunction,\n ShouldRevalidateFunctionArgs,\n To,\n UIMatch,\n} from \"react-router\";\nexport {\n AbortedDeferredError,\n Await,\n MemoryRouter,\n Navigate,\n NavigationType,\n Outlet,\n Route,\n Router,\n Routes,\n createMemoryRouter,\n createPath,\n createRoutesFromChildren,\n createRoutesFromElements,\n defer,\n isRouteErrorResponse,\n generatePath,\n json,\n matchPath,\n matchRoutes,\n parsePath,\n redirect,\n redirectDocument,\n renderMatches,\n resolvePath,\n useActionData,\n useAsyncError,\n useAsyncValue,\n useBlocker,\n useHref,\n useInRouterContext,\n useLoaderData,\n useLocation,\n useMatch,\n useMatches,\n useNavigate,\n useNavigation,\n useNavigationType,\n useOutlet,\n useOutletContext,\n useParams,\n useResolvedPath,\n useRevalidator,\n useRouteError,\n useRouteLoaderData,\n useRoutes,\n} from \"react-router\";\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n UNSAFE_DataRouterContext,\n UNSAFE_DataRouterStateContext,\n UNSAFE_NavigationContext,\n UNSAFE_LocationContext,\n UNSAFE_RouteContext,\n UNSAFE_useRouteId,\n} from \"react-router\";\n//#endregion\n\ndeclare global {\n var __staticRouterHydrationData: HydrationState | undefined;\n interface Document {\n startViewTransition(cb: () => Promise<void> | void): ViewTransition;\n }\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Routers\n////////////////////////////////////////////////////////////////////////////////\n\ninterface DOMRouterOpts {\n basename?: string;\n future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n hydrationData?: HydrationState;\n window?: Window;\n}\n\nexport function createBrowserRouter(\n routes: RouteObject[],\n opts?: DOMRouterOpts\n): RemixRouter {\n return createRouter({\n basename: opts?.basename,\n future: {\n ...opts?.future,\n v7_prependBasename: true,\n },\n history: createBrowserHistory({ window: opts?.window }),\n hydrationData: opts?.hydrationData || parseHydrationData(),\n routes,\n mapRouteProperties,\n window: opts?.window,\n }).initialize();\n}\n\nexport function createHashRouter(\n routes: RouteObject[],\n opts?: DOMRouterOpts\n): RemixRouter {\n return createRouter({\n basename: opts?.basename,\n future: {\n ...opts?.future,\n v7_prependBasename: true,\n },\n history: createHashHistory({ window: opts?.window }),\n hydrationData: opts?.hydrationData || parseHydrationData(),\n routes,\n mapRouteProperties,\n window: opts?.window,\n }).initialize();\n}\n\nfunction parseHydrationData(): HydrationState | undefined {\n let state = window?.__staticRouterHydrationData;\n if (state && state.errors) {\n state = {\n ...state,\n errors: deserializeErrors(state.errors),\n };\n }\n return state;\n}\n\nfunction deserializeErrors(\n errors: RemixRouter[\"state\"][\"errors\"]\n): RemixRouter[\"state\"][\"errors\"] {\n if (!errors) return null;\n let entries = Object.entries(errors);\n let serialized: RemixRouter[\"state\"][\"errors\"] = {};\n for (let [key, val] of entries) {\n // Hey you! If you change this, please change the corresponding logic in\n // serializeErrors in react-router-dom/server.tsx :)\n if (val && val.__type === \"RouteErrorResponse\") {\n serialized[key] = new ErrorResponseImpl(\n val.status,\n val.statusText,\n val.data,\n val.internal === true\n );\n } else if (val && val.__type === \"Error\") {\n // Attempt to reconstruct the right type of Error (i.e., ReferenceError)\n if (val.__subType) {\n let ErrorConstructor = window[val.__subType];\n if (typeof ErrorConstructor === \"function\") {\n try {\n // @ts-expect-error\n let error = new ErrorConstructor(val.message);\n // Wipe away the client-side stack trace. Nothing to fill it in with\n // because we don't serialize SSR stack traces for security reasons\n error.stack = \"\";\n serialized[key] = error;\n } catch (e) {\n // no-op - fall through and create a normal Error\n }\n }\n }\n\n if (serialized[key] == null) {\n let error = new Error(val.message);\n // Wipe away the client-side stack trace. Nothing to fill it in with\n // because we don't serialize SSR stack traces for security reasons\n error.stack = \"\";\n serialized[key] = error;\n }\n } else {\n serialized[key] = val;\n }\n }\n return serialized;\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Contexts\n////////////////////////////////////////////////////////////////////////////////\n\ntype ViewTransitionContextObject =\n | {\n isTransitioning: false;\n }\n | {\n isTransitioning: true;\n flushSync: boolean;\n currentLocation: Location;\n nextLocation: Location;\n };\n\nconst ViewTransitionContext = React.createContext<ViewTransitionContextObject>({\n isTransitioning: false,\n});\nif (__DEV__) {\n ViewTransitionContext.displayName = \"ViewTransition\";\n}\n\nexport { ViewTransitionContext as UNSAFE_ViewTransitionContext };\n\n// TODO: (v7) Change the useFetcher data from `any` to `unknown`\ntype FetchersContextObject = Map<string, any>;\n\nconst FetchersContext = React.createContext<FetchersContextObject>(new Map());\nif (__DEV__) {\n FetchersContext.displayName = \"Fetchers\";\n}\n\nexport { FetchersContext as UNSAFE_FetchersContext };\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Components\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n Webpack + React 17 fails to compile on any of the following because webpack\n complains that `startTransition` doesn't exist in `React`:\n * import { startTransition } from \"react\"\n * import * as React from from \"react\";\n \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n * import * as React from from \"react\";\n \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n Moving it to a constant such as the following solves the Webpack/React 17 issue:\n * import * as React from from \"react\";\n const START_TRANSITION = \"startTransition\";\n START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n However, that introduces webpack/terser minification issues in production builds\n in React 18 where minification/obfuscation ends up removing the call of\n React.startTransition entirely from the first half of the ternary. Grabbing\n this exported reference once up front resolves that issue.\n\n See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\nconst FLUSH_SYNC = \"flushSync\";\nconst flushSyncImpl = ReactDOM[FLUSH_SYNC];\n\nfunction startTransitionSafe(cb: () => void) {\n if (startTransitionImpl) {\n startTransitionImpl(cb);\n } else {\n cb();\n }\n}\n\nfunction flushSyncSafe(cb: () => void) {\n if (flushSyncImpl) {\n flushSyncImpl(cb);\n } else {\n cb();\n }\n}\n\ninterface ViewTransition {\n finished: Promise<void>;\n ready: Promise<void>;\n updateCallbackDone: Promise<void>;\n skipTransition(): void;\n}\n\nclass Deferred<T> {\n status: \"pending\" | \"resolved\" | \"rejected\" = \"pending\";\n promise: Promise<T>;\n // @ts-expect-error - no initializer\n resolve: (value: T) => void;\n // @ts-expect-error - no initializer\n reject: (reason?: unknown) => void;\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = (value) => {\n if (this.status === \"pending\") {\n this.status = \"resolved\";\n resolve(value);\n }\n };\n this.reject = (reason) => {\n if (this.status === \"pending\") {\n this.status = \"rejected\";\n reject(reason);\n }\n };\n });\n }\n}\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n fallbackElement,\n router,\n future,\n}: RouterProviderProps): React.ReactElement {\n let [state, setStateImpl] = React.useState(router.state);\n let [pendingState, setPendingState] = React.useState<RouterState>();\n let [vtContext, setVtContext] = React.useState<ViewTransitionContextObject>({\n isTransitioning: false,\n });\n let [renderDfd, setRenderDfd] = React.useState<Deferred<void>>();\n let [transition, setTransition] = React.useState<ViewTransition>();\n let [interruption, setInterruption] = React.useState<{\n state: RouterState;\n currentLocation: Location;\n nextLocation: Location;\n }>();\n let fetcherData = React.useRef<Map<string, any>>(new Map());\n let { v7_startTransition } = future || {};\n\n let optInStartTransition = React.useCallback(\n (cb: () => void) => {\n if (v7_startTransition) {\n startTransitionSafe(cb);\n } else {\n cb();\n }\n },\n [v7_startTransition]\n );\n\n let setState = React.useCallback<RouterSubscriber>(\n (\n newState: RouterState,\n {\n deletedFetchers,\n unstable_flushSync: flushSync,\n unstable_viewTransitionOpts: viewTransitionOpts,\n }\n ) => {\n deletedFetchers.forEach((key) => fetcherData.current.delete(key));\n newState.fetchers.forEach((fetcher, key) => {\n if (fetcher.data !== undefined) {\n fetcherData.current.set(key, fetcher.data);\n }\n });\n\n let isViewTransitionUnavailable =\n router.window == null ||\n typeof router.window.document.startViewTransition !== \"function\";\n\n // If this isn't a view transition or it's not available in this browser,\n // just update and be done with it\n if (!viewTransitionOpts || isViewTransitionUnavailable) {\n if (flushSync) {\n flushSyncSafe(() => setStateImpl(newState));\n } else {\n optInStartTransition(() => setStateImpl(newState));\n }\n return;\n }\n\n // flushSync + startViewTransition\n if (flushSync) {\n // Flush through the context to mark DOM elements as transition=ing\n flushSyncSafe(() => {\n // Cancel any pending transitions\n if (transition) {\n renderDfd && renderDfd.resolve();\n transition.skipTransition();\n }\n setVtContext({\n isTransitioning: true,\n flushSync: true,\n currentLocation: viewTransitionOpts.currentLocation,\n nextLocation: viewTransitionOpts.nextLocation,\n });\n });\n\n // Update the DOM\n let t = router.window!.document.startViewTransition(() => {\n flushSyncSafe(() => setStateImpl(newState));\n });\n\n // Clean up after the animation completes\n t.finished.finally(() => {\n flushSyncSafe(() => {\n setRenderDfd(undefined);\n setTransition(undefined);\n setPendingState(undefined);\n setVtContext({ isTransitioning: false });\n });\n });\n\n flushSyncSafe(() => setTransition(t));\n return;\n }\n\n // startTransition + startViewTransition\n if (transition) {\n // Interrupting an in-progress transition, cancel and let everything flush\n // out, and then kick off a new transition from the interruption state\n renderDfd && renderDfd.resolve();\n transition.skipTransition();\n setInterruption({\n state: newState,\n currentLocation: viewTransitionOpts.currentLocation,\n nextLocation: viewTransitionOpts.nextLocation,\n });\n } else {\n // Completed navigation update with opted-in view transitions, let 'er rip\n setPendingState(newState);\n setVtContext({\n isTransitioning: true,\n flushSync: false,\n currentLocation: viewTransitionOpts.currentLocation,\n nextLocation: viewTransitionOpts.nextLocation,\n });\n }\n },\n [router.window, transition, renderDfd, fetcherData, optInStartTransition]\n );\n\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n // When we start a view transition, create a Deferred we can use for the\n // eventual \"completed\" render\n React.useEffect(() => {\n if (vtContext.isTransitioning && !vtContext.flushSync) {\n setRenderDfd(new Deferred<void>());\n }\n }, [vtContext]);\n\n // Once the deferred is created, kick off startViewTransition() to update the\n // DOM and then wait on the Deferred to resolve (indicating the DOM update has\n // happened)\n React.useEffect(() => {\n if (renderDfd && pendingState && router.window) {\n let newState = pendingState;\n let renderPromise = renderDfd.promise;\n let transition = router.window.document.startViewTransition(async () => {\n optInStartTransition(() => setStateImpl(newState));\n await renderPromise;\n });\n transition.finished.finally(() => {\n setRenderDfd(undefined);\n setTransition(undefined);\n setPendingState(undefined);\n setVtContext({ isTransitioning: false });\n });\n setTransition(transition);\n }\n }, [optInStartTransition, pendingState, renderDfd, router.window]);\n\n // When the new location finally renders and is committed to the DOM, this\n // effect will run to resolve the transition\n React.useEffect(() => {\n if (\n renderDfd &&\n pendingState &&\n state.location.key === pendingState.location.key\n ) {\n renderDfd.resolve();\n }\n }, [renderDfd, transition, state.location, pendingState]);\n\n // If we get interrupted with a new navigation during a transition, we skip\n // the active transition, let it cleanup, then kick it off again here\n React.useEffect(() => {\n if (!vtContext.isTransitioning && interruption) {\n setPendingState(interruption.state);\n setVtContext({\n isTransitioning: true,\n flushSync: false,\n currentLocation: interruption.currentLocation,\n nextLocation: interruption.nextLocation,\n });\n setInterruption(undefined);\n }\n }, [vtContext.isTransitioning, interruption]);\n\n let navigator = React.useMemo((): Navigator => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: (n) => router.navigate(n),\n push: (to, state, opts) =>\n router.navigate(to, {\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n replace: (to, state, opts) =>\n router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n };\n }, [router]);\n\n let basename = router.basename || \"/\";\n\n let dataRouterContext = React.useMemo(\n () => ({\n router,\n navigator,\n static: false,\n basename,\n }),\n [router, navigator, basename]\n );\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a <script> here\n // containing the hydrated server-side staticContext (from StaticRouterProvider).\n // useId relies on the component tree structure to generate deterministic id's\n // so we need to ensure it remains the same on the client even though\n // we don't need the <script> tag\n return (\n <>\n <DataRouterContext.Provider value={dataRouterContext}>\n <DataRouterStateContext.Provider value={state}>\n <FetchersContext.Provider value={fetcherData.current}>\n <ViewTransitionContext.Provider value={vtContext}>\n <Router\n basename={basename}\n location={state.location}\n navigationType={state.historyAction}\n navigator={navigator}\n >\n {state.initialized ? (\n <DataRoutes routes={router.routes} state={state} />\n ) : (\n fallbackElement\n )}\n </Router>\n </ViewTransitionContext.Provider>\n </FetchersContext.Provider>\n </DataRouterStateContext.Provider>\n </DataRouterContext.Provider>\n {null}\n </>\n );\n}\n\nfunction DataRoutes({\n routes,\n state,\n}: {\n routes: DataRouteObject[];\n state: RouterState;\n}): React.ReactElement | null {\n return useRoutesImpl(routes, undefined, state);\n}\n\nexport interface BrowserRouterProps {\n basename?: string;\n children?: React.ReactNode;\n future?: Partial<FutureConfig>;\n window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Provides the cleanest URLs.\n */\nexport function BrowserRouter({\n basename,\n children,\n future,\n window,\n}: BrowserRouterProps) {\n let historyRef = React.useRef<BrowserHistory>();\n if (historyRef.current == null) {\n historyRef.current = createBrowserHistory({ window, v5Compat: true });\n }\n\n let history = historyRef.current;\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n />\n );\n}\n\nexport interface HashRouterProps {\n basename?: string;\n children?: React.ReactNode;\n future?: Partial<FutureConfig>;\n window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Stores the location in the hash\n * portion of the URL so it is not sent to the server.\n */\nexport function HashRouter({\n basename,\n children,\n future,\n window,\n}: HashRouterProps) {\n let historyRef = React.useRef<HashHistory>();\n if (historyRef.current == null) {\n historyRef.current = createHashHistory({ window, v5Compat: true });\n }\n\n let history = historyRef.current;\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n />\n );\n}\n\nexport interface HistoryRouterProps {\n basename?: string;\n children?: React.ReactNode;\n future?: FutureConfig;\n history: History;\n}\n\n/**\n * A `<Router>` that accepts a pre-instantiated history object. It's important\n * to note that using your own history object is highly discouraged and may add\n * two versions of the history library to your bundles unless you use the same\n * version of the history library that React Router uses internally.\n */\nfunction HistoryRouter({\n basename,\n children,\n future,\n history,\n}: HistoryRouterProps) {\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n />\n );\n}\n\nif (__DEV__) {\n HistoryRouter.displayName = \"unstable_HistoryRouter\";\n}\n\nexport { HistoryRouter as unstable_HistoryRouter };\n\nexport interface LinkProps\n extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> {\n reloadDocument?: boolean;\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n to: To;\n unstable_viewTransition?: boolean;\n}\n\nconst isBrowser =\n typeof window !== \"undefined\" &&\n typeof window.document !== \"undefined\" &&\n typeof window.document.createElement !== \"undefined\";\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\n/**\n * The public API for rendering a history-aware `<a>`.\n */\nexport const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(\n function LinkWithRef(\n {\n onClick,\n relative,\n reloadDocument,\n replace,\n state,\n target,\n to,\n preventScrollReset,\n unstable_viewTransition,\n ...rest\n },\n ref\n ) {\n let { basename } = React.useContext(NavigationContext);\n\n // Rendered into <a href> for absolute URLs\n let absoluteHref;\n let isExternal = false;\n\n if (typeof to === \"string\" && ABSOLUTE_URL_REGEX.test(to)) {\n // Render the absolute href server- and client-side\n absoluteHref = to;\n\n // Only check for external origins client-side\n if (isBrowser) {\n try {\n let currentUrl = new URL(window.location.href);\n let targetUrl = to.startsWith(\"//\")\n ? new URL(currentUrl.protocol + to)\n : new URL(to);\n let path = stripBasename(targetUrl.pathname, basename);\n\n if (targetUrl.origin === currentUrl.origin && path != null) {\n // Strip the protocol/origin/basename for same-origin absolute URLs\n to = path + targetUrl.search + targetUrl.hash;\n } else {\n isExternal = true;\n }\n } catch (e) {\n // We can't do external URL detection without a valid URL\n warning(\n false,\n `<Link to=\"${to}\"> contains an invalid URL which will probably break ` +\n `when clicked - please update to a valid URL path.`\n );\n }\n }\n }\n\n // Rendered into <a href> for relative URLs\n let href = useHref(to, { relative });\n\n let internalOnClick = useLinkClickHandler(to, {\n replace,\n state,\n target,\n preventScrollReset,\n relative,\n unstable_viewTransition,\n });\n function handleClick(\n event: React.MouseEvent<HTMLAnchorElement, MouseEvent>\n ) {\n if (onClick) onClick(event);\n if (!event.defaultPrevented) {\n internalOnClick(event);\n }\n }\n\n return (\n // eslint-disable-next-line jsx-a11y/anchor-has-content\n <a\n {...rest}\n href={absoluteHref || href}\n onClick={isExternal || reloadDocument ? onClick : handleClick}\n ref={ref}\n target={target}\n />\n );\n }\n);\n\nif (__DEV__) {\n Link.displayName = \"Link\";\n}\n\ntype NavLinkRenderProps = {\n isActive: boolean;\n isPending: boolean;\n isTransitioning: boolean;\n};\n\nexport interface NavLinkProps\n extends Omit<LinkProps, \"className\" | \"style\" | \"children\"> {\n children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode);\n caseSensitive?: boolean;\n className?: string | ((props: NavLinkRenderProps) => string | undefined);\n end?: boolean;\n style?:\n | React.CSSProperties\n | ((props: NavLinkRenderProps) => React.CSSProperties | undefined);\n}\n\n/**\n * A `<Link>` wrapper that knows if it's \"active\" or not.\n */\nexport const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(\n function NavLinkWithRef(\n {\n \"aria-current\": ariaCurrentProp = \"page\",\n caseSensitive = false,\n className: classNameProp = \"\",\n end = false,\n style: styleProp,\n to,\n unstable_viewTransition,\n children,\n ...rest\n },\n ref\n ) {\n let path = useResolvedPath(to, { relative: rest.relative });\n let location = useLocation();\n let routerState = React.useContext(DataRouterStateContext);\n let { navigator } = React.useContext(NavigationContext);\n let isTransitioning =\n routerState != null &&\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useViewTransitionState(path) &&\n unstable_viewTransition === true;\n\n let toPathname = navigator.encodeLocation\n ? navigator.encodeLocation(path).pathname\n : path.pathname;\n let locationPathname = location.pathname;\n let nextLocationPathname =\n routerState && routerState.navigation && routerState.navigation.location\n ? routerState.navigation.location.pathname\n : null;\n\n if (!caseSensitive) {\n locationPathname = locationPathname.toLowerCase();\n nextLocationPathname = nextLocationPathname\n ? nextLocationPathname.toLowerCase()\n : null;\n toPathname = toPathname.toLowerCase();\n }\n\n // If the `to` has a trailing slash, look at that exact spot. Otherwise,\n // we're looking for a slash _after_ what's in `to`. For example:\n //\n // <NavLink to=\"/users\"> and <NavLink to=\"/users/\">\n // both want to look for a / at index 6 to match URL `/users/matt`\n const endSlashPosition =\n toPathname !== \"/\" && toPathname.endsWith(\"/\")\n ? toPathname.length - 1\n : toPathname.length;\n let isActive =\n locationPathname === toPathname ||\n (!end &&\n locationPathname.startsWith(toPathname) &&\n locationPathname.charAt(endSlashPosition) === \"/\");\n\n let isPending =\n nextLocationPathname != null &&\n (nextLocationPathname === toPathname ||\n (!end &&\n nextLocationPathname.startsWith(toPathname) &&\n nextLocationPathname.charAt(toPathname.length) === \"/\"));\n\n let renderProps = {\n isActive,\n isPending,\n isTransitioning,\n };\n\n let ariaCurrent = isActive ? ariaCurrentProp : undefined;\n\n let className: string | undefined;\n if (typeof classNameProp === \"function\") {\n className = classNameProp(renderProps);\n } else {\n // If the className prop is not a function, we use a default `active`\n // class for <NavLink />s that are active. In v5 `active` was the default\n // value for `activeClassName`, but we are removing that API and can still\n // use the old default behavior for a cleaner upgrade path and keep the\n // simple styling rules working as they currently do.\n className = [\n classNameProp,\n isActive ? \"active\" : null,\n isPending ? \"pending\" : null,\n isTransitioning ? \"transitioning\" : null,\n ]\n .filter(Boolean)\n .join(\" \");\n }\n\n let style =\n typeof styleProp === \"function\" ? styleProp(renderProps) : styleProp;\n\n return (\n <Link\n {...rest}\n aria-current={ariaCurrent}\n className={className}\n ref={ref}\n style={style}\n to={to}\n unstable_viewTransition={unstable_viewTransition}\n >\n {typeof children === \"function\" ? children(renderProps) : children}\n </Link>\n );\n }\n);\n\nif (__DEV__) {\n NavLink.displayName = \"NavLink\";\n}\n\nexport interface FetcherFormProps\n extends React.FormHTMLAttributes<HTMLFormElement> {\n /**\n * The HTTP verb to use when the form is submit. Supports \"get\", \"post\",\n * \"put\", \"delete\", \"patch\".\n */\n method?: HTMLFormMethod;\n\n /**\n * `<form encType>` - enhancing beyond the normal string type and limiting\n * to the built-in browser supported values\n */\n encType?:\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"text/plain\";\n\n /**\n * Normal `<form action>` but supports React Router's relative paths.\n */\n action?: string;\n\n /**\n * Determines whether the form action is relative to the route hierarchy or\n * the pathname. Use this if you want to opt out of navigating the route\n * hierarchy and want to instead route based on /-delimited URL segments\n */\n relative?: RelativeRoutingType;\n\n /**\n * Prevent the scroll position from resetting to the top of the viewport on\n * completion of the navigation when using the <ScrollRestoration> component\n */\n preventScrollReset?: boolean;\n\n /**\n * A function to call when the form is submitted. If you call\n * `event.preventDefault()` then this form will not do anything.\n */\n onSubmit?: React.FormEventHandler<HTMLFormElement>;\n}\n\nexport interface FormProps extends FetcherFormProps {\n /**\n * Indicate a specific fetcherKey to use when using navigate=false\n */\n fetcherKey?: string;\n\n /**\n * navigate=false will use a fetcher instead of a navigation\n */\n navigate?: boolean;\n\n /**\n * Forces a full document navigation instead of a fetch.\n */\n reloadDocument?: boolean;\n\n /**\n * Replaces the current entry in the browser history stack when the form\n * navigates. Use this if you don't want the user to be able to click \"back\"\n * to the page with the form on it.\n */\n replace?: boolean;\n\n /**\n * State object to add to the history stack entry for this navigation\n */\n state?: any;\n\n /**\n * Enable view transitions on this Form navigation\n */\n unstable_viewTransition?: boolean;\n}\n\ntype HTMLSubmitEvent = React.BaseSyntheticEvent<\n SubmitEvent,\n Event,\n HTMLFormElement\n>;\n\ntype HTMLFormSubmitter = HTMLButtonElement | HTMLInputElement;\n\n/**\n * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except\n * that the interaction with the server is with `fetch` instead of new document\n * requests, allowing components to add nicer UX to the page as the form is\n * submitted and returns with data.\n */\nexport const Form = React.forwardRef<HTMLFormElement, FormProps>(\n (\n {\n fetcherKey,\n navigate,\n reloadDocument,\n replace,\n state,\n method = defaultMethod,\n action,\n onSubmit,\n relative,\n preventScrollReset,\n unstable_viewTransition,\n ...props\n },\n forwardedRef\n ) => {\n let submit = useSubmit();\n let formAction = useFormAction(action, { relative });\n let formMethod: HTMLFormMethod =\n method.toLowerCase() === \"get\" ? \"get\" : \"post\";\n\n let submitHandler: React.FormEventHandler<HTMLFormElement> = (event) => {\n onSubmit && onSubmit(event);\n if (event.defaultPrevented) return;\n event.preventDefault();\n\n let submitter = (event as unknown as HTMLSubmitEvent).nativeEvent\n .submitter as HTMLFormSubmitter | null;\n\n let submitMethod =\n (submitter?.getAttribute(\"formmethod\") as HTMLFormMethod | undefined) ||\n method;\n\n submit(submitter || event.currentTarget, {\n fetcherKey,\n method: submitMethod,\n navigate,\n replace,\n state,\n relative,\n preventScrollReset,\n unstable_viewTransition,\n });\n };\n\n return (\n <form\n ref={forwardedRef}\n method={formMethod}\n action={formAction}\n onSubmit={reloadDocument ? onSubmit : submitHandler}\n {...props}\n />\n );\n }\n);\n\nif (__DEV__) {\n Form.displayName = \"Form\";\n}\n\nexport interface ScrollRestorationProps {\n getKey?: GetScrollRestorationKeyFunction;\n storageKey?: string;\n}\n\n/**\n * This component will emulate the browser's scroll restoration on location\n * changes.\n */\nexport function ScrollRestoration({\n getKey,\n storageKey,\n}: ScrollRestorationProps) {\n useScrollRestoration({ getKey, storageKey });\n return null;\n}\n\nif (__DEV__) {\n ScrollRestoration.displayName = \"ScrollRestoration\";\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hooks\n////////////////////////////////////////////////////////////////////////////////\n\nenum DataRouterHook {\n UseScrollRestoration = \"useScrollRestoration\",\n UseSubmit = \"useSubmit\",\n UseSubmitFetcher = \"useSubmitFetcher\",\n UseFetcher = \"useFetcher\",\n useViewTransitionState = \"useViewTransitionState\",\n}\n\nenum DataRouterStateHook {\n UseFetcher = \"useFetcher\",\n UseFetchers = \"useFetchers\",\n UseScrollRestoration = \"useScrollRestoration\",\n}\n\n// Internal hooks\n\nfunction getDataRouterConsoleError(\n hookName: DataRouterHook | DataRouterStateHook\n) {\n return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n let ctx = React.useContext(DataRouterContext);\n invariant(ctx, getDataRouterConsoleError(hookName));\n return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n let state = React.useContext(DataRouterStateContext);\n invariant(state, getDataRouterConsoleError(hookName));\n return state;\n}\n\n// External hooks\n\n/**\n * Handles the click behavior for router `<Link>` components. This is useful if\n * you need to create custom `<Link>` components with the same click behavior we\n * use in our exported `<Link>`.\n */\nexport function useLinkClickHandler<E extends Element = HTMLAnchorElement>(\n to: To,\n {\n target,\n replace: replaceProp,\n state,\n preventScrollReset,\n relative,\n unstable_viewTransition,\n }: {\n target?: React.HTMLAttributeAnchorTarget;\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_viewTransition?: boolean;\n } = {}\n): (event: React.MouseEvent<E, MouseEvent>) => void {\n let navigate = useNavigate();\n let location = useLocation();\n let path = useResolvedPath(to, { relative });\n\n return React.useCallback(\n (event: React.MouseEvent<E, MouseEvent>) => {\n if (shouldProcessLinkClick(event, target)) {\n event.preventDefault();\n\n // If the URL hasn't changed, a regular <a> will do a replace instead of\n // a push, so do the same here unless the replace prop is explicitly set\n let replace =\n replaceProp !== undefined\n ? replaceProp\n : createPath(location) === createPath(path);\n\n navigate(to, {\n replace,\n state,\n preventScrollReset,\n relative,\n unstable_viewTransition,\n });\n }\n },\n [\n location,\n navigate,\n path,\n replaceProp,\n state,\n target,\n to,\n preventScrollReset,\n relative,\n unstable_viewTransition,\n ]\n );\n}\n\n/**\n * A convenient wrapper for reading and writing search parameters via the\n * URLSearchParams interface.\n */\nexport function useSearchParams(\n defaultInit?: URLSearchParamsInit\n): [URLSearchParams, SetURLSearchParams] {\n warning(\n typeof URLSearchParams !== \"undefined\",\n `You cannot use the \\`useSearchParams\\` hook in a browser that does not ` +\n `support the URLSearchParams API. If you need to support Internet ` +\n `Explorer 11, we recommend you load a polyfill such as ` +\n `https://github.com/ungap/url-search-params\\n\\n` +\n `If you're unsure how to load polyfills, we recommend you check out ` +\n `https://polyfill.io/v3/ which provides some recommendations about how ` +\n `to load polyfills only for users that need them, instead of for every ` +\n `user.`\n );\n\n let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));\n let hasSetSearchParamsRef = React.useRef(false);\n\n let location = useLocation();\n let searchParams = React.useMemo(\n () =>\n // Only merge in the defaults if we haven't yet called setSearchParams.\n // Once we call that we want those to take precedence, otherwise you can't\n // remove a param with setSearchParams({}) if it has an initial value\n getSearchParamsForLocation(\n location.search,\n hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current\n ),\n [location.search]\n );\n\n let navigate = useNavigate();\n let setSearchParams = React.useCallback<SetURLSearchParams>(\n (nextInit, navigateOptions) => {\n const newSearchParams = createSearchParams(\n typeof nextInit === \"function\" ? nextInit(searchParams) : nextInit\n );\n hasSetSearchParamsRef.current = true;\n navigate(\"?\" + newSearchParams, navigateOptions);\n },\n [navigate, searchParams]\n );\n\n return [searchParams, setSearchParams];\n}\n\nexport type SetURLSearchParams = (\n nextInit?:\n | URLSearchParamsInit\n | ((prev: URLSearchParams) => URLSearchParamsInit),\n navigateOpts?: NavigateOptions\n) => void;\n\n/**\n * Submits a HTML `<form>` to the server without reloading the page.\n */\nexport interface SubmitFunction {\n (\n /**\n * Specifies the `<form>` to be submitted to the server, a specific\n * `<button>` or `<input type=\"submit\">` to use to submit the form, or some\n * arbitrary data to submit.\n *\n * Note: When using a `<button>` its `name` and `value` will also be\n * included in the form data that is submitted.\n */\n target: SubmitTarget,\n\n /**\n * Options that override the `<form>`'s own attributes. Required when\n * submitting arbitrary data without a backing `<form>`.\n */\n options?: SubmitOptions\n ): void;\n}\n\n/**\n * Submits a fetcher `<form>` to the server without reloading the page.\n */\nexport interface FetcherSubmitFunction {\n (\n target: SubmitTarget,\n // Fetchers cannot replace or set state because they are not navigation events\n options?: Omit<SubmitOptions, \"replace\" | \"state\">\n ): void;\n}\n\nfunction validateClientSideSubmission() {\n if (typeof document === \"undefined\") {\n throw new Error(\n \"You are calling submit during the server render. \" +\n \"Try calling submit within a `useEffect` or callback instead.\"\n );\n }\n}\n\nlet fetcherId = 0;\nlet getUniqueFetcherId = () => `__${String(++fetcherId)}__`;\n\n/**\n * Returns a function that may be used to programmatically submit a form (or\n * some arbitrary data) to the server.\n */\nexport function useSubmit(): SubmitFunction {\n let { router } = useDataRouterContext(DataRouterHook.UseSubmit);\n let { basename } = React.useContext(NavigationContext);\n let currentRouteId = useRouteId();\n\n return React.useCallback<SubmitFunction>(\n (target, options = {}) => {\n validateClientSideSubmission();\n\n let { action, method, encType, formData, body } = getFormSubmissionInfo(\n target,\n basename\n );\n\n if (options.navigate === false) {\n let key = options.fetcherKey || getUniqueFetcherId();\n router.fetch(key, currentRouteId, options.action || action, {\n preventScrollReset: options.preventScrollReset,\n formData,\n body,\n formMethod: options.method || (method as HTMLFormMethod),\n formEncType: options.encType || (encType as FormEncType),\n unstable_flushSync: options.unstable_flushSync,\n });\n } else {\n router.navigate(options.action || action, {\n preventScrollReset: options.preventScrollReset,\n formData,\n body,\n formMethod: options.method || (method as HTMLFormMethod),\n formEncType: options.encType || (encType as FormEncType),\n replace: options.replace,\n state: options.state,\n fromRouteId: currentRouteId,\n unstable_flushSync: options.unstable_flushSync,\n unstable_viewTransition: options.unstable_viewTransition,\n });\n }\n },\n [router, basename, currentRouteId]\n );\n}\n\n// v7: Eventually we should deprecate this entirely in favor of using the\n// router method directly?\nexport function useFormAction(\n action?: string,\n { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n let { basename } = React.useContext(NavigationContext);\n let routeContext = React.useContext(RouteContext);\n invariant(routeContext, \"useFormAction must be used inside a RouteContext\");\n\n let [match] = routeContext.matches.slice(-1);\n // Shallow clone path so we can modify it below, otherwise we modify the\n // object referenced by useMemo inside useResolvedPath\n let path = { ...useResolvedPath(action ? action : \".\", { relative }) };\n\n // If no action was specified, browsers will persist current search params\n // when determining the path, so match that behavior\n // https://github.com/remix-run/remix/issues/927\n let location = useLocation();\n if (action == null) {\n // Safe to write to this directly here since if action was undefined, we\n // would have called useResolvedPath(\".\") which will never include a search\n path.search = location.search;\n\n // When grabbing search params from the URL, remove any included ?index param\n // since it might not apply to our contextual route. We add it back based\n // on match.route.index below\n let params = new URLSearchParams(path.search);\n if (params.has(\"index\") && params.get(\"index\") === \"\") {\n params.delete(\"index\");\n path.search = params.toString() ? `?${params.toString()}` : \"\";\n }\n }\n\n if ((!action || action === \".\") && match.route.index) {\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n }\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the form action. If this is a root navigation, then just use\n // the raw basename which allows the basename to have full control over the\n // presence of a trailing slash on root actions\n if (basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\nexport type FetcherWithComponents<TData> = Fetcher<TData> & {\n Form: React.ForwardRefExoticComponent<\n FetcherFormProps & React.RefAttributes<HTMLFormElement>\n >;\n submit: FetcherSubmitFunction;\n load: (href: string, opts?: { unstable_flushSync?: boolean }) => void;\n};\n\n// TODO: (v7) Change the useFetcher generic default from `any` to `unknown`\n\n/**\n * Interacts with route loaders and actions without causing a navigation. Great\n * for any interaction that stays on the same page.\n */\nexport function useFetcher<TData = any>({\n key,\n}: { key?: string } = {}): FetcherWithComponents<TData> {\n let { router } = useDataRouterContext(DataRouterHook.UseFetcher);\n let state = useDataRouterState(DataRouterStateHook.UseFetcher);\n let fetcherData = React.useContext(FetchersContext);\n let route = React.useContext(RouteContext);\n let routeId = route.matches[route.matches.length - 1]?.route.id;\n\n invariant(fetcherData, `useFetcher must be used inside a FetchersContext`);\n invariant(route, `useFetcher must be used inside a RouteContext`);\n invariant(\n routeId != null,\n `useFetcher can only be used on routes that contain a unique \"id\"`\n );\n\n // Fetcher key handling\n let [fetcherKey, setFetcherKey] = React.useState<string>(key || \"\");\n if (key && key !== fetcherKey) {\n setFetcherKey(key);\n } else if (!fetcherKey) {\n setFetcherKey(getUniqueFetcherId());\n }\n\n // Registration/cleanup\n React.useEffect(() => {\n router.getFetcher(fetcherKey);\n return () => {\n // Tell the router we've unmounted - if v7_fetcherPersist is enabled this\n // will not delete immediately but instead queue up a delete after the\n // fetcher returns to an `idle` state\n router.deleteFetcher(fetcherKey);\n };\n }, [router, fetcherKey]);\n\n // Fetcher additions\n let load = React.useCallback(\n (href: string, opts?: { unstable_flushSync?: boolean }) => {\n invariant(routeId, \"No routeId available for fetcher.load()\");\n router.fetch(fetcherKey, routeId, href, opts);\n },\n [fetcherKey, routeId, router]\n );\n\n let submitImpl = useSubmit();\n let submit = React.useCallback<FetcherSubmitFunction>(\n (target, opts) => {\n submitImpl(target, {\n ...opts,\n navigate: false,\n fetcherKey,\n });\n },\n [fetcherKey, submitImpl]\n );\n\n let FetcherForm = React.useMemo(() => {\n let FetcherForm = React.forwardRef<HTMLFormElement, FetcherFormProps>(\n (props, ref) => {\n return (\n <Form {...props} navigate={false} fetcherKey={fetcherKey} ref={ref} />\n );\n }\n );\n if (__DEV__) {\n FetcherForm.displayName = \"fetcher.Form\";\n }\n return FetcherForm;\n }, [fetcherKey]);\n\n // Exposed FetcherWithComponents\n let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;\n let data = fetcherData.get(fetcherKey);\n let fetcherWithComponents = React.useMemo(\n () => ({\n Form: FetcherForm,\n submit,\n load,\n ...fetcher,\n data,\n }),\n [FetcherForm, submit, load, fetcher, data]\n );\n\n return fetcherWithComponents;\n}\n\n/**\n * Provides all fetchers currently on the page. Useful for layouts and parent\n * routes that need to provide pending/optimistic UI regarding the fetch.\n */\nexport function useFetchers(): (Fetcher & { key: string })[] {\n let state = useDataRouterState(DataRouterStateHook.UseFetchers);\n return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({\n ...fetcher,\n key,\n }));\n}\n\nconst SCROLL_RESTORATION_STORAGE_KEY = \"react-router-scroll-positions\";\nlet savedScrollPositions: Record<string, number> = {};\n\n/**\n * When rendered inside a RouterProvider, will restore scroll positions on navigations\n */\nfunction useScrollRestoration({\n getKey,\n storageKey,\n}: {\n getKey?: GetScrollRestorationKeyFunction;\n storageKey?: string;\n} = {}) {\n let { router } = useDataRouterContext(DataRouterHook.UseScrollRestoration);\n let { restoreScrollPosition, preventScrollReset } = useDataRouterState(\n DataRouterStateHook.UseScrollRestoration\n );\n let { basename } = React.useContext(NavigationContext);\n let location = useLocation();\n let matches = useMatches();\n let navigation = useNavigation();\n\n // Trigger manual scroll restoration while we're active\n React.useEffect(() => {\n window.history.scrollRestoration = \"manual\";\n return () => {\n window.history.scrollRestoration = \"auto\";\n };\n }, []);\n\n // Save positions on pagehide\n usePageHide(\n React.useCallback(() => {\n if (navigation.state === \"idle\") {\n let key = (getKey ? getKey(location, matches) : null) || location.key;\n savedScrollPositions[key] = window.scrollY;\n }\n try {\n sessionStorage.setItem(\n storageKey || SCROLL_RESTORATION_STORAGE_KEY,\n JSON.stringify(savedScrollPositions)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`\n );\n }\n window.history.scrollRestoration = \"auto\";\n }, [storageKey, getKey, navigation.state, location, matches])\n );\n\n // Read in any saved scroll locations\n if (typeof document !== \"undefined\") {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(() => {\n try {\n let sessionPositions = sessionStorage.getItem(\n storageKey || SCROLL_RESTORATION_STORAGE_KEY\n );\n if (sessionPositions) {\n savedScrollPositions = JSON.parse(sessionPositions);\n }\n } catch (e) {\n // no-op, use default empty object\n }\n }, [storageKey]);\n\n // Enable scroll restoration in the router\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(() => {\n let getKeyWithoutBasename: GetScrollRestorationKeyFunction | undefined =\n getKey && basename !== \"/\"\n ? (location, matches) =>\n getKey(\n // Strip the basename to match useLocation()\n {\n ...location,\n pathname:\n stripBasename(location.pathname, basename) ||\n location.pathname,\n },\n matches\n )\n : getKey;\n let disableScrollRestoration = router?.enableScrollRestoration(\n savedScrollPositions,\n () => window.scrollY,\n getKeyWithoutBasename\n );\n return () => disableScrollRestoration && disableScrollRestoration();\n }, [router, basename, getKey]);\n\n // Restore scrolling when state.restoreScrollPosition changes\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(() => {\n // Explicit false means don't do anything (used for submissions)\n if (restoreScrollPosition === false) {\n return;\n }\n\n // been here before, scroll to it\n if (typeof restoreScrollPosition === \"number\") {\n window.scrollTo(0, restoreScrollPosition);\n return;\n }\n\n // try to scroll to the hash\n if (location.hash) {\n let el = document.getElementById(\n decodeURIComponent(location.hash.slice(1))\n );\n if (el) {\n el.scrollIntoView();\n return;\n }\n }\n\n // Don't reset if this navigation opted out\n if (preventScrollReset === true) {\n return;\n }\n\n // otherwise go to the top on new locations\n window.scrollTo(0, 0);\n }, [location, restoreScrollPosition, preventScrollReset]);\n }\n}\n\nexport { useScrollRestoration as UNSAFE_useScrollRestoration };\n\n/**\n * Setup a callback to be fired on the window's `beforeunload` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nexport function useBeforeUnload(\n callback: (event: BeforeUnloadEvent) => any,\n options?: { capture?: boolean }\n): void {\n let { capture } = options || {};\n React.useEffect(() => {\n let opts = capture != null ? { capture } : undefined;\n window.addEventListener(\"beforeunload\", callback, opts);\n return () => {\n window.removeEventListener(\"beforeunload\", callback, opts);\n };\n }, [callback, capture]);\n}\n\n/**\n * Setup a callback to be fired on the window's `pagehide` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes. This event is better supported than beforeunload across browsers.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nfunction usePageHide(\n callback: (event: PageTransitionEvent) => any,\n options?: { capture?: boolean }\n): void {\n let { capture } = options || {};\n React.useEffect(() => {\n let opts = capture != null ? { capture } : undefined;\n window.addEventListener(\"pagehide\", callback, opts);\n return () => {\n window.removeEventListener(\"pagehide\", callback, opts);\n };\n }, [callback, capture]);\n}\n\n/**\n * Wrapper around useBlocker to show a window.confirm prompt to users instead\n * of building a custom UI with useBlocker.\n *\n * Warning: This has *a lot of rough edges* and behaves very differently (and\n * very incorrectly in some cases) across browsers if user click addition\n * back/forward navigations while the confirm is open. Use at your own risk.\n */\nfunction usePrompt({\n when,\n message,\n}: {\n when: boolean | BlockerFunction;\n message: string;\n}) {\n let blocker = useBlocker(when);\n\n React.useEffect(() => {\n if (blocker.state === \"blocked\") {\n let proceed = window.confirm(message);\n if (proceed) {\n // This timeout is needed to avoid a weird \"race\" on POP navigations\n // between the `window.history` revert navigation and the result of\n // `window.confirm`\n setTimeout(blocker.proceed, 0);\n } else {\n blocker.reset();\n }\n }\n }, [blocker, message]);\n\n React.useEffect(() => {\n if (blocker.state === \"blocked\" && !when) {\n blocker.reset();\n }\n }, [blocker, when]);\n}\n\nexport { usePrompt as unstable_usePrompt };\n\n/**\n * Return a boolean indicating if there is an active view transition to the\n * given href. You can use this value to render CSS classes or viewTransitionName\n * styles onto your elements\n *\n * @param href The destination href\n * @param [opts.relative] Relative routing type (\"route\" | \"path\")\n */\nfunction useViewTransitionState(\n to: To,\n opts: { relative?: RelativeRoutingType } = {}\n) {\n let vtContext = React.useContext(ViewTransitionContext);\n\n invariant(\n vtContext != null,\n \"`unstable_useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. \" +\n \"Did you accidentally import `RouterProvider` from `react-router`?\"\n );\n\n let { basename } = useDataRouterContext(\n DataRouterHook.useViewTransitionState\n );\n let path = useResolvedPath(to, { relative: opts.relative });\n if (!vtContext.isTransitioning) {\n return false;\n }\n\n let currentPath =\n stripBasename(vtContext.currentLocation.pathname, basename) ||\n vtContext.currentLocation.pathname;\n let nextPath =\n stripBasename(vtContext.nextLocation.pathname, basename) ||\n vtContext.nextLocation.pathname;\n\n // Transition is active if we're going to or coming from the indicated\n // destination. This ensures that other PUSH navigations that reverse\n // an indicated transition apply. I.e., on the list view you have:\n //\n // <NavLink to=\"/details/1\" unstable_viewTransition>\n //\n // If you click the breadcrumb back to the list view:\n //\n // <NavLink to=\"/list\" unstable_viewTransition>\n //\n // We should apply the transition because it's indicated as active going\n // from /list -> /details/1 and therefore should be active on the reverse\n // (even though this isn't strictly a POP reverse)\n return (\n matchPath(path.pathname, nextPath) != null ||\n matchPath(path.pathname, currentPath) != null\n );\n}\n\nexport { useViewTransitionState as unstable_useViewTransitionState };\n\n//#endregion\n","import { Link, useLocation} from \"react-router-dom\";\n\n\n\nconst Header = () => {\n const location = useLocation();\n\n return(\n <div className=\"header\">\n <div className=\"x1\">\n <div className=\"logo\"><Link className=\"Link\" to=\"Friendly-Betting/\">logo</Link>\n \n </div>\n </div>\n <div className=\"x1\">Friendly Bets</div>\n <div className=\"flex pages x1\">\n {location.pathname !== \"/SignIn\" ? <Link className=\"Link\" to=\"Friendly-Betting/SignIn\">Sign In</Link>: <Link className=\"Link\" to=\"/\">Sign In</Link>\n \n \n \n }\n <Link className=\"Link\" to=\"Friendly-Betting/Bet\">Bets</Link>\n <Link className=\"Link\" to=\"Friendly-Betting/Friends\">Friends</Link>\n </div>\n </div>\n )\n}\n\nexport default Header;","import React from 'react';\n\nconst NotFound = () => {\n return (\n <div>\n <h1>404</h1>\n <p>Page not found!</p>\n </div>\n );\n};\n\nexport default NotFound;","import React from 'react';\nimport { useState, useEffect } from 'react'; \nimport { auth } from \"../Config/firebase-config\";\nimport { Link } from \"react-router-dom\";\n\n\n\nconst Welcome = () => {\n\n const [signedIn, setSignedIn] = useState(true);\n\n console.log(auth?.currentUser?.email)\n\n useEffect(() => {\n isAuthenticated();\n }, []);\n\n const isAuthenticated = () => {\n const currentUserEmail = auth?.currentUser?.email;\n const isAuthenticated = currentUserEmail !== undefined;\n setSignedIn(isAuthenticated);\n };\n\n return (\n <div className='pad'>\n {signedIn ? (\n <div>\n \n {/* Render the authenticated content */}\n <h1>Welcome, User!</h1>\n <p>This is the authenticated content.</p>\n </div>\n ) : (\n <div>\n {/* Render the non-authenticated content */}\n <h1>Please sign in to access this content.</h1>\n <Link className=\"Link\" to=\"Friendly-Betting/SignIn\">Sign In</Link>\n </div>\n )}\n </div>\n );\n};\n\nexport default Welcome;","// extracted by mini-css-extract-plugin\nexport default {\"MoneyLine\":\"MoneyLine_MoneyLine__GZY-g\",\"betContainer\":\"MoneyLine_betContainer__MPUkR\",\"bet\":\"MoneyLine_bet__iBwWG\",\"contestant\":\"MoneyLine_contestant__VUCuJ\",\"contestantInput\":\"MoneyLine_contestantInput__RtHW6\",\"label\":\"MoneyLine_label__SXs1d\",\"odds\":\"MoneyLine_odds__5UKBZ\",\"ViewLabel\":\"MoneyLine_ViewLabel__dee3p\",\"betLabel\":\"MoneyLine_betLabel__xK-Pn\"};","// extracted by mini-css-extract-plugin\nexport default {\"disable\":\"Players_disable__2Lrxc\",\"friends\":\"Players_friends__S-rHI\",\"addFiendForm\":\"Players_addFiendForm__No56b\",\"x\":\"Players_x__50IpE\",\"or\":\"Players_or__vxIC5\",\"shareBet\":\"Players_shareBet__IEGN8\",\"friendsLabel\":\"Players_friendsLabel__doMbx\",\"container\":\"Players_container__wuYC4\",\"checkmark\":\"Players_checkmark__OI0Ce\"};","\nimport React, { useState } from 'react';\nimport css from \"./Players.module.css\";\n\nconst AddFriend = (props) => {\n const [accountNumber, setAccountNumber] = useState('');\n const [phone, setPhone] = useState('');\n const [email, setEmail] = useState('');\n const [name, setName] = useState('');\n\n const handleAccountNumberChange = (e) => {\n setAccountNumber(e.target.value);\n };\n\n const handlePhoneChange = (e) => {\n setPhone(e.target.value);\n };\n\n const handleEmailChange = (e) => {\n setEmail(e.target.value);\n };\n\n const handleNameChange = (e) => {\n setName(e.target.value);\n };\n\n const handleSubmit = (e) => {\n e.preventDefault();\n if(name !== \"\" && email !== \"\" && phone !== \"\"){\n props.addNewPlayers({\n \"name\": name,\n \"email\": email,\n \"phone\": phone\n })\n }\n // Handle form submission here\n // You can access the values using the state variables (accountNumber, phone, email, name)\n };\n\n\n return (\n <form className={css.addFiendForm} onSubmit={handleSubmit}>\n <div className={css.x}><span onClick={props.disable}>x</span></div>\n <label>\n <span>Account Number:</span>\n <input type=\"text\" value={accountNumber} onChange={handleAccountNumberChange} />\n </label>\n <br />\n <br />\n <div className={css.or}>or</div>\n <br />\n <label>\n <span>Name:</span>\n <input type=\"text\" value={name} onChange={handleNameChange} />\n </label>\n <br />\n <label>\n Email:\n <input type=\"email\" value={email} onChange={handleEmailChange} />\n </label>\n <br />\n <label>\n <span>Phone:</span>\n <input type=\"phone\" value={phone} onChange={handlePhoneChange} />\n </label>\n <br />\n <button type=\"submit\" >Add Friend</button>\n </form>\n );\n};\n\nexport default AddFriend;\n","import AddFriend from \"./AddFriend\"\nimport React, { useState } from 'react';\nimport css from \"./Players.module.css\";\n\n\nconst Players = () => {\n\n const [json,setJson] = useState({\n \"friends\": [\n \n {\n \n \n \"name\": \"John\",\n \"email\": \"johnRyan@gmail.com\",\n \"phone\": \"1234567890\"\n \n \n },\n {\n \n \"name\": \"Jack\",\n \"email\": \"JackRyan@gmail.com\",\n \"phone\": \"1234567890\"\n \n \n },\n {\n \n \"name\": \"Another Person\",\n \"email\": \"Person@gmail.com\",\n \"phone\": \"1234567890\"\n \n \n }\n \n ]\n });\n const addJson = (newJson) => {\n setJson(prevJson => ({\n ...prevJson,\n friends: [...prevJson.friends, newJson]\n \n }));\n swapDisplayPlayers();\n \n }\n const [displayPlayers, setDisplayPlayers] = useState(false)\n const swapDisplayPlayers = () => {\n setDisplayPlayers((current) => !current)\n }\n return (\n <div className={css.friends}>\n {json[\"friends\"].map((friend) => (\n <div key={friend.id}>\n <h3>{friend[\"name\"]}</h3>\n <p>Email: {friend[\"email\"]}</p>\n <p>Phone: {friend[\"phone\"]}</p>\n </div>\n ))}\n <div>\n {\n displayPlayers ?\n <div>\n <AddFriend addNewPlayers ={addJson} disable={swapDisplayPlayers}/>\n <button className={css.disable} >Add Friend</button>\n </div>\n :\n <button onClick={swapDisplayPlayers} >Add Friend</button>\n }\n \n </div>\n </div>\n )\n}\n\nexport default Players","import React from 'react';\nimport css from './Players.module.css';\nimport {useState} from 'react';\n\n\n\n\nconst ShareBet = (props) => {\n\n const [json,setJson] = useState({\n \"friends\": [\n \n {\n \n \n \"name\": \"John\",\n \"email\": \"johnRyan@gmail.com\",\n \"phone\": \"1234567890\"\n \n \n },\n {\n \n \"name\": \"Jack\",\n \"email\": \"JackRyan@gmail.com\",\n \"phone\": \"1234567890\"\n \n \n },\n {\n \n \"name\": \"Another Person\",\n \"email\": \"Person@gmail.com\",\n \"phone\": \"1234567890\"\n \n \n }\n \n ]\n });\n\n \n\n const handleSubmit = (e) => {\n e.preventDefault();\n // Logic to share the bet\n console.log('Sharing bet');\n }\n\n \n return (\n <div className={css.shareBet}>\n <div className={css.x}><span onClick={props.display}>x</span></div>\n <div className={css.friendsLabel}><span>friends</span></div>\n <form onSubmit={handleSubmit}>\n {//props.friends.map((friend ) => (\n json[\"friends\"].map((friend) => (\n <label className={css.container}>\n {friend.name}\n <input className={css.input} type=\"checkbox\" name=\"\" id=\"\" />\n <span className={css.checkmark}></span>\n \n </label>\n ))}\n <button type=\"submit\">Send</button>\n </form>\n </div>\n \n );\n};\n\nexport default ShareBet;\n","import React, { useState } from 'react';\nimport css from './MoneyLine.module.css';\nimport Players from '../Players/Players';\nimport ShareBet from '../Players/ShareBet';\nimport {db} from '../../../Config/firebase-config';\nimport { addDoc, collection } from 'firebase/firestore';\n\nconst CreateMoneyLine = () => {\n const [bet, setBet] = useState('');\n const [contestant1, setContestant1] = useState('');\n const [contestant2, setContestant2] = useState('');\n\n \n const [odds1, setOdds1] = useState(0);\n const [odds2, setOdds2] = useState(0);\n\n\n\n\n const [shareDisplay, setShareDisplay] = useState(false);\n\n \n\n\n\n const handleShare = () => {\n setShareDisplay((current) => !current);\n }\n\n const handleSubmit = async (e) => {\n e.preventDefault();\n handleShare();\n try {\n await addDoc(collection(db, \"bets\"), {\n type: \"Money Line\",\n bet: bet,\n })\n \n await addDoc(collection(db, \"MoneyLineBets\"), {\n bet: bet,\n contestant1: contestant1,\n contestant1Odds: odds1,\n contestant2: contestant2,\n contestant2Odds: odds2,\n })\n } catch (e) {\n console.error(e);\n }\n // Logic to create the moneyline bet using the team and odds values\n console.log('Creating moneyline bet:');\n };\n\n return (\n <div className='flex'>\n <div className='x2'>\n <form className={css.MoneyLine} onSubmit={handleSubmit}>\n <div className={css.betContainer}>\n Bet:\n <div className={css.bet}>\n <textarea type=\"text\" name=\"\" id=\"\" onChange={(e) => setBet(e.target.value)} />\n </div>\n </div>\n <div className='flex'>\n <div className={css.contestant}>\n <div><span className={css.label}>Contestant 1</span></div>\n <input\n type=\"text\"\n name=\"\"\n value={contestant1}\n className={css.contestantInput}\n onChange={(e) => setContestant1(e.target.value)}\n \n />\n <div className={css.odds}>\n <span>(+ or - odds)</span>\n <input type=\"number\" onChange={(e) => setOdds1(Number(e.target.value))}/>\n </div>\n </div>\n <div className={css.contestant}>\n <div><span className={css.label}>Contestant 2</span></div>\n <input \n type=\"text\"\n name=\"\"\n value={contestant2}\n className={css.contestantInput}\n onChange={(e) => setContestant2(e.target.value)}\n \n /> \n <div className={css.odds}>\n <span>(+ or - odds)</span>\n <input type=\"number\" onChange={(e) => setOdds2(Number(e.target.value))}/>\n </div>\n </div>\n </div>\n \n <button type=\"submit\">Create Bet</button>\n </form>\n </div>\n <div className=\"x1\">\n <Players />\n </div>\n <div>\n {shareDisplay ? <ShareBet display={handleShare} /> : null}\n \n </div>\n </div>\n );\n};\n\nexport default CreateMoneyLine;\n","import React from 'react';\nimport CreateMoneyLine from './CreateMoneyLine';\n\nconst MoneyLine = () => {\n \n\n return (\n <div className='pad'>\n <h1>Money Line Bets</h1>\n <CreateMoneyLine />\n </div>\n );\n};\n\nexport default MoneyLine;\n","// extracted by mini-css-extract-plugin\nexport default {\"OverUnder\":\"OverUnder_OverUnder__lZCyp\",\"betContainer\":\"OverUnder_betContainer__GC+uq\",\"bet\":\"OverUnder_bet__SUjBe\",\"setting\":\"OverUnder_setting__o-g2F\",\"input\":\"OverUnder_input__FR6oC\",\"betLabel\":\"OverUnder_betLabel__fUG2h\",\"lineLabel\":\"OverUnder_lineLabel__uLemh\",\"line\":\"OverUnder_line__xiV+Z\",\"actualLine\":\"OverUnder_actualLine__NevcO\",\"remain\":\"OverUnder_remain__s69rd\",\"section\":\"OverUnder_section__A+HHD\",\"pad\":\"OverUnder_pad__Qx6VE\"};","import React from 'react';\nimport css from './OverUnder.module.css';\nimport Players from '../Players/Players';\nimport ShareBet from '../Players/ShareBet';\nimport {useState} from 'react';\nimport {db} from '../../../Config/firebase-config';\nimport { addDoc, collection } from 'firebase/firestore';\n\nconst CreateOverUnder = () => {\n \n const [bet, setBet] = useState('');\n const [line, setLine] = useState(0);\n\n\n const [shareDisplay, setShareDisplay] = useState(false);\n \n const handleShare = () => {\n setShareDisplay((current) => !current);\n }\n\n const handelSubmit = async (e) => {\n e.preventDefault();\n handleShare();\n try {\n await addDoc(collection(db, \"bets\"), {\n type: \"Over Under\",\n bet: bet,\n })\n \n await addDoc(collection(db, \"OverUnderBets\"), {\n bet: bet,\n line: line,\n })\n } catch (e) {\n console.error(e);\n }\n console.log('Creating over under bet');\n }\n\n return (\n <div className='flex'>\n <div className={css.OverUnder}>\n <form onSubmit={handelSubmit}>\n <div className={css.betContainer}>\n Proposition:\n <div className={css.bet}>\n <textarea type=\"text\" onChange={(e) => {setBet(e.target.value)}}/>\n </div>\n </div>\n <div>\n <div className={css.setting}>\n <span className={css.label}>Line:</span>\n <input className={css.input} type=\"number\" step=\"0.5\" onChange={(e) =>{setLine(Number(e.target.value))}} />\n </div>\n </div>\n <button type=\"submit\">Create bet</button>\n </form>\n </div>\n\n <div className=\"x1\">\n <Players />\n </div>\n <div>\n {shareDisplay ? <ShareBet display={handleShare} /> : null}\n \n </div>\n \n </div>\n );\n};\n\nexport default CreateOverUnder;\n","import React from 'react';\nimport CreateOverUnder from './CreateOverUnder';\n\nconst OverUnder = () => {\n return (\n <div className='pad'>\n <h1>OverUnder Component</h1>\n <CreateOverUnder />\n </div>\n );\n};\n\nexport default OverUnder;\n","// extracted by mini-css-extract-plugin\nexport default {\"prop\":\"Prop_prop__DRZFt\",\"betContainer\":\"Prop_betContainer__KSYFf\",\"bet\":\"Prop_bet__7E-T-\",\"PreSetBetting\":\"Prop_PreSetBetting__MzpqW\",\"settings\":\"Prop_settings__9dmn0\",\"title\":\"Prop_title__GEvyW\",\"label\":\"Prop_label__zDU93\",\"x\":\"Prop_x__tu9O2\",\"option\":\"Prop_option__nu2JJ\",\"optionInput\":\"Prop_optionInput__MuLBG\",\"options\":\"Prop_options__EQ8Hr\"};","import React, { useState, useEffect } from 'react';\nimport css from './Prop.module.css';\n\nconst PreSetBettingOptions = (prop) => {\n const [howMany, setHowMany] = useState(0);\n const [howManyOptions, setHowManyOptions] = useState([]);\n\n const [options, setOptions] = useState([]);\n\n\n const addOptions = (e, i) => {\n setOptions((current) => {options[i] = e.target.value; return options});\n }\n\n const addOneMore = () => {\n setHowMany(howMany + 1);\n }\n\n useEffect(() => {\n let options = [];\n for (let i = 0; i < howMany; i++) {\n options.push(i);\n }\n setHowManyOptions(options);\n }, [howMany]);\n\n const handleSubmit = (e) => {\n e.preventDefault();\n prop.setOptions(options);\n console.log('Saving preset betting options');\n }\n\n return (\n <div className={css.PreSetBetting}>\n <div className={css.x}><span onClick={prop.display}>x</span></div>\n <div className={css.title}><span>Preset Betting Options</span></div>\n <form onSubmit={handleSubmit}>\n {howManyOptions.map((option, index) => (\n <div className={css.option} key={index}>\n <span className={css.label}>{option+1}:</span>\n <input className={css.optionInput} type=\"text\" onChange={(e) => addOptions(e, index)} placeholder='Who or what' />\n </div>\n ))}\n <button type=\"submit\">Save</button>\n </form>\n <button onClick={addOneMore}>Add Option</button>\n </div>\n );\n};\n\nexport default PreSetBettingOptions;","import React from 'react';\nimport css from './Prop.module.css';\nimport { useState } from 'react';\nimport PreSetBettingOptions from './PreSetBettingOptions';\nimport Players from '../Players/Players';\nimport ShareBet from '../Players/ShareBet';\nimport {db} from '../../../Config/firebase-config';\nimport { addDoc, collection } from 'firebase/firestore';\n\nconst CreateProp = () => {\n\n const [bet, setBet] = useState('');\n const [Options, setOptions] = useState([]);\n\n\n const [isChecked, setIsChecked] = useState(false);\n const [shareDisplay, setShareDisplay] = useState(false);\n\n const handlesSetOptions = (options) => {\n setOptions(options);\n }\n \n const handleShare = () => {\n setShareDisplay((current) => !current);\n }\n\n \n const handleCheckboxChange = (event) => {\n setIsChecked(event.target.checked);\n };\n\n const handelSubmit = async (e) => { \n e.preventDefault();\n handleShare();\n try {\n await addDoc(collection(db, \"bets\"), {\n type: \"Prop\",\n bet: bet,\n })\n \n await addDoc(collection(db, \"PropBets\"), {\n bet: bet,\n options: Options,\n })\n } catch (e) {\n console.error(e);\n }\n console.log('Creating prop bet');\n }\n return (\n <div className='flex'>\n <div className={css.prop} >\n <form onSubmit={handelSubmit}>\n <div className={css.betContainer}>\n Proposition:\n <div className={css.bet}>\n <textarea type=\"text\" onChange={(e) => {setBet(e.target.value)}} />\n </div>\n </div>\n <div className={css.settings}>\n <input type=\"checkbox\" id=\"preSetBetting\" checked={isChecked} onChange={handleCheckboxChange} />\n <label htmlFor=\"preSetBetting\">Pre Set Betting Options</label>\n </div>\n <button type=\"submit\">Create bet</button>\n </form>\n </div>\n <div>\n {isChecked ? <PreSetBettingOptions setOptions={handlesSetOptions} display={handleCheckboxChange}/> : null}\n </div>\n <div className=\"x1\">\n <Players />\n </div>\n <div>\n {shareDisplay ? <ShareBet display={handleShare} /> : null}\n \n </div>\n </div>\n );\n};\n\nexport default CreateProp;\n","import React from 'react';\nimport CreateProp from './CreateProp';\n\nconst Prop = () => {\n return (\n <div className='pad'>\n <h1>Prop Bets</h1>\n <CreateProp />\n </div>\n );\n};\n\nexport default Prop;\n","import React, { useState, useEffect } from 'react';\nimport css from './MoneyLine.module.css';\nimport Players from '../Players/Players';\nimport ShareBet from '../Players/ShareBet';\nimport { useLocation } from 'react-router-dom';\nimport {db} from '../../../Config/firebase-config';\nimport { collection, getDocs, where , query } from 'firebase/firestore';\n\n\nconst ViewMoneyLine = () => {\n\n const [bets, setBets] = useState([])\n\n\n const location = useLocation()\n const { bet } = location.state\n\n \n useEffect(() => {\n const fetchBet = async () => {\n try{\n const MoneyLineBetCollection = collection(db, \"MoneyLineBets\");\n const q = query(MoneyLineBetCollection, where(\"bet\", \"==\", bet.bet));\n const querySnapshot = await getDocs(q);\n setBets(querySnapshot.docs[0].data());\n\n } catch (e) {\n console.error(e);\n }\n }\n fetchBet();\n }, [])\n\n\n return (\n <div className='flex pad'>\n <div className='x2'>\n\n\n <div>\n <h1 className={css.betLabel}>{bets.bet}</h1>\n\n <div className='blob'>\n\n <div className={css.ViewLabel}>\n <button className=\"betButton\">Bet</button>\n <h2>{bets.contestant1} </h2>\n {bets.contestant1Odds > 0 ? <p className='green'>(+{bets.contestant1Odds})</p> : <p className=\"red\">({bets.contestant1Odds})</p>}\n </div>\n <hr />\n <div className={css.ViewLabel}>\n <button className=\"betButton\">Bet</button>\n <h2>{bets.contestant2} </h2>\n {bets.contestant2Odds > 0 ? <p className='green'>(+{bets.contestant2Odds})</p> : <p className='red'>({bets.contestant2Odds})</p>}\n </div>\n </div>\n \n </div>\n\n\n\n </div>\n <div className=\"x1\">\n <Players />\n </div>\n </div>\n );\n};\n\nexport default ViewMoneyLine;\n","import React from 'react';\nimport { useState, useEffect } from 'react';\nimport { useLocation } from 'react-router-dom';\nimport Players from '../Players/Players';\nimport css from './OverUnder.module.css';\nimport {db} from '../../../Config/firebase-config';\nimport { collection, getDocs, where , query } from 'firebase/firestore';\n\nconst ViewOverUnder = () => {\n\n const [bets, setBets] = useState([])\n\n const location = useLocation()\n const { bet } = location.state\n\n\n useEffect(() => {\n\n const fetchBet = async () => {\n try{\n const MoneyLineBetCollection = collection(db, \"OverUnderBets\");\n const q = query(MoneyLineBetCollection, where(\"bet\", \"==\", bet.bet));\n const querySnapshot = await getDocs(q);\n setBets(querySnapshot.docs[0].data());\n\n } catch (e) {\n console.error(e);\n }\n }\n fetchBet();\n }, [])\n return (\n <div className='flex pad'>\n <div className='x2'>\n <div >\n <h1 className={css.betLabel} >{bets.bet}</h1>\n <div className={`blob row ${css.pad}`}>\n <div className={css.section}>\n <button className={`betButton ${css.button}`}>Under</button>\n <p>8 others have taken the under</p>\n </div>\n <div className={css.line}>\n <div className={css.lineLabel}><span>Line</span></div>\n <div className={css.actualLine}>{bets.line}</div> \n <div className={css.remain}>3 people have not voted</div>\n </div>\n <div className={css.section}>\n <button className='betButton'>Over</button>\n <p>12 others have taken the over</p>\n </div>\n </div>\n </div>\n </div>\n <div className=\"x1\">\n <Players />\n </div>\n \n </div>\n );\n};\n\nexport default ViewOverUnder;\n","import React from 'react';\nimport { useState, useEffect } from 'react';\nimport { useLocation } from 'react-router-dom';\nimport Players from '../Players/Players';\nimport css from './Prop.module.css';\nimport {db} from '../../../Config/firebase-config';\nimport { collection, getDocs, where , query } from 'firebase/firestore';\nconst ViewProp = () => {\n\n const [bets, setBets] = useState([])\n const [length, setLength] = useState(0)\n\n const location = useLocation()\n const { bet } = location.state\n\n\n useEffect(() => {\n\n const fetchBet = async () => {\n try{\n const MoneyLineBetCollection = collection(db, \"PropBets\");\n const q = query(MoneyLineBetCollection, where(\"bet\", \"==\", bet.bet));\n const querySnapshot = await getDocs(q);\n setBets(querySnapshot.docs[0].data());\n setLength(querySnapshot.docs[0].data().options.length)\n \n\n } catch (e) {\n console.error(e);\n }\n }\n fetchBet();\n }, [])\n\n\n return (\n <div>\n <div className='flex pad'>\n <div className='x2'>\n <div>\n <h1>{bets.bet}</h1>\n {length > 0 ? (\n <div>\n <h4><span>Betting</span></h4> \n <div className={css.options}>\n {bets.options.map((option, index) => (\n <div key={index}>\n <p>{option}</p>\n </div>\n )\n )}\n </div>\n </div>\n ): (null)}\n </div>\n </div>\n <div className=\"x1\">\n <Players />\n </div>\n \n </div>\n </div>\n );\n};\n\nexport default ViewProp;\n","// extracted by mini-css-extract-plugin\nexport default {\"betNav\":\"Bets_betNav__NdIy7\",\"BettingLinks\":\"Bets_BettingLinks__UtSL7\",\"x\":\"Bets_x__IOVNi\",\"bet\":\"Bets_bet__pvKP6\",\"link\":\"Bets_link__ibFCG\"};","import React from 'react';\nimport {useNavigate } from 'react-router-dom';\nimport css from './Bets.module.css';\n\nconst BetNav = (props) => {\n const navigate = useNavigate();\n\n const goToMoneyLine = () => {\n navigate('/Friendly-Betting/MoneyLineBets')\n }\n const goToOverUnder = () => {\n navigate('/Friendly-Betting/OverUnderBets')\n }\n const goToProps = () => {\n navigate('/Friendly-Betting/PropBets')\n }\n return (\n <div className={css.betNav}>\n <div className={css.x}><span onClick={props.swap} >x</span></div>\n <h1><span>Bets</span></h1>\n <div className={css.BettingLinks}>\n <div>\n <div onClick={goToMoneyLine} className='Link' >Money Line Bets</div>\n </div>\n <div>\n <div onClick={goToOverUnder} className='Link' >Over / Under Bets</div>\n </div>\n <div>\n <div onClick={goToProps} className='Link' >Prop Bets</div>\n </div>\n </div>\n </div>\n );\n};\n\nexport default BetNav;\n","import React from 'react';\nimport css from './Bets.module.css';\nimport {Link} from 'react-router-dom';\n\n\n\nconst DisplayBet = (props) => {\n\n const viewBet = () => {\n if(props.bet.type === \"Money Line\"){\n return \"MoneyLineBets/\"\n }\n else if(props.bet.type === \"Over Under\"){\n return \"OverUnderBets/\"\n }\n else if(props.bet.type === \"Prop\"){\n return \"PropBets/\"\n }\n }\n\n return (\n <div onClick={viewBet}>\n <Link \n to={`/Friendly-Betting/Bet/${viewBet()}`}\n state={{\"bet\":props.bet}}x\n className={css.link}\n \n >\n <div className={css.bet} key={props.bet.id}>\n <h4>{props.bet.type}</h4>\n <p>{props.bet.bet}</p>\n </div>\n </Link>\n </div>\n );\n}\n\nexport default DisplayBet;","import React from 'react';\nimport { useState, useEffect } from 'react';\nimport BetNav from './BetNav';\nimport {db} from '../../Config/firebase-config';\nimport { collection, getDocs } from 'firebase/firestore';\nimport DisplayBet from './DisplayBet';\nimport Players from './Players/Players';\n\n\nconst DisplayAllBets = () => {\n\n const [json, setJson] = useState(\"\")\n const [display, setDisplay] = useState(false)\n const [bets, setBets] = useState([])\n\n\n useEffect(() => {\n const getBets = async () => {\n try{\n const data = await getDocs(collection(db, \"bets\"));\n const filteredData = data.docs.map(doc => ({\n ...doc.data(), \n id: doc.id,\n }));\n console.log(filteredData);\n setBets(filteredData);\n } catch (e) {\n console.error(e);\n }\n }\n \n getBets();\n }, [])\n\n const swapDisplay = () => {\n setDisplay((current) => !current)\n }\n return (\n <div className='flex pad'>\n <div className='x2'>\n {json === \" \" ? (\n <div>\n <h3>You are not in any bets yet</h3>\n <button onClick={swapDisplay}>Create One!</button>\n {display ? <BetNav swap={swapDisplay}/> : null}\n\n </div>\n ) : (\n <div>\n {bets.map((bet) => (\n <DisplayBet bet={bet} />\n ))}\n <button onClick={swapDisplay}>Create One!</button>\n {display ? <BetNav swap={swapDisplay}/> : null}\n </div>\n ) }\n </div>\n <div className='x1'>\n <Players />\n </div>\n </div>\n );\n}\n\nexport default DisplayAllBets;\n","import React from 'react';\n\nfunction Friends() {\n return (\n <div>\n <h1>Friends</h1>\n </div>\n );\n}\n\nexport default Friends;\n","\nimport './App.css';\nimport SignIn from './Components/SignInPage/SignIn';\nimport CreateAccount from './Components/SignInPage/CreateAccount';\nimport Header from './Components/Header';\nimport NotFound from './Components/NotFound';\nimport { BrowserRouter as Router, Routes, Route } from 'react-router-dom';\nimport Welcome from './Components/Welcome';\nimport MoneyLine from './Components/Bets/MoneyLineBets/MoneyLine';\nimport OverUnder from './Components/Bets/OverUnderBets/OverUnder';\nimport Prop from './Components/Bets/PropBets/Prop';\nimport ViewMoneyLine from './Components/Bets/MoneyLineBets/ViewMoneyLine';\nimport ViewOverUnder from './Components/Bets/OverUnderBets/ViewOverUnder';\nimport ViewProp from './Components/Bets/PropBets/ViewProp';\nimport DisplayAllBets from './Components/Bets/DisplayAllBets';\nimport Friends from './Components/Friends/Friends';\n\n\n\n\n\n\nfunction App() {\n\n \n \n return (\n <Router>\n <Header />\n <Routes>\n <Route path=\"Friendly-Betting/\" element={<Welcome />} />\n \n <Route path=\"Friendly-Betting/SignIn\" element={ <SignIn />} />\n \n <Route path=\"Friendly-Betting/CreateAccount\" element={<CreateAccount />} />\n <Route path=\"Friendly-Betting/Bet\" element={<DisplayAllBets />} />\n <Route path=\"Friendly-Betting/Friends\" element={<Friends />} />\n\n <Route path=\"Friendly-Betting/MoneyLineBets\" element={<MoneyLine />} />\n <Route path=\"Friendly-Betting/OverUnderBets\" element={<OverUnder />} />\n <Route path=\"Friendly-Betting/PropBets\" element={<Prop />} />\n\n <Route path=\"/Friendly-Betting/Bet/MoneyLineBets/\" element={<ViewMoneyLine />} />\n <Route path=\"/Friendly-Betting/Bet/OverUnderBets/\" element={<ViewOverUnder />} />\n <Route path=\"/Friendly-Betting/Bet/PropBets/\" element={<ViewProp />} />\n\n\n\n <Route path=\"/*\" element={<NotFound />} />\n </Routes>\n </Router>\n );\n}\n\nexport default App;\n","const reportWebVitals = onPerfEntry => {\n if (onPerfEntry && onPerfEntry instanceof Function) {\n import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {\n getCLS(onPerfEntry);\n getFID(onPerfEntry);\n getFCP(onPerfEntry);\n getLCP(onPerfEntry);\n getTTFB(onPerfEntry);\n });\n }\n};\n\nexport default reportWebVitals;\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport './index.css';\nimport App from './App';\nimport reportWebVitals from './reportWebVitals';\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(\n <React.StrictMode>\n <App />\n </React.StrictMode>\n);\n\n// If you want to start measuring performance in your app, pass a function\n// to log results (for example: reportWebVitals(console.log))\n// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals\nreportWebVitals();\n"],"names":["aa","require","ca","p","a","b","c","arguments","length","encodeURIComponent","da","Set","ea","fa","ha","add","ia","window","document","createElement","ja","Object","prototype","hasOwnProperty","ka","la","ma","v","d","e","f","g","this","acceptsBooleans","attributeName","attributeNamespace","mustUseProperty","propertyName","type","sanitizeURL","removeEmptyString","z","split","forEach","toLowerCase","ra","sa","toUpperCase","ta","slice","pa","isNaN","qa","call","test","oa","removeAttribute","setAttribute","setAttributeNS","replace","xlinkHref","ua","__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED","va","Symbol","for","wa","ya","za","Aa","Ba","Ca","Da","Ea","Fa","Ga","Ha","Ia","Ja","iterator","Ka","La","A","assign","Ma","Error","stack","trim","match","Na","Oa","prepareStackTrace","defineProperty","set","Reflect","construct","l","h","k","displayName","includes","name","Pa","tag","render","Qa","$$typeof","_context","_payload","_init","Ra","Sa","Ta","nodeName","Va","_valueTracker","getOwnPropertyDescriptor","constructor","get","configurable","enumerable","getValue","setValue","stopTracking","Ua","Wa","checked","value","Xa","activeElement","body","Ya","defaultChecked","defaultValue","_wrapperState","initialChecked","Za","initialValue","controlled","ab","bb","cb","db","ownerDocument","eb","Array","isArray","fb","options","selected","defaultSelected","disabled","gb","dangerouslySetInnerHTML","children","hb","ib","jb","textContent","kb","lb","mb","nb","namespaceURI","innerHTML","valueOf","toString","firstChild","removeChild","appendChild","MSApp","execUnsafeLocalFunction","ob","lastChild","nodeType","nodeValue","pb","animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth","qb","rb","sb","style","indexOf","setProperty","keys","charAt","substring","tb","menuitem","area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr","ub","vb","is","wb","xb","target","srcElement","correspondingUseElement","parentNode","yb","zb","Ab","Bb","Cb","stateNode","Db","Eb","push","Fb","Gb","Hb","Ib","Jb","Kb","Lb","Mb","addEventListener","removeEventListener","Nb","apply","m","onError","Ob","Pb","Qb","Rb","Sb","Tb","Vb","alternate","return","flags","Wb","memoizedState","dehydrated","Xb","Zb","child","sibling","current","Yb","$b","ac","unstable_scheduleCallback","bc","unstable_cancelCallback","cc","unstable_shouldYield","dc","unstable_requestPaint","B","unstable_now","ec","unstable_getCurrentPriorityLevel","fc","unstable_ImmediatePriority","gc","unstable_UserBlockingPriority","hc","unstable_NormalPriority","ic","unstable_LowPriority","jc","unstable_IdlePriority","kc","lc","oc","Math","clz32","pc","qc","log","LN2","rc","sc","tc","uc","pendingLanes","suspendedLanes","pingedLanes","entangledLanes","entanglements","vc","xc","yc","zc","Ac","eventTimes","Cc","C","Dc","Ec","Fc","Gc","Hc","Ic","Jc","Kc","Lc","Mc","Nc","Oc","Map","Pc","Qc","Rc","Sc","delete","pointerId","Tc","nativeEvent","blockedOn","domEventName","eventSystemFlags","targetContainers","Vc","Wc","priority","isDehydrated","containerInfo","Xc","Yc","dispatchEvent","shift","Zc","$c","ad","bd","cd","ReactCurrentBatchConfig","dd","ed","transition","fd","gd","hd","id","Uc","stopPropagation","jd","kd","ld","md","nd","od","keyCode","charCode","pd","qd","rd","_reactName","_targetInst","currentTarget","isDefaultPrevented","defaultPrevented","returnValue","isPropagationStopped","preventDefault","cancelBubble","persist","isPersistent","wd","xd","yd","sd","eventPhase","bubbles","cancelable","timeStamp","Date","now","isTrusted","td","ud","view","detail","vd","Ad","screenX","screenY","clientX","clientY","pageX","pageY","ctrlKey","shiftKey","altKey","metaKey","getModifierState","zd","button","buttons","relatedTarget","fromElement","toElement","movementX","movementY","Bd","Dd","dataTransfer","Fd","Hd","animationName","elapsedTime","pseudoElement","Id","clipboardData","Jd","Ld","data","Md","Esc","Spacebar","Left","Up","Right","Down","Del","Win","Menu","Apps","Scroll","MozPrintableKey","Nd","Od","Alt","Control","Meta","Shift","Pd","Qd","key","String","fromCharCode","code","location","repeat","locale","which","Rd","Td","width","height","pressure","tangentialPressure","tiltX","tiltY","twist","pointerType","isPrimary","Vd","touches","targetTouches","changedTouches","Xd","Yd","deltaX","wheelDeltaX","deltaY","wheelDeltaY","wheelDelta","deltaZ","deltaMode","Zd","$d","ae","be","documentMode","ce","de","ee","fe","ge","he","ie","le","color","date","datetime","email","month","number","password","range","search","tel","text","time","url","week","me","ne","oe","event","listeners","pe","qe","re","se","te","ue","ve","we","xe","ye","ze","oninput","Ae","detachEvent","Be","Ce","attachEvent","De","Ee","Fe","He","Ie","Je","Ke","node","offset","nextSibling","Le","contains","compareDocumentPosition","Me","HTMLIFrameElement","contentWindow","href","Ne","contentEditable","Oe","focusedElem","selectionRange","documentElement","start","end","selectionStart","selectionEnd","min","defaultView","getSelection","extend","rangeCount","anchorNode","anchorOffset","focusNode","focusOffset","createRange","setStart","removeAllRanges","addRange","setEnd","element","left","scrollLeft","top","scrollTop","focus","Pe","Qe","Re","Se","Te","Ue","Ve","We","animationend","animationiteration","animationstart","transitionend","Xe","Ye","Ze","animation","$e","af","bf","cf","df","ef","ff","gf","hf","lf","mf","concat","nf","Ub","instance","listener","D","of","has","pf","qf","rf","random","sf","bind","capture","passive","n","t","J","x","u","w","F","tf","uf","parentWindow","vf","wf","na","xa","$a","ba","je","char","ke","unshift","xf","yf","zf","Af","Bf","Cf","Df","Ef","__html","Ff","setTimeout","Gf","clearTimeout","Hf","Promise","Jf","queueMicrotask","resolve","then","catch","If","Kf","Lf","Mf","previousSibling","Nf","Of","Pf","Qf","Rf","Sf","Tf","Uf","E","G","Vf","H","Wf","Xf","Yf","contextTypes","__reactInternalMemoizedUnmaskedChildContext","__reactInternalMemoizedMaskedChildContext","Zf","childContextTypes","$f","ag","bg","getChildContext","cg","__reactInternalMemoizedMergedChildContext","dg","eg","fg","gg","hg","jg","kg","lg","mg","ng","og","pg","qg","rg","sg","tg","ug","vg","wg","xg","yg","I","zg","Ag","Bg","elementType","deletions","Cg","pendingProps","overflow","treeContext","retryLane","Dg","mode","Eg","Fg","Gg","memoizedProps","Hg","Ig","Jg","Kg","Lg","defaultProps","Mg","Ng","Og","Pg","Qg","Rg","_currentValue","Sg","childLanes","Tg","dependencies","firstContext","lanes","Ug","Vg","context","memoizedValue","next","Wg","Xg","Yg","interleaved","Zg","$g","ah","updateQueue","baseState","firstBaseUpdate","lastBaseUpdate","shared","pending","effects","bh","ch","eventTime","lane","payload","callback","dh","K","eh","fh","gh","q","r","y","hh","ih","jh","Component","refs","kh","nh","isMounted","_reactInternals","enqueueSetState","L","lh","mh","enqueueReplaceState","enqueueForceUpdate","oh","shouldComponentUpdate","isPureReactComponent","ph","contextType","state","updater","qh","componentWillReceiveProps","UNSAFE_componentWillReceiveProps","rh","props","getDerivedStateFromProps","getSnapshotBeforeUpdate","UNSAFE_componentWillMount","componentWillMount","componentDidMount","sh","ref","_owner","_stringRef","th","join","uh","vh","index","wh","xh","yh","implementation","zh","Ah","done","Bh","Ch","Dh","Eh","Fh","Gh","Hh","Ih","tagName","Jh","Kh","Lh","M","Mh","revealOrder","Nh","Oh","_workInProgressVersionPrimary","Ph","ReactCurrentDispatcher","Qh","Rh","N","O","P","Sh","Th","Uh","Vh","Q","Wh","Xh","Yh","Zh","$h","ai","bi","ci","baseQueue","queue","di","ei","fi","lastRenderedReducer","action","hasEagerState","eagerState","lastRenderedState","dispatch","gi","hi","ii","ji","ki","getSnapshot","li","mi","R","ni","lastEffect","stores","oi","pi","qi","ri","create","destroy","deps","si","ti","ui","vi","wi","xi","yi","zi","Ai","Bi","Ci","Di","Ei","Fi","Gi","Hi","Ii","Ji","readContext","useCallback","useContext","useEffect","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useReducer","useRef","useState","useDebugValue","useDeferredValue","useTransition","useMutableSource","useSyncExternalStore","useId","unstable_isNewReconciler","identifierPrefix","Ki","message","digest","Li","Mi","console","error","Ni","WeakMap","Oi","Pi","Qi","Ri","getDerivedStateFromError","componentDidCatch","Si","componentStack","Ti","pingCache","Ui","Vi","Wi","Xi","ReactCurrentOwner","Yi","Zi","$i","aj","bj","compare","cj","dj","ej","baseLanes","cachePool","transitions","fj","gj","hj","ij","jj","UNSAFE_componentWillUpdate","componentWillUpdate","componentDidUpdate","kj","lj","pendingContext","mj","Aj","Bj","Cj","Dj","nj","oj","pj","fallback","qj","rj","tj","dataset","dgst","uj","vj","_reactRetry","sj","subtreeFlags","wj","xj","isBackwards","rendering","renderingStartTime","last","tail","tailMode","yj","Ej","S","Fj","Gj","wasMultiple","multiple","suppressHydrationWarning","onClick","onclick","size","createElementNS","autoFocus","createTextNode","T","Hj","Ij","Jj","Kj","U","Lj","WeakSet","V","Mj","W","Nj","Oj","Qj","Rj","Sj","Tj","Uj","Vj","Wj","insertBefore","_reactRootContainer","Xj","X","Yj","Zj","ak","onCommitFiberUnmount","componentWillUnmount","bk","ck","dk","ek","fk","isHidden","gk","hk","display","ik","jk","kk","lk","__reactInternalSnapshotBeforeUpdate","src","Wk","mk","ceil","nk","ok","pk","Y","Z","qk","rk","sk","tk","uk","Infinity","vk","wk","xk","yk","zk","Ak","Bk","Ck","Dk","Ek","callbackNode","expirationTimes","expiredLanes","wc","callbackPriority","ig","Fk","Gk","Hk","Ik","Jk","Kk","Lk","Mk","Nk","Ok","Pk","finishedWork","finishedLanes","Qk","timeoutHandle","Rk","Sk","Tk","Uk","Vk","mutableReadLanes","Bc","Pj","onCommitFiberRoot","mc","onRecoverableError","Xk","onPostCommitFiberRoot","Yk","Zk","al","isReactComponent","pendingChildren","bl","mutableSourceEagerHydrationData","cl","cache","pendingSuspenseBoundaries","el","fl","gl","hl","il","jl","zj","$k","ll","reportError","ml","_internalRoot","nl","ol","pl","ql","sl","rl","unmount","unstable_scheduleHydration","splice","querySelectorAll","JSON","stringify","form","tl","usingClientEntryPoint","Events","ul","findFiberByHostInstance","bundleType","version","rendererPackageName","vl","rendererConfig","overrideHookState","overrideHookStateDeletePath","overrideHookStateRenamePath","overrideProps","overridePropsDeletePath","overridePropsRenamePath","setErrorHandler","setSuspenseHandler","scheduleUpdate","currentDispatcherRef","findHostInstanceByFiber","findHostInstancesForRefresh","scheduleRefresh","scheduleRoot","setRefreshHandler","getCurrentFiber","reconcilerVersion","__REACT_DEVTOOLS_GLOBAL_HOOK__","wl","isDisabled","supportsFiber","inject","exports","createPortal","dl","createRoot","unstable_strictMode","findDOMNode","flushSync","hydrate","hydrateRoot","hydratedSources","_getVersion","_source","unmountComponentAtNode","unstable_batchedUpdates","unstable_renderSubtreeIntoContainer","checkDCE","err","module","__self","__source","jsx","jsxs","setState","forceUpdate","escape","_status","_result","default","Children","map","count","toArray","only","Fragment","Profiler","PureComponent","StrictMode","Suspense","cloneElement","createContext","_currentValue2","_threadCount","Provider","Consumer","_defaultValue","_globalName","createFactory","createRef","forwardRef","isValidElement","lazy","memo","startTransition","unstable_act","pop","sortIndex","performance","setImmediate","startTime","expirationTime","priorityLevel","navigator","scheduling","isInputPending","MessageChannel","port2","port1","onmessage","postMessage","unstable_Profiling","unstable_continueExecution","unstable_forceFrameRate","floor","unstable_getFirstCallbackNode","unstable_next","unstable_pauseExecution","unstable_runWithPriority","delay","unstable_wrapCallback","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","leafPrototypes","getProto","getPrototypeOf","obj","__esModule","ns","def","getOwnPropertyNames","definition","o","chunkId","all","reduce","promises","miniCssF","globalThis","Function","prop","inProgress","dataWebpackPrefix","script","needAttach","scripts","getElementsByTagName","i","s","getAttribute","charset","timeout","nc","onScriptComplete","prev","onerror","onload","doneFns","fn","head","toStringTag","installedChunks","j","installedChunkData","promise","reject","errorType","realSrc","request","webpackJsonpCallback","parentChunkLoadingFunction","chunkIds","moreModules","runtime","some","chunkLoadingGlobal","self","stringToByteArray$1","str","out","charCodeAt","base64","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","webSafe","init_","byteToCharMap","output","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","encodeString","btoa","decodeString","bytes","pos","c1","c2","c3","byteArrayToString","decodeStringToByteArray","charToByteMap","byte4","DecodeBase64StringError","base64urlEncodeWithoutPadding","utf8Bytes","base64Encode","base64Decode","getDefaultsFromGlobal","global","getGlobal","__FIREBASE_DEFAULTS__","getDefaults","getDefaultsFromEnvVariable","process","defaultsJsonString","parse","getDefaultsFromCookie","cookie","decoded","info","getDefaultEmulatorHost","productName","_a","_b","emulatorHosts","getDefaultAppConfig","config","getExperimentalSetting","Deferred","wrapCallback","getUA","isBrowserExtension","chrome","browser","isIndexedDBAvailable","indexedDB","validateIndexedDBOpenable","preExist","DB_CHECK_NAME","open","onsuccess","result","close","deleteDatabase","onupgradeneeded","FirebaseError","customData","super","setPrototypeOf","captureStackTrace","ErrorFactory","service","serviceName","errors","fullCode","template","PATTERN","_","replaceTemplate","fullMessage","deepEqual","aKeys","bKeys","aProp","bProp","isObject","thing","querystring","querystringParams","params","entries","arrayVal","querystringDecode","token","decodeURIComponent","extractQuerystring","queryStart","fragmentStart","ObserverProxy","executor","onNoObservers","observers","unsubscribes","observerCount","task","finalized","forEachObserver","observer","complete","subscribe","nextOrObserver","methods","method","implementsAnyMethods","noop","unsub","unsubscribeOne","finalError","sendOne","DEFAULT_INTERVAL_MILLIS","DEFAULT_BACKOFF_FACTOR","MAX_VALUE_MILLIS","RANDOM_FACTOR","calculateBackoffMillis","backoffCount","backoffFactor","currBaseValue","pow","randomWait","round","getModularInstance","_delegate","instanceFactory","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","setMultipleInstances","setServiceProps","setInstanceCreatedCallback","DEFAULT_ENTRY_NAME","container","component","instances","instancesDeferred","instancesOptions","onInitCallbacks","identifier","normalizedIdentifier","normalizeInstanceIdentifier","deferred","isInitialized","shouldAutoInitialize","getOrInitializeService","instanceIdentifier","getImmediate","optional","getComponent","setComponent","isComponentEager","instanceDeferred","clearInstance","services","from","values","filter","INTERNAL","_delete","isComponentSet","getOptions","initialize","opts","onInit","existingCallbacks","existingInstance","invokeOnInitCallbacks","callbacks","_ref","ComponentContainer","providers","addComponent","provider","getProvider","addOrOverwriteComponent","getProviders","LogLevel","levelStringToEnum","DEBUG","VERBOSE","INFO","WARN","ERROR","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","logType","logLevel","toISOString","_len","args","_key","Logger","_logLevel","_logHandler","_userLogHandler","val","TypeError","setLogLevel","logHandler","userLogHandler","debug","_len2","_key2","_len3","_key3","_len4","_key4","warn","_len5","_key5","_len6","_key6","instanceOfAny","object","constructors","idbProxyableTypes","cursorAdvanceMethods","cursorRequestMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","idbProxyTraps","receiver","IDBTransaction","objectStoreNames","objectStore","wrap","wrapFunction","func","IDBDatabase","transaction","IDBCursor","advance","continue","continuePrimaryKey","unwrap","storeNames","tx","sort","transformCachableValue","unlisten","DOMException","cacheDonePromiseForTransaction","IDBObjectStore","IDBIndex","Proxy","IDBRequest","success","promisifyRequest","newValue","readMethods","writeMethods","cachedMethods","getMethod","targetFuncName","useIndex","isWrite","async","storeName","store","oldTraps","PlatformLoggerServiceImpl","getPlatformInfoString","isVersionServiceProvider","library","logString","logger","PLATFORM_LOG_STRING","name$o","_apps","_components","_addComponent","app","_registerComponent","componentName","_getProvider","heartbeatController","triggerHeartbeat","ERROR_FACTORY","FirebaseAppImpl","_isDeleted","_options","_config","_name","_automaticDataCollectionEnabled","automaticDataCollectionEnabled","_container","checkDestroyed","isDeleted","appName","SDK_VERSION","initializeApp","rawConfig","existingApp","newApp","getApp","registerVersion","libraryKeyOrName","variant","libraryMismatch","versionMismatch","warning","DB_NAME","DB_VERSION","STORE_NAME","dbPromise","getDbPromise","blocked","upgrade","blocking","terminated","openPromise","oldVersion","newVersion","openDB","createObjectStore","originalErrorMessage","writeHeartbeatsToIndexedDB","heartbeatObject","put","computeKey","idbGetError","appId","HeartbeatServiceImpl","_heartbeatsCache","_storage","HeartbeatStorageImpl","_heartbeatsCachePromise","read","agent","getUTCDateString","heartbeats","lastSentHeartbeatDate","singleDateHeartbeat","hbTimestamp","overwrite","getHeartbeatsHeader","heartbeatsToSend","unsentEntries","heartbeatsCache","maxSize","heartbeatEntry","find","dates","countBytes","extractHeartbeatsForHeader","headerString","_canUseIndexedDBPromise","runIndexedDBEnvironmentCheck","idbHeartbeatObject","readHeartbeatsFromIndexedDB","heartbeatsObject","existingHeartbeatsObject","version$1","replaceTraps","PENDING_TIMEOUT_MS","PACKAGE_VERSION","INTERNAL_AUTH_VERSION","INSTALLATIONS_API_URL","TOKEN_EXPIRATION_BUFFER","isServerError","getInstallationsEndpoint","projectId","extractAuthTokenInfoFromResponse","response","requestStatus","expiresIn","responseExpiresIn","Number","creationTime","getErrorFromResponse","requestName","errorData","json","serverCode","serverMessage","serverStatus","status","getHeaders","_ref2","apiKey","Headers","Accept","getHeadersWithAuth","appConfig","_ref3","refreshToken","headers","append","getAuthorizationHeader","retryIfServerError","sleep","ms","VALID_FID_PATTERN","INVALID_FID","generateFid","fidByteArray","Uint8Array","crypto","msCrypto","getRandomValues","fid","b64String","array","substr","encode","getKey","fidChangeCallbacks","fidChanged","callFidChangeCallbacks","channel","getBroadcastChannel","closeBroadcastChannel","broadcastFidChange","broadcastChannel","BroadcastChannel","DATABASE_NAME","DATABASE_VERSION","OBJECT_STORE_NAME","oldValue","remove","update","updateFn","getInstallationEntry","installations","registrationPromise","installationEntry","oldEntry","entry","registrationStatus","clearTimedOutRequest","updateOrCreateInstallationEntry","entryWithPromise","onLine","inProgressEntry","registrationTime","registeredInstallationEntry","_ref4","_ref5","heartbeatServiceProvider","endpoint","heartbeatService","heartbeatsHeader","authVersion","sdkVersion","fetch","responseValue","authToken","createInstallationRequest","registerInstallation","waitUntilFidRegistration","triggerRegistrationIfNecessary","updateInstallationRequest","generateAuthTokenRequest","_ref6","_ref7","getGenerateAuthTokenEndpoint","installation","refreshAuthToken","tokenPromise","forceRefresh","isEntryRegistered","oldAuthToken","isAuthTokenExpired","isAuthTokenValid","updateAuthTokenRequest","waitUntilAuthTokenRequest","inProgressAuthToken","requestTime","makeAuthTokenRequestInProgressEntry","updatedInstallationEntry","fetchAuthTokenFromServer","getToken","installationsImpl","completeInstallationRegistration","getMissingValueError","valueName","INSTALLATIONS_NAME","publicFactory","configKeys","keyName","extractAppConfig","internalFactory","getId","ANALYTICS_TYPE","GA_FID_KEY","ORIGIN_KEY","FETCH_TIMEOUT_MILLIS","DYNAMIC_CONFIG_URL","GTAG_URL","createGtagTrustedTypesScriptURL","startsWith","gtagURL","promiseAllSettled","insertScriptTag","dataLayerName","measurementId","trustedTypesPolicy","policyName","policyOptions","trustedTypes","createPolicy","createTrustedTypesPolicy","createScriptURL","gtagScriptURL","wrapGtag","gtagCore","initializationPromisesMap","dynamicConfigPromisesList","measurementIdToAppId","command","gtagParams","initializationPromisesToWaitFor","gaSendToList","dynamicConfigResults","sendToId","foundConfig","initializationPromise","gtagOnEvent","correspondingAppId","gtagOnConfig","fieldName","customParams","LONG_RETRY_FACTOR","defaultRetryData","throttleMetadata","intervalMillis","getThrottleMetadata","setThrottleMetadata","metadata","deleteThrottleMetadata","fetchDynamicConfigWithRetry","retryData","timeoutMillis","throttleEndTimeMillis","signal","AnalyticsAbortSignal","abort","attemptFetchDynamicConfigWithRetry","appFields","backoffMillis","max","setAbortableTimeout","appUrl","errorMessage","jsonResponse","_ignored","httpStatus","responseMessage","fetchDynamicConfig","isRetriableError","defaultEventParametersForInit","defaultConsentSettingsForInit","_setConsentDefaultForInit","consentSettings","_setDefaultEventParametersForInit","_initializeAnalytics","dynamicConfigPromise","fidPromise","errorInfo","validateIndexedDB","envIsValid","dynamicConfig","scriptTags","findGtagScriptOnPage","configProperties","AnalyticsService","gtagCoreFunction","wrappedGtagFunction","gtagName","globalInitDone","warnOnBrowserContextMismatch","mismatchedEnvMessages","cookieEnabled","details","factory","dataLayer","getOrCreateDataLayer","wrappedGtag","gtagFunctionName","_args","wrapOrCreateGtag","logEvent","analyticsInstance","eventName","eventParams","gtagFunction","logEvent$1","analyticsOptions","analytics","reason","__rest","getOwnPropertySymbols","propertyIsEnumerable","SuppressedError","_prodErrorMap","prodErrorMap","_DEFAULT_AUTH_ERROR_FACTORY","logClient","_logError","msg","_fail","authOrCode","rest","createErrorInternal","_createError","_errorWithCustomMessage","auth","errorMap","fullParams","_errorFactory","_assert","assertion","_key7","debugFail","failure","debugAssert","_getCurrentUrl","_isHttpOrHttps","_getCurrentScheme","protocol","Delay","shortDelay","longDelay","isMobile","_emulatorUrl","path","emulator","FetchProvider","fetchImpl","headersImpl","responseImpl","Response","SERVER_ERROR_MAP","DEFAULT_API_TIMEOUT_MS","_addTidIfNecessary","tenantId","_performApiRequest","_performFetchWithErrorHandling","query","_getAdditionalHeaders","languageCode","_getFinalTarget","apiHost","referrerPolicy","customErrorMap","fetchFn","_canInitEmulator","networkTimeout","NetworkTimeout","race","clearNetworkTimeout","_makeTaggedError","serverErrorCode","serverErrorMessage","authError","_performSignInRequest","serverResponse","_serverResponse","host","apiScheme","_parseEnforcementState","enforcementStateStr","timer","errorParams","phoneNumber","_tokenResponse","isEnterprise","grecaptcha","enterprise","RecaptchaConfig","siteKey","recaptchaEnforcementState","recaptchaKey","getProviderEnforcementState","providerStr","enforcementState","isProviderEnabled","getRecaptchaConfig","utcTimestampToDateString","utcTimestamp","getTime","toUTCString","secondsStringToMilliseconds","seconds","_parseToken","algorithm","signature","_logoutIfInvalidated","user","isUserInvalidated","currentUser","signOut","ProactiveRefresh","isRunning","timerId","errorBackoff","_start","schedule","_stop","getInterval","wasError","interval","stsTokenManager","iteration","getIdToken","UserMetadata","createdAt","lastLoginAt","_initializeTime","lastSignInTime","_copy","toJSON","_reloadWithoutSaving","idToken","getAccountInfo","users","coreAccount","_notifyReloadListener","newProviderData","providerUserInfo","providerId","uid","rawId","photoURL","photoUrl","providerData","original","newData","oldIsAnonymous","isAnonymous","newIsAnonymous","passwordHash","updates","localId","emailVerified","StsTokenManager","accessToken","isExpired","updateFromServerResponse","parsedToken","exp","iat","_tokenExpiresIn","updateTokensAndExpiration","refresh","clearRefreshToken","oldToken","tokenApiHost","access_token","expires_in","refresh_token","requestStsToken","expiresInSec","fromJSON","manager","_assign","_clone","_performRefresh","assertStringOrUndefined","UserImpl","opt","proactiveRefresh","reloadUserInfo","reloadListener","_persistUserIfCurrent","_notifyListenersIfCurrent","getIdTokenResult","userInternal","claims","auth_time","firebase","signInProvider","authTime","issuedAtTime","signInSecondFactor","reload","userInfo","newUser","_onReload","_startProactiveRefresh","_stopProactiveRefresh","_updateTokensIfNecessary","tokensRefreshed","deleteAccount","_redirectEventId","_fromJSON","_c","_d","_e","_f","_g","_h","plainObjectTokenManager","_fromIdTokenResponse","idTokenResponse","instanceCache","_getInstance","cls","InMemoryPersistence","storage","_isAvailable","_set","_get","_remove","_addListener","_listener","_removeListener","inMemoryPersistence","_persistenceKeyName","PersistenceUserManager","persistence","userKey","fullUserKey","fullPersistenceKey","boundEventHandler","_onStorageEvent","setCurrentUser","getCurrentUser","blob","removeCurrentUser","savePersistenceForRedirect","setPersistence","newPersistence","persistenceHierarchy","availablePersistences","selectedPersistence","userToMigrate","migrationHierarchy","_shouldAllowMigration","_getBrowserName","userAgent","_isIEMobile","_isFirefox","_isBlackBerry","_isWebOS","_isSafari","_isChromeIOS","_isAndroid","matches","_isIOS","_isIE10","isIE","_isMobileBrowser","_getClientVersion","clientPlatform","reportedPlatform","frameworks","reportedFrameworks","AuthMiddlewareQueue","pushCallback","onAbort","wrappedCallback","runMiddleware","nextUser","onAbortStack","beforeStateCallback","reverse","originalMessage","PasswordPolicyImpl","responseOptions","customStrengthOptions","minPasswordLength","maxPasswordLength","containsLowercaseCharacter","containsLowercaseLetter","containsUppercaseCharacter","containsUppercaseLetter","containsNumericCharacter","containsNonAlphanumericCharacter","allowedNonAlphanumericCharacters","forceUpgradeOnSignin","schemaVersion","validatePassword","isValid","passwordPolicy","validatePasswordLengthOptions","validatePasswordCharacterOptions","meetsMinPasswordLength","meetsMaxPasswordLength","passwordChar","updatePasswordCharacterOptionsStatuses","AuthImpl","appCheckServiceProvider","emulatorConfig","operations","authStateSubscription","Subscription","idTokenSubscription","beforeStateQueue","redirectUser","isProactiveRefreshEnabled","EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION","_isInitialized","_deleted","_initializationPromise","_popupRedirectResolver","_agentRecaptchaConfig","_tenantRecaptchaConfigs","_projectPasswordPolicy","_tenantPasswordPolicies","lastNotifiedUid","settings","appVerificationDisabledForTesting","clientVersion","sdkClientVersion","_initializeWithPersistence","popupRedirectResolver","persistenceManager","_shouldInitProactively","_initialize","initializeCurrentUser","assertedPersistence","_currentUser","_updateCurrentUser","previouslyStoredUser","futureCurrentUser","needsTocheckMiddleware","authDomain","getOrInitRedirectPersistenceManager","redirectUserEventId","storedUserEventId","tryRedirectSignIn","directlySetCurrentUser","_overrideRedirectResult","reloadAndSetCurrentUserOrClear","redirectResolver","_completeRedirectFn","_setRedirectUser","useDeviceLanguage","navigatorLanguage","languages","language","_getUserLanguage","updateCurrentUser","userExtern","skipBeforeStateCallbacks","notifyAuthListeners","redirectPersistenceManager","_getRecaptchaConfig","_getPasswordPolicyInternal","_updatePasswordPolicy","_getPasswordPolicy","_getPersistence","_updateErrorMap","onAuthStateChanged","completed","registerStateListener","beforeAuthStateChanged","onIdTokenChanged","authStateReady","unsubscribe","revokeAccessToken","tokenType","revokeToken","redirectManager","resolver","_redirectPersistence","_redirectUserForId","currentUid","subscription","isUnsubscribed","addObserver","_logFramework","framework","_getFrameworks","appCheckToken","_getAppCheckToken","appCheckTokenResult","_logWarn","_castAuth","proxy","createSubscribe","_loadJS","getScriptParentElement","_generateCallbackName","prefix","RecaptchaEnterpriseVerifier","authExtern","verify","retrieveRecaptchaToken","ready","execute","clientType","retrieveSiteKey","injectRecaptchaFields","captchaResp","verifier","captchaResponse","newRequest","handleRecaptchaFlow","authInstance","actionName","actionMethod","requestWithRecaptcha","connectAuthEmulator","authInternal","disableWarnings","extractProtocol","port","authority","exec","hostAndPort","bracketedIPv6","parsePort","extractHostAndPort","portStr","freeze","attachBanner","sty","innerText","position","backgroundColor","border","bottom","margin","textAlign","classList","readyState","emitEmulatorWarning","protocolEnd","AuthCredential","signInMethod","_getIdTokenResponse","_auth","_linkToIdToken","_idToken","_getReauthenticationResolver","linkEmailPassword","signInWithPassword","EmailAuthCredential","_email","_password","_tenantId","_fromEmailAndPassword","_fromEmailAndCode","oobCode","returnSecureToken","signInWithEmailLink$1","signInWithEmailLinkForLinking","signInWithIdp","OAuthCredential","pendingToken","_fromParams","cred","nonce","oauthToken","oauthTokenSecret","secret","buildRequest","autoCreate","requestUri","postBody","VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_","PhoneAuthCredential","_fromVerification","verificationId","verificationCode","_fromTokenResponse","temporaryProof","signInWithPhoneNumber$1","_makeVerificationRequest","linkWithPhoneNumber$1","operation","verifyPhoneNumberForExisting","sessionInfo","ActionCodeURL","actionLink","searchParams","parseMode","continueUrl","parseLink","doubleDeepLink","iOSDeepLink","parseDeepLink","EmailAuthProvider","PROVIDER_ID","credential","credentialWithLink","emailLink","actionCodeUrl","EMAIL_PASSWORD_SIGN_IN_METHOD","EMAIL_LINK_SIGN_IN_METHOD","FederatedAuthProvider","defaultLanguageCode","customParameters","setDefaultLanguage","setCustomParameters","customOAuthParameters","getCustomParameters","BaseOAuthProvider","scopes","addScope","scope","getScopes","FacebookAuthProvider","FACEBOOK_SIGN_IN_METHOD","credentialFromResult","userCredential","credentialFromTaggedObject","credentialFromError","tokenResponse","oauthAccessToken","GoogleAuthProvider","GOOGLE_SIGN_IN_METHOD","oauthIdToken","GithubAuthProvider","GITHUB_SIGN_IN_METHOD","TwitterAuthProvider","TWITTER_SIGN_IN_METHOD","signUp","UserCredentialImpl","operationType","providerIdForResponse","_forOperation","MultiFactorError","_fromErrorAndOperation","_processCredentialSavingMfaContextIfNecessary","_link$1","bypassAuthState","_reauthenticate","parsed","sub","_signInWithCredential","recachePasswordPolicy","STORAGE_AVAILABLE_KEY","BrowserPersistenceClass","storageRetriever","setItem","removeItem","getItem","BrowserLocalPersistence","localStorage","poll","onStorageEvent","localCache","pollTimer","safariLocalStorageNotSynced","_iframeCannotSyncWebStorage","_isIframe","fallbackToPolling","forAllChangedKeys","_oldValue","notifyListeners","detachListener","stopPolling","storedValue","triggerListeners","startPolling","setInterval","StorageEvent","clearInterval","attachListener","browserLocalPersistence","BrowserSessionPersistence","sessionStorage","browserSessionPersistence","Receiver","eventTarget","handlersMap","handleEvent","receivers","isListeningto","newInstance","messageEvent","eventId","eventType","handlers","ports","handler","origin","fulfilled","_allSettled","_subscribe","eventHandler","_unsubscribe","_generateEventId","digits","Sender","removeMessageHandler","messageChannel","onMessage","_send","completionTimer","ackTimer","finally","_window","_isWorker","DB_OBJECTSTORE_NAME","DB_DATA_KEYPATH","DBPromise","toPromise","getObjectStore","isReadWrite","_openDatabase","keyPath","_deleteDatabase","_putObject","_deleteObject","IndexedDBLocalPersistence","pendingWrites","sender","serviceWorkerReceiverAvailable","activeServiceWorker","_workerInitializationPromise","initializeServiceWorkerMessaging","_openDb","_withRetries","op","numAttempts","initializeReceiver","initializeSender","_origin","keyProcessed","_poll","_data","serviceWorker","active","_getActiveServiceWorker","results","notifyServiceWorker","controller","_getServiceWorkerController","_withPendingWrite","write","getObject","getAllRequest","getAll","keysInResult","fbase_key","localKey","indexedDBLocalPersistence","RECAPTCHA_VERIFIER_TYPE","_verifyPhoneNumber","recaptchaToken","phoneInfoOptions","session","startEnrollPhoneMfa","phoneEnrollmentInfo","phoneSessionInfo","mfaEnrollmentId","multiFactorHint","multiFactorUid","startSignInPhoneMfa","mfaPendingCredential","phoneSignInInfo","phoneResponseInfo","sendPhoneVerificationCode","_reset","PhoneAuthProvider","verifyPhoneNumber","phoneOptions","applicationVerifier","_ref12","_withDefaultResolver","resolverOverride","PHONE_SIGN_IN_METHOD","IdpCredential","_buildIdpRequest","sessionId","returnIdpCredential","_signIn","_reauth","_link","AbstractPopupRedirectOperation","pendingPromise","eventManager","onExecution","registerConsumer","onAuthEvent","urlResponse","getIdpTask","unregisterAndCleanUp","unregisterConsumer","cleanUp","_POLL_WINDOW_CLOSE_TIMEOUT","PopupOperation","authWindow","pollId","currentPopupAction","cancel","executeNotNull","_openPopup","associatedEvent","_originValidation","_isIframeWebStorageSupported","isSupported","pollUserCancellation","closed","PENDING_REDIRECT_KEY","redirectOutcomeMap","RedirectAction","readyOutcome","hasPendingRedirect","pendingRedirectKey","resolverPersistence","_getAndClearPendingRedirectStatus","_getRedirectResult","resolverExtern","AuthEventManager","cachedEventUids","consumers","queuedRedirectEvent","hasHandledPotentialRedirect","lastProcessedEventTime","authEventConsumer","isEventForConsumer","sendToConsumer","saveEventToCache","onEvent","hasEventBeenHandled","handled","consumer","isNullRedirectEvent","isRedirectEvent","eventIdMatches","clear","eventUid","_ref13","IP_ADDRESS_REGEX","HTTP_REGEX","_validateOrigin","authorizedDomains","_getProjectConfig","domain","matchDomain","expected","currentUrl","hostname","URL","ceUrl","escapedDomainPattern","RegExp","NETWORK_TIMEOUT","resetUnloadedGapiModules","beacon","___jsl","hint","CP","cachedGApiLoader","_loadGapi","loadGapiIframe","gapi","load","iframes","getContext","ontimeout","Iframe","cbName","loadGapi","PING_TIMEOUT","IFRAME_PATH","EMULATED_IFRAME_PATH","IFRAME_ATTRIBUTES","tabindex","EID_FROM_APIHOST","getIframeUrl","eid","fw","BASE_POPUP_OPTIONS","resizable","statusbar","toolbar","AuthPopup","_open","screen","availHeight","availWidth","scrollbars","optionsString","accum","_ref14","standalone","_isIOSStandalone","click","createEvent","initMouseEvent","openAsNewWindowIOS","newWin","WIDGET_PATH","EMULATOR_WIDGET_PATH","FIREBASE_APP_CHECK_FRAGMENT_ID","_getRedirectUrl","authType","redirectUrl","additionalParams","isEmpty","tid","paramsDict","appCheckTokenFragment","_ref15","getHandlerBase","WEB_STORAGE_SUPPORT_KEY","browserPopupRedirectResolver","eventManagers","originValidationPromises","_openRedirect","_setWindowLocation","initAndGetManager","iframe","where","messageHandlersFilter","CROSS_ORIGIN_IFRAMES_FILTER","attributes","dontclear","restyle","setHideOnLeave","networkError","networkErrorTimer","clearTimerAndResolve","ping","_openIframe","register","iframeEvent","authEvent","send","AuthInterop","internalListeners","getUid","assertAuthConfigured","addAuthTokenListener","updateProactiveRefresh","removeAuthTokenListener","authIdTokenMaxAge","lastPostedIdToken","_ref16","hierarchy","_initializeAuthInstance","_instanceIdentifier","_instance","getVersionForPlatform","goog","commonjsGlobal","$","parseFloat","parseInt","once","addListener","removeListener","reset","initializeRunner","module$contents$goog$async$run_run.processWorkQueue","ga","STAT_EVENT","stat","NO_ERROR","TIMEOUT","OPEN","XMLHttpRequest","getResponseHeader","TextDecoder","decode","stream","getAllResponseHeaders","abs","decodeURI","encodeURI","PerformanceNavigationTiming","getEntriesByType","nextHopProtocol","onabort","responseType","responseText","statusText","onreadystatechange","credentials","Request","arrayBuffer","ReadableStream","getReader","setRequestHeader","mozResponseArrayBuffer","Cd","internalChannelParams","Ed","xmlHttpFactory","useFetchStreams","supportsCrossDomainXhr","concurrentRequestLimit","fastHandshake","encodeInitMessageHeaders","forceLongPolling","detectBufferingProxy","longPollingTimeout","Gd","sendBeacon","Image","Kd","isActive","messageUrlParams","messageHeaders","clientProtocolHeaderRequired","initMessageHeaders","messageContentType","sendRawJson","httpSessionIdParam","__headers__","statusCode","__status__","__sm__","blockSize","Sd","FormData","withCredentials","__data__","isFinite","Ud","Wd","and","or","xor","createWebChannel","HTTP_ERROR","COMPLETE","EventType","CLOSE","MESSAGE","listen","listenOnce","getLastError","getLastErrorCode","getStatus","getResponseJson","getResponseText","setWithCredentials","multiply","modulo","toNumber","getBits","fromNumber","fromString","createWebChannelTransport","esm","getStatEventTarget","ErrorCode","Event","Stat","PROXY","NOPROXY","FetchXmlHttpFactory","WebChannel","XhrIo","Md5","Integer","User","isAuthenticated","toKey","isEqual","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","__PRIVATE_getLogLevel","__PRIVATE_logDebug","__PRIVATE_argToString","__PRIVATE_logError","__PRIVATE_logWarn","fail","__PRIVATE_hardAssert","__PRIVATE_debugCast","OK","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","UNAVAILABLE","DATA_LOSS","FirestoreError","__PRIVATE_Deferred","__PRIVATE_OAuthToken","__PRIVATE_EmptyAuthCredentialsProvider","invalidateToken","enqueueRetryable","shutdown","__PRIVATE_EmulatorAuthCredentialsProvider","changeListener","__PRIVATE_FirebaseAuthCredentialsProvider","__PRIVATE_guardedChangeListener","__PRIVATE_awaitNextToken","__PRIVATE_registerAuth","__PRIVATE_FirstPartyToken","__PRIVATE_FirstPartyAuthCredentialsProvider","AppCheckToken","__PRIVATE_FirebaseAppCheckTokenProvider","appCheck","onTokenChanged","__PRIVATE_registerAppCheck","addTokenListener","removeTokenListener","__PRIVATE_randomBytes","__PRIVATE_AutoId","newId","__PRIVATE_primitiveComparator","__PRIVATE_arrayEquals","every","Timestamp","nanoseconds","fromMillis","fromDate","toDate","toMillis","_compareTo","padStart","SnapshotVersion","timestamp","fromTimestamp","compareTo","toMicroseconds","toTimestamp","BasePath","segments","len","comparator","limit","popFirst","popLast","firstSegment","lastSegment","isPrefixOf","isImmediateParentOf","ResourcePath","canonicalString","emptyPath","FieldPath$1","isValidIdentifier","isKeyField","keyField","fromServerFormat","__PRIVATE_addCurrentSegment","DocumentKey","fromPath","fromName","empty","collectionGroup","hasCollectionId","getCollectionGroup","getCollectionPath","isDocumentKey","fromSegments","FieldIndex","indexId","fields","indexState","UNKNOWN_ID","__PRIVATE_newIndexOffsetSuccessorFromReadTime","IndexOffset","__PRIVATE_newIndexOffsetFromDocument","readTime","documentKey","largestBatchId","__PRIVATE_indexOffsetComparator","PersistenceTransaction","onCommittedListeners","addOnCommittedListener","raiseOnCommittedEvent","__PRIVATE_ignoreIfPrimaryLeaseLoss","PersistencePromise","nextCallback","catchCallback","isDone","callbackAttached","wrapFailure","wrapSuccess","wrapUserFunction","waitFor","mapArray","doWhile","__PRIVATE_isIndexedDbTransactionError","__PRIVATE_ListenSequence","previousValue","sequenceNumberHandler","writeSequenceNumber","__PRIVATE_isNullOrUndefined","__PRIVATE_isNegativeZero","isSafeInteger","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","__PRIVATE_objectSize","SortedMap","root","LLRBNode","EMPTY","insert","copy","BLACK","right","minKey","maxKey","inorderTraversal","reverseTraversal","getIterator","SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","isReverse","nodeStack","getNext","hasNext","peek","RED","fixUp","removeMin","isRed","moveRedLeft","rotateRight","moveRedRight","rotateLeft","colorFlip","checkMaxDepth","check","SortedSet","first","forEachInRange","forEachWhile","firstAfterOrEqual","SortedSetIterator","unionWith","iter","FieldMask","covers","__PRIVATE_Base64DecodeError","ByteString","binaryString","fromBase64String","fromUint8Array","toBase64","toUint8Array","approximateByteSize","EMPTY_BYTE_STRING","__PRIVATE_normalizeTimestamp","nanos","__PRIVATE_normalizeNumber","__PRIVATE_normalizeByteString","__PRIVATE_isServerTimestamp","mapValue","__type__","stringValue","__PRIVATE_getPreviousValue","__previous_value__","__PRIVATE_getLocalWriteTime","__local_write_time__","timestampValue","DatabaseInfo","databaseId","persistenceKey","ssl","autoDetectLongPolling","longPollingOptions","DatabaseId","database","isDefaultDatabase","__PRIVATE_typeOrder","__PRIVATE_isMaxValue","__PRIVATE_valueEquals","booleanValue","bytesValue","referenceValue","geoPointValue","latitude","longitude","integerValue","doubleValue","arrayValue","__PRIVATE_arrayValueContains","__PRIVATE_valueCompare","__PRIVATE_compareTimestamps","canonicalId","__PRIVATE_canonifyValue","__PRIVATE_refValue","__PRIVATE_isNullValue","__PRIVATE_isNanValue","__PRIVATE_isMapValue","__PRIVATE_deepClone","ObjectValue","field","getFieldsMap","setAll","applyChanges","clone","__PRIVATE_extractFieldMask","MutableDocument","documentType","createTime","documentState","newInvalidDocument","newFoundDocument","newNoDocument","newUnknownDocument","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","Bound","inclusive","__PRIVATE_boundCompareToDocument","dir","__PRIVATE_boundEquals","OrderBy","__PRIVATE_orderByEquals","Filter","FieldFilter","createKeyFieldInFilter","__PRIVATE_KeyFieldFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","__PRIVATE_NotInFilter","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_KeyFieldInFilter","__PRIVATE_KeyFieldNotInFilter","matchesComparison","isInequality","getFlattenedFilters","getFilters","CompositeFilter","filters","__PRIVATE_compositeFilterIsConjunction","__PRIVATE_compositeFilterIsFlatConjunction","__PRIVATE_compositeFilterIsFlat","__PRIVATE_canonifyFilter","__PRIVATE_filterEquals","__PRIVATE_stringifyFilter","__PRIVATE_extractDocumentKeysFromArrayValue","nullValue","__PRIVATE_TargetImpl","orderBy","startAt","endAt","__PRIVATE_newTarget","__PRIVATE_canonifyTarget","__PRIVATE_targetEquals","__PRIVATE_targetIsDocumentTarget","__PRIVATE_QueryImpl","explicitOrderBy","limitType","__PRIVATE_newQuery","__PRIVATE_newQueryForPath","__PRIVATE_queryMatchesAllDocuments","__PRIVATE_isCollectionGroupQuery","__PRIVATE_queryNormalizedOrderBy","__PRIVATE_queryToTarget","__PRIVATE__queryToTarget","__PRIVATE_queryWithAddedFilter","__PRIVATE_queryWithLimit","__PRIVATE_queryEquals","__PRIVATE_canonifyQuery","__PRIVATE_stringifyQuery","__PRIVATE_queryMatches","__PRIVATE_queryCollectionGroup","__PRIVATE_newQueryComparator","__PRIVATE_compareDocs","ObjectMap","mapKeyFn","equalsFn","inner","innerSize","__PRIVATE_mutableDocumentMap","documentMap","__PRIVATE_convertOverlayedDocumentMapToDocumentMap","overlayedDocument","__PRIVATE_newOverlayMap","__PRIVATE_newDocumentKeyMap","__PRIVATE_newMutationMap","__PRIVATE_documentKeySet","__PRIVATE_targetIdSet","__PRIVATE_toDouble","useProto3Json","__PRIVATE_toInteger","TransformOperation","__PRIVATE_applyTransformOperationToLocalView","__PRIVATE_ServerTimestampTransform","__PRIVATE_ArrayUnionTransformOperation","__PRIVATE_applyArrayUnionTransformOperation","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_applyArrayRemoveTransformOperation","__PRIVATE_computeTransformOperationBaseValue","asNumber","serializer","__PRIVATE_applyTransformOperationToRemoteDocument","__PRIVATE_NumericIncrementTransformOperation","elements","__PRIVATE_coercedFieldValuesArray","MutationResult","transformResults","Precondition","updateTime","exists","none","isNone","__PRIVATE_preconditionIsValidForDocument","Mutation","__PRIVATE_calculateOverlayMutation","__PRIVATE_DeleteMutation","__PRIVATE_SetMutation","__PRIVATE_PatchMutation","__PRIVATE_mutationApplyToRemoteDocument","__PRIVATE_serverTransformResults","fieldTransforms","precondition","__PRIVATE_getPatch","__PRIVATE_mutationApplyToLocalView","__PRIVATE_localTransformResults","fieldMask","__PRIVATE_mutationExtractBaseValue","transform","__PRIVATE_mutationEquals","__PRIVATE_fieldTransformEquals","getFieldMask","__PRIVATE_VerifyMutation","MutationBatch","batchId","localWriteTime","baseMutations","mutations","applyToRemoteDocument","mutationResults","applyToLocalView","applyToLocalDocumentSet","mutatedFields","MutationBatchResult","batch","commitVersion","docVersions","Overlay","mutation","ExistenceFilter","unchangedNames","__PRIVATE_isPermanentError","__PRIVATE_mapCodeFromRpcCode","__PRIVATE_newTextEncoder","TextEncoder","__PRIVATE_getMd5HashValue","__PRIVATE_get64BitUints","DataView","buffer","getUint32","BloomFilter","bitmap","padding","hashCount","__PRIVATE_BloomFilterError","mightContain","RemoteEvent","snapshotVersion","targetChanges","targetMismatches","documentUpdates","resolvedLimboDocuments","createSynthesizedRemoteEventForCurrentChange","TargetChange","createSynthesizedTargetChangeForCurrentChange","resumeToken","addedDocuments","modifiedDocuments","removedDocuments","__PRIVATE_DocumentWatchChange","removedTargetIds","__PRIVATE_ExistenceFilterChange","targetId","__PRIVATE_WatchTargetChange","targetIds","cause","__PRIVATE_TargetState","__PRIVATE_snapshotChangesMap","__PRIVATE_WatchChangeAggregator","__PRIVATE_documentTargetMap","Ge","forEachTarget","removeTarget","et","tt","localCacheCount","existenceFilterCount","bloomFilter","applied","bitmapLength","bits","nt","rt","getRemoteKeysForTarget","it","st","purpose","ot","_t","asc","desc","in","JsonProtoSerializer","__PRIVATE_toInt32Proto","__PRIVATE_toBytes","__PRIVATE_toVersion","__PRIVATE_fromVersion","__PRIVATE_toResourceName","__PRIVATE_fromResourceName","__PRIVATE_isValidResourceName","__PRIVATE_toName","__PRIVATE_extractLocalPathFromResourceName","__PRIVATE_toQueryPath","__PRIVATE_fromQueryPath","__PRIVATE_getEncodedDatabaseId","__PRIVATE_toMutationDocument","toMutation","updateMask","__PRIVATE_toDocumentMask","updateTransforms","fieldPath","setToServerValue","appendMissingElements","removeAllFromArray","increment","currentDocument","__PRIVATE_toDocumentsTarget","documents","__PRIVATE_toQueryTarget","structuredQuery","parent","collectionId","allDescendants","__PRIVATE_toFilter","__PRIVATE_toFieldPathReference","direction","__PRIVATE_toDirection","before","__PRIVATE_convertQueryTargetToQuery","__PRIVATE_fromFilter","__PRIVATE_fromFieldPathReference","unaryFilter","NaN","fieldFilter","compositeFilter","__PRIVATE_toOperatorName","__PRIVATE_toCompositeOperatorName","fieldPaths","TargetData","sequenceNumber","lastLimboFreeSnapshotVersion","expectedCount","withSequenceNumber","withResumeToken","withExpectedCount","withLastLimboFreeSnapshotVersion","__PRIVATE_LocalSerializer","ut","__PRIVATE_fromBundledQuery","__PRIVATE_FirestoreIndexValueWriter","ht","Pt","It","Tt","Et","dt","At","Rt","Vt","ft","gt","yt","wt","St","__PRIVATE_MemoryIndexManager","on","__PRIVATE_MemoryCollectionParentIndex","addToCollectionParentIndex","getCollectionParents","getEntries","addFieldIndex","deleteFieldIndex","deleteAllFieldIndexes","createTargetIndexes","getDocumentsMatchingTarget","getIndexType","getFieldIndexes","getNextCollectionGroupToUpdate","getMinOffset","getMinOffsetFromCollectionGroup","updateCollectionGroup","updateIndexEntries","LruParams","cacheSizeCollectionThreshold","percentileToCollect","maximumSequenceNumbersToCollect","withCacheSize","DEFAULT_COLLECTION_PERCENTILE","DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT","DEFAULT","DISABLED","__PRIVATE_TargetIdGenerator","xn","On","Nn","RemoteDocumentChangeBuffer","changes","changesApplied","addEntry","assertNotApplied","removeEntry","getEntry","getFromCache","getAllFromCache","OverlayedDocument","LocalDocumentsView","remoteDocumentCache","mutationQueue","documentOverlayCache","indexManager","getDocument","getOverlay","getDocuments","getLocalViewOfDocuments","populateOverlays","computeViews","getOverlayedDocuments","getOverlays","recalculateAndSaveOverlays","getAllMutationBatchesAffectingDocumentKeys","saveOverlays","recalculateAndSaveOverlaysForDocumentKeys","getDocumentsMatchingQuery","getDocumentsMatchingDocumentQuery","getDocumentsMatchingCollectionGroupQuery","getDocumentsMatchingCollectionQuery","getNextDocuments","getAllFromCollectionGroup","getOverlaysForCollectionGroup","getOverlaysForCollection","__PRIVATE_MemoryBundleCache","ur","cr","getBundleMetadata","saveBundleMetadata","getNamedQuery","saveNamedQuery","bundledQuery","__PRIVATE_MemoryDocumentOverlayCache","overlays","lr","lt","removeOverlaysForBatchId","__PRIVATE_ReferenceSet","__PRIVATE_DocReference","Pr","Ir","Tr","addReference","Er","removeReference","dr","Ar","Rr","Vr","mr","containsKey","gr","__PRIVATE_MemoryMutationQueue","referenceDelegate","pr","yr","checkEmpty","addMutationBatch","lookupMutationBatch","wr","getNextMutationBatchAfterBatchId","Sr","getHighestUnacknowledgedBatchId","getAllMutationBatches","getAllMutationBatchesAffectingDocumentKey","POSITIVE_INFINITY","getAllMutationBatchesAffectingQuery","removeMutationBatch","Dr","markPotentiallyOrphaned","Fn","performConsistencyCheck","__PRIVATE_MemoryRemoteDocumentCacheImpl","Cr","docs","setIndexManager","vr","newChangeBuffer","__PRIVATE_MemoryRemoteDocumentChangeBuffer","getSize","_r","__PRIVATE_MemoryTargetCache","Fr","lastRemoteSnapshotVersion","highestTargetId","Mr","Or","targetCount","Nr","getLastRemoteSnapshotVersion","getHighestSequenceNumber","allocateTargetId","setTargetsMetadata","kn","addTargetData","updateTargetData","removeTargetData","removeTargets","removeMatchingKeysForTargetId","getTargetCount","getTargetData","addMatchingKeys","removeMatchingKeys","getMatchingKeysForTargetId","__PRIVATE_MemoryPersistence","Br","Lr","kr","qr","Qr","Kr","started","setDatabaseDeletedListener","setNetworkEnabled","getIndexManager","getDocumentOverlayCache","getMutationQueue","getTargetCache","getRemoteDocumentCache","getBundleCache","runTransaction","__PRIVATE_MemoryTransaction","$r","Ur","Wr","currentSequenceNumber","__PRIVATE_MemoryEagerDelegate","Gr","zr","jr","Hr","Jr","updateLimboDocument","__PRIVATE_LocalViewChanges","fromCache","docChanges","doc","QueryContext","_documentReadCount","documentReadCount","incrementDocumentReadCount","__PRIVATE_QueryEngine","__PRIVATE_LocalStoreImpl","es","ts","rs","ss","os","localDocuments","collectGarbage","collect","__PRIVATE_newLocalStore","__PRIVATE_localStoreHandleUserChange","_s","removedBatchIds","addedBatchIds","__PRIVATE_localStoreGetLastRemoteSnapshotVersion","__PRIVATE_populateDocumentChangeBuffer","us","cs","__PRIVATE_localStoreGetNextMutationBatch","__PRIVATE_localStoreAllocateTarget","__PRIVATE_localStoreReleaseTarget","__PRIVATE_localStoreExecuteQuery","__PRIVATE_setMaxReadTime","ls","__PRIVATE_LocalClientState","activeTargetIds","ds","As","Es","updateTimeMs","__PRIVATE_MemorySharedClientState","eo","no","onlineStateHandler","addPendingMutation","updateMutationState","addLocalQueryTarget","updateQueryState","removeLocalQueryTarget","isLocalQueryTarget","clearQueryState","getAllActiveQueryTargets","isActiveQueryTarget","handleUserChange","setOnlineState","notifyBundleLoaded","__PRIVATE_NoopConnectivityMonitor","ro","__PRIVATE_BrowserConnectivityMonitor","io","so","oo","_o","ao","uo","__PRIVATE_generateUniqueDebugId","BatchGetDocuments","Commit","RunQuery","RunAggregationQuery","__PRIVATE_StreamBridge","co","lo","ho","Po","Io","To","Eo","Ao","Ro","Vo","__PRIVATE_WebChannelConnection","databaseInfo","mo","fo","po","yo","wo","So","bo","Do","Co","vo","forwardChannelRequestTimeoutMs","timeoutSeconds","__PRIVATE_closeFn","__PRIVATE_unguardedEventListen","__PRIVATE_newSerializer","__PRIVATE_ExponentialBackoff","Fo","Mo","xo","Oo","No","Bo","Lo","ko","qo","enqueueAfterDelay","Qo","skipDelay","__PRIVATE_PersistentStream","Ko","$o","connection","authCredentialsProvider","appCheckCredentialsProvider","Uo","Wo","Go","zo","jo","Ho","Jo","stop","Yo","Zo","Xo","e_","t_","n_","r_","i_","_ref9","s_","o_","__","enqueueAndForget","__PRIVATE_PersistentListenStream","targetChange","targetChangeType","documentChange","documentDelete","documentRemove","__PRIVATE_fromWatchChange","a_","u_","addTarget","__PRIVATE_toListenRequestLabels","labels","c_","__PRIVATE_PersistentWriteStream","l_","h_","lastStreamToken","P_","streamToken","__PRIVATE_fromWriteResults","writeResults","commitTime","I_","T_","E_","writes","__PRIVATE_DatastoreImpl","authCredentials","appCheckCredentials","d_","A_","_ref10","_ref11","terminate","__PRIVATE_OnlineStateTracker","asyncQueue","V_","m_","f_","g_","p_","y_","w_","S_","__PRIVATE_RemoteStoreImpl","localStore","datastore","remoteSyncer","b_","D_","C_","v_","F_","__PRIVATE_canUseNetwork","__PRIVATE_disableNetworkInternal","M_","__PRIVATE_enableNetworkInternal","__PRIVATE_remoteStoreListen","__PRIVATE_shouldStartWatchStream","__PRIVATE_startWatchStream","__PRIVATE_ensureWatchStream","__PRIVATE_sendWatchRequest","__PRIVATE_remoteStoreUnlisten","__PRIVATE_sendUnwatchRequest","x_","__PRIVATE_getDatabaseId","__PRIVATE_cleanUpWatchStreamState","__PRIVATE_onWatchStreamOpen","__PRIVATE_onWatchStreamClose","__PRIVATE_onWatchStreamChange","rejectListen","__PRIVATE_disableNetworkUntilRecovery","applyRemoteEvent","__PRIVATE_executeWithRecovery","__PRIVATE_fillWritePipeline","__PRIVATE_ensureWriteStream","__PRIVATE_canAddToWritePipeline","__PRIVATE_addToWritePipeline","__PRIVATE_shouldStartWriteStream","__PRIVATE_startWriteStream","__PRIVATE_onWriteStreamOpen","__PRIVATE_onWriteHandshakeComplete","__PRIVATE_onMutationResult","applySuccessfulWrite","__PRIVATE_onWriteStreamClose","rejectFailedWrite","__PRIVATE_remoteStoreHandleCredentialChange","verifyOperationInProgress","handleCredentialChange","__PRIVATE_remoteStoreApplyPrimaryState","O_","N_","DelayedOperation","targetTimeMs","removalCallback","createAndSchedule","timerHandle","handleDelayElapsed","__PRIVATE_wrapInUserErrorIfRecoverable","DocumentSet","keyedMap","sortedSet","emptySet","__PRIVATE_DocumentChangeSet","B_","L_","ViewSnapshot","oldDocs","mutatedKeys","syncStateChanged","excludesMetadataChanges","hasCachedResults","fromInitialDocuments","__PRIVATE_QueryListenersInfo","k_","__PRIVATE_EventManagerImpl","queries","onlineState","q_","__PRIVATE_eventManagerListen","onListen","Q_","K_","__PRIVATE_raiseSnapshotsInSyncEvent","__PRIVATE_eventManagerUnlisten","onUnlisten","__PRIVATE_eventManagerOnWatchChange","__PRIVATE_eventManagerOnWatchError","__PRIVATE_QueryListener","U_","W_","G_","includeMetadataChanges","z_","j_","H_","J_","__PRIVATE_AddedLimboDocument","__PRIVATE_RemovedLimboDocument","__PRIVATE_View","snapshot","__PRIVATE_QueryView","LimboResolution","__PRIVATE_SyncEngineImpl","remoteStore","sharedClientState","maxConcurrentLimboResolutions","isPrimaryClient","__PRIVATE_syncEngineListen","__PRIVATE_ensureWatchCallbacks","__PRIVATE_initializeViewAndComputeSnapshot","__PRIVATE_updateTrackedLimbos","__PRIVATE_syncEngineUnlisten","__PRIVATE_removeAndCleanupTarget","__PRIVATE_syncEngineApplyRemoteEvent","trackRemovals","__PRIVATE_localStoreApplyRemoteEventToLocalCache","__PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore","__PRIVATE_syncEngineApplyOnlineStateChange","__PRIVATE_syncEngineRejectListen","__PRIVATE_pumpEnqueuedLimboResolutions","__PRIVATE_syncEngineApplySuccessfulWrite","__PRIVATE_localStoreAcknowledgeBatch","__PRIVATE_processUserCallback","__PRIVATE_triggerPendingWritesCallbacks","__PRIVATE_syncEngineRejectFailedWrite","__PRIVATE_removeLimboTarget","__PRIVATE_trackLimboChange","__PRIVATE_syncEngineHandleCredentialChange","__PRIVATE_syncEngineGetRemoteKeysForTarget","__PRIVATE_syncEngineEnsureWriteCallbacks","MemoryOfflineComponentProvider","synchronizeTabs","createSharedClientState","createPersistence","createLocalStore","gcScheduler","createGarbageCollectionScheduler","indexBackfillerScheduler","createIndexBackfillerScheduler","initialUser","OnlineComponentProvider","createDatastore","createRemoteStore","createEventManager","syncEngine","createSyncEngine","__PRIVATE_AsyncObserver","muted","FirestoreClient","clientId","authCredentialListener","appCheckCredentialListener","getConfiguration","setCredentialChangeListener","setAppCheckTokenChangeListener","verifyNotTerminated","isShuttingDown","enterRestrictedMode","enqueueAndForgetEvenWhileRestricted","_onlineComponents","_offlineComponents","__PRIVATE_setOfflineComponentProvider","__PRIVATE_setOnlineComponentProvider","__PRIVATE_ensureOfflineComponents","__PRIVATE_canFallbackFromIndexedDbError","_uninitializedComponentsProvider","_offline","__PRIVATE_ensureOnlineComponents","_online","__PRIVATE_getSyncEngine","__PRIVATE_getEventManager","__PRIVATE_firestoreClientGetDocumentsViaSnapshotListener","__PRIVATE_cloneLongPollingOptions","__PRIVATE_validateNonEmptyArgument","__PRIVATE_validateDocumentPath","__PRIVATE_validateCollectionPath","__PRIVATE_valueDescription","__PRIVATE_cast","FirestoreSettingsImpl","ignoreUndefinedProperties","cacheSizeBytes","__PRIVATE_validateIsNotUsedTogether","experimentalForceLongPolling","experimentalAutoDetectLongPolling","experimentalLongPollingOptions","Firestore$1","_authCredentials","_appCheckCredentials","_databaseId","_app","_persistenceKey","_settings","_settingsFrozen","_initialized","_terminated","_terminateTask","_setSettings","sessionIndex","iamToken","authTokenFactory","client","_getSettings","_freezeSettings","_terminate","connectFirestoreEmulator","mockUserToken","project","user_id","iss","aud","sign_in_provider","identities","alg","createMockUserToken","Query","converter","_query","firestore","withConverter","DocumentReference","_path","CollectionReference","collection","_len7","__PRIVATE_AsyncQueueImpl","eu","tu","nu","ru","iu","visibilityState","enqueue","su","ou","_u","au","uu","cu","lu","hu","Firestore","_queue","_firestoreClient","__PRIVATE_configureFirestore","ensureFirestoreConfigured","_offlineComponentProvider","_onlineComponentProvider","_offlineKind","kind","Bytes","_byteString","FieldPath","_len9","_key9","_internalPath","FieldValue","_methodName","GeoPoint","_lat","_long","ParsedSetData","__PRIVATE_isWrite","__PRIVATE_ParseContextImpl","Pu","Iu","Tu","Eu","du","Au","Ru","Vu","mu","__PRIVATE_createError","methodName","fu","gu","__PRIVATE_UserDataReader","pu","__PRIVATE_newUserDataReader","__PRIVATE_parseSetData","merge","mergeFields","__PRIVATE_validatePlainObject","__PRIVATE_parseObject","__PRIVATE_fieldPathFromArgument$1","__PRIVATE_fieldMaskContains","__PRIVATE_parseQueryValue","__PRIVATE_parseData","__PRIVATE_looksLikeJsonObject","_toFieldTransform","__PRIVATE_fieldPathFromDotSeparatedString","DocumentSnapshot$1","_firestore","_userDataWriter","_document","_converter","QueryDocumentSnapshot$1","fromFirestore","convertValue","__PRIVATE_fieldPathFromArgument","__PRIVATE_validateHasExplicitOrderByForLimitToLast","AppliableConstraint","QueryConstraint","_len10","_key10","QueryCompositeFilterConstraint","QueryFieldFilterConstraint","_apply","_field","_op","_value","_create","_parse","__PRIVATE_validateNewFieldFilter","__PRIVATE_validateDisjunctiveFilterElements","__PRIVATE_parseDocumentIdValue","_queryConstraints","_getOperator","_getQueryConstraints","AbstractUserDataWriter","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertObjectMap","convertDocumentKey","__PRIVATE_applyFirestoreDataConverter","toFirestore","SnapshotMetadata","DocumentSnapshot","_firestoreImpl","QueryDocumentSnapshot","serverTimestamps","QuerySnapshot","_snapshot","_cachedChanges","_cachedChangesIncludeMetadataChanges","oldIndex","newIndex","__PRIVATE_resultChangeType","__PRIVATE_ExpUserDataWriter","getDocs","addDoc","_len8","_key8","executeWrite","__PRIVATE_syncEngineWrite","storageBucket","messagingSenderId","analyticsProvider","initializeAnalytics","getAnalytics","initializeAuth","authTokenSyncUrl","mintCookie","idTokenResult","idTokenAge","authEmulatorHost","getAuth","separatorIndex","lastIndexOf","getDefaultEmulatorHostnameAndPort","getFirestore","Action","PopStateEventType","invariant","cond","getHistoryState","usr","idx","createLocation","to","_extends","pathname","hash","parsePath","createPath","parsedPath","hashIndex","searchIndex","getUrlBasedHistory","getLocation","createHref","validateLocation","v5Compat","globalHistory","history","Pop","getIndex","handlePop","nextIndex","delta","createURL","replaceState","encodeLocation","Push","historyState","pushState","Replace","go","ResultType","matchRoutes","routes","locationArg","basename","stripBasename","branches","flattenRoutes","score","siblings","compareIndexes","routesMeta","childrenIndex","rankRouteBranches","matchRouteBranch","safelyDecodeURI","parentsMeta","parentPath","flattenRoute","route","relativePath","caseSensitive","joinPaths","computeScore","_route$path","exploded","explodeOptionalSegments","isOptional","endsWith","required","restExploded","subpath","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","initialScore","segment","branch","matchedParams","matchedPathname","remainingPathname","matchPath","pathnameBase","normalizePathname","pattern","matcher","compiledParams","regexpSource","paramName","compilePath","captureGroups","splatValue","safelyDecodeURIComponent","startIndex","nextChar","getInvalidPathError","dest","getPathContributingMatches","getResolveToMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","isEmptyPath","toPathname","toSegments","routePathnameIndex","fromPathname","resolvePathname","normalizeSearch","normalizeHash","resolvePath","hasExplicitTrailingSlash","hasCurrentTrailingSlash","paths","isRouteErrorResponse","internal","validMutationMethodsArr","validRequestMethodsArr","DataRouterContext","React","DataRouterStateContext","NavigationContext","LocationContext","RouteContext","outlet","isDataRoute","RouteErrorContext","useInRouterContext","useLocation","UNSAFE_invariant","useIsomorphicLayoutEffect","static","useNavigate","router","useDataRouterContext","DataRouterHook","UseNavigateStable","useCurrentRouteId","DataRouterStateHook","activeRef","navigate","fromRouteId","useNavigateStable","dataRouterContext","routePathnamesJson","UNSAFE_getResolveToMatches","relative","useNavigateUnstable","useResolvedPath","_temp2","useRoutesImpl","dataRouterState","parentMatches","routeMatch","parentParams","parentPathnameBase","locationFromContext","_parsedLocationArg$pa","parsedLocationArg","renderedMatches","_renderMatches","navigationType","DefaultErrorComponent","_state$errors","useDataRouterState","UseRouteError","routeId","useRouteError","lightgrey","preStyles","fontStyle","defaultErrorElement","RenderErrorBoundary","revalidation","routeContext","RenderedRoute","staticContext","errorElement","ErrorBoundary","_deepestRenderedBoundaryId","_dataRouterState2","_dataRouterState","errorIndex","findIndex","reduceRight","getChildren","hookName","ctx","useRouteContext","thisRoute","Route","_props","Router","basenameProp","locationProp","staticProp","navigationContext","locationContext","trailingPathname","Routes","createRoutesFromChildren","treePath","loader","hasErrorBoundary","shouldRevalidate","handle","SignIn","_auth$currentUser","setEmail","setPassword","signInTransition","setSignInTransition","_jsxs","className","css","_jsx","placeholder","onChange","signUpResponse","createUserWithEmailAndPassword","toCreateAccount","CreateAccount","toSignIn","startTransitionImpl","ReactDOM","BrowserRouter","future","historyRef","setStateImpl","v7_startTransition","newState","isBrowser","ABSOLUTE_URL_REGEX","Link","absoluteHref","reloadDocument","preventScrollReset","unstable_viewTransition","_objectWithoutPropertiesLoose","_excluded","UNSAFE_NavigationContext","isExternal","targetUrl","_temp","joinedPathname","useHref","internalOnClick","replaceProp","isModifiedEvent","shouldProcessLinkClick","useLinkClickHandler","Header","NotFound","Welcome","signedIn","setSignedIn","_auth$currentUser2","currentUserEmail","accountNumber","setAccountNumber","phone","setPhone","setName","addFiendForm","onSubmit","addNewPlayers","disable","Players","setJson","displayPlayers","setDisplayPlayers","swapDisplayPlayers","friends","friend","AddFriend","newJson","prevJson","shareBet","friendsLabel","checkmark","CreateMoneyLine","bet","setBet","contestant1","setContestant1","contestant2","setContestant2","odds1","setOdds1","odds2","setOdds2","shareDisplay","setShareDisplay","handleShare","contestant1Odds","contestant2Odds","ShareBet","MoneyLine","CreateOverUnder","line","setLine","OverUnder","betContainer","setting","label","step","howMany","setHowMany","howManyOptions","setHowManyOptions","setOptions","option","addOptions","addOneMore","CreateProp","Options","isChecked","setIsChecked","handleCheckboxChange","htmlFor","PreSetBettingOptions","Prop","ViewMoneyLine","bets","setBets","querySnapshot","fetchBet","ViewOverUnder","betLabel","pad","section","lineLabel","actualLine","remain","ViewProp","setLength","swap","goToMoneyLine","goToOverUnder","goToProps","viewBet","DisplayAllBets","setDisplay","filteredData","getBets","swapDisplay","BetNav","DisplayBet","Friends","onPerfEntry","getCLS","getFID","getFCP","getLCP","getTTFB","getElementById","App","reportWebVitals"],"sourceRoot":""} \ No newline at end of file diff --git a/static/js/main.e9c9ba71.js b/static/js/main.fc2a7381.js similarity index 85% rename from static/js/main.e9c9ba71.js rename to static/js/main.fc2a7381.js index db454eb..e9583bd 100644 --- a/static/js/main.e9c9ba71.js +++ b/static/js/main.fc2a7381.js @@ -1,3 +1,3 @@ -/*! For license information please see main.e9c9ba71.js.LICENSE.txt */ -(()=>{"use strict";var e={463:(e,t,n)=>{var r=n(791),i=n(296);function s(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var a=new Set,o={};function l(e,t){c(e,t),c(e+"Capture",t)}function c(e,t){for(o[e]=t,e=0;e<t.length;e++)a.add(t[e])}var u=!("undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement),h=Object.prototype.hasOwnProperty,d=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,f={},p={};function m(e,t,n,r,i,s,a){this.acceptsBooleans=2===t||3===t||4===t,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=a}var g={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach((function(e){g[e]=new m(e,0,!1,e,null,!1,!1)})),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach((function(e){var t=e[0];g[t]=new m(t,1,!1,e[1],null,!1,!1)})),["contentEditable","draggable","spellCheck","value"].forEach((function(e){g[e]=new m(e,2,!1,e.toLowerCase(),null,!1,!1)})),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach((function(e){g[e]=new m(e,2,!1,e,null,!1,!1)})),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach((function(e){g[e]=new m(e,3,!1,e.toLowerCase(),null,!1,!1)})),["checked","multiple","muted","selected"].forEach((function(e){g[e]=new m(e,3,!0,e,null,!1,!1)})),["capture","download"].forEach((function(e){g[e]=new m(e,4,!1,e,null,!1,!1)})),["cols","rows","size","span"].forEach((function(e){g[e]=new m(e,6,!1,e,null,!1,!1)})),["rowSpan","start"].forEach((function(e){g[e]=new m(e,5,!1,e.toLowerCase(),null,!1,!1)}));var v=/[\-:]([a-z])/g;function y(e){return e[1].toUpperCase()}function w(e,t,n,r){var i=g.hasOwnProperty(t)?g[t]:null;(null!==i?0!==i.type:r||!(2<t.length)||"o"!==t[0]&&"O"!==t[0]||"n"!==t[1]&&"N"!==t[1])&&(function(e,t,n,r){if(null===t||"undefined"===typeof t||function(e,t,n,r){if(null!==n&&0===n.type)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return!r&&(null!==n?!n.acceptsBooleans:"data-"!==(e=e.toLowerCase().slice(0,5))&&"aria-"!==e);default:return!1}}(e,t,n,r))return!0;if(r)return!1;if(null!==n)switch(n.type){case 3:return!t;case 4:return!1===t;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}(t,n,i,r)&&(n=null),r||null===i?function(e){return!!h.call(p,e)||!h.call(f,e)&&(d.test(e)?p[e]=!0:(f[e]=!0,!1))}(t)&&(null===n?e.removeAttribute(t):e.setAttribute(t,""+n)):i.mustUseProperty?e[i.propertyName]=null===n?3!==i.type&&"":n:(t=i.attributeName,r=i.attributeNamespace,null===n?e.removeAttribute(t):(n=3===(i=i.type)||4===i&&!0===n?"":""+n,r?e.setAttributeNS(r,t,n):e.setAttribute(t,n))))}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach((function(e){var t=e.replace(v,y);g[t]=new m(t,1,!1,e,null,!1,!1)})),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach((function(e){var t=e.replace(v,y);g[t]=new m(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)})),["xml:base","xml:lang","xml:space"].forEach((function(e){var t=e.replace(v,y);g[t]=new m(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)})),["tabIndex","crossOrigin"].forEach((function(e){g[e]=new m(e,1,!1,e.toLowerCase(),null,!1,!1)})),g.xlinkHref=new m("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach((function(e){g[e]=new m(e,1,!1,e.toLowerCase(),null,!0,!0)}));var b=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,_=Symbol.for("react.element"),E=Symbol.for("react.portal"),S=Symbol.for("react.fragment"),k=Symbol.for("react.strict_mode"),I=Symbol.for("react.profiler"),T=Symbol.for("react.provider"),C=Symbol.for("react.context"),x=Symbol.for("react.forward_ref"),N=Symbol.for("react.suspense"),A=Symbol.for("react.suspense_list"),P=Symbol.for("react.memo"),R=Symbol.for("react.lazy");Symbol.for("react.scope"),Symbol.for("react.debug_trace_mode");var O=Symbol.for("react.offscreen");Symbol.for("react.legacy_hidden"),Symbol.for("react.cache"),Symbol.for("react.tracing_marker");var D=Symbol.iterator;function L(e){return null===e||"object"!==typeof e?null:"function"===typeof(e=D&&e[D]||e["@@iterator"])?e:null}var M,j=Object.assign;function F(e){if(void 0===M)try{throw Error()}catch(n){var t=n.stack.trim().match(/\n( *(at )?)/);M=t&&t[1]||""}return"\n"+M+e}var U=!1;function V(e,t){if(!e||U)return"";U=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),"object"===typeof Reflect&&Reflect.construct){try{Reflect.construct(t,[])}catch(c){var r=c}Reflect.construct(e,[],t)}else{try{t.call()}catch(c){r=c}e.call(t.prototype)}else{try{throw Error()}catch(c){r=c}e()}}catch(c){if(c&&r&&"string"===typeof c.stack){for(var i=c.stack.split("\n"),s=r.stack.split("\n"),a=i.length-1,o=s.length-1;1<=a&&0<=o&&i[a]!==s[o];)o--;for(;1<=a&&0<=o;a--,o--)if(i[a]!==s[o]){if(1!==a||1!==o)do{if(a--,0>--o||i[a]!==s[o]){var l="\n"+i[a].replace(" at new "," at ");return e.displayName&&l.includes("<anonymous>")&&(l=l.replace("<anonymous>",e.displayName)),l}}while(1<=a&&0<=o);break}}}finally{U=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?F(e):""}function B(e){switch(e.tag){case 5:return F(e.type);case 16:return F("Lazy");case 13:return F("Suspense");case 19:return F("SuspenseList");case 0:case 2:case 15:return e=V(e.type,!1);case 11:return e=V(e.type.render,!1);case 1:return e=V(e.type,!0);default:return""}}function z(e){if(null==e)return null;if("function"===typeof e)return e.displayName||e.name||null;if("string"===typeof e)return e;switch(e){case S:return"Fragment";case E:return"Portal";case I:return"Profiler";case k:return"StrictMode";case N:return"Suspense";case A:return"SuspenseList"}if("object"===typeof e)switch(e.$$typeof){case C:return(e.displayName||"Context")+".Consumer";case T:return(e._context.displayName||"Context")+".Provider";case x:var t=e.render;return(e=e.displayName)||(e=""!==(e=t.displayName||t.name||"")?"ForwardRef("+e+")":"ForwardRef"),e;case P:return null!==(t=e.displayName||null)?t:z(e.type)||"Memo";case R:t=e._payload,e=e._init;try{return z(e(t))}catch(n){}}return null}function q(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=(e=t.render).displayName||e.name||"",t.displayName||(""!==e?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return z(t);case 8:return t===k?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"===typeof t)return t.displayName||t.name||null;if("string"===typeof t)return t}return null}function H(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":case"object":return e;default:return""}}function W(e){var t=e.type;return(e=e.nodeName)&&"input"===e.toLowerCase()&&("checkbox"===t||"radio"===t)}function K(e){e._valueTracker||(e._valueTracker=function(e){var t=W(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&"undefined"!==typeof n&&"function"===typeof n.get&&"function"===typeof n.set){var i=n.get,s=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(e){r=""+e,s.call(this,e)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(e){r=""+e},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}(e))}function G(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=W(e)?e.checked?"true":"false":e.value),(e=r)!==n&&(t.setValue(e),!0)}function Q(e){if("undefined"===typeof(e=e||("undefined"!==typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(t){return e.body}}function $(e,t){var n=t.checked;return j({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=n?n:e._wrapperState.initialChecked})}function Y(e,t){var n=null==t.defaultValue?"":t.defaultValue,r=null!=t.checked?t.checked:t.defaultChecked;n=H(null!=t.value?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:"checkbox"===t.type||"radio"===t.type?null!=t.checked:null!=t.value}}function X(e,t){null!=(t=t.checked)&&w(e,"checked",t,!1)}function J(e,t){X(e,t);var n=H(t.value),r=t.type;if(null!=n)"number"===r?(0===n&&""===e.value||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if("submit"===r||"reset"===r)return void e.removeAttribute("value");t.hasOwnProperty("value")?ee(e,t.type,n):t.hasOwnProperty("defaultValue")&&ee(e,t.type,H(t.defaultValue)),null==t.checked&&null!=t.defaultChecked&&(e.defaultChecked=!!t.defaultChecked)}function Z(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!("submit"!==r&&"reset"!==r||void 0!==t.value&&null!==t.value))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}""!==(n=e.name)&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,""!==n&&(e.name=n)}function ee(e,t,n){"number"===t&&Q(e.ownerDocument)===e||(null==n?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var te=Array.isArray;function ne(e,t,n,r){if(e=e.options,t){t={};for(var i=0;i<n.length;i++)t["$"+n[i]]=!0;for(n=0;n<e.length;n++)i=t.hasOwnProperty("$"+e[n].value),e[n].selected!==i&&(e[n].selected=i),i&&r&&(e[n].defaultSelected=!0)}else{for(n=""+H(n),t=null,i=0;i<e.length;i++){if(e[i].value===n)return e[i].selected=!0,void(r&&(e[i].defaultSelected=!0));null!==t||e[i].disabled||(t=e[i])}null!==t&&(t.selected=!0)}}function re(e,t){if(null!=t.dangerouslySetInnerHTML)throw Error(s(91));return j({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function ie(e,t){var n=t.value;if(null==n){if(n=t.children,t=t.defaultValue,null!=n){if(null!=t)throw Error(s(92));if(te(n)){if(1<n.length)throw Error(s(93));n=n[0]}t=n}null==t&&(t=""),n=t}e._wrapperState={initialValue:H(n)}}function se(e,t){var n=H(t.value),r=H(t.defaultValue);null!=n&&((n=""+n)!==e.value&&(e.value=n),null==t.defaultValue&&e.defaultValue!==n&&(e.defaultValue=n)),null!=r&&(e.defaultValue=""+r)}function ae(e){var t=e.textContent;t===e._wrapperState.initialValue&&""!==t&&null!==t&&(e.value=t)}function oe(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function le(e,t){return null==e||"http://www.w3.org/1999/xhtml"===e?oe(t):"http://www.w3.org/2000/svg"===e&&"foreignObject"===t?"http://www.w3.org/1999/xhtml":e}var ce,ue,he=(ue=function(e,t){if("http://www.w3.org/2000/svg"!==e.namespaceURI||"innerHTML"in e)e.innerHTML=t;else{for((ce=ce||document.createElement("div")).innerHTML="<svg>"+t.valueOf().toString()+"</svg>",t=ce.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}},"undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(e,t,n,r){MSApp.execUnsafeLocalFunction((function(){return ue(e,t)}))}:ue);function de(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&3===n.nodeType)return void(n.nodeValue=t)}e.textContent=t}var fe={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},pe=["Webkit","ms","Moz","O"];function me(e,t,n){return null==t||"boolean"===typeof t||""===t?"":n||"number"!==typeof t||0===t||fe.hasOwnProperty(e)&&fe[e]?(""+t).trim():t+"px"}function ge(e,t){for(var n in e=e.style,t)if(t.hasOwnProperty(n)){var r=0===n.indexOf("--"),i=me(n,t[n],r);"float"===n&&(n="cssFloat"),r?e.setProperty(n,i):e[n]=i}}Object.keys(fe).forEach((function(e){pe.forEach((function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),fe[t]=fe[e]}))}));var ve=j({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ye(e,t){if(t){if(ve[e]&&(null!=t.children||null!=t.dangerouslySetInnerHTML))throw Error(s(137,e));if(null!=t.dangerouslySetInnerHTML){if(null!=t.children)throw Error(s(60));if("object"!==typeof t.dangerouslySetInnerHTML||!("__html"in t.dangerouslySetInnerHTML))throw Error(s(61))}if(null!=t.style&&"object"!==typeof t.style)throw Error(s(62))}}function we(e,t){if(-1===e.indexOf("-"))return"string"===typeof t.is;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var be=null;function _e(e){return(e=e.target||e.srcElement||window).correspondingUseElement&&(e=e.correspondingUseElement),3===e.nodeType?e.parentNode:e}var Ee=null,Se=null,ke=null;function Ie(e){if(e=wi(e)){if("function"!==typeof Ee)throw Error(s(280));var t=e.stateNode;t&&(t=_i(t),Ee(e.stateNode,e.type,t))}}function Te(e){Se?ke?ke.push(e):ke=[e]:Se=e}function Ce(){if(Se){var e=Se,t=ke;if(ke=Se=null,Ie(e),t)for(e=0;e<t.length;e++)Ie(t[e])}}function xe(e,t){return e(t)}function Ne(){}var Ae=!1;function Pe(e,t,n){if(Ae)return e(t,n);Ae=!0;try{return xe(e,t,n)}finally{Ae=!1,(null!==Se||null!==ke)&&(Ne(),Ce())}}function Re(e,t){var n=e.stateNode;if(null===n)return null;var r=_i(n);if(null===r)return null;n=r[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(r=!r.disabled)||(r=!("button"===(e=e.type)||"input"===e||"select"===e||"textarea"===e)),e=!r;break e;default:e=!1}if(e)return null;if(n&&"function"!==typeof n)throw Error(s(231,t,typeof n));return n}var Oe=!1;if(u)try{var De={};Object.defineProperty(De,"passive",{get:function(){Oe=!0}}),window.addEventListener("test",De,De),window.removeEventListener("test",De,De)}catch(ue){Oe=!1}function Le(e,t,n,r,i,s,a,o,l){var c=Array.prototype.slice.call(arguments,3);try{t.apply(n,c)}catch(u){this.onError(u)}}var Me=!1,je=null,Fe=!1,Ue=null,Ve={onError:function(e){Me=!0,je=e}};function Be(e,t,n,r,i,s,a,o,l){Me=!1,je=null,Le.apply(Ve,arguments)}function ze(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do{0!==(4098&(t=e).flags)&&(n=t.return),e=t.return}while(e)}return 3===t.tag?n:null}function qe(e){if(13===e.tag){var t=e.memoizedState;if(null===t&&(null!==(e=e.alternate)&&(t=e.memoizedState)),null!==t)return t.dehydrated}return null}function He(e){if(ze(e)!==e)throw Error(s(188))}function We(e){return null!==(e=function(e){var t=e.alternate;if(!t){if(null===(t=ze(e)))throw Error(s(188));return t!==e?null:e}for(var n=e,r=t;;){var i=n.return;if(null===i)break;var a=i.alternate;if(null===a){if(null!==(r=i.return)){n=r;continue}break}if(i.child===a.child){for(a=i.child;a;){if(a===n)return He(i),e;if(a===r)return He(i),t;a=a.sibling}throw Error(s(188))}if(n.return!==r.return)n=i,r=a;else{for(var o=!1,l=i.child;l;){if(l===n){o=!0,n=i,r=a;break}if(l===r){o=!0,r=i,n=a;break}l=l.sibling}if(!o){for(l=a.child;l;){if(l===n){o=!0,n=a,r=i;break}if(l===r){o=!0,r=a,n=i;break}l=l.sibling}if(!o)throw Error(s(189))}}if(n.alternate!==r)throw Error(s(190))}if(3!==n.tag)throw Error(s(188));return n.stateNode.current===n?e:t}(e))?Ke(e):null}function Ke(e){if(5===e.tag||6===e.tag)return e;for(e=e.child;null!==e;){var t=Ke(e);if(null!==t)return t;e=e.sibling}return null}var Ge=i.unstable_scheduleCallback,Qe=i.unstable_cancelCallback,$e=i.unstable_shouldYield,Ye=i.unstable_requestPaint,Xe=i.unstable_now,Je=i.unstable_getCurrentPriorityLevel,Ze=i.unstable_ImmediatePriority,et=i.unstable_UserBlockingPriority,tt=i.unstable_NormalPriority,nt=i.unstable_LowPriority,rt=i.unstable_IdlePriority,it=null,st=null;var at=Math.clz32?Math.clz32:function(e){return e>>>=0,0===e?32:31-(ot(e)/lt|0)|0},ot=Math.log,lt=Math.LN2;var ct=64,ut=4194304;function ht(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return 4194240&e;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return 130023424&e;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function dt(e,t){var n=e.pendingLanes;if(0===n)return 0;var r=0,i=e.suspendedLanes,s=e.pingedLanes,a=268435455&n;if(0!==a){var o=a&~i;0!==o?r=ht(o):0!==(s&=a)&&(r=ht(s))}else 0!==(a=n&~i)?r=ht(a):0!==s&&(r=ht(s));if(0===r)return 0;if(0!==t&&t!==r&&0===(t&i)&&((i=r&-r)>=(s=t&-t)||16===i&&0!==(4194240&s)))return t;if(0!==(4&r)&&(r|=16&n),0!==(t=e.entangledLanes))for(e=e.entanglements,t&=r;0<t;)i=1<<(n=31-at(t)),r|=e[n],t&=~i;return r}function ft(e,t){switch(e){case 1:case 2:case 4:return t+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;default:return-1}}function pt(e){return 0!==(e=-1073741825&e.pendingLanes)?e:1073741824&e?1073741824:0}function mt(){var e=ct;return 0===(4194240&(ct<<=1))&&(ct=64),e}function gt(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function vt(e,t,n){e.pendingLanes|=t,536870912!==t&&(e.suspendedLanes=0,e.pingedLanes=0),(e=e.eventTimes)[t=31-at(t)]=n}function yt(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-at(n),i=1<<r;i&t|e[r]&t&&(e[r]|=t),n&=~i}}var wt=0;function bt(e){return 1<(e&=-e)?4<e?0!==(268435455&e)?16:536870912:4:1}var _t,Et,St,kt,It,Tt=!1,Ct=[],xt=null,Nt=null,At=null,Pt=new Map,Rt=new Map,Ot=[],Dt="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function Lt(e,t){switch(e){case"focusin":case"focusout":xt=null;break;case"dragenter":case"dragleave":Nt=null;break;case"mouseover":case"mouseout":At=null;break;case"pointerover":case"pointerout":Pt.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":Rt.delete(t.pointerId)}}function Mt(e,t,n,r,i,s){return null===e||e.nativeEvent!==s?(e={blockedOn:t,domEventName:n,eventSystemFlags:r,nativeEvent:s,targetContainers:[i]},null!==t&&(null!==(t=wi(t))&&Et(t)),e):(e.eventSystemFlags|=r,t=e.targetContainers,null!==i&&-1===t.indexOf(i)&&t.push(i),e)}function jt(e){var t=yi(e.target);if(null!==t){var n=ze(t);if(null!==n)if(13===(t=n.tag)){if(null!==(t=qe(n)))return e.blockedOn=t,void It(e.priority,(function(){St(n)}))}else if(3===t&&n.stateNode.current.memoizedState.isDehydrated)return void(e.blockedOn=3===n.tag?n.stateNode.containerInfo:null)}e.blockedOn=null}function Ft(e){if(null!==e.blockedOn)return!1;for(var t=e.targetContainers;0<t.length;){var n=$t(e.domEventName,e.eventSystemFlags,t[0],e.nativeEvent);if(null!==n)return null!==(t=wi(n))&&Et(t),e.blockedOn=n,!1;var r=new(n=e.nativeEvent).constructor(n.type,n);be=r,n.target.dispatchEvent(r),be=null,t.shift()}return!0}function Ut(e,t,n){Ft(e)&&n.delete(t)}function Vt(){Tt=!1,null!==xt&&Ft(xt)&&(xt=null),null!==Nt&&Ft(Nt)&&(Nt=null),null!==At&&Ft(At)&&(At=null),Pt.forEach(Ut),Rt.forEach(Ut)}function Bt(e,t){e.blockedOn===t&&(e.blockedOn=null,Tt||(Tt=!0,i.unstable_scheduleCallback(i.unstable_NormalPriority,Vt)))}function zt(e){function t(t){return Bt(t,e)}if(0<Ct.length){Bt(Ct[0],e);for(var n=1;n<Ct.length;n++){var r=Ct[n];r.blockedOn===e&&(r.blockedOn=null)}}for(null!==xt&&Bt(xt,e),null!==Nt&&Bt(Nt,e),null!==At&&Bt(At,e),Pt.forEach(t),Rt.forEach(t),n=0;n<Ot.length;n++)(r=Ot[n]).blockedOn===e&&(r.blockedOn=null);for(;0<Ot.length&&null===(n=Ot[0]).blockedOn;)jt(n),null===n.blockedOn&&Ot.shift()}var qt=b.ReactCurrentBatchConfig,Ht=!0;function Wt(e,t,n,r){var i=wt,s=qt.transition;qt.transition=null;try{wt=1,Gt(e,t,n,r)}finally{wt=i,qt.transition=s}}function Kt(e,t,n,r){var i=wt,s=qt.transition;qt.transition=null;try{wt=4,Gt(e,t,n,r)}finally{wt=i,qt.transition=s}}function Gt(e,t,n,r){if(Ht){var i=$t(e,t,n,r);if(null===i)Hr(e,t,r,Qt,n),Lt(e,r);else if(function(e,t,n,r,i){switch(t){case"focusin":return xt=Mt(xt,e,t,n,r,i),!0;case"dragenter":return Nt=Mt(Nt,e,t,n,r,i),!0;case"mouseover":return At=Mt(At,e,t,n,r,i),!0;case"pointerover":var s=i.pointerId;return Pt.set(s,Mt(Pt.get(s)||null,e,t,n,r,i)),!0;case"gotpointercapture":return s=i.pointerId,Rt.set(s,Mt(Rt.get(s)||null,e,t,n,r,i)),!0}return!1}(i,e,t,n,r))r.stopPropagation();else if(Lt(e,r),4&t&&-1<Dt.indexOf(e)){for(;null!==i;){var s=wi(i);if(null!==s&&_t(s),null===(s=$t(e,t,n,r))&&Hr(e,t,r,Qt,n),s===i)break;i=s}null!==i&&r.stopPropagation()}else Hr(e,t,r,null,n)}}var Qt=null;function $t(e,t,n,r){if(Qt=null,null!==(e=yi(e=_e(r))))if(null===(t=ze(e)))e=null;else if(13===(n=t.tag)){if(null!==(e=qe(t)))return e;e=null}else if(3===n){if(t.stateNode.current.memoizedState.isDehydrated)return 3===t.tag?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null);return Qt=e,null}function Yt(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(Je()){case Ze:return 1;case et:return 4;case tt:case nt:return 16;case rt:return 536870912;default:return 16}default:return 16}}var Xt=null,Jt=null,Zt=null;function en(){if(Zt)return Zt;var e,t,n=Jt,r=n.length,i="value"in Xt?Xt.value:Xt.textContent,s=i.length;for(e=0;e<r&&n[e]===i[e];e++);var a=r-e;for(t=1;t<=a&&n[r-t]===i[s-t];t++);return Zt=i.slice(e,1<t?1-t:void 0)}function tn(e){var t=e.keyCode;return"charCode"in e?0===(e=e.charCode)&&13===t&&(e=13):e=t,10===e&&(e=13),32<=e||13===e?e:0}function nn(){return!0}function rn(){return!1}function sn(e){function t(t,n,r,i,s){for(var a in this._reactName=t,this._targetInst=r,this.type=n,this.nativeEvent=i,this.target=s,this.currentTarget=null,e)e.hasOwnProperty(a)&&(t=e[a],this[a]=t?t(i):i[a]);return this.isDefaultPrevented=(null!=i.defaultPrevented?i.defaultPrevented:!1===i.returnValue)?nn:rn,this.isPropagationStopped=rn,this}return j(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!==typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=nn)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!==typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=nn)},persist:function(){},isPersistent:nn}),t}var an,on,ln,cn={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},un=sn(cn),hn=j({},cn,{view:0,detail:0}),dn=sn(hn),fn=j({},hn,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:In,button:0,buttons:0,relatedTarget:function(e){return void 0===e.relatedTarget?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==ln&&(ln&&"mousemove"===e.type?(an=e.screenX-ln.screenX,on=e.screenY-ln.screenY):on=an=0,ln=e),an)},movementY:function(e){return"movementY"in e?e.movementY:on}}),pn=sn(fn),mn=sn(j({},fn,{dataTransfer:0})),gn=sn(j({},hn,{relatedTarget:0})),vn=sn(j({},cn,{animationName:0,elapsedTime:0,pseudoElement:0})),yn=j({},cn,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),wn=sn(yn),bn=sn(j({},cn,{data:0})),_n={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},En={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},Sn={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function kn(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):!!(e=Sn[e])&&!!t[e]}function In(){return kn}var Tn=j({},hn,{key:function(e){if(e.key){var t=_n[e.key]||e.key;if("Unidentified"!==t)return t}return"keypress"===e.type?13===(e=tn(e))?"Enter":String.fromCharCode(e):"keydown"===e.type||"keyup"===e.type?En[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:In,charCode:function(e){return"keypress"===e.type?tn(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?tn(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}}),Cn=sn(Tn),xn=sn(j({},fn,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0})),Nn=sn(j({},hn,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:In})),An=sn(j({},cn,{propertyName:0,elapsedTime:0,pseudoElement:0})),Pn=j({},fn,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),Rn=sn(Pn),On=[9,13,27,32],Dn=u&&"CompositionEvent"in window,Ln=null;u&&"documentMode"in document&&(Ln=document.documentMode);var Mn=u&&"TextEvent"in window&&!Ln,jn=u&&(!Dn||Ln&&8<Ln&&11>=Ln),Fn=String.fromCharCode(32),Un=!1;function Vn(e,t){switch(e){case"keyup":return-1!==On.indexOf(t.keyCode);case"keydown":return 229!==t.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Bn(e){return"object"===typeof(e=e.detail)&&"data"in e?e.data:null}var zn=!1;var qn={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Hn(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!qn[e.type]:"textarea"===t}function Wn(e,t,n,r){Te(r),0<(t=Kr(t,"onChange")).length&&(n=new un("onChange","change",null,n,r),e.push({event:n,listeners:t}))}var Kn=null,Gn=null;function Qn(e){Fr(e,0)}function $n(e){if(G(bi(e)))return e}function Yn(e,t){if("change"===e)return t}var Xn=!1;if(u){var Jn;if(u){var Zn="oninput"in document;if(!Zn){var er=document.createElement("div");er.setAttribute("oninput","return;"),Zn="function"===typeof er.oninput}Jn=Zn}else Jn=!1;Xn=Jn&&(!document.documentMode||9<document.documentMode)}function tr(){Kn&&(Kn.detachEvent("onpropertychange",nr),Gn=Kn=null)}function nr(e){if("value"===e.propertyName&&$n(Gn)){var t=[];Wn(t,Gn,e,_e(e)),Pe(Qn,t)}}function rr(e,t,n){"focusin"===e?(tr(),Gn=n,(Kn=t).attachEvent("onpropertychange",nr)):"focusout"===e&&tr()}function ir(e){if("selectionchange"===e||"keyup"===e||"keydown"===e)return $n(Gn)}function sr(e,t){if("click"===e)return $n(t)}function ar(e,t){if("input"===e||"change"===e)return $n(t)}var or="function"===typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e===1/t)||e!==e&&t!==t};function lr(e,t){if(or(e,t))return!0;if("object"!==typeof e||null===e||"object"!==typeof t||null===t)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(r=0;r<n.length;r++){var i=n[r];if(!h.call(t,i)||!or(e[i],t[i]))return!1}return!0}function cr(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function ur(e,t){var n,r=cr(e);for(e=0;r;){if(3===r.nodeType){if(n=e+r.textContent.length,e<=t&&n>=t)return{node:r,offset:t-e};e=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=cr(r)}}function hr(e,t){return!(!e||!t)&&(e===t||(!e||3!==e.nodeType)&&(t&&3===t.nodeType?hr(e,t.parentNode):"contains"in e?e.contains(t):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(t))))}function dr(){for(var e=window,t=Q();t instanceof e.HTMLIFrameElement;){try{var n="string"===typeof t.contentWindow.location.href}catch(r){n=!1}if(!n)break;t=Q((e=t.contentWindow).document)}return t}function fr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===t||"true"===e.contentEditable)}function pr(e){var t=dr(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&hr(n.ownerDocument.documentElement,n)){if(null!==r&&fr(n))if(t=r.start,void 0===(e=r.end)&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if((e=(t=n.ownerDocument||document)&&t.defaultView||window).getSelection){e=e.getSelection();var i=n.textContent.length,s=Math.min(r.start,i);r=void 0===r.end?s:Math.min(r.end,i),!e.extend&&s>r&&(i=r,r=s,s=i),i=ur(n,s);var a=ur(n,r);i&&a&&(1!==e.rangeCount||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&((t=t.createRange()).setStart(i.node,i.offset),e.removeAllRanges(),s>r?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}for(t=[],e=n;e=e.parentNode;)1===e.nodeType&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for("function"===typeof n.focus&&n.focus(),n=0;n<t.length;n++)(e=t[n]).element.scrollLeft=e.left,e.element.scrollTop=e.top}}var mr=u&&"documentMode"in document&&11>=document.documentMode,gr=null,vr=null,yr=null,wr=!1;function br(e,t,n){var r=n.window===n?n.document:9===n.nodeType?n:n.ownerDocument;wr||null==gr||gr!==Q(r)||("selectionStart"in(r=gr)&&fr(r)?r={start:r.selectionStart,end:r.selectionEnd}:r={anchorNode:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset},yr&&lr(yr,r)||(yr=r,0<(r=Kr(vr,"onSelect")).length&&(t=new un("onSelect","select",null,t,n),e.push({event:t,listeners:r}),t.target=gr)))}function _r(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var Er={animationend:_r("Animation","AnimationEnd"),animationiteration:_r("Animation","AnimationIteration"),animationstart:_r("Animation","AnimationStart"),transitionend:_r("Transition","TransitionEnd")},Sr={},kr={};function Ir(e){if(Sr[e])return Sr[e];if(!Er[e])return e;var t,n=Er[e];for(t in n)if(n.hasOwnProperty(t)&&t in kr)return Sr[e]=n[t];return e}u&&(kr=document.createElement("div").style,"AnimationEvent"in window||(delete Er.animationend.animation,delete Er.animationiteration.animation,delete Er.animationstart.animation),"TransitionEvent"in window||delete Er.transitionend.transition);var Tr=Ir("animationend"),Cr=Ir("animationiteration"),xr=Ir("animationstart"),Nr=Ir("transitionend"),Ar=new Map,Pr="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function Rr(e,t){Ar.set(e,t),l(t,[e])}for(var Or=0;Or<Pr.length;Or++){var Dr=Pr[Or];Rr(Dr.toLowerCase(),"on"+(Dr[0].toUpperCase()+Dr.slice(1)))}Rr(Tr,"onAnimationEnd"),Rr(Cr,"onAnimationIteration"),Rr(xr,"onAnimationStart"),Rr("dblclick","onDoubleClick"),Rr("focusin","onFocus"),Rr("focusout","onBlur"),Rr(Nr,"onTransitionEnd"),c("onMouseEnter",["mouseout","mouseover"]),c("onMouseLeave",["mouseout","mouseover"]),c("onPointerEnter",["pointerout","pointerover"]),c("onPointerLeave",["pointerout","pointerover"]),l("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),l("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),l("onBeforeInput",["compositionend","keypress","textInput","paste"]),l("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Lr="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Mr=new Set("cancel close invalid load scroll toggle".split(" ").concat(Lr));function jr(e,t,n){var r=e.type||"unknown-event";e.currentTarget=n,function(e,t,n,r,i,a,o,l,c){if(Be.apply(this,arguments),Me){if(!Me)throw Error(s(198));var u=je;Me=!1,je=null,Fe||(Fe=!0,Ue=u)}}(r,t,void 0,e),e.currentTarget=null}function Fr(e,t){t=0!==(4&t);for(var n=0;n<e.length;n++){var r=e[n],i=r.event;r=r.listeners;e:{var s=void 0;if(t)for(var a=r.length-1;0<=a;a--){var o=r[a],l=o.instance,c=o.currentTarget;if(o=o.listener,l!==s&&i.isPropagationStopped())break e;jr(i,o,c),s=l}else for(a=0;a<r.length;a++){if(l=(o=r[a]).instance,c=o.currentTarget,o=o.listener,l!==s&&i.isPropagationStopped())break e;jr(i,o,c),s=l}}}if(Fe)throw e=Ue,Fe=!1,Ue=null,e}function Ur(e,t){var n=t[mi];void 0===n&&(n=t[mi]=new Set);var r=e+"__bubble";n.has(r)||(qr(t,e,2,!1),n.add(r))}function Vr(e,t,n){var r=0;t&&(r|=4),qr(n,e,r,t)}var Br="_reactListening"+Math.random().toString(36).slice(2);function zr(e){if(!e[Br]){e[Br]=!0,a.forEach((function(t){"selectionchange"!==t&&(Mr.has(t)||Vr(t,!1,e),Vr(t,!0,e))}));var t=9===e.nodeType?e:e.ownerDocument;null===t||t[Br]||(t[Br]=!0,Vr("selectionchange",!1,t))}}function qr(e,t,n,r){switch(Yt(t)){case 1:var i=Wt;break;case 4:i=Kt;break;default:i=Gt}n=i.bind(null,t,n,e),i=void 0,!Oe||"touchstart"!==t&&"touchmove"!==t&&"wheel"!==t||(i=!0),r?void 0!==i?e.addEventListener(t,n,{capture:!0,passive:i}):e.addEventListener(t,n,!0):void 0!==i?e.addEventListener(t,n,{passive:i}):e.addEventListener(t,n,!1)}function Hr(e,t,n,r,i){var s=r;if(0===(1&t)&&0===(2&t)&&null!==r)e:for(;;){if(null===r)return;var a=r.tag;if(3===a||4===a){var o=r.stateNode.containerInfo;if(o===i||8===o.nodeType&&o.parentNode===i)break;if(4===a)for(a=r.return;null!==a;){var l=a.tag;if((3===l||4===l)&&((l=a.stateNode.containerInfo)===i||8===l.nodeType&&l.parentNode===i))return;a=a.return}for(;null!==o;){if(null===(a=yi(o)))return;if(5===(l=a.tag)||6===l){r=s=a;continue e}o=o.parentNode}}r=r.return}Pe((function(){var r=s,i=_e(n),a=[];e:{var o=Ar.get(e);if(void 0!==o){var l=un,c=e;switch(e){case"keypress":if(0===tn(n))break e;case"keydown":case"keyup":l=Cn;break;case"focusin":c="focus",l=gn;break;case"focusout":c="blur",l=gn;break;case"beforeblur":case"afterblur":l=gn;break;case"click":if(2===n.button)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":l=pn;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":l=mn;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":l=Nn;break;case Tr:case Cr:case xr:l=vn;break;case Nr:l=An;break;case"scroll":l=dn;break;case"wheel":l=Rn;break;case"copy":case"cut":case"paste":l=wn;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":l=xn}var u=0!==(4&t),h=!u&&"scroll"===e,d=u?null!==o?o+"Capture":null:o;u=[];for(var f,p=r;null!==p;){var m=(f=p).stateNode;if(5===f.tag&&null!==m&&(f=m,null!==d&&(null!=(m=Re(p,d))&&u.push(Wr(p,m,f)))),h)break;p=p.return}0<u.length&&(o=new l(o,c,null,n,i),a.push({event:o,listeners:u}))}}if(0===(7&t)){if(l="mouseout"===e||"pointerout"===e,(!(o="mouseover"===e||"pointerover"===e)||n===be||!(c=n.relatedTarget||n.fromElement)||!yi(c)&&!c[pi])&&(l||o)&&(o=i.window===i?i:(o=i.ownerDocument)?o.defaultView||o.parentWindow:window,l?(l=r,null!==(c=(c=n.relatedTarget||n.toElement)?yi(c):null)&&(c!==(h=ze(c))||5!==c.tag&&6!==c.tag)&&(c=null)):(l=null,c=r),l!==c)){if(u=pn,m="onMouseLeave",d="onMouseEnter",p="mouse","pointerout"!==e&&"pointerover"!==e||(u=xn,m="onPointerLeave",d="onPointerEnter",p="pointer"),h=null==l?o:bi(l),f=null==c?o:bi(c),(o=new u(m,p+"leave",l,n,i)).target=h,o.relatedTarget=f,m=null,yi(i)===r&&((u=new u(d,p+"enter",c,n,i)).target=f,u.relatedTarget=h,m=u),h=m,l&&c)e:{for(d=c,p=0,f=u=l;f;f=Gr(f))p++;for(f=0,m=d;m;m=Gr(m))f++;for(;0<p-f;)u=Gr(u),p--;for(;0<f-p;)d=Gr(d),f--;for(;p--;){if(u===d||null!==d&&u===d.alternate)break e;u=Gr(u),d=Gr(d)}u=null}else u=null;null!==l&&Qr(a,o,l,u,!1),null!==c&&null!==h&&Qr(a,h,c,u,!0)}if("select"===(l=(o=r?bi(r):window).nodeName&&o.nodeName.toLowerCase())||"input"===l&&"file"===o.type)var g=Yn;else if(Hn(o))if(Xn)g=ar;else{g=ir;var v=rr}else(l=o.nodeName)&&"input"===l.toLowerCase()&&("checkbox"===o.type||"radio"===o.type)&&(g=sr);switch(g&&(g=g(e,r))?Wn(a,g,n,i):(v&&v(e,o,r),"focusout"===e&&(v=o._wrapperState)&&v.controlled&&"number"===o.type&&ee(o,"number",o.value)),v=r?bi(r):window,e){case"focusin":(Hn(v)||"true"===v.contentEditable)&&(gr=v,vr=r,yr=null);break;case"focusout":yr=vr=gr=null;break;case"mousedown":wr=!0;break;case"contextmenu":case"mouseup":case"dragend":wr=!1,br(a,n,i);break;case"selectionchange":if(mr)break;case"keydown":case"keyup":br(a,n,i)}var y;if(Dn)e:{switch(e){case"compositionstart":var w="onCompositionStart";break e;case"compositionend":w="onCompositionEnd";break e;case"compositionupdate":w="onCompositionUpdate";break e}w=void 0}else zn?Vn(e,n)&&(w="onCompositionEnd"):"keydown"===e&&229===n.keyCode&&(w="onCompositionStart");w&&(jn&&"ko"!==n.locale&&(zn||"onCompositionStart"!==w?"onCompositionEnd"===w&&zn&&(y=en()):(Jt="value"in(Xt=i)?Xt.value:Xt.textContent,zn=!0)),0<(v=Kr(r,w)).length&&(w=new bn(w,e,null,n,i),a.push({event:w,listeners:v}),y?w.data=y:null!==(y=Bn(n))&&(w.data=y))),(y=Mn?function(e,t){switch(e){case"compositionend":return Bn(t);case"keypress":return 32!==t.which?null:(Un=!0,Fn);case"textInput":return(e=t.data)===Fn&&Un?null:e;default:return null}}(e,n):function(e,t){if(zn)return"compositionend"===e||!Dn&&Vn(e,t)?(e=en(),Zt=Jt=Xt=null,zn=!1,e):null;switch(e){case"paste":default:return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return jn&&"ko"!==t.locale?null:t.data}}(e,n))&&(0<(r=Kr(r,"onBeforeInput")).length&&(i=new bn("onBeforeInput","beforeinput",null,n,i),a.push({event:i,listeners:r}),i.data=y))}Fr(a,t)}))}function Wr(e,t,n){return{instance:e,listener:t,currentTarget:n}}function Kr(e,t){for(var n=t+"Capture",r=[];null!==e;){var i=e,s=i.stateNode;5===i.tag&&null!==s&&(i=s,null!=(s=Re(e,n))&&r.unshift(Wr(e,s,i)),null!=(s=Re(e,t))&&r.push(Wr(e,s,i))),e=e.return}return r}function Gr(e){if(null===e)return null;do{e=e.return}while(e&&5!==e.tag);return e||null}function Qr(e,t,n,r,i){for(var s=t._reactName,a=[];null!==n&&n!==r;){var o=n,l=o.alternate,c=o.stateNode;if(null!==l&&l===r)break;5===o.tag&&null!==c&&(o=c,i?null!=(l=Re(n,s))&&a.unshift(Wr(n,l,o)):i||null!=(l=Re(n,s))&&a.push(Wr(n,l,o))),n=n.return}0!==a.length&&e.push({event:t,listeners:a})}var $r=/\r\n?/g,Yr=/\u0000|\uFFFD/g;function Xr(e){return("string"===typeof e?e:""+e).replace($r,"\n").replace(Yr,"")}function Jr(e,t,n){if(t=Xr(t),Xr(e)!==t&&n)throw Error(s(425))}function Zr(){}var ei=null,ti=null;function ni(e,t){return"textarea"===e||"noscript"===e||"string"===typeof t.children||"number"===typeof t.children||"object"===typeof t.dangerouslySetInnerHTML&&null!==t.dangerouslySetInnerHTML&&null!=t.dangerouslySetInnerHTML.__html}var ri="function"===typeof setTimeout?setTimeout:void 0,ii="function"===typeof clearTimeout?clearTimeout:void 0,si="function"===typeof Promise?Promise:void 0,ai="function"===typeof queueMicrotask?queueMicrotask:"undefined"!==typeof si?function(e){return si.resolve(null).then(e).catch(oi)}:ri;function oi(e){setTimeout((function(){throw e}))}function li(e,t){var n=t,r=0;do{var i=n.nextSibling;if(e.removeChild(n),i&&8===i.nodeType)if("/$"===(n=i.data)){if(0===r)return e.removeChild(i),void zt(t);r--}else"$"!==n&&"$?"!==n&&"$!"!==n||r++;n=i}while(n);zt(t)}function ci(e){for(;null!=e;e=e.nextSibling){var t=e.nodeType;if(1===t||3===t)break;if(8===t){if("$"===(t=e.data)||"$!"===t||"$?"===t)break;if("/$"===t)return null}}return e}function ui(e){e=e.previousSibling;for(var t=0;e;){if(8===e.nodeType){var n=e.data;if("$"===n||"$!"===n||"$?"===n){if(0===t)return e;t--}else"/$"===n&&t++}e=e.previousSibling}return null}var hi=Math.random().toString(36).slice(2),di="__reactFiber$"+hi,fi="__reactProps$"+hi,pi="__reactContainer$"+hi,mi="__reactEvents$"+hi,gi="__reactListeners$"+hi,vi="__reactHandles$"+hi;function yi(e){var t=e[di];if(t)return t;for(var n=e.parentNode;n;){if(t=n[pi]||n[di]){if(n=t.alternate,null!==t.child||null!==n&&null!==n.child)for(e=ui(e);null!==e;){if(n=e[di])return n;e=ui(e)}return t}n=(e=n).parentNode}return null}function wi(e){return!(e=e[di]||e[pi])||5!==e.tag&&6!==e.tag&&13!==e.tag&&3!==e.tag?null:e}function bi(e){if(5===e.tag||6===e.tag)return e.stateNode;throw Error(s(33))}function _i(e){return e[fi]||null}var Ei=[],Si=-1;function ki(e){return{current:e}}function Ii(e){0>Si||(e.current=Ei[Si],Ei[Si]=null,Si--)}function Ti(e,t){Si++,Ei[Si]=e.current,e.current=t}var Ci={},xi=ki(Ci),Ni=ki(!1),Ai=Ci;function Pi(e,t){var n=e.type.contextTypes;if(!n)return Ci;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var i,s={};for(i in n)s[i]=t[i];return r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function Ri(e){return null!==(e=e.childContextTypes)&&void 0!==e}function Oi(){Ii(Ni),Ii(xi)}function Di(e,t,n){if(xi.current!==Ci)throw Error(s(168));Ti(xi,t),Ti(Ni,n)}function Li(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,"function"!==typeof r.getChildContext)return n;for(var i in r=r.getChildContext())if(!(i in t))throw Error(s(108,q(e)||"Unknown",i));return j({},n,r)}function Mi(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Ci,Ai=xi.current,Ti(xi,e),Ti(Ni,Ni.current),!0}function ji(e,t,n){var r=e.stateNode;if(!r)throw Error(s(169));n?(e=Li(e,t,Ai),r.__reactInternalMemoizedMergedChildContext=e,Ii(Ni),Ii(xi),Ti(xi,e)):Ii(Ni),Ti(Ni,n)}var Fi=null,Ui=!1,Vi=!1;function Bi(e){null===Fi?Fi=[e]:Fi.push(e)}function zi(){if(!Vi&&null!==Fi){Vi=!0;var e=0,t=wt;try{var n=Fi;for(wt=1;e<n.length;e++){var r=n[e];do{r=r(!0)}while(null!==r)}Fi=null,Ui=!1}catch(i){throw null!==Fi&&(Fi=Fi.slice(e+1)),Ge(Ze,zi),i}finally{wt=t,Vi=!1}}return null}var qi=[],Hi=0,Wi=null,Ki=0,Gi=[],Qi=0,$i=null,Yi=1,Xi="";function Ji(e,t){qi[Hi++]=Ki,qi[Hi++]=Wi,Wi=e,Ki=t}function Zi(e,t,n){Gi[Qi++]=Yi,Gi[Qi++]=Xi,Gi[Qi++]=$i,$i=e;var r=Yi;e=Xi;var i=32-at(r)-1;r&=~(1<<i),n+=1;var s=32-at(t)+i;if(30<s){var a=i-i%5;s=(r&(1<<a)-1).toString(32),r>>=a,i-=a,Yi=1<<32-at(t)+i|n<<i|r,Xi=s+e}else Yi=1<<s|n<<i|r,Xi=e}function es(e){null!==e.return&&(Ji(e,1),Zi(e,1,0))}function ts(e){for(;e===Wi;)Wi=qi[--Hi],qi[Hi]=null,Ki=qi[--Hi],qi[Hi]=null;for(;e===$i;)$i=Gi[--Qi],Gi[Qi]=null,Xi=Gi[--Qi],Gi[Qi]=null,Yi=Gi[--Qi],Gi[Qi]=null}var ns=null,rs=null,is=!1,ss=null;function as(e,t){var n=Rc(5,null,null,0);n.elementType="DELETED",n.stateNode=t,n.return=e,null===(t=e.deletions)?(e.deletions=[n],e.flags|=16):t.push(n)}function os(e,t){switch(e.tag){case 5:var n=e.type;return null!==(t=1!==t.nodeType||n.toLowerCase()!==t.nodeName.toLowerCase()?null:t)&&(e.stateNode=t,ns=e,rs=ci(t.firstChild),!0);case 6:return null!==(t=""===e.pendingProps||3!==t.nodeType?null:t)&&(e.stateNode=t,ns=e,rs=null,!0);case 13:return null!==(t=8!==t.nodeType?null:t)&&(n=null!==$i?{id:Yi,overflow:Xi}:null,e.memoizedState={dehydrated:t,treeContext:n,retryLane:1073741824},(n=Rc(18,null,null,0)).stateNode=t,n.return=e,e.child=n,ns=e,rs=null,!0);default:return!1}}function ls(e){return 0!==(1&e.mode)&&0===(128&e.flags)}function cs(e){if(is){var t=rs;if(t){var n=t;if(!os(e,t)){if(ls(e))throw Error(s(418));t=ci(n.nextSibling);var r=ns;t&&os(e,t)?as(r,n):(e.flags=-4097&e.flags|2,is=!1,ns=e)}}else{if(ls(e))throw Error(s(418));e.flags=-4097&e.flags|2,is=!1,ns=e}}}function us(e){for(e=e.return;null!==e&&5!==e.tag&&3!==e.tag&&13!==e.tag;)e=e.return;ns=e}function hs(e){if(e!==ns)return!1;if(!is)return us(e),is=!0,!1;var t;if((t=3!==e.tag)&&!(t=5!==e.tag)&&(t="head"!==(t=e.type)&&"body"!==t&&!ni(e.type,e.memoizedProps)),t&&(t=rs)){if(ls(e))throw ds(),Error(s(418));for(;t;)as(e,t),t=ci(t.nextSibling)}if(us(e),13===e.tag){if(!(e=null!==(e=e.memoizedState)?e.dehydrated:null))throw Error(s(317));e:{for(e=e.nextSibling,t=0;e;){if(8===e.nodeType){var n=e.data;if("/$"===n){if(0===t){rs=ci(e.nextSibling);break e}t--}else"$"!==n&&"$!"!==n&&"$?"!==n||t++}e=e.nextSibling}rs=null}}else rs=ns?ci(e.stateNode.nextSibling):null;return!0}function ds(){for(var e=rs;e;)e=ci(e.nextSibling)}function fs(){rs=ns=null,is=!1}function ps(e){null===ss?ss=[e]:ss.push(e)}var ms=b.ReactCurrentBatchConfig;function gs(e,t){if(e&&e.defaultProps){for(var n in t=j({},t),e=e.defaultProps)void 0===t[n]&&(t[n]=e[n]);return t}return t}var vs=ki(null),ys=null,ws=null,bs=null;function _s(){bs=ws=ys=null}function Es(e){var t=vs.current;Ii(vs),e._currentValue=t}function Ss(e,t,n){for(;null!==e;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,null!==r&&(r.childLanes|=t)):null!==r&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function ks(e,t){ys=e,bs=ws=null,null!==(e=e.dependencies)&&null!==e.firstContext&&(0!==(e.lanes&t)&&(bo=!0),e.firstContext=null)}function Is(e){var t=e._currentValue;if(bs!==e)if(e={context:e,memoizedValue:t,next:null},null===ws){if(null===ys)throw Error(s(308));ws=e,ys.dependencies={lanes:0,firstContext:e}}else ws=ws.next=e;return t}var Ts=null;function Cs(e){null===Ts?Ts=[e]:Ts.push(e)}function xs(e,t,n,r){var i=t.interleaved;return null===i?(n.next=n,Cs(t)):(n.next=i.next,i.next=n),t.interleaved=n,Ns(e,r)}function Ns(e,t){e.lanes|=t;var n=e.alternate;for(null!==n&&(n.lanes|=t),n=e,e=e.return;null!==e;)e.childLanes|=t,null!==(n=e.alternate)&&(n.childLanes|=t),n=e,e=e.return;return 3===n.tag?n.stateNode:null}var As=!1;function Ps(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Rs(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Os(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Ds(e,t,n){var r=e.updateQueue;if(null===r)return null;if(r=r.shared,0!==(2&Nl)){var i=r.pending;return null===i?t.next=t:(t.next=i.next,i.next=t),r.pending=t,Ns(e,n)}return null===(i=r.interleaved)?(t.next=t,Cs(r)):(t.next=i.next,i.next=t),r.interleaved=t,Ns(e,n)}function Ls(e,t,n){if(null!==(t=t.updateQueue)&&(t=t.shared,0!==(4194240&n))){var r=t.lanes;n|=r&=e.pendingLanes,t.lanes=n,yt(e,n)}}function Ms(e,t){var n=e.updateQueue,r=e.alternate;if(null!==r&&n===(r=r.updateQueue)){var i=null,s=null;if(null!==(n=n.firstBaseUpdate)){do{var a={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};null===s?i=s=a:s=s.next=a,n=n.next}while(null!==n);null===s?i=s=t:s=s.next=t}else i=s=t;return n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:s,shared:r.shared,effects:r.effects},void(e.updateQueue=n)}null===(e=n.lastBaseUpdate)?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function js(e,t,n,r){var i=e.updateQueue;As=!1;var s=i.firstBaseUpdate,a=i.lastBaseUpdate,o=i.shared.pending;if(null!==o){i.shared.pending=null;var l=o,c=l.next;l.next=null,null===a?s=c:a.next=c,a=l;var u=e.alternate;null!==u&&((o=(u=u.updateQueue).lastBaseUpdate)!==a&&(null===o?u.firstBaseUpdate=c:o.next=c,u.lastBaseUpdate=l))}if(null!==s){var h=i.baseState;for(a=0,u=c=l=null,o=s;;){var d=o.lane,f=o.eventTime;if((r&d)===d){null!==u&&(u=u.next={eventTime:f,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var p=e,m=o;switch(d=t,f=n,m.tag){case 1:if("function"===typeof(p=m.payload)){h=p.call(f,h,d);break e}h=p;break e;case 3:p.flags=-65537&p.flags|128;case 0:if(null===(d="function"===typeof(p=m.payload)?p.call(f,h,d):p)||void 0===d)break e;h=j({},h,d);break e;case 2:As=!0}}null!==o.callback&&0!==o.lane&&(e.flags|=64,null===(d=i.effects)?i.effects=[o]:d.push(o))}else f={eventTime:f,lane:d,tag:o.tag,payload:o.payload,callback:o.callback,next:null},null===u?(c=u=f,l=h):u=u.next=f,a|=d;if(null===(o=o.next)){if(null===(o=i.shared.pending))break;o=(d=o).next,d.next=null,i.lastBaseUpdate=d,i.shared.pending=null}}if(null===u&&(l=h),i.baseState=l,i.firstBaseUpdate=c,i.lastBaseUpdate=u,null!==(t=i.shared.interleaved)){i=t;do{a|=i.lane,i=i.next}while(i!==t)}else null===s&&(i.shared.lanes=0);jl|=a,e.lanes=a,e.memoizedState=h}}function Fs(e,t,n){if(e=t.effects,t.effects=null,null!==e)for(t=0;t<e.length;t++){var r=e[t],i=r.callback;if(null!==i){if(r.callback=null,r=n,"function"!==typeof i)throw Error(s(191,i));i.call(r)}}}var Us=(new r.Component).refs;function Vs(e,t,n,r){n=null===(n=n(r,t=e.memoizedState))||void 0===n?t:j({},t,n),e.memoizedState=n,0===e.lanes&&(e.updateQueue.baseState=n)}var Bs={isMounted:function(e){return!!(e=e._reactInternals)&&ze(e)===e},enqueueSetState:function(e,t,n){e=e._reactInternals;var r=tc(),i=nc(e),s=Os(r,i);s.payload=t,void 0!==n&&null!==n&&(s.callback=n),null!==(t=Ds(e,s,i))&&(rc(t,e,i,r),Ls(t,e,i))},enqueueReplaceState:function(e,t,n){e=e._reactInternals;var r=tc(),i=nc(e),s=Os(r,i);s.tag=1,s.payload=t,void 0!==n&&null!==n&&(s.callback=n),null!==(t=Ds(e,s,i))&&(rc(t,e,i,r),Ls(t,e,i))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var n=tc(),r=nc(e),i=Os(n,r);i.tag=2,void 0!==t&&null!==t&&(i.callback=t),null!==(t=Ds(e,i,r))&&(rc(t,e,r,n),Ls(t,e,r))}};function zs(e,t,n,r,i,s,a){return"function"===typeof(e=e.stateNode).shouldComponentUpdate?e.shouldComponentUpdate(r,s,a):!t.prototype||!t.prototype.isPureReactComponent||(!lr(n,r)||!lr(i,s))}function qs(e,t,n){var r=!1,i=Ci,s=t.contextType;return"object"===typeof s&&null!==s?s=Is(s):(i=Ri(t)?Ai:xi.current,s=(r=null!==(r=t.contextTypes)&&void 0!==r)?Pi(e,i):Ci),t=new t(n,s),e.memoizedState=null!==t.state&&void 0!==t.state?t.state:null,t.updater=Bs,e.stateNode=t,t._reactInternals=e,r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=i,e.__reactInternalMemoizedMaskedChildContext=s),t}function Hs(e,t,n,r){e=t.state,"function"===typeof t.componentWillReceiveProps&&t.componentWillReceiveProps(n,r),"function"===typeof t.UNSAFE_componentWillReceiveProps&&t.UNSAFE_componentWillReceiveProps(n,r),t.state!==e&&Bs.enqueueReplaceState(t,t.state,null)}function Ws(e,t,n,r){var i=e.stateNode;i.props=n,i.state=e.memoizedState,i.refs=Us,Ps(e);var s=t.contextType;"object"===typeof s&&null!==s?i.context=Is(s):(s=Ri(t)?Ai:xi.current,i.context=Pi(e,s)),i.state=e.memoizedState,"function"===typeof(s=t.getDerivedStateFromProps)&&(Vs(e,t,s,n),i.state=e.memoizedState),"function"===typeof t.getDerivedStateFromProps||"function"===typeof i.getSnapshotBeforeUpdate||"function"!==typeof i.UNSAFE_componentWillMount&&"function"!==typeof i.componentWillMount||(t=i.state,"function"===typeof i.componentWillMount&&i.componentWillMount(),"function"===typeof i.UNSAFE_componentWillMount&&i.UNSAFE_componentWillMount(),t!==i.state&&Bs.enqueueReplaceState(i,i.state,null),js(e,n,i,r),i.state=e.memoizedState),"function"===typeof i.componentDidMount&&(e.flags|=4194308)}function Ks(e,t,n){if(null!==(e=n.ref)&&"function"!==typeof e&&"object"!==typeof e){if(n._owner){if(n=n._owner){if(1!==n.tag)throw Error(s(309));var r=n.stateNode}if(!r)throw Error(s(147,e));var i=r,a=""+e;return null!==t&&null!==t.ref&&"function"===typeof t.ref&&t.ref._stringRef===a?t.ref:(t=function(e){var t=i.refs;t===Us&&(t=i.refs={}),null===e?delete t[a]:t[a]=e},t._stringRef=a,t)}if("string"!==typeof e)throw Error(s(284));if(!n._owner)throw Error(s(290,e))}return e}function Gs(e,t){throw e=Object.prototype.toString.call(t),Error(s(31,"[object Object]"===e?"object with keys {"+Object.keys(t).join(", ")+"}":e))}function Qs(e){return(0,e._init)(e._payload)}function $s(e){function t(t,n){if(e){var r=t.deletions;null===r?(t.deletions=[n],t.flags|=16):r.push(n)}}function n(n,r){if(!e)return null;for(;null!==r;)t(n,r),r=r.sibling;return null}function r(e,t){for(e=new Map;null!==t;)null!==t.key?e.set(t.key,t):e.set(t.index,t),t=t.sibling;return e}function i(e,t){return(e=Dc(e,t)).index=0,e.sibling=null,e}function a(t,n,r){return t.index=r,e?null!==(r=t.alternate)?(r=r.index)<n?(t.flags|=2,n):r:(t.flags|=2,n):(t.flags|=1048576,n)}function o(t){return e&&null===t.alternate&&(t.flags|=2),t}function l(e,t,n,r){return null===t||6!==t.tag?((t=Fc(n,e.mode,r)).return=e,t):((t=i(t,n)).return=e,t)}function c(e,t,n,r){var s=n.type;return s===S?h(e,t,n.props.children,r,n.key):null!==t&&(t.elementType===s||"object"===typeof s&&null!==s&&s.$$typeof===R&&Qs(s)===t.type)?((r=i(t,n.props)).ref=Ks(e,t,n),r.return=e,r):((r=Lc(n.type,n.key,n.props,null,e.mode,r)).ref=Ks(e,t,n),r.return=e,r)}function u(e,t,n,r){return null===t||4!==t.tag||t.stateNode.containerInfo!==n.containerInfo||t.stateNode.implementation!==n.implementation?((t=Uc(n,e.mode,r)).return=e,t):((t=i(t,n.children||[])).return=e,t)}function h(e,t,n,r,s){return null===t||7!==t.tag?((t=Mc(n,e.mode,r,s)).return=e,t):((t=i(t,n)).return=e,t)}function d(e,t,n){if("string"===typeof t&&""!==t||"number"===typeof t)return(t=Fc(""+t,e.mode,n)).return=e,t;if("object"===typeof t&&null!==t){switch(t.$$typeof){case _:return(n=Lc(t.type,t.key,t.props,null,e.mode,n)).ref=Ks(e,null,t),n.return=e,n;case E:return(t=Uc(t,e.mode,n)).return=e,t;case R:return d(e,(0,t._init)(t._payload),n)}if(te(t)||L(t))return(t=Mc(t,e.mode,n,null)).return=e,t;Gs(e,t)}return null}function f(e,t,n,r){var i=null!==t?t.key:null;if("string"===typeof n&&""!==n||"number"===typeof n)return null!==i?null:l(e,t,""+n,r);if("object"===typeof n&&null!==n){switch(n.$$typeof){case _:return n.key===i?c(e,t,n,r):null;case E:return n.key===i?u(e,t,n,r):null;case R:return f(e,t,(i=n._init)(n._payload),r)}if(te(n)||L(n))return null!==i?null:h(e,t,n,r,null);Gs(e,n)}return null}function p(e,t,n,r,i){if("string"===typeof r&&""!==r||"number"===typeof r)return l(t,e=e.get(n)||null,""+r,i);if("object"===typeof r&&null!==r){switch(r.$$typeof){case _:return c(t,e=e.get(null===r.key?n:r.key)||null,r,i);case E:return u(t,e=e.get(null===r.key?n:r.key)||null,r,i);case R:return p(e,t,n,(0,r._init)(r._payload),i)}if(te(r)||L(r))return h(t,e=e.get(n)||null,r,i,null);Gs(t,r)}return null}function m(i,s,o,l){for(var c=null,u=null,h=s,m=s=0,g=null;null!==h&&m<o.length;m++){h.index>m?(g=h,h=null):g=h.sibling;var v=f(i,h,o[m],l);if(null===v){null===h&&(h=g);break}e&&h&&null===v.alternate&&t(i,h),s=a(v,s,m),null===u?c=v:u.sibling=v,u=v,h=g}if(m===o.length)return n(i,h),is&&Ji(i,m),c;if(null===h){for(;m<o.length;m++)null!==(h=d(i,o[m],l))&&(s=a(h,s,m),null===u?c=h:u.sibling=h,u=h);return is&&Ji(i,m),c}for(h=r(i,h);m<o.length;m++)null!==(g=p(h,i,m,o[m],l))&&(e&&null!==g.alternate&&h.delete(null===g.key?m:g.key),s=a(g,s,m),null===u?c=g:u.sibling=g,u=g);return e&&h.forEach((function(e){return t(i,e)})),is&&Ji(i,m),c}function g(i,o,l,c){var u=L(l);if("function"!==typeof u)throw Error(s(150));if(null==(l=u.call(l)))throw Error(s(151));for(var h=u=null,m=o,g=o=0,v=null,y=l.next();null!==m&&!y.done;g++,y=l.next()){m.index>g?(v=m,m=null):v=m.sibling;var w=f(i,m,y.value,c);if(null===w){null===m&&(m=v);break}e&&m&&null===w.alternate&&t(i,m),o=a(w,o,g),null===h?u=w:h.sibling=w,h=w,m=v}if(y.done)return n(i,m),is&&Ji(i,g),u;if(null===m){for(;!y.done;g++,y=l.next())null!==(y=d(i,y.value,c))&&(o=a(y,o,g),null===h?u=y:h.sibling=y,h=y);return is&&Ji(i,g),u}for(m=r(i,m);!y.done;g++,y=l.next())null!==(y=p(m,i,g,y.value,c))&&(e&&null!==y.alternate&&m.delete(null===y.key?g:y.key),o=a(y,o,g),null===h?u=y:h.sibling=y,h=y);return e&&m.forEach((function(e){return t(i,e)})),is&&Ji(i,g),u}return function e(r,s,a,l){if("object"===typeof a&&null!==a&&a.type===S&&null===a.key&&(a=a.props.children),"object"===typeof a&&null!==a){switch(a.$$typeof){case _:e:{for(var c=a.key,u=s;null!==u;){if(u.key===c){if((c=a.type)===S){if(7===u.tag){n(r,u.sibling),(s=i(u,a.props.children)).return=r,r=s;break e}}else if(u.elementType===c||"object"===typeof c&&null!==c&&c.$$typeof===R&&Qs(c)===u.type){n(r,u.sibling),(s=i(u,a.props)).ref=Ks(r,u,a),s.return=r,r=s;break e}n(r,u);break}t(r,u),u=u.sibling}a.type===S?((s=Mc(a.props.children,r.mode,l,a.key)).return=r,r=s):((l=Lc(a.type,a.key,a.props,null,r.mode,l)).ref=Ks(r,s,a),l.return=r,r=l)}return o(r);case E:e:{for(u=a.key;null!==s;){if(s.key===u){if(4===s.tag&&s.stateNode.containerInfo===a.containerInfo&&s.stateNode.implementation===a.implementation){n(r,s.sibling),(s=i(s,a.children||[])).return=r,r=s;break e}n(r,s);break}t(r,s),s=s.sibling}(s=Uc(a,r.mode,l)).return=r,r=s}return o(r);case R:return e(r,s,(u=a._init)(a._payload),l)}if(te(a))return m(r,s,a,l);if(L(a))return g(r,s,a,l);Gs(r,a)}return"string"===typeof a&&""!==a||"number"===typeof a?(a=""+a,null!==s&&6===s.tag?(n(r,s.sibling),(s=i(s,a)).return=r,r=s):(n(r,s),(s=Fc(a,r.mode,l)).return=r,r=s),o(r)):n(r,s)}}var Ys=$s(!0),Xs=$s(!1),Js={},Zs=ki(Js),ea=ki(Js),ta=ki(Js);function na(e){if(e===Js)throw Error(s(174));return e}function ra(e,t){switch(Ti(ta,t),Ti(ea,e),Ti(Zs,Js),e=t.nodeType){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:le(null,"");break;default:t=le(t=(e=8===e?t.parentNode:t).namespaceURI||null,e=e.tagName)}Ii(Zs),Ti(Zs,t)}function ia(){Ii(Zs),Ii(ea),Ii(ta)}function sa(e){na(ta.current);var t=na(Zs.current),n=le(t,e.type);t!==n&&(Ti(ea,e),Ti(Zs,n))}function aa(e){ea.current===e&&(Ii(Zs),Ii(ea))}var oa=ki(0);function la(e){for(var t=e;null!==t;){if(13===t.tag){var n=t.memoizedState;if(null!==n&&(null===(n=n.dehydrated)||"$?"===n.data||"$!"===n.data))return t}else if(19===t.tag&&void 0!==t.memoizedProps.revealOrder){if(0!==(128&t.flags))return t}else if(null!==t.child){t.child.return=t,t=t.child;continue}if(t===e)break;for(;null===t.sibling;){if(null===t.return||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var ca=[];function ua(){for(var e=0;e<ca.length;e++)ca[e]._workInProgressVersionPrimary=null;ca.length=0}var ha=b.ReactCurrentDispatcher,da=b.ReactCurrentBatchConfig,fa=0,pa=null,ma=null,ga=null,va=!1,ya=!1,wa=0,ba=0;function _a(){throw Error(s(321))}function Ea(e,t){if(null===t)return!1;for(var n=0;n<t.length&&n<e.length;n++)if(!or(e[n],t[n]))return!1;return!0}function Sa(e,t,n,r,i,a){if(fa=a,pa=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,ha.current=null===e||null===e.memoizedState?ao:oo,e=n(r,i),ya){a=0;do{if(ya=!1,wa=0,25<=a)throw Error(s(301));a+=1,ga=ma=null,t.updateQueue=null,ha.current=lo,e=n(r,i)}while(ya)}if(ha.current=so,t=null!==ma&&null!==ma.next,fa=0,ga=ma=pa=null,va=!1,t)throw Error(s(300));return e}function ka(){var e=0!==wa;return wa=0,e}function Ia(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return null===ga?pa.memoizedState=ga=e:ga=ga.next=e,ga}function Ta(){if(null===ma){var e=pa.alternate;e=null!==e?e.memoizedState:null}else e=ma.next;var t=null===ga?pa.memoizedState:ga.next;if(null!==t)ga=t,ma=e;else{if(null===e)throw Error(s(310));e={memoizedState:(ma=e).memoizedState,baseState:ma.baseState,baseQueue:ma.baseQueue,queue:ma.queue,next:null},null===ga?pa.memoizedState=ga=e:ga=ga.next=e}return ga}function Ca(e,t){return"function"===typeof t?t(e):t}function xa(e){var t=Ta(),n=t.queue;if(null===n)throw Error(s(311));n.lastRenderedReducer=e;var r=ma,i=r.baseQueue,a=n.pending;if(null!==a){if(null!==i){var o=i.next;i.next=a.next,a.next=o}r.baseQueue=i=a,n.pending=null}if(null!==i){a=i.next,r=r.baseState;var l=o=null,c=null,u=a;do{var h=u.lane;if((fa&h)===h)null!==c&&(c=c.next={lane:0,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null}),r=u.hasEagerState?u.eagerState:e(r,u.action);else{var d={lane:h,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null};null===c?(l=c=d,o=r):c=c.next=d,pa.lanes|=h,jl|=h}u=u.next}while(null!==u&&u!==a);null===c?o=r:c.next=l,or(r,t.memoizedState)||(bo=!0),t.memoizedState=r,t.baseState=o,t.baseQueue=c,n.lastRenderedState=r}if(null!==(e=n.interleaved)){i=e;do{a=i.lane,pa.lanes|=a,jl|=a,i=i.next}while(i!==e)}else null===i&&(n.lanes=0);return[t.memoizedState,n.dispatch]}function Na(e){var t=Ta(),n=t.queue;if(null===n)throw Error(s(311));n.lastRenderedReducer=e;var r=n.dispatch,i=n.pending,a=t.memoizedState;if(null!==i){n.pending=null;var o=i=i.next;do{a=e(a,o.action),o=o.next}while(o!==i);or(a,t.memoizedState)||(bo=!0),t.memoizedState=a,null===t.baseQueue&&(t.baseState=a),n.lastRenderedState=a}return[a,r]}function Aa(){}function Pa(e,t){var n=pa,r=Ta(),i=t(),a=!or(r.memoizedState,i);if(a&&(r.memoizedState=i,bo=!0),r=r.queue,qa(Da.bind(null,n,r,e),[e]),r.getSnapshot!==t||a||null!==ga&&1&ga.memoizedState.tag){if(n.flags|=2048,Fa(9,Oa.bind(null,n,r,i,t),void 0,null),null===Al)throw Error(s(349));0!==(30&fa)||Ra(n,t,i)}return i}function Ra(e,t,n){e.flags|=16384,e={getSnapshot:t,value:n},null===(t=pa.updateQueue)?(t={lastEffect:null,stores:null},pa.updateQueue=t,t.stores=[e]):null===(n=t.stores)?t.stores=[e]:n.push(e)}function Oa(e,t,n,r){t.value=n,t.getSnapshot=r,La(t)&&Ma(e)}function Da(e,t,n){return n((function(){La(t)&&Ma(e)}))}function La(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!or(e,n)}catch(r){return!0}}function Ma(e){var t=Ns(e,1);null!==t&&rc(t,e,1,-1)}function ja(e){var t=Ia();return"function"===typeof e&&(e=e()),t.memoizedState=t.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Ca,lastRenderedState:e},t.queue=e,e=e.dispatch=to.bind(null,pa,e),[t.memoizedState,e]}function Fa(e,t,n,r){return e={tag:e,create:t,destroy:n,deps:r,next:null},null===(t=pa.updateQueue)?(t={lastEffect:null,stores:null},pa.updateQueue=t,t.lastEffect=e.next=e):null===(n=t.lastEffect)?t.lastEffect=e.next=e:(r=n.next,n.next=e,e.next=r,t.lastEffect=e),e}function Ua(){return Ta().memoizedState}function Va(e,t,n,r){var i=Ia();pa.flags|=e,i.memoizedState=Fa(1|t,n,void 0,void 0===r?null:r)}function Ba(e,t,n,r){var i=Ta();r=void 0===r?null:r;var s=void 0;if(null!==ma){var a=ma.memoizedState;if(s=a.destroy,null!==r&&Ea(r,a.deps))return void(i.memoizedState=Fa(t,n,s,r))}pa.flags|=e,i.memoizedState=Fa(1|t,n,s,r)}function za(e,t){return Va(8390656,8,e,t)}function qa(e,t){return Ba(2048,8,e,t)}function Ha(e,t){return Ba(4,2,e,t)}function Wa(e,t){return Ba(4,4,e,t)}function Ka(e,t){return"function"===typeof t?(e=e(),t(e),function(){t(null)}):null!==t&&void 0!==t?(e=e(),t.current=e,function(){t.current=null}):void 0}function Ga(e,t,n){return n=null!==n&&void 0!==n?n.concat([e]):null,Ba(4,4,Ka.bind(null,t,e),n)}function Qa(){}function $a(e,t){var n=Ta();t=void 0===t?null:t;var r=n.memoizedState;return null!==r&&null!==t&&Ea(t,r[1])?r[0]:(n.memoizedState=[e,t],e)}function Ya(e,t){var n=Ta();t=void 0===t?null:t;var r=n.memoizedState;return null!==r&&null!==t&&Ea(t,r[1])?r[0]:(e=e(),n.memoizedState=[e,t],e)}function Xa(e,t,n){return 0===(21&fa)?(e.baseState&&(e.baseState=!1,bo=!0),e.memoizedState=n):(or(n,t)||(n=mt(),pa.lanes|=n,jl|=n,e.baseState=!0),t)}function Ja(e,t){var n=wt;wt=0!==n&&4>n?n:4,e(!0);var r=da.transition;da.transition={};try{e(!1),t()}finally{wt=n,da.transition=r}}function Za(){return Ta().memoizedState}function eo(e,t,n){var r=nc(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},no(e))ro(t,n);else if(null!==(n=xs(e,t,n,r))){rc(n,e,r,tc()),io(n,t,r)}}function to(e,t,n){var r=nc(e),i={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(no(e))ro(t,i);else{var s=e.alternate;if(0===e.lanes&&(null===s||0===s.lanes)&&null!==(s=t.lastRenderedReducer))try{var a=t.lastRenderedState,o=s(a,n);if(i.hasEagerState=!0,i.eagerState=o,or(o,a)){var l=t.interleaved;return null===l?(i.next=i,Cs(t)):(i.next=l.next,l.next=i),void(t.interleaved=i)}}catch(c){}null!==(n=xs(e,t,i,r))&&(rc(n,e,r,i=tc()),io(n,t,r))}}function no(e){var t=e.alternate;return e===pa||null!==t&&t===pa}function ro(e,t){ya=va=!0;var n=e.pending;null===n?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function io(e,t,n){if(0!==(4194240&n)){var r=t.lanes;n|=r&=e.pendingLanes,t.lanes=n,yt(e,n)}}var so={readContext:Is,useCallback:_a,useContext:_a,useEffect:_a,useImperativeHandle:_a,useInsertionEffect:_a,useLayoutEffect:_a,useMemo:_a,useReducer:_a,useRef:_a,useState:_a,useDebugValue:_a,useDeferredValue:_a,useTransition:_a,useMutableSource:_a,useSyncExternalStore:_a,useId:_a,unstable_isNewReconciler:!1},ao={readContext:Is,useCallback:function(e,t){return Ia().memoizedState=[e,void 0===t?null:t],e},useContext:Is,useEffect:za,useImperativeHandle:function(e,t,n){return n=null!==n&&void 0!==n?n.concat([e]):null,Va(4194308,4,Ka.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Va(4194308,4,e,t)},useInsertionEffect:function(e,t){return Va(4,2,e,t)},useMemo:function(e,t){var n=Ia();return t=void 0===t?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Ia();return t=void 0!==n?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=eo.bind(null,pa,e),[r.memoizedState,e]},useRef:function(e){return e={current:e},Ia().memoizedState=e},useState:ja,useDebugValue:Qa,useDeferredValue:function(e){return Ia().memoizedState=e},useTransition:function(){var e=ja(!1),t=e[0];return e=Ja.bind(null,e[1]),Ia().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=pa,i=Ia();if(is){if(void 0===n)throw Error(s(407));n=n()}else{if(n=t(),null===Al)throw Error(s(349));0!==(30&fa)||Ra(r,t,n)}i.memoizedState=n;var a={value:n,getSnapshot:t};return i.queue=a,za(Da.bind(null,r,a,e),[e]),r.flags|=2048,Fa(9,Oa.bind(null,r,a,n,t),void 0,null),n},useId:function(){var e=Ia(),t=Al.identifierPrefix;if(is){var n=Xi;t=":"+t+"R"+(n=(Yi&~(1<<32-at(Yi)-1)).toString(32)+n),0<(n=wa++)&&(t+="H"+n.toString(32)),t+=":"}else t=":"+t+"r"+(n=ba++).toString(32)+":";return e.memoizedState=t},unstable_isNewReconciler:!1},oo={readContext:Is,useCallback:$a,useContext:Is,useEffect:qa,useImperativeHandle:Ga,useInsertionEffect:Ha,useLayoutEffect:Wa,useMemo:Ya,useReducer:xa,useRef:Ua,useState:function(){return xa(Ca)},useDebugValue:Qa,useDeferredValue:function(e){return Xa(Ta(),ma.memoizedState,e)},useTransition:function(){return[xa(Ca)[0],Ta().memoizedState]},useMutableSource:Aa,useSyncExternalStore:Pa,useId:Za,unstable_isNewReconciler:!1},lo={readContext:Is,useCallback:$a,useContext:Is,useEffect:qa,useImperativeHandle:Ga,useInsertionEffect:Ha,useLayoutEffect:Wa,useMemo:Ya,useReducer:Na,useRef:Ua,useState:function(){return Na(Ca)},useDebugValue:Qa,useDeferredValue:function(e){var t=Ta();return null===ma?t.memoizedState=e:Xa(t,ma.memoizedState,e)},useTransition:function(){return[Na(Ca)[0],Ta().memoizedState]},useMutableSource:Aa,useSyncExternalStore:Pa,useId:Za,unstable_isNewReconciler:!1};function co(e,t){try{var n="",r=t;do{n+=B(r),r=r.return}while(r);var i=n}catch(s){i="\nError generating stack: "+s.message+"\n"+s.stack}return{value:e,source:t,stack:i,digest:null}}function uo(e,t,n){return{value:e,source:null,stack:null!=n?n:null,digest:null!=t?t:null}}function ho(e,t){try{console.error(t.value)}catch(n){setTimeout((function(){throw n}))}}var fo="function"===typeof WeakMap?WeakMap:Map;function po(e,t,n){(n=Os(-1,n)).tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){Wl||(Wl=!0,Kl=r),ho(0,t)},n}function mo(e,t,n){(n=Os(-1,n)).tag=3;var r=e.type.getDerivedStateFromError;if("function"===typeof r){var i=t.value;n.payload=function(){return r(i)},n.callback=function(){ho(0,t)}}var s=e.stateNode;return null!==s&&"function"===typeof s.componentDidCatch&&(n.callback=function(){ho(0,t),"function"!==typeof r&&(null===Gl?Gl=new Set([this]):Gl.add(this));var e=t.stack;this.componentDidCatch(t.value,{componentStack:null!==e?e:""})}),n}function go(e,t,n){var r=e.pingCache;if(null===r){r=e.pingCache=new fo;var i=new Set;r.set(t,i)}else void 0===(i=r.get(t))&&(i=new Set,r.set(t,i));i.has(n)||(i.add(n),e=Tc.bind(null,e,t,n),t.then(e,e))}function vo(e){do{var t;if((t=13===e.tag)&&(t=null===(t=e.memoizedState)||null!==t.dehydrated),t)return e;e=e.return}while(null!==e);return null}function yo(e,t,n,r,i){return 0===(1&e.mode)?(e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,1===n.tag&&(null===n.alternate?n.tag=17:((t=Os(-1,1)).tag=2,Ds(n,t,1))),n.lanes|=1),e):(e.flags|=65536,e.lanes=i,e)}var wo=b.ReactCurrentOwner,bo=!1;function _o(e,t,n,r){t.child=null===e?Xs(t,null,n,r):Ys(t,e.child,n,r)}function Eo(e,t,n,r,i){n=n.render;var s=t.ref;return ks(t,i),r=Sa(e,t,n,r,s,i),n=ka(),null===e||bo?(is&&n&&es(t),t.flags|=1,_o(e,t,r,i),t.child):(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,Wo(e,t,i))}function So(e,t,n,r,i){if(null===e){var s=n.type;return"function"!==typeof s||Oc(s)||void 0!==s.defaultProps||null!==n.compare||void 0!==n.defaultProps?((e=Lc(n.type,null,r,t,t.mode,i)).ref=t.ref,e.return=t,t.child=e):(t.tag=15,t.type=s,ko(e,t,s,r,i))}if(s=e.child,0===(e.lanes&i)){var a=s.memoizedProps;if((n=null!==(n=n.compare)?n:lr)(a,r)&&e.ref===t.ref)return Wo(e,t,i)}return t.flags|=1,(e=Dc(s,r)).ref=t.ref,e.return=t,t.child=e}function ko(e,t,n,r,i){if(null!==e){var s=e.memoizedProps;if(lr(s,r)&&e.ref===t.ref){if(bo=!1,t.pendingProps=r=s,0===(e.lanes&i))return t.lanes=e.lanes,Wo(e,t,i);0!==(131072&e.flags)&&(bo=!0)}}return Co(e,t,n,r,i)}function Io(e,t,n){var r=t.pendingProps,i=r.children,s=null!==e?e.memoizedState:null;if("hidden"===r.mode)if(0===(1&t.mode))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},Ti(Dl,Ol),Ol|=n;else{if(0===(1073741824&n))return e=null!==s?s.baseLanes|n:n,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,Ti(Dl,Ol),Ol|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=null!==s?s.baseLanes:n,Ti(Dl,Ol),Ol|=r}else null!==s?(r=s.baseLanes|n,t.memoizedState=null):r=n,Ti(Dl,Ol),Ol|=r;return _o(e,t,i,n),t.child}function To(e,t){var n=t.ref;(null===e&&null!==n||null!==e&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function Co(e,t,n,r,i){var s=Ri(n)?Ai:xi.current;return s=Pi(t,s),ks(t,i),n=Sa(e,t,n,r,s,i),r=ka(),null===e||bo?(is&&r&&es(t),t.flags|=1,_o(e,t,n,i),t.child):(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,Wo(e,t,i))}function xo(e,t,n,r,i){if(Ri(n)){var s=!0;Mi(t)}else s=!1;if(ks(t,i),null===t.stateNode)Ho(e,t),qs(t,n,r),Ws(t,n,r,i),r=!0;else if(null===e){var a=t.stateNode,o=t.memoizedProps;a.props=o;var l=a.context,c=n.contextType;"object"===typeof c&&null!==c?c=Is(c):c=Pi(t,c=Ri(n)?Ai:xi.current);var u=n.getDerivedStateFromProps,h="function"===typeof u||"function"===typeof a.getSnapshotBeforeUpdate;h||"function"!==typeof a.UNSAFE_componentWillReceiveProps&&"function"!==typeof a.componentWillReceiveProps||(o!==r||l!==c)&&Hs(t,a,r,c),As=!1;var d=t.memoizedState;a.state=d,js(t,r,a,i),l=t.memoizedState,o!==r||d!==l||Ni.current||As?("function"===typeof u&&(Vs(t,n,u,r),l=t.memoizedState),(o=As||zs(t,n,o,r,d,l,c))?(h||"function"!==typeof a.UNSAFE_componentWillMount&&"function"!==typeof a.componentWillMount||("function"===typeof a.componentWillMount&&a.componentWillMount(),"function"===typeof a.UNSAFE_componentWillMount&&a.UNSAFE_componentWillMount()),"function"===typeof a.componentDidMount&&(t.flags|=4194308)):("function"===typeof a.componentDidMount&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=l),a.props=r,a.state=l,a.context=c,r=o):("function"===typeof a.componentDidMount&&(t.flags|=4194308),r=!1)}else{a=t.stateNode,Rs(e,t),o=t.memoizedProps,c=t.type===t.elementType?o:gs(t.type,o),a.props=c,h=t.pendingProps,d=a.context,"object"===typeof(l=n.contextType)&&null!==l?l=Is(l):l=Pi(t,l=Ri(n)?Ai:xi.current);var f=n.getDerivedStateFromProps;(u="function"===typeof f||"function"===typeof a.getSnapshotBeforeUpdate)||"function"!==typeof a.UNSAFE_componentWillReceiveProps&&"function"!==typeof a.componentWillReceiveProps||(o!==h||d!==l)&&Hs(t,a,r,l),As=!1,d=t.memoizedState,a.state=d,js(t,r,a,i);var p=t.memoizedState;o!==h||d!==p||Ni.current||As?("function"===typeof f&&(Vs(t,n,f,r),p=t.memoizedState),(c=As||zs(t,n,c,r,d,p,l)||!1)?(u||"function"!==typeof a.UNSAFE_componentWillUpdate&&"function"!==typeof a.componentWillUpdate||("function"===typeof a.componentWillUpdate&&a.componentWillUpdate(r,p,l),"function"===typeof a.UNSAFE_componentWillUpdate&&a.UNSAFE_componentWillUpdate(r,p,l)),"function"===typeof a.componentDidUpdate&&(t.flags|=4),"function"===typeof a.getSnapshotBeforeUpdate&&(t.flags|=1024)):("function"!==typeof a.componentDidUpdate||o===e.memoizedProps&&d===e.memoizedState||(t.flags|=4),"function"!==typeof a.getSnapshotBeforeUpdate||o===e.memoizedProps&&d===e.memoizedState||(t.flags|=1024),t.memoizedProps=r,t.memoizedState=p),a.props=r,a.state=p,a.context=l,r=c):("function"!==typeof a.componentDidUpdate||o===e.memoizedProps&&d===e.memoizedState||(t.flags|=4),"function"!==typeof a.getSnapshotBeforeUpdate||o===e.memoizedProps&&d===e.memoizedState||(t.flags|=1024),r=!1)}return No(e,t,n,r,s,i)}function No(e,t,n,r,i,s){To(e,t);var a=0!==(128&t.flags);if(!r&&!a)return i&&ji(t,n,!1),Wo(e,t,s);r=t.stateNode,wo.current=t;var o=a&&"function"!==typeof n.getDerivedStateFromError?null:r.render();return t.flags|=1,null!==e&&a?(t.child=Ys(t,e.child,null,s),t.child=Ys(t,null,o,s)):_o(e,t,o,s),t.memoizedState=r.state,i&&ji(t,n,!0),t.child}function Ao(e){var t=e.stateNode;t.pendingContext?Di(0,t.pendingContext,t.pendingContext!==t.context):t.context&&Di(0,t.context,!1),ra(e,t.containerInfo)}function Po(e,t,n,r,i){return fs(),ps(i),t.flags|=256,_o(e,t,n,r),t.child}var Ro,Oo,Do,Lo,Mo={dehydrated:null,treeContext:null,retryLane:0};function jo(e){return{baseLanes:e,cachePool:null,transitions:null}}function Fo(e,t,n){var r,i=t.pendingProps,a=oa.current,o=!1,l=0!==(128&t.flags);if((r=l)||(r=(null===e||null!==e.memoizedState)&&0!==(2&a)),r?(o=!0,t.flags&=-129):null!==e&&null===e.memoizedState||(a|=1),Ti(oa,1&a),null===e)return cs(t),null!==(e=t.memoizedState)&&null!==(e=e.dehydrated)?(0===(1&t.mode)?t.lanes=1:"$!"===e.data?t.lanes=8:t.lanes=1073741824,null):(l=i.children,e=i.fallback,o?(i=t.mode,o=t.child,l={mode:"hidden",children:l},0===(1&i)&&null!==o?(o.childLanes=0,o.pendingProps=l):o=jc(l,i,0,null),e=Mc(e,i,n,null),o.return=t,e.return=t,o.sibling=e,t.child=o,t.child.memoizedState=jo(n),t.memoizedState=Mo,e):Uo(t,l));if(null!==(a=e.memoizedState)&&null!==(r=a.dehydrated))return function(e,t,n,r,i,a,o){if(n)return 256&t.flags?(t.flags&=-257,Vo(e,t,o,r=uo(Error(s(422))))):null!==t.memoizedState?(t.child=e.child,t.flags|=128,null):(a=r.fallback,i=t.mode,r=jc({mode:"visible",children:r.children},i,0,null),(a=Mc(a,i,o,null)).flags|=2,r.return=t,a.return=t,r.sibling=a,t.child=r,0!==(1&t.mode)&&Ys(t,e.child,null,o),t.child.memoizedState=jo(o),t.memoizedState=Mo,a);if(0===(1&t.mode))return Vo(e,t,o,null);if("$!"===i.data){if(r=i.nextSibling&&i.nextSibling.dataset)var l=r.dgst;return r=l,Vo(e,t,o,r=uo(a=Error(s(419)),r,void 0))}if(l=0!==(o&e.childLanes),bo||l){if(null!==(r=Al)){switch(o&-o){case 4:i=2;break;case 16:i=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:i=32;break;case 536870912:i=268435456;break;default:i=0}0!==(i=0!==(i&(r.suspendedLanes|o))?0:i)&&i!==a.retryLane&&(a.retryLane=i,Ns(e,i),rc(r,e,i,-1))}return gc(),Vo(e,t,o,r=uo(Error(s(421))))}return"$?"===i.data?(t.flags|=128,t.child=e.child,t=xc.bind(null,e),i._reactRetry=t,null):(e=a.treeContext,rs=ci(i.nextSibling),ns=t,is=!0,ss=null,null!==e&&(Gi[Qi++]=Yi,Gi[Qi++]=Xi,Gi[Qi++]=$i,Yi=e.id,Xi=e.overflow,$i=t),t=Uo(t,r.children),t.flags|=4096,t)}(e,t,l,i,r,a,n);if(o){o=i.fallback,l=t.mode,r=(a=e.child).sibling;var c={mode:"hidden",children:i.children};return 0===(1&l)&&t.child!==a?((i=t.child).childLanes=0,i.pendingProps=c,t.deletions=null):(i=Dc(a,c)).subtreeFlags=14680064&a.subtreeFlags,null!==r?o=Dc(r,o):(o=Mc(o,l,n,null)).flags|=2,o.return=t,i.return=t,i.sibling=o,t.child=i,i=o,o=t.child,l=null===(l=e.child.memoizedState)?jo(n):{baseLanes:l.baseLanes|n,cachePool:null,transitions:l.transitions},o.memoizedState=l,o.childLanes=e.childLanes&~n,t.memoizedState=Mo,i}return e=(o=e.child).sibling,i=Dc(o,{mode:"visible",children:i.children}),0===(1&t.mode)&&(i.lanes=n),i.return=t,i.sibling=null,null!==e&&(null===(n=t.deletions)?(t.deletions=[e],t.flags|=16):n.push(e)),t.child=i,t.memoizedState=null,i}function Uo(e,t){return(t=jc({mode:"visible",children:t},e.mode,0,null)).return=e,e.child=t}function Vo(e,t,n,r){return null!==r&&ps(r),Ys(t,e.child,null,n),(e=Uo(t,t.pendingProps.children)).flags|=2,t.memoizedState=null,e}function Bo(e,t,n){e.lanes|=t;var r=e.alternate;null!==r&&(r.lanes|=t),Ss(e.return,t,n)}function zo(e,t,n,r,i){var s=e.memoizedState;null===s?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:i}:(s.isBackwards=t,s.rendering=null,s.renderingStartTime=0,s.last=r,s.tail=n,s.tailMode=i)}function qo(e,t,n){var r=t.pendingProps,i=r.revealOrder,s=r.tail;if(_o(e,t,r.children,n),0!==(2&(r=oa.current)))r=1&r|2,t.flags|=128;else{if(null!==e&&0!==(128&e.flags))e:for(e=t.child;null!==e;){if(13===e.tag)null!==e.memoizedState&&Bo(e,n,t);else if(19===e.tag)Bo(e,n,t);else if(null!==e.child){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;null===e.sibling;){if(null===e.return||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(Ti(oa,r),0===(1&t.mode))t.memoizedState=null;else switch(i){case"forwards":for(n=t.child,i=null;null!==n;)null!==(e=n.alternate)&&null===la(e)&&(i=n),n=n.sibling;null===(n=i)?(i=t.child,t.child=null):(i=n.sibling,n.sibling=null),zo(t,!1,i,n,s);break;case"backwards":for(n=null,i=t.child,t.child=null;null!==i;){if(null!==(e=i.alternate)&&null===la(e)){t.child=i;break}e=i.sibling,i.sibling=n,n=i,i=e}zo(t,!0,n,null,s);break;case"together":zo(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function Ho(e,t){0===(1&t.mode)&&null!==e&&(e.alternate=null,t.alternate=null,t.flags|=2)}function Wo(e,t,n){if(null!==e&&(t.dependencies=e.dependencies),jl|=t.lanes,0===(n&t.childLanes))return null;if(null!==e&&t.child!==e.child)throw Error(s(153));if(null!==t.child){for(n=Dc(e=t.child,e.pendingProps),t.child=n,n.return=t;null!==e.sibling;)e=e.sibling,(n=n.sibling=Dc(e,e.pendingProps)).return=t;n.sibling=null}return t.child}function Ko(e,t){if(!is)switch(e.tailMode){case"hidden":t=e.tail;for(var n=null;null!==t;)null!==t.alternate&&(n=t),t=t.sibling;null===n?e.tail=null:n.sibling=null;break;case"collapsed":n=e.tail;for(var r=null;null!==n;)null!==n.alternate&&(r=n),n=n.sibling;null===r?t||null===e.tail?e.tail=null:e.tail.sibling=null:r.sibling=null}}function Go(e){var t=null!==e.alternate&&e.alternate.child===e.child,n=0,r=0;if(t)for(var i=e.child;null!==i;)n|=i.lanes|i.childLanes,r|=14680064&i.subtreeFlags,r|=14680064&i.flags,i.return=e,i=i.sibling;else for(i=e.child;null!==i;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags,r|=i.flags,i.return=e,i=i.sibling;return e.subtreeFlags|=r,e.childLanes=n,t}function Qo(e,t,n){var r=t.pendingProps;switch(ts(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Go(t),null;case 1:case 17:return Ri(t.type)&&Oi(),Go(t),null;case 3:return r=t.stateNode,ia(),Ii(Ni),Ii(xi),ua(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),null!==e&&null!==e.child||(hs(t)?t.flags|=4:null===e||e.memoizedState.isDehydrated&&0===(256&t.flags)||(t.flags|=1024,null!==ss&&(oc(ss),ss=null))),Oo(e,t),Go(t),null;case 5:aa(t);var i=na(ta.current);if(n=t.type,null!==e&&null!=t.stateNode)Do(e,t,n,r,i),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!r){if(null===t.stateNode)throw Error(s(166));return Go(t),null}if(e=na(Zs.current),hs(t)){r=t.stateNode,n=t.type;var a=t.memoizedProps;switch(r[di]=t,r[fi]=a,e=0!==(1&t.mode),n){case"dialog":Ur("cancel",r),Ur("close",r);break;case"iframe":case"object":case"embed":Ur("load",r);break;case"video":case"audio":for(i=0;i<Lr.length;i++)Ur(Lr[i],r);break;case"source":Ur("error",r);break;case"img":case"image":case"link":Ur("error",r),Ur("load",r);break;case"details":Ur("toggle",r);break;case"input":Y(r,a),Ur("invalid",r);break;case"select":r._wrapperState={wasMultiple:!!a.multiple},Ur("invalid",r);break;case"textarea":ie(r,a),Ur("invalid",r)}for(var l in ye(n,a),i=null,a)if(a.hasOwnProperty(l)){var c=a[l];"children"===l?"string"===typeof c?r.textContent!==c&&(!0!==a.suppressHydrationWarning&&Jr(r.textContent,c,e),i=["children",c]):"number"===typeof c&&r.textContent!==""+c&&(!0!==a.suppressHydrationWarning&&Jr(r.textContent,c,e),i=["children",""+c]):o.hasOwnProperty(l)&&null!=c&&"onScroll"===l&&Ur("scroll",r)}switch(n){case"input":K(r),Z(r,a,!0);break;case"textarea":K(r),ae(r);break;case"select":case"option":break;default:"function"===typeof a.onClick&&(r.onclick=Zr)}r=i,t.updateQueue=r,null!==r&&(t.flags|=4)}else{l=9===i.nodeType?i:i.ownerDocument,"http://www.w3.org/1999/xhtml"===e&&(e=oe(n)),"http://www.w3.org/1999/xhtml"===e?"script"===n?((e=l.createElement("div")).innerHTML="<script><\/script>",e=e.removeChild(e.firstChild)):"string"===typeof r.is?e=l.createElement(n,{is:r.is}):(e=l.createElement(n),"select"===n&&(l=e,r.multiple?l.multiple=!0:r.size&&(l.size=r.size))):e=l.createElementNS(e,n),e[di]=t,e[fi]=r,Ro(e,t,!1,!1),t.stateNode=e;e:{switch(l=we(n,r),n){case"dialog":Ur("cancel",e),Ur("close",e),i=r;break;case"iframe":case"object":case"embed":Ur("load",e),i=r;break;case"video":case"audio":for(i=0;i<Lr.length;i++)Ur(Lr[i],e);i=r;break;case"source":Ur("error",e),i=r;break;case"img":case"image":case"link":Ur("error",e),Ur("load",e),i=r;break;case"details":Ur("toggle",e),i=r;break;case"input":Y(e,r),i=$(e,r),Ur("invalid",e);break;case"option":default:i=r;break;case"select":e._wrapperState={wasMultiple:!!r.multiple},i=j({},r,{value:void 0}),Ur("invalid",e);break;case"textarea":ie(e,r),i=re(e,r),Ur("invalid",e)}for(a in ye(n,i),c=i)if(c.hasOwnProperty(a)){var u=c[a];"style"===a?ge(e,u):"dangerouslySetInnerHTML"===a?null!=(u=u?u.__html:void 0)&&he(e,u):"children"===a?"string"===typeof u?("textarea"!==n||""!==u)&&de(e,u):"number"===typeof u&&de(e,""+u):"suppressContentEditableWarning"!==a&&"suppressHydrationWarning"!==a&&"autoFocus"!==a&&(o.hasOwnProperty(a)?null!=u&&"onScroll"===a&&Ur("scroll",e):null!=u&&w(e,a,u,l))}switch(n){case"input":K(e),Z(e,r,!1);break;case"textarea":K(e),ae(e);break;case"option":null!=r.value&&e.setAttribute("value",""+H(r.value));break;case"select":e.multiple=!!r.multiple,null!=(a=r.value)?ne(e,!!r.multiple,a,!1):null!=r.defaultValue&&ne(e,!!r.multiple,r.defaultValue,!0);break;default:"function"===typeof i.onClick&&(e.onclick=Zr)}switch(n){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}}r&&(t.flags|=4)}null!==t.ref&&(t.flags|=512,t.flags|=2097152)}return Go(t),null;case 6:if(e&&null!=t.stateNode)Lo(e,t,e.memoizedProps,r);else{if("string"!==typeof r&&null===t.stateNode)throw Error(s(166));if(n=na(ta.current),na(Zs.current),hs(t)){if(r=t.stateNode,n=t.memoizedProps,r[di]=t,(a=r.nodeValue!==n)&&null!==(e=ns))switch(e.tag){case 3:Jr(r.nodeValue,n,0!==(1&e.mode));break;case 5:!0!==e.memoizedProps.suppressHydrationWarning&&Jr(r.nodeValue,n,0!==(1&e.mode))}a&&(t.flags|=4)}else(r=(9===n.nodeType?n:n.ownerDocument).createTextNode(r))[di]=t,t.stateNode=r}return Go(t),null;case 13:if(Ii(oa),r=t.memoizedState,null===e||null!==e.memoizedState&&null!==e.memoizedState.dehydrated){if(is&&null!==rs&&0!==(1&t.mode)&&0===(128&t.flags))ds(),fs(),t.flags|=98560,a=!1;else if(a=hs(t),null!==r&&null!==r.dehydrated){if(null===e){if(!a)throw Error(s(318));if(!(a=null!==(a=t.memoizedState)?a.dehydrated:null))throw Error(s(317));a[di]=t}else fs(),0===(128&t.flags)&&(t.memoizedState=null),t.flags|=4;Go(t),a=!1}else null!==ss&&(oc(ss),ss=null),a=!0;if(!a)return 65536&t.flags?t:null}return 0!==(128&t.flags)?(t.lanes=n,t):((r=null!==r)!==(null!==e&&null!==e.memoizedState)&&r&&(t.child.flags|=8192,0!==(1&t.mode)&&(null===e||0!==(1&oa.current)?0===Ll&&(Ll=3):gc())),null!==t.updateQueue&&(t.flags|=4),Go(t),null);case 4:return ia(),Oo(e,t),null===e&&zr(t.stateNode.containerInfo),Go(t),null;case 10:return Es(t.type._context),Go(t),null;case 19:if(Ii(oa),null===(a=t.memoizedState))return Go(t),null;if(r=0!==(128&t.flags),null===(l=a.rendering))if(r)Ko(a,!1);else{if(0!==Ll||null!==e&&0!==(128&e.flags))for(e=t.child;null!==e;){if(null!==(l=la(e))){for(t.flags|=128,Ko(a,!1),null!==(r=l.updateQueue)&&(t.updateQueue=r,t.flags|=4),t.subtreeFlags=0,r=n,n=t.child;null!==n;)e=r,(a=n).flags&=14680066,null===(l=a.alternate)?(a.childLanes=0,a.lanes=e,a.child=null,a.subtreeFlags=0,a.memoizedProps=null,a.memoizedState=null,a.updateQueue=null,a.dependencies=null,a.stateNode=null):(a.childLanes=l.childLanes,a.lanes=l.lanes,a.child=l.child,a.subtreeFlags=0,a.deletions=null,a.memoizedProps=l.memoizedProps,a.memoizedState=l.memoizedState,a.updateQueue=l.updateQueue,a.type=l.type,e=l.dependencies,a.dependencies=null===e?null:{lanes:e.lanes,firstContext:e.firstContext}),n=n.sibling;return Ti(oa,1&oa.current|2),t.child}e=e.sibling}null!==a.tail&&Xe()>ql&&(t.flags|=128,r=!0,Ko(a,!1),t.lanes=4194304)}else{if(!r)if(null!==(e=la(l))){if(t.flags|=128,r=!0,null!==(n=e.updateQueue)&&(t.updateQueue=n,t.flags|=4),Ko(a,!0),null===a.tail&&"hidden"===a.tailMode&&!l.alternate&&!is)return Go(t),null}else 2*Xe()-a.renderingStartTime>ql&&1073741824!==n&&(t.flags|=128,r=!0,Ko(a,!1),t.lanes=4194304);a.isBackwards?(l.sibling=t.child,t.child=l):(null!==(n=a.last)?n.sibling=l:t.child=l,a.last=l)}return null!==a.tail?(t=a.tail,a.rendering=t,a.tail=t.sibling,a.renderingStartTime=Xe(),t.sibling=null,n=oa.current,Ti(oa,r?1&n|2:1&n),t):(Go(t),null);case 22:case 23:return dc(),r=null!==t.memoizedState,null!==e&&null!==e.memoizedState!==r&&(t.flags|=8192),r&&0!==(1&t.mode)?0!==(1073741824&Ol)&&(Go(t),6&t.subtreeFlags&&(t.flags|=8192)):Go(t),null;case 24:case 25:return null}throw Error(s(156,t.tag))}function $o(e,t){switch(ts(t),t.tag){case 1:return Ri(t.type)&&Oi(),65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 3:return ia(),Ii(Ni),Ii(xi),ua(),0!==(65536&(e=t.flags))&&0===(128&e)?(t.flags=-65537&e|128,t):null;case 5:return aa(t),null;case 13:if(Ii(oa),null!==(e=t.memoizedState)&&null!==e.dehydrated){if(null===t.alternate)throw Error(s(340));fs()}return 65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 19:return Ii(oa),null;case 4:return ia(),null;case 10:return Es(t.type._context),null;case 22:case 23:return dc(),null;default:return null}}Ro=function(e,t){for(var n=t.child;null!==n;){if(5===n.tag||6===n.tag)e.appendChild(n.stateNode);else if(4!==n.tag&&null!==n.child){n.child.return=n,n=n.child;continue}if(n===t)break;for(;null===n.sibling;){if(null===n.return||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}},Oo=function(){},Do=function(e,t,n,r){var i=e.memoizedProps;if(i!==r){e=t.stateNode,na(Zs.current);var s,a=null;switch(n){case"input":i=$(e,i),r=$(e,r),a=[];break;case"select":i=j({},i,{value:void 0}),r=j({},r,{value:void 0}),a=[];break;case"textarea":i=re(e,i),r=re(e,r),a=[];break;default:"function"!==typeof i.onClick&&"function"===typeof r.onClick&&(e.onclick=Zr)}for(u in ye(n,r),n=null,i)if(!r.hasOwnProperty(u)&&i.hasOwnProperty(u)&&null!=i[u])if("style"===u){var l=i[u];for(s in l)l.hasOwnProperty(s)&&(n||(n={}),n[s]="")}else"dangerouslySetInnerHTML"!==u&&"children"!==u&&"suppressContentEditableWarning"!==u&&"suppressHydrationWarning"!==u&&"autoFocus"!==u&&(o.hasOwnProperty(u)?a||(a=[]):(a=a||[]).push(u,null));for(u in r){var c=r[u];if(l=null!=i?i[u]:void 0,r.hasOwnProperty(u)&&c!==l&&(null!=c||null!=l))if("style"===u)if(l){for(s in l)!l.hasOwnProperty(s)||c&&c.hasOwnProperty(s)||(n||(n={}),n[s]="");for(s in c)c.hasOwnProperty(s)&&l[s]!==c[s]&&(n||(n={}),n[s]=c[s])}else n||(a||(a=[]),a.push(u,n)),n=c;else"dangerouslySetInnerHTML"===u?(c=c?c.__html:void 0,l=l?l.__html:void 0,null!=c&&l!==c&&(a=a||[]).push(u,c)):"children"===u?"string"!==typeof c&&"number"!==typeof c||(a=a||[]).push(u,""+c):"suppressContentEditableWarning"!==u&&"suppressHydrationWarning"!==u&&(o.hasOwnProperty(u)?(null!=c&&"onScroll"===u&&Ur("scroll",e),a||l===c||(a=[])):(a=a||[]).push(u,c))}n&&(a=a||[]).push("style",n);var u=a;(t.updateQueue=u)&&(t.flags|=4)}},Lo=function(e,t,n,r){n!==r&&(t.flags|=4)};var Yo=!1,Xo=!1,Jo="function"===typeof WeakSet?WeakSet:Set,Zo=null;function el(e,t){var n=e.ref;if(null!==n)if("function"===typeof n)try{n(null)}catch(r){Ic(e,t,r)}else n.current=null}function tl(e,t,n){try{n()}catch(r){Ic(e,t,r)}}var nl=!1;function rl(e,t,n){var r=t.updateQueue;if(null!==(r=null!==r?r.lastEffect:null)){var i=r=r.next;do{if((i.tag&e)===e){var s=i.destroy;i.destroy=void 0,void 0!==s&&tl(t,n,s)}i=i.next}while(i!==r)}}function il(e,t){if(null!==(t=null!==(t=t.updateQueue)?t.lastEffect:null)){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function sl(e){var t=e.ref;if(null!==t){var n=e.stateNode;e.tag,e=n,"function"===typeof t?t(e):t.current=e}}function al(e){var t=e.alternate;null!==t&&(e.alternate=null,al(t)),e.child=null,e.deletions=null,e.sibling=null,5===e.tag&&(null!==(t=e.stateNode)&&(delete t[di],delete t[fi],delete t[mi],delete t[gi],delete t[vi])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function ol(e){return 5===e.tag||3===e.tag||4===e.tag}function ll(e){e:for(;;){for(;null===e.sibling;){if(null===e.return||ol(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;5!==e.tag&&6!==e.tag&&18!==e.tag;){if(2&e.flags)continue e;if(null===e.child||4===e.tag)continue e;e.child.return=e,e=e.child}if(!(2&e.flags))return e.stateNode}}function cl(e,t,n){var r=e.tag;if(5===r||6===r)e=e.stateNode,t?8===n.nodeType?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(8===n.nodeType?(t=n.parentNode).insertBefore(e,n):(t=n).appendChild(e),null!==(n=n._reactRootContainer)&&void 0!==n||null!==t.onclick||(t.onclick=Zr));else if(4!==r&&null!==(e=e.child))for(cl(e,t,n),e=e.sibling;null!==e;)cl(e,t,n),e=e.sibling}function ul(e,t,n){var r=e.tag;if(5===r||6===r)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(4!==r&&null!==(e=e.child))for(ul(e,t,n),e=e.sibling;null!==e;)ul(e,t,n),e=e.sibling}var hl=null,dl=!1;function fl(e,t,n){for(n=n.child;null!==n;)pl(e,t,n),n=n.sibling}function pl(e,t,n){if(st&&"function"===typeof st.onCommitFiberUnmount)try{st.onCommitFiberUnmount(it,n)}catch(o){}switch(n.tag){case 5:Xo||el(n,t);case 6:var r=hl,i=dl;hl=null,fl(e,t,n),dl=i,null!==(hl=r)&&(dl?(e=hl,n=n.stateNode,8===e.nodeType?e.parentNode.removeChild(n):e.removeChild(n)):hl.removeChild(n.stateNode));break;case 18:null!==hl&&(dl?(e=hl,n=n.stateNode,8===e.nodeType?li(e.parentNode,n):1===e.nodeType&&li(e,n),zt(e)):li(hl,n.stateNode));break;case 4:r=hl,i=dl,hl=n.stateNode.containerInfo,dl=!0,fl(e,t,n),hl=r,dl=i;break;case 0:case 11:case 14:case 15:if(!Xo&&(null!==(r=n.updateQueue)&&null!==(r=r.lastEffect))){i=r=r.next;do{var s=i,a=s.destroy;s=s.tag,void 0!==a&&(0!==(2&s)||0!==(4&s))&&tl(n,t,a),i=i.next}while(i!==r)}fl(e,t,n);break;case 1:if(!Xo&&(el(n,t),"function"===typeof(r=n.stateNode).componentWillUnmount))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){Ic(n,t,o)}fl(e,t,n);break;case 21:fl(e,t,n);break;case 22:1&n.mode?(Xo=(r=Xo)||null!==n.memoizedState,fl(e,t,n),Xo=r):fl(e,t,n);break;default:fl(e,t,n)}}function ml(e){var t=e.updateQueue;if(null!==t){e.updateQueue=null;var n=e.stateNode;null===n&&(n=e.stateNode=new Jo),t.forEach((function(t){var r=Nc.bind(null,e,t);n.has(t)||(n.add(t),t.then(r,r))}))}}function gl(e,t){var n=t.deletions;if(null!==n)for(var r=0;r<n.length;r++){var i=n[r];try{var a=e,o=t,l=o;e:for(;null!==l;){switch(l.tag){case 5:hl=l.stateNode,dl=!1;break e;case 3:case 4:hl=l.stateNode.containerInfo,dl=!0;break e}l=l.return}if(null===hl)throw Error(s(160));pl(a,o,i),hl=null,dl=!1;var c=i.alternate;null!==c&&(c.return=null),i.return=null}catch(u){Ic(i,t,u)}}if(12854&t.subtreeFlags)for(t=t.child;null!==t;)vl(t,e),t=t.sibling}function vl(e,t){var n=e.alternate,r=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(gl(t,e),yl(e),4&r){try{rl(3,e,e.return),il(3,e)}catch(g){Ic(e,e.return,g)}try{rl(5,e,e.return)}catch(g){Ic(e,e.return,g)}}break;case 1:gl(t,e),yl(e),512&r&&null!==n&&el(n,n.return);break;case 5:if(gl(t,e),yl(e),512&r&&null!==n&&el(n,n.return),32&e.flags){var i=e.stateNode;try{de(i,"")}catch(g){Ic(e,e.return,g)}}if(4&r&&null!=(i=e.stateNode)){var a=e.memoizedProps,o=null!==n?n.memoizedProps:a,l=e.type,c=e.updateQueue;if(e.updateQueue=null,null!==c)try{"input"===l&&"radio"===a.type&&null!=a.name&&X(i,a),we(l,o);var u=we(l,a);for(o=0;o<c.length;o+=2){var h=c[o],d=c[o+1];"style"===h?ge(i,d):"dangerouslySetInnerHTML"===h?he(i,d):"children"===h?de(i,d):w(i,h,d,u)}switch(l){case"input":J(i,a);break;case"textarea":se(i,a);break;case"select":var f=i._wrapperState.wasMultiple;i._wrapperState.wasMultiple=!!a.multiple;var p=a.value;null!=p?ne(i,!!a.multiple,p,!1):f!==!!a.multiple&&(null!=a.defaultValue?ne(i,!!a.multiple,a.defaultValue,!0):ne(i,!!a.multiple,a.multiple?[]:"",!1))}i[fi]=a}catch(g){Ic(e,e.return,g)}}break;case 6:if(gl(t,e),yl(e),4&r){if(null===e.stateNode)throw Error(s(162));i=e.stateNode,a=e.memoizedProps;try{i.nodeValue=a}catch(g){Ic(e,e.return,g)}}break;case 3:if(gl(t,e),yl(e),4&r&&null!==n&&n.memoizedState.isDehydrated)try{zt(t.containerInfo)}catch(g){Ic(e,e.return,g)}break;case 4:default:gl(t,e),yl(e);break;case 13:gl(t,e),yl(e),8192&(i=e.child).flags&&(a=null!==i.memoizedState,i.stateNode.isHidden=a,!a||null!==i.alternate&&null!==i.alternate.memoizedState||(zl=Xe())),4&r&&ml(e);break;case 22:if(h=null!==n&&null!==n.memoizedState,1&e.mode?(Xo=(u=Xo)||h,gl(t,e),Xo=u):gl(t,e),yl(e),8192&r){if(u=null!==e.memoizedState,(e.stateNode.isHidden=u)&&!h&&0!==(1&e.mode))for(Zo=e,h=e.child;null!==h;){for(d=Zo=h;null!==Zo;){switch(p=(f=Zo).child,f.tag){case 0:case 11:case 14:case 15:rl(4,f,f.return);break;case 1:el(f,f.return);var m=f.stateNode;if("function"===typeof m.componentWillUnmount){r=f,n=f.return;try{t=r,m.props=t.memoizedProps,m.state=t.memoizedState,m.componentWillUnmount()}catch(g){Ic(r,n,g)}}break;case 5:el(f,f.return);break;case 22:if(null!==f.memoizedState){El(d);continue}}null!==p?(p.return=f,Zo=p):El(d)}h=h.sibling}e:for(h=null,d=e;;){if(5===d.tag){if(null===h){h=d;try{i=d.stateNode,u?"function"===typeof(a=i.style).setProperty?a.setProperty("display","none","important"):a.display="none":(l=d.stateNode,o=void 0!==(c=d.memoizedProps.style)&&null!==c&&c.hasOwnProperty("display")?c.display:null,l.style.display=me("display",o))}catch(g){Ic(e,e.return,g)}}}else if(6===d.tag){if(null===h)try{d.stateNode.nodeValue=u?"":d.memoizedProps}catch(g){Ic(e,e.return,g)}}else if((22!==d.tag&&23!==d.tag||null===d.memoizedState||d===e)&&null!==d.child){d.child.return=d,d=d.child;continue}if(d===e)break e;for(;null===d.sibling;){if(null===d.return||d.return===e)break e;h===d&&(h=null),d=d.return}h===d&&(h=null),d.sibling.return=d.return,d=d.sibling}}break;case 19:gl(t,e),yl(e),4&r&&ml(e);case 21:}}function yl(e){var t=e.flags;if(2&t){try{e:{for(var n=e.return;null!==n;){if(ol(n)){var r=n;break e}n=n.return}throw Error(s(160))}switch(r.tag){case 5:var i=r.stateNode;32&r.flags&&(de(i,""),r.flags&=-33),ul(e,ll(e),i);break;case 3:case 4:var a=r.stateNode.containerInfo;cl(e,ll(e),a);break;default:throw Error(s(161))}}catch(o){Ic(e,e.return,o)}e.flags&=-3}4096&t&&(e.flags&=-4097)}function wl(e,t,n){Zo=e,bl(e,t,n)}function bl(e,t,n){for(var r=0!==(1&e.mode);null!==Zo;){var i=Zo,s=i.child;if(22===i.tag&&r){var a=null!==i.memoizedState||Yo;if(!a){var o=i.alternate,l=null!==o&&null!==o.memoizedState||Xo;o=Yo;var c=Xo;if(Yo=a,(Xo=l)&&!c)for(Zo=i;null!==Zo;)l=(a=Zo).child,22===a.tag&&null!==a.memoizedState?Sl(i):null!==l?(l.return=a,Zo=l):Sl(i);for(;null!==s;)Zo=s,bl(s,t,n),s=s.sibling;Zo=i,Yo=o,Xo=c}_l(e)}else 0!==(8772&i.subtreeFlags)&&null!==s?(s.return=i,Zo=s):_l(e)}}function _l(e){for(;null!==Zo;){var t=Zo;if(0!==(8772&t.flags)){var n=t.alternate;try{if(0!==(8772&t.flags))switch(t.tag){case 0:case 11:case 15:Xo||il(5,t);break;case 1:var r=t.stateNode;if(4&t.flags&&!Xo)if(null===n)r.componentDidMount();else{var i=t.elementType===t.type?n.memoizedProps:gs(t.type,n.memoizedProps);r.componentDidUpdate(i,n.memoizedState,r.__reactInternalSnapshotBeforeUpdate)}var a=t.updateQueue;null!==a&&Fs(t,a,r);break;case 3:var o=t.updateQueue;if(null!==o){if(n=null,null!==t.child)switch(t.child.tag){case 5:case 1:n=t.child.stateNode}Fs(t,o,n)}break;case 5:var l=t.stateNode;if(null===n&&4&t.flags){n=l;var c=t.memoizedProps;switch(t.type){case"button":case"input":case"select":case"textarea":c.autoFocus&&n.focus();break;case"img":c.src&&(n.src=c.src)}}break;case 6:case 4:case 12:case 19:case 17:case 21:case 22:case 23:case 25:break;case 13:if(null===t.memoizedState){var u=t.alternate;if(null!==u){var h=u.memoizedState;if(null!==h){var d=h.dehydrated;null!==d&&zt(d)}}}break;default:throw Error(s(163))}Xo||512&t.flags&&sl(t)}catch(f){Ic(t,t.return,f)}}if(t===e){Zo=null;break}if(null!==(n=t.sibling)){n.return=t.return,Zo=n;break}Zo=t.return}}function El(e){for(;null!==Zo;){var t=Zo;if(t===e){Zo=null;break}var n=t.sibling;if(null!==n){n.return=t.return,Zo=n;break}Zo=t.return}}function Sl(e){for(;null!==Zo;){var t=Zo;try{switch(t.tag){case 0:case 11:case 15:var n=t.return;try{il(4,t)}catch(l){Ic(t,n,l)}break;case 1:var r=t.stateNode;if("function"===typeof r.componentDidMount){var i=t.return;try{r.componentDidMount()}catch(l){Ic(t,i,l)}}var s=t.return;try{sl(t)}catch(l){Ic(t,s,l)}break;case 5:var a=t.return;try{sl(t)}catch(l){Ic(t,a,l)}}}catch(l){Ic(t,t.return,l)}if(t===e){Zo=null;break}var o=t.sibling;if(null!==o){o.return=t.return,Zo=o;break}Zo=t.return}}var kl,Il=Math.ceil,Tl=b.ReactCurrentDispatcher,Cl=b.ReactCurrentOwner,xl=b.ReactCurrentBatchConfig,Nl=0,Al=null,Pl=null,Rl=0,Ol=0,Dl=ki(0),Ll=0,Ml=null,jl=0,Fl=0,Ul=0,Vl=null,Bl=null,zl=0,ql=1/0,Hl=null,Wl=!1,Kl=null,Gl=null,Ql=!1,$l=null,Yl=0,Xl=0,Jl=null,Zl=-1,ec=0;function tc(){return 0!==(6&Nl)?Xe():-1!==Zl?Zl:Zl=Xe()}function nc(e){return 0===(1&e.mode)?1:0!==(2&Nl)&&0!==Rl?Rl&-Rl:null!==ms.transition?(0===ec&&(ec=mt()),ec):0!==(e=wt)?e:e=void 0===(e=window.event)?16:Yt(e.type)}function rc(e,t,n,r){if(50<Xl)throw Xl=0,Jl=null,Error(s(185));vt(e,n,r),0!==(2&Nl)&&e===Al||(e===Al&&(0===(2&Nl)&&(Fl|=n),4===Ll&&lc(e,Rl)),ic(e,r),1===n&&0===Nl&&0===(1&t.mode)&&(ql=Xe()+500,Ui&&zi()))}function ic(e,t){var n=e.callbackNode;!function(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,s=e.pendingLanes;0<s;){var a=31-at(s),o=1<<a,l=i[a];-1===l?0!==(o&n)&&0===(o&r)||(i[a]=ft(o,t)):l<=t&&(e.expiredLanes|=o),s&=~o}}(e,t);var r=dt(e,e===Al?Rl:0);if(0===r)null!==n&&Qe(n),e.callbackNode=null,e.callbackPriority=0;else if(t=r&-r,e.callbackPriority!==t){if(null!=n&&Qe(n),1===t)0===e.tag?function(e){Ui=!0,Bi(e)}(cc.bind(null,e)):Bi(cc.bind(null,e)),ai((function(){0===(6&Nl)&&zi()})),n=null;else{switch(bt(r)){case 1:n=Ze;break;case 4:n=et;break;case 16:default:n=tt;break;case 536870912:n=rt}n=Ac(n,sc.bind(null,e))}e.callbackPriority=t,e.callbackNode=n}}function sc(e,t){if(Zl=-1,ec=0,0!==(6&Nl))throw Error(s(327));var n=e.callbackNode;if(Sc()&&e.callbackNode!==n)return null;var r=dt(e,e===Al?Rl:0);if(0===r)return null;if(0!==(30&r)||0!==(r&e.expiredLanes)||t)t=vc(e,r);else{t=r;var i=Nl;Nl|=2;var a=mc();for(Al===e&&Rl===t||(Hl=null,ql=Xe()+500,fc(e,t));;)try{wc();break}catch(l){pc(e,l)}_s(),Tl.current=a,Nl=i,null!==Pl?t=0:(Al=null,Rl=0,t=Ll)}if(0!==t){if(2===t&&(0!==(i=pt(e))&&(r=i,t=ac(e,i))),1===t)throw n=Ml,fc(e,0),lc(e,r),ic(e,Xe()),n;if(6===t)lc(e,r);else{if(i=e.current.alternate,0===(30&r)&&!function(e){for(var t=e;;){if(16384&t.flags){var n=t.updateQueue;if(null!==n&&null!==(n=n.stores))for(var r=0;r<n.length;r++){var i=n[r],s=i.getSnapshot;i=i.value;try{if(!or(s(),i))return!1}catch(o){return!1}}}if(n=t.child,16384&t.subtreeFlags&&null!==n)n.return=t,t=n;else{if(t===e)break;for(;null===t.sibling;){if(null===t.return||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}(i)&&(2===(t=vc(e,r))&&(0!==(a=pt(e))&&(r=a,t=ac(e,a))),1===t))throw n=Ml,fc(e,0),lc(e,r),ic(e,Xe()),n;switch(e.finishedWork=i,e.finishedLanes=r,t){case 0:case 1:throw Error(s(345));case 2:case 5:Ec(e,Bl,Hl);break;case 3:if(lc(e,r),(130023424&r)===r&&10<(t=zl+500-Xe())){if(0!==dt(e,0))break;if(((i=e.suspendedLanes)&r)!==r){tc(),e.pingedLanes|=e.suspendedLanes&i;break}e.timeoutHandle=ri(Ec.bind(null,e,Bl,Hl),t);break}Ec(e,Bl,Hl);break;case 4:if(lc(e,r),(4194240&r)===r)break;for(t=e.eventTimes,i=-1;0<r;){var o=31-at(r);a=1<<o,(o=t[o])>i&&(i=o),r&=~a}if(r=i,10<(r=(120>(r=Xe()-r)?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Il(r/1960))-r)){e.timeoutHandle=ri(Ec.bind(null,e,Bl,Hl),r);break}Ec(e,Bl,Hl);break;default:throw Error(s(329))}}}return ic(e,Xe()),e.callbackNode===n?sc.bind(null,e):null}function ac(e,t){var n=Vl;return e.current.memoizedState.isDehydrated&&(fc(e,t).flags|=256),2!==(e=vc(e,t))&&(t=Bl,Bl=n,null!==t&&oc(t)),e}function oc(e){null===Bl?Bl=e:Bl.push.apply(Bl,e)}function lc(e,t){for(t&=~Ul,t&=~Fl,e.suspendedLanes|=t,e.pingedLanes&=~t,e=e.expirationTimes;0<t;){var n=31-at(t),r=1<<n;e[n]=-1,t&=~r}}function cc(e){if(0!==(6&Nl))throw Error(s(327));Sc();var t=dt(e,0);if(0===(1&t))return ic(e,Xe()),null;var n=vc(e,t);if(0!==e.tag&&2===n){var r=pt(e);0!==r&&(t=r,n=ac(e,r))}if(1===n)throw n=Ml,fc(e,0),lc(e,t),ic(e,Xe()),n;if(6===n)throw Error(s(345));return e.finishedWork=e.current.alternate,e.finishedLanes=t,Ec(e,Bl,Hl),ic(e,Xe()),null}function uc(e,t){var n=Nl;Nl|=1;try{return e(t)}finally{0===(Nl=n)&&(ql=Xe()+500,Ui&&zi())}}function hc(e){null!==$l&&0===$l.tag&&0===(6&Nl)&&Sc();var t=Nl;Nl|=1;var n=xl.transition,r=wt;try{if(xl.transition=null,wt=1,e)return e()}finally{wt=r,xl.transition=n,0===(6&(Nl=t))&&zi()}}function dc(){Ol=Dl.current,Ii(Dl)}function fc(e,t){e.finishedWork=null,e.finishedLanes=0;var n=e.timeoutHandle;if(-1!==n&&(e.timeoutHandle=-1,ii(n)),null!==Pl)for(n=Pl.return;null!==n;){var r=n;switch(ts(r),r.tag){case 1:null!==(r=r.type.childContextTypes)&&void 0!==r&&Oi();break;case 3:ia(),Ii(Ni),Ii(xi),ua();break;case 5:aa(r);break;case 4:ia();break;case 13:case 19:Ii(oa);break;case 10:Es(r.type._context);break;case 22:case 23:dc()}n=n.return}if(Al=e,Pl=e=Dc(e.current,null),Rl=Ol=t,Ll=0,Ml=null,Ul=Fl=jl=0,Bl=Vl=null,null!==Ts){for(t=0;t<Ts.length;t++)if(null!==(r=(n=Ts[t]).interleaved)){n.interleaved=null;var i=r.next,s=n.pending;if(null!==s){var a=s.next;s.next=i,r.next=a}n.pending=r}Ts=null}return e}function pc(e,t){for(;;){var n=Pl;try{if(_s(),ha.current=so,va){for(var r=pa.memoizedState;null!==r;){var i=r.queue;null!==i&&(i.pending=null),r=r.next}va=!1}if(fa=0,ga=ma=pa=null,ya=!1,wa=0,Cl.current=null,null===n||null===n.return){Ll=1,Ml=t,Pl=null;break}e:{var a=e,o=n.return,l=n,c=t;if(t=Rl,l.flags|=32768,null!==c&&"object"===typeof c&&"function"===typeof c.then){var u=c,h=l,d=h.tag;if(0===(1&h.mode)&&(0===d||11===d||15===d)){var f=h.alternate;f?(h.updateQueue=f.updateQueue,h.memoizedState=f.memoizedState,h.lanes=f.lanes):(h.updateQueue=null,h.memoizedState=null)}var p=vo(o);if(null!==p){p.flags&=-257,yo(p,o,l,0,t),1&p.mode&&go(a,u,t),c=u;var m=(t=p).updateQueue;if(null===m){var g=new Set;g.add(c),t.updateQueue=g}else m.add(c);break e}if(0===(1&t)){go(a,u,t),gc();break e}c=Error(s(426))}else if(is&&1&l.mode){var v=vo(o);if(null!==v){0===(65536&v.flags)&&(v.flags|=256),yo(v,o,l,0,t),ps(co(c,l));break e}}a=c=co(c,l),4!==Ll&&(Ll=2),null===Vl?Vl=[a]:Vl.push(a),a=o;do{switch(a.tag){case 3:a.flags|=65536,t&=-t,a.lanes|=t,Ms(a,po(0,c,t));break e;case 1:l=c;var y=a.type,w=a.stateNode;if(0===(128&a.flags)&&("function"===typeof y.getDerivedStateFromError||null!==w&&"function"===typeof w.componentDidCatch&&(null===Gl||!Gl.has(w)))){a.flags|=65536,t&=-t,a.lanes|=t,Ms(a,mo(a,l,t));break e}}a=a.return}while(null!==a)}_c(n)}catch(b){t=b,Pl===n&&null!==n&&(Pl=n=n.return);continue}break}}function mc(){var e=Tl.current;return Tl.current=so,null===e?so:e}function gc(){0!==Ll&&3!==Ll&&2!==Ll||(Ll=4),null===Al||0===(268435455&jl)&&0===(268435455&Fl)||lc(Al,Rl)}function vc(e,t){var n=Nl;Nl|=2;var r=mc();for(Al===e&&Rl===t||(Hl=null,fc(e,t));;)try{yc();break}catch(i){pc(e,i)}if(_s(),Nl=n,Tl.current=r,null!==Pl)throw Error(s(261));return Al=null,Rl=0,Ll}function yc(){for(;null!==Pl;)bc(Pl)}function wc(){for(;null!==Pl&&!$e();)bc(Pl)}function bc(e){var t=kl(e.alternate,e,Ol);e.memoizedProps=e.pendingProps,null===t?_c(e):Pl=t,Cl.current=null}function _c(e){var t=e;do{var n=t.alternate;if(e=t.return,0===(32768&t.flags)){if(null!==(n=Qo(n,t,Ol)))return void(Pl=n)}else{if(null!==(n=$o(n,t)))return n.flags&=32767,void(Pl=n);if(null===e)return Ll=6,void(Pl=null);e.flags|=32768,e.subtreeFlags=0,e.deletions=null}if(null!==(t=t.sibling))return void(Pl=t);Pl=t=e}while(null!==t);0===Ll&&(Ll=5)}function Ec(e,t,n){var r=wt,i=xl.transition;try{xl.transition=null,wt=1,function(e,t,n,r){do{Sc()}while(null!==$l);if(0!==(6&Nl))throw Error(s(327));n=e.finishedWork;var i=e.finishedLanes;if(null===n)return null;if(e.finishedWork=null,e.finishedLanes=0,n===e.current)throw Error(s(177));e.callbackNode=null,e.callbackPriority=0;var a=n.lanes|n.childLanes;if(function(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0<n;){var i=31-at(n),s=1<<i;t[i]=0,r[i]=-1,e[i]=-1,n&=~s}}(e,a),e===Al&&(Pl=Al=null,Rl=0),0===(2064&n.subtreeFlags)&&0===(2064&n.flags)||Ql||(Ql=!0,Ac(tt,(function(){return Sc(),null}))),a=0!==(15990&n.flags),0!==(15990&n.subtreeFlags)||a){a=xl.transition,xl.transition=null;var o=wt;wt=1;var l=Nl;Nl|=4,Cl.current=null,function(e,t){if(ei=Ht,fr(e=dr())){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{var r=(n=(n=e.ownerDocument)&&n.defaultView||window).getSelection&&n.getSelection();if(r&&0!==r.rangeCount){n=r.anchorNode;var i=r.anchorOffset,a=r.focusNode;r=r.focusOffset;try{n.nodeType,a.nodeType}catch(_){n=null;break e}var o=0,l=-1,c=-1,u=0,h=0,d=e,f=null;t:for(;;){for(var p;d!==n||0!==i&&3!==d.nodeType||(l=o+i),d!==a||0!==r&&3!==d.nodeType||(c=o+r),3===d.nodeType&&(o+=d.nodeValue.length),null!==(p=d.firstChild);)f=d,d=p;for(;;){if(d===e)break t;if(f===n&&++u===i&&(l=o),f===a&&++h===r&&(c=o),null!==(p=d.nextSibling))break;f=(d=f).parentNode}d=p}n=-1===l||-1===c?null:{start:l,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(ti={focusedElem:e,selectionRange:n},Ht=!1,Zo=t;null!==Zo;)if(e=(t=Zo).child,0!==(1028&t.subtreeFlags)&&null!==e)e.return=t,Zo=e;else for(;null!==Zo;){t=Zo;try{var m=t.alternate;if(0!==(1024&t.flags))switch(t.tag){case 0:case 11:case 15:case 5:case 6:case 4:case 17:break;case 1:if(null!==m){var g=m.memoizedProps,v=m.memoizedState,y=t.stateNode,w=y.getSnapshotBeforeUpdate(t.elementType===t.type?g:gs(t.type,g),v);y.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var b=t.stateNode.containerInfo;1===b.nodeType?b.textContent="":9===b.nodeType&&b.documentElement&&b.removeChild(b.documentElement);break;default:throw Error(s(163))}}catch(_){Ic(t,t.return,_)}if(null!==(e=t.sibling)){e.return=t.return,Zo=e;break}Zo=t.return}m=nl,nl=!1}(e,n),vl(n,e),pr(ti),Ht=!!ei,ti=ei=null,e.current=n,wl(n,e,i),Ye(),Nl=l,wt=o,xl.transition=a}else e.current=n;if(Ql&&(Ql=!1,$l=e,Yl=i),a=e.pendingLanes,0===a&&(Gl=null),function(e){if(st&&"function"===typeof st.onCommitFiberRoot)try{st.onCommitFiberRoot(it,e,void 0,128===(128&e.current.flags))}catch(t){}}(n.stateNode),ic(e,Xe()),null!==t)for(r=e.onRecoverableError,n=0;n<t.length;n++)i=t[n],r(i.value,{componentStack:i.stack,digest:i.digest});if(Wl)throw Wl=!1,e=Kl,Kl=null,e;0!==(1&Yl)&&0!==e.tag&&Sc(),a=e.pendingLanes,0!==(1&a)?e===Jl?Xl++:(Xl=0,Jl=e):Xl=0,zi()}(e,t,n,r)}finally{xl.transition=i,wt=r}return null}function Sc(){if(null!==$l){var e=bt(Yl),t=xl.transition,n=wt;try{if(xl.transition=null,wt=16>e?16:e,null===$l)var r=!1;else{if(e=$l,$l=null,Yl=0,0!==(6&Nl))throw Error(s(331));var i=Nl;for(Nl|=4,Zo=e.current;null!==Zo;){var a=Zo,o=a.child;if(0!==(16&Zo.flags)){var l=a.deletions;if(null!==l){for(var c=0;c<l.length;c++){var u=l[c];for(Zo=u;null!==Zo;){var h=Zo;switch(h.tag){case 0:case 11:case 15:rl(8,h,a)}var d=h.child;if(null!==d)d.return=h,Zo=d;else for(;null!==Zo;){var f=(h=Zo).sibling,p=h.return;if(al(h),h===u){Zo=null;break}if(null!==f){f.return=p,Zo=f;break}Zo=p}}}var m=a.alternate;if(null!==m){var g=m.child;if(null!==g){m.child=null;do{var v=g.sibling;g.sibling=null,g=v}while(null!==g)}}Zo=a}}if(0!==(2064&a.subtreeFlags)&&null!==o)o.return=a,Zo=o;else e:for(;null!==Zo;){if(0!==(2048&(a=Zo).flags))switch(a.tag){case 0:case 11:case 15:rl(9,a,a.return)}var y=a.sibling;if(null!==y){y.return=a.return,Zo=y;break e}Zo=a.return}}var w=e.current;for(Zo=w;null!==Zo;){var b=(o=Zo).child;if(0!==(2064&o.subtreeFlags)&&null!==b)b.return=o,Zo=b;else e:for(o=w;null!==Zo;){if(0!==(2048&(l=Zo).flags))try{switch(l.tag){case 0:case 11:case 15:il(9,l)}}catch(E){Ic(l,l.return,E)}if(l===o){Zo=null;break e}var _=l.sibling;if(null!==_){_.return=l.return,Zo=_;break e}Zo=l.return}}if(Nl=i,zi(),st&&"function"===typeof st.onPostCommitFiberRoot)try{st.onPostCommitFiberRoot(it,e)}catch(E){}r=!0}return r}finally{wt=n,xl.transition=t}}return!1}function kc(e,t,n){e=Ds(e,t=po(0,t=co(n,t),1),1),t=tc(),null!==e&&(vt(e,1,t),ic(e,t))}function Ic(e,t,n){if(3===e.tag)kc(e,e,n);else for(;null!==t;){if(3===t.tag){kc(t,e,n);break}if(1===t.tag){var r=t.stateNode;if("function"===typeof t.type.getDerivedStateFromError||"function"===typeof r.componentDidCatch&&(null===Gl||!Gl.has(r))){t=Ds(t,e=mo(t,e=co(n,e),1),1),e=tc(),null!==t&&(vt(t,1,e),ic(t,e));break}}t=t.return}}function Tc(e,t,n){var r=e.pingCache;null!==r&&r.delete(t),t=tc(),e.pingedLanes|=e.suspendedLanes&n,Al===e&&(Rl&n)===n&&(4===Ll||3===Ll&&(130023424&Rl)===Rl&&500>Xe()-zl?fc(e,0):Ul|=n),ic(e,t)}function Cc(e,t){0===t&&(0===(1&e.mode)?t=1:(t=ut,0===(130023424&(ut<<=1))&&(ut=4194304)));var n=tc();null!==(e=Ns(e,t))&&(vt(e,t,n),ic(e,n))}function xc(e){var t=e.memoizedState,n=0;null!==t&&(n=t.retryLane),Cc(e,n)}function Nc(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,i=e.memoizedState;null!==i&&(n=i.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(s(314))}null!==r&&r.delete(t),Cc(e,n)}function Ac(e,t){return Ge(e,t)}function Pc(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Rc(e,t,n,r){return new Pc(e,t,n,r)}function Oc(e){return!(!(e=e.prototype)||!e.isReactComponent)}function Dc(e,t){var n=e.alternate;return null===n?((n=Rc(e.tag,t,e.key,e.mode)).elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=14680064&e.flags,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=null===t?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Lc(e,t,n,r,i,a){var o=2;if(r=e,"function"===typeof e)Oc(e)&&(o=1);else if("string"===typeof e)o=5;else e:switch(e){case S:return Mc(n.children,i,a,t);case k:o=8,i|=8;break;case I:return(e=Rc(12,n,t,2|i)).elementType=I,e.lanes=a,e;case N:return(e=Rc(13,n,t,i)).elementType=N,e.lanes=a,e;case A:return(e=Rc(19,n,t,i)).elementType=A,e.lanes=a,e;case O:return jc(n,i,a,t);default:if("object"===typeof e&&null!==e)switch(e.$$typeof){case T:o=10;break e;case C:o=9;break e;case x:o=11;break e;case P:o=14;break e;case R:o=16,r=null;break e}throw Error(s(130,null==e?e:typeof e,""))}return(t=Rc(o,n,t,i)).elementType=e,t.type=r,t.lanes=a,t}function Mc(e,t,n,r){return(e=Rc(7,e,r,t)).lanes=n,e}function jc(e,t,n,r){return(e=Rc(22,e,r,t)).elementType=O,e.lanes=n,e.stateNode={isHidden:!1},e}function Fc(e,t,n){return(e=Rc(6,e,null,t)).lanes=n,e}function Uc(e,t,n){return(t=Rc(4,null!==e.children?e.children:[],e.key,t)).lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Vc(e,t,n,r,i){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=gt(0),this.expirationTimes=gt(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=gt(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function Bc(e,t,n,r,i,s,a,o,l){return e=new Vc(e,t,n,o,l),1===t?(t=1,!0===s&&(t|=8)):t=0,s=Rc(3,null,null,t),e.current=s,s.stateNode=e,s.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ps(s),e}function zc(e){if(!e)return Ci;e:{if(ze(e=e._reactInternals)!==e||1!==e.tag)throw Error(s(170));var t=e;do{switch(t.tag){case 3:t=t.stateNode.context;break e;case 1:if(Ri(t.type)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break e}}t=t.return}while(null!==t);throw Error(s(171))}if(1===e.tag){var n=e.type;if(Ri(n))return Li(e,n,t)}return t}function qc(e,t,n,r,i,s,a,o,l){return(e=Bc(n,r,!0,e,0,s,0,o,l)).context=zc(null),n=e.current,(s=Os(r=tc(),i=nc(n))).callback=void 0!==t&&null!==t?t:null,Ds(n,s,i),e.current.lanes=i,vt(e,i,r),ic(e,r),e}function Hc(e,t,n,r){var i=t.current,s=tc(),a=nc(i);return n=zc(n),null===t.context?t.context=n:t.pendingContext=n,(t=Os(s,a)).payload={element:e},null!==(r=void 0===r?null:r)&&(t.callback=r),null!==(e=Ds(i,t,a))&&(rc(e,i,a,s),Ls(e,i,a)),a}function Wc(e){return(e=e.current).child?(e.child.tag,e.child.stateNode):null}function Kc(e,t){if(null!==(e=e.memoizedState)&&null!==e.dehydrated){var n=e.retryLane;e.retryLane=0!==n&&n<t?n:t}}function Gc(e,t){Kc(e,t),(e=e.alternate)&&Kc(e,t)}kl=function(e,t,n){if(null!==e)if(e.memoizedProps!==t.pendingProps||Ni.current)bo=!0;else{if(0===(e.lanes&n)&&0===(128&t.flags))return bo=!1,function(e,t,n){switch(t.tag){case 3:Ao(t),fs();break;case 5:sa(t);break;case 1:Ri(t.type)&&Mi(t);break;case 4:ra(t,t.stateNode.containerInfo);break;case 10:var r=t.type._context,i=t.memoizedProps.value;Ti(vs,r._currentValue),r._currentValue=i;break;case 13:if(null!==(r=t.memoizedState))return null!==r.dehydrated?(Ti(oa,1&oa.current),t.flags|=128,null):0!==(n&t.child.childLanes)?Fo(e,t,n):(Ti(oa,1&oa.current),null!==(e=Wo(e,t,n))?e.sibling:null);Ti(oa,1&oa.current);break;case 19:if(r=0!==(n&t.childLanes),0!==(128&e.flags)){if(r)return qo(e,t,n);t.flags|=128}if(null!==(i=t.memoizedState)&&(i.rendering=null,i.tail=null,i.lastEffect=null),Ti(oa,oa.current),r)break;return null;case 22:case 23:return t.lanes=0,Io(e,t,n)}return Wo(e,t,n)}(e,t,n);bo=0!==(131072&e.flags)}else bo=!1,is&&0!==(1048576&t.flags)&&Zi(t,Ki,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ho(e,t),e=t.pendingProps;var i=Pi(t,xi.current);ks(t,n),i=Sa(null,t,r,e,i,n);var a=ka();return t.flags|=1,"object"===typeof i&&null!==i&&"function"===typeof i.render&&void 0===i.$$typeof?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Ri(r)?(a=!0,Mi(t)):a=!1,t.memoizedState=null!==i.state&&void 0!==i.state?i.state:null,Ps(t),i.updater=Bs,t.stateNode=i,i._reactInternals=t,Ws(t,r,e,n),t=No(null,t,r,!0,a,n)):(t.tag=0,is&&a&&es(t),_o(null,t,i,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ho(e,t),e=t.pendingProps,r=(i=r._init)(r._payload),t.type=r,i=t.tag=function(e){if("function"===typeof e)return Oc(e)?1:0;if(void 0!==e&&null!==e){if((e=e.$$typeof)===x)return 11;if(e===P)return 14}return 2}(r),e=gs(r,e),i){case 0:t=Co(null,t,r,e,n);break e;case 1:t=xo(null,t,r,e,n);break e;case 11:t=Eo(null,t,r,e,n);break e;case 14:t=So(null,t,r,gs(r.type,e),n);break e}throw Error(s(306,r,""))}return t;case 0:return r=t.type,i=t.pendingProps,Co(e,t,r,i=t.elementType===r?i:gs(r,i),n);case 1:return r=t.type,i=t.pendingProps,xo(e,t,r,i=t.elementType===r?i:gs(r,i),n);case 3:e:{if(Ao(t),null===e)throw Error(s(387));r=t.pendingProps,i=(a=t.memoizedState).element,Rs(e,t),js(t,r,null,n);var o=t.memoizedState;if(r=o.element,a.isDehydrated){if(a={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=a,t.memoizedState=a,256&t.flags){t=Po(e,t,r,n,i=co(Error(s(423)),t));break e}if(r!==i){t=Po(e,t,r,n,i=co(Error(s(424)),t));break e}for(rs=ci(t.stateNode.containerInfo.firstChild),ns=t,is=!0,ss=null,n=Xs(t,null,r,n),t.child=n;n;)n.flags=-3&n.flags|4096,n=n.sibling}else{if(fs(),r===i){t=Wo(e,t,n);break e}_o(e,t,r,n)}t=t.child}return t;case 5:return sa(t),null===e&&cs(t),r=t.type,i=t.pendingProps,a=null!==e?e.memoizedProps:null,o=i.children,ni(r,i)?o=null:null!==a&&ni(r,a)&&(t.flags|=32),To(e,t),_o(e,t,o,n),t.child;case 6:return null===e&&cs(t),null;case 13:return Fo(e,t,n);case 4:return ra(t,t.stateNode.containerInfo),r=t.pendingProps,null===e?t.child=Ys(t,null,r,n):_o(e,t,r,n),t.child;case 11:return r=t.type,i=t.pendingProps,Eo(e,t,r,i=t.elementType===r?i:gs(r,i),n);case 7:return _o(e,t,t.pendingProps,n),t.child;case 8:case 12:return _o(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,i=t.pendingProps,a=t.memoizedProps,o=i.value,Ti(vs,r._currentValue),r._currentValue=o,null!==a)if(or(a.value,o)){if(a.children===i.children&&!Ni.current){t=Wo(e,t,n);break e}}else for(null!==(a=t.child)&&(a.return=t);null!==a;){var l=a.dependencies;if(null!==l){o=a.child;for(var c=l.firstContext;null!==c;){if(c.context===r){if(1===a.tag){(c=Os(-1,n&-n)).tag=2;var u=a.updateQueue;if(null!==u){var h=(u=u.shared).pending;null===h?c.next=c:(c.next=h.next,h.next=c),u.pending=c}}a.lanes|=n,null!==(c=a.alternate)&&(c.lanes|=n),Ss(a.return,n,t),l.lanes|=n;break}c=c.next}}else if(10===a.tag)o=a.type===t.type?null:a.child;else if(18===a.tag){if(null===(o=a.return))throw Error(s(341));o.lanes|=n,null!==(l=o.alternate)&&(l.lanes|=n),Ss(o,n,t),o=a.sibling}else o=a.child;if(null!==o)o.return=a;else for(o=a;null!==o;){if(o===t){o=null;break}if(null!==(a=o.sibling)){a.return=o.return,o=a;break}o=o.return}a=o}_o(e,t,i.children,n),t=t.child}return t;case 9:return i=t.type,r=t.pendingProps.children,ks(t,n),r=r(i=Is(i)),t.flags|=1,_o(e,t,r,n),t.child;case 14:return i=gs(r=t.type,t.pendingProps),So(e,t,r,i=gs(r.type,i),n);case 15:return ko(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:gs(r,i),Ho(e,t),t.tag=1,Ri(r)?(e=!0,Mi(t)):e=!1,ks(t,n),qs(t,r,i),Ws(t,r,i,n),No(null,t,r,!0,e,n);case 19:return qo(e,t,n);case 22:return Io(e,t,n)}throw Error(s(156,t.tag))};var Qc="function"===typeof reportError?reportError:function(e){console.error(e)};function $c(e){this._internalRoot=e}function Yc(e){this._internalRoot=e}function Xc(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType)}function Jc(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType&&(8!==e.nodeType||" react-mount-point-unstable "!==e.nodeValue))}function Zc(){}function eu(e,t,n,r,i){var s=n._reactRootContainer;if(s){var a=s;if("function"===typeof i){var o=i;i=function(){var e=Wc(a);o.call(e)}}Hc(t,a,e,i)}else a=function(e,t,n,r,i){if(i){if("function"===typeof r){var s=r;r=function(){var e=Wc(a);s.call(e)}}var a=qc(t,r,e,0,null,!1,0,"",Zc);return e._reactRootContainer=a,e[pi]=a.current,zr(8===e.nodeType?e.parentNode:e),hc(),a}for(;i=e.lastChild;)e.removeChild(i);if("function"===typeof r){var o=r;r=function(){var e=Wc(l);o.call(e)}}var l=Bc(e,0,!1,null,0,!1,0,"",Zc);return e._reactRootContainer=l,e[pi]=l.current,zr(8===e.nodeType?e.parentNode:e),hc((function(){Hc(t,l,n,r)})),l}(n,t,e,i,r);return Wc(a)}Yc.prototype.render=$c.prototype.render=function(e){var t=this._internalRoot;if(null===t)throw Error(s(409));Hc(e,t,null,null)},Yc.prototype.unmount=$c.prototype.unmount=function(){var e=this._internalRoot;if(null!==e){this._internalRoot=null;var t=e.containerInfo;hc((function(){Hc(null,e,null,null)})),t[pi]=null}},Yc.prototype.unstable_scheduleHydration=function(e){if(e){var t=kt();e={blockedOn:null,target:e,priority:t};for(var n=0;n<Ot.length&&0!==t&&t<Ot[n].priority;n++);Ot.splice(n,0,e),0===n&&jt(e)}},_t=function(e){switch(e.tag){case 3:var t=e.stateNode;if(t.current.memoizedState.isDehydrated){var n=ht(t.pendingLanes);0!==n&&(yt(t,1|n),ic(t,Xe()),0===(6&Nl)&&(ql=Xe()+500,zi()))}break;case 13:hc((function(){var t=Ns(e,1);if(null!==t){var n=tc();rc(t,e,1,n)}})),Gc(e,1)}},Et=function(e){if(13===e.tag){var t=Ns(e,134217728);if(null!==t)rc(t,e,134217728,tc());Gc(e,134217728)}},St=function(e){if(13===e.tag){var t=nc(e),n=Ns(e,t);if(null!==n)rc(n,e,t,tc());Gc(e,t)}},kt=function(){return wt},It=function(e,t){var n=wt;try{return wt=e,t()}finally{wt=n}},Ee=function(e,t,n){switch(t){case"input":if(J(e,n),t=n.name,"radio"===n.type&&null!=t){for(n=e;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<n.length;t++){var r=n[t];if(r!==e&&r.form===e.form){var i=_i(r);if(!i)throw Error(s(90));G(r),J(r,i)}}}break;case"textarea":se(e,n);break;case"select":null!=(t=n.value)&&ne(e,!!n.multiple,t,!1)}},xe=uc,Ne=hc;var tu={usingClientEntryPoint:!1,Events:[wi,bi,_i,Te,Ce,uc]},nu={findFiberByHostInstance:yi,bundleType:0,version:"18.2.0",rendererPackageName:"react-dom"},ru={bundleType:nu.bundleType,version:nu.version,rendererPackageName:nu.rendererPackageName,rendererConfig:nu.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:b.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return null===(e=We(e))?null:e.stateNode},findFiberByHostInstance:nu.findFiberByHostInstance||function(){return null},findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.2.0-next-9e3b772b8-20220608"};if("undefined"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__){var iu=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!iu.isDisabled&&iu.supportsFiber)try{it=iu.inject(ru),st=iu}catch(ue){}}t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=tu,t.createPortal=function(e,t){var n=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!Xc(t))throw Error(s(200));return function(e,t,n){var r=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:E,key:null==r?null:""+r,children:e,containerInfo:t,implementation:n}}(e,t,null,n)},t.createRoot=function(e,t){if(!Xc(e))throw Error(s(299));var n=!1,r="",i=Qc;return null!==t&&void 0!==t&&(!0===t.unstable_strictMode&&(n=!0),void 0!==t.identifierPrefix&&(r=t.identifierPrefix),void 0!==t.onRecoverableError&&(i=t.onRecoverableError)),t=Bc(e,1,!1,null,0,n,0,r,i),e[pi]=t.current,zr(8===e.nodeType?e.parentNode:e),new $c(t)},t.findDOMNode=function(e){if(null==e)return null;if(1===e.nodeType)return e;var t=e._reactInternals;if(void 0===t){if("function"===typeof e.render)throw Error(s(188));throw e=Object.keys(e).join(","),Error(s(268,e))}return e=null===(e=We(t))?null:e.stateNode},t.flushSync=function(e){return hc(e)},t.hydrate=function(e,t,n){if(!Jc(t))throw Error(s(200));return eu(null,e,t,!0,n)},t.hydrateRoot=function(e,t,n){if(!Xc(e))throw Error(s(405));var r=null!=n&&n.hydratedSources||null,i=!1,a="",o=Qc;if(null!==n&&void 0!==n&&(!0===n.unstable_strictMode&&(i=!0),void 0!==n.identifierPrefix&&(a=n.identifierPrefix),void 0!==n.onRecoverableError&&(o=n.onRecoverableError)),t=qc(t,null,e,1,null!=n?n:null,i,0,a,o),e[pi]=t.current,zr(e),r)for(e=0;e<r.length;e++)i=(i=(n=r[e])._getVersion)(n._source),null==t.mutableSourceEagerHydrationData?t.mutableSourceEagerHydrationData=[n,i]:t.mutableSourceEagerHydrationData.push(n,i);return new Yc(t)},t.render=function(e,t,n){if(!Jc(t))throw Error(s(200));return eu(null,e,t,!1,n)},t.unmountComponentAtNode=function(e){if(!Jc(e))throw Error(s(40));return!!e._reactRootContainer&&(hc((function(){eu(null,null,e,!1,(function(){e._reactRootContainer=null,e[pi]=null}))})),!0)},t.unstable_batchedUpdates=uc,t.unstable_renderSubtreeIntoContainer=function(e,t,n,r){if(!Jc(n))throw Error(s(200));if(null==e||void 0===e._reactInternals)throw Error(s(38));return eu(e,t,n,!1,r)},t.version="18.2.0-next-9e3b772b8-20220608"},250:(e,t,n)=>{var r=n(164);t.createRoot=r.createRoot,t.hydrateRoot=r.hydrateRoot},164:(e,t,n)=>{!function e(){if("undefined"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}(),e.exports=n(463)},374:(e,t,n)=>{var r=n(791),i=Symbol.for("react.element"),s=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,o=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function c(e,t,n){var r,s={},c=null,u=null;for(r in void 0!==n&&(c=""+n),void 0!==t.key&&(c=""+t.key),void 0!==t.ref&&(u=t.ref),t)a.call(t,r)&&!l.hasOwnProperty(r)&&(s[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps)void 0===s[r]&&(s[r]=t[r]);return{$$typeof:i,type:e,key:c,ref:u,props:s,_owner:o.current}}t.jsx=c,t.jsxs=c},117:(e,t)=>{var n=Symbol.for("react.element"),r=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),o=Symbol.for("react.provider"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),h=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),f=Symbol.iterator;var p={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},m=Object.assign,g={};function v(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||p}function y(){}function w(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||p}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if("object"!==typeof e&&"function"!==typeof e&&null!=e)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},y.prototype=v.prototype;var b=w.prototype=new y;b.constructor=w,m(b,v.prototype),b.isPureReactComponent=!0;var _=Array.isArray,E=Object.prototype.hasOwnProperty,S={current:null},k={key:!0,ref:!0,__self:!0,__source:!0};function I(e,t,r){var i,s={},a=null,o=null;if(null!=t)for(i in void 0!==t.ref&&(o=t.ref),void 0!==t.key&&(a=""+t.key),t)E.call(t,i)&&!k.hasOwnProperty(i)&&(s[i]=t[i]);var l=arguments.length-2;if(1===l)s.children=r;else if(1<l){for(var c=Array(l),u=0;u<l;u++)c[u]=arguments[u+2];s.children=c}if(e&&e.defaultProps)for(i in l=e.defaultProps)void 0===s[i]&&(s[i]=l[i]);return{$$typeof:n,type:e,key:a,ref:o,props:s,_owner:S.current}}function T(e){return"object"===typeof e&&null!==e&&e.$$typeof===n}var C=/\/+/g;function x(e,t){return"object"===typeof e&&null!==e&&null!=e.key?function(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,(function(e){return t[e]}))}(""+e.key):t.toString(36)}function N(e,t,i,s,a){var o=typeof e;"undefined"!==o&&"boolean"!==o||(e=null);var l=!1;if(null===e)l=!0;else switch(o){case"string":case"number":l=!0;break;case"object":switch(e.$$typeof){case n:case r:l=!0}}if(l)return a=a(l=e),e=""===s?"."+x(l,0):s,_(a)?(i="",null!=e&&(i=e.replace(C,"$&/")+"/"),N(a,t,i,"",(function(e){return e}))):null!=a&&(T(a)&&(a=function(e,t){return{$$typeof:n,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}(a,i+(!a.key||l&&l.key===a.key?"":(""+a.key).replace(C,"$&/")+"/")+e)),t.push(a)),1;if(l=0,s=""===s?".":s+":",_(e))for(var c=0;c<e.length;c++){var u=s+x(o=e[c],c);l+=N(o,t,i,u,a)}else if(u=function(e){return null===e||"object"!==typeof e?null:"function"===typeof(e=f&&e[f]||e["@@iterator"])?e:null}(e),"function"===typeof u)for(e=u.call(e),c=0;!(o=e.next()).done;)l+=N(o=o.value,t,i,u=s+x(o,c++),a);else if("object"===o)throw t=String(e),Error("Objects are not valid as a React child (found: "+("[object Object]"===t?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return l}function A(e,t,n){if(null==e)return e;var r=[],i=0;return N(e,r,"","",(function(e){return t.call(n,e,i++)})),r}function P(e){if(-1===e._status){var t=e._result;(t=t()).then((function(t){0!==e._status&&-1!==e._status||(e._status=1,e._result=t)}),(function(t){0!==e._status&&-1!==e._status||(e._status=2,e._result=t)})),-1===e._status&&(e._status=0,e._result=t)}if(1===e._status)return e._result.default;throw e._result}var R={current:null},O={transition:null},D={ReactCurrentDispatcher:R,ReactCurrentBatchConfig:O,ReactCurrentOwner:S};t.Children={map:A,forEach:function(e,t,n){A(e,(function(){t.apply(this,arguments)}),n)},count:function(e){var t=0;return A(e,(function(){t++})),t},toArray:function(e){return A(e,(function(e){return e}))||[]},only:function(e){if(!T(e))throw Error("React.Children.only expected to receive a single React element child.");return e}},t.Component=v,t.Fragment=i,t.Profiler=a,t.PureComponent=w,t.StrictMode=s,t.Suspense=u,t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=D,t.cloneElement=function(e,t,r){if(null===e||void 0===e)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var i=m({},e.props),s=e.key,a=e.ref,o=e._owner;if(null!=t){if(void 0!==t.ref&&(a=t.ref,o=S.current),void 0!==t.key&&(s=""+t.key),e.type&&e.type.defaultProps)var l=e.type.defaultProps;for(c in t)E.call(t,c)&&!k.hasOwnProperty(c)&&(i[c]=void 0===t[c]&&void 0!==l?l[c]:t[c])}var c=arguments.length-2;if(1===c)i.children=r;else if(1<c){l=Array(c);for(var u=0;u<c;u++)l[u]=arguments[u+2];i.children=l}return{$$typeof:n,type:e.type,key:s,ref:a,props:i,_owner:o}},t.createContext=function(e){return(e={$$typeof:l,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null}).Provider={$$typeof:o,_context:e},e.Consumer=e},t.createElement=I,t.createFactory=function(e){var t=I.bind(null,e);return t.type=e,t},t.createRef=function(){return{current:null}},t.forwardRef=function(e){return{$$typeof:c,render:e}},t.isValidElement=T,t.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:P}},t.memo=function(e,t){return{$$typeof:h,type:e,compare:void 0===t?null:t}},t.startTransition=function(e){var t=O.transition;O.transition={};try{e()}finally{O.transition=t}},t.unstable_act=function(){throw Error("act(...) is not supported in production builds of React.")},t.useCallback=function(e,t){return R.current.useCallback(e,t)},t.useContext=function(e){return R.current.useContext(e)},t.useDebugValue=function(){},t.useDeferredValue=function(e){return R.current.useDeferredValue(e)},t.useEffect=function(e,t){return R.current.useEffect(e,t)},t.useId=function(){return R.current.useId()},t.useImperativeHandle=function(e,t,n){return R.current.useImperativeHandle(e,t,n)},t.useInsertionEffect=function(e,t){return R.current.useInsertionEffect(e,t)},t.useLayoutEffect=function(e,t){return R.current.useLayoutEffect(e,t)},t.useMemo=function(e,t){return R.current.useMemo(e,t)},t.useReducer=function(e,t,n){return R.current.useReducer(e,t,n)},t.useRef=function(e){return R.current.useRef(e)},t.useState=function(e){return R.current.useState(e)},t.useSyncExternalStore=function(e,t,n){return R.current.useSyncExternalStore(e,t,n)},t.useTransition=function(){return R.current.useTransition()},t.version="18.2.0"},791:(e,t,n)=>{e.exports=n(117)},184:(e,t,n)=>{e.exports=n(374)},813:(e,t)=>{function n(e,t){var n=e.length;e.push(t);e:for(;0<n;){var r=n-1>>>1,i=e[r];if(!(0<s(i,t)))break e;e[r]=t,e[n]=i,n=r}}function r(e){return 0===e.length?null:e[0]}function i(e){if(0===e.length)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;e:for(var r=0,i=e.length,a=i>>>1;r<a;){var o=2*(r+1)-1,l=e[o],c=o+1,u=e[c];if(0>s(l,n))c<i&&0>s(u,l)?(e[r]=u,e[c]=n,r=c):(e[r]=l,e[o]=n,r=o);else{if(!(c<i&&0>s(u,n)))break e;e[r]=u,e[c]=n,r=c}}}return t}function s(e,t){var n=e.sortIndex-t.sortIndex;return 0!==n?n:e.id-t.id}if("object"===typeof performance&&"function"===typeof performance.now){var a=performance;t.unstable_now=function(){return a.now()}}else{var o=Date,l=o.now();t.unstable_now=function(){return o.now()-l}}var c=[],u=[],h=1,d=null,f=3,p=!1,m=!1,g=!1,v="function"===typeof setTimeout?setTimeout:null,y="function"===typeof clearTimeout?clearTimeout:null,w="undefined"!==typeof setImmediate?setImmediate:null;function b(e){for(var t=r(u);null!==t;){if(null===t.callback)i(u);else{if(!(t.startTime<=e))break;i(u),t.sortIndex=t.expirationTime,n(c,t)}t=r(u)}}function _(e){if(g=!1,b(e),!m)if(null!==r(c))m=!0,O(E);else{var t=r(u);null!==t&&D(_,t.startTime-e)}}function E(e,n){m=!1,g&&(g=!1,y(T),T=-1),p=!0;var s=f;try{for(b(n),d=r(c);null!==d&&(!(d.expirationTime>n)||e&&!N());){var a=d.callback;if("function"===typeof a){d.callback=null,f=d.priorityLevel;var o=a(d.expirationTime<=n);n=t.unstable_now(),"function"===typeof o?d.callback=o:d===r(c)&&i(c),b(n)}else i(c);d=r(c)}if(null!==d)var l=!0;else{var h=r(u);null!==h&&D(_,h.startTime-n),l=!1}return l}finally{d=null,f=s,p=!1}}"undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var S,k=!1,I=null,T=-1,C=5,x=-1;function N(){return!(t.unstable_now()-x<C)}function A(){if(null!==I){var e=t.unstable_now();x=e;var n=!0;try{n=I(!0,e)}finally{n?S():(k=!1,I=null)}}else k=!1}if("function"===typeof w)S=function(){w(A)};else if("undefined"!==typeof MessageChannel){var P=new MessageChannel,R=P.port2;P.port1.onmessage=A,S=function(){R.postMessage(null)}}else S=function(){v(A,0)};function O(e){I=e,k||(k=!0,S())}function D(e,n){T=v((function(){e(t.unstable_now())}),n)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(e){e.callback=null},t.unstable_continueExecution=function(){m||p||(m=!0,O(E))},t.unstable_forceFrameRate=function(e){0>e||125<e?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):C=0<e?Math.floor(1e3/e):5},t.unstable_getCurrentPriorityLevel=function(){return f},t.unstable_getFirstCallbackNode=function(){return r(c)},t.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},t.unstable_pauseExecution=function(){},t.unstable_requestPaint=function(){},t.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},t.unstable_scheduleCallback=function(e,i,s){var a=t.unstable_now();switch("object"===typeof s&&null!==s?s="number"===typeof(s=s.delay)&&0<s?a+s:a:s=a,e){case 1:var o=-1;break;case 2:o=250;break;case 5:o=1073741823;break;case 4:o=1e4;break;default:o=5e3}return e={id:h++,callback:i,priorityLevel:e,startTime:s,expirationTime:o=s+o,sortIndex:-1},s>a?(e.sortIndex=s,n(u,e),null===r(c)&&e===r(u)&&(g?(y(T),T=-1):g=!0,D(_,s-a))):(e.sortIndex=o,n(c,e),m||p||(m=!0,O(E))),e},t.unstable_shouldYield=N,t.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}},296:(e,t,n)=>{e.exports=n(813)}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var s=t[r]={exports:{}};return e[r](s,s.exports,n),s.exports}n.m=e,(()=>{var e,t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;n.t=function(r,i){if(1&i&&(r=this(r)),8&i)return r;if("object"===typeof r&&r){if(4&i&&r.__esModule)return r;if(16&i&&"function"===typeof r.then)return r}var s=Object.create(null);n.r(s);var a={};e=e||[null,t({}),t([]),t(t)];for(var o=2&i&&r;"object"==typeof o&&!~e.indexOf(o);o=t(o))Object.getOwnPropertyNames(o).forEach((e=>a[e]=()=>r[e]));return a.default=()=>r,n.d(s,a),s}})(),n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.f={},n.e=e=>Promise.all(Object.keys(n.f).reduce(((t,r)=>(n.f[r](e,t),t)),[])),n.u=e=>"static/js/"+e+".7e4c938d.chunk.js",n.miniCssF=e=>{},n.g=function(){if("object"===typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"===typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{var e={},t="friendlybetting:";n.l=(r,i,s,a)=>{if(e[r])e[r].push(i);else{var o,l;if(void 0!==s)for(var c=document.getElementsByTagName("script"),u=0;u<c.length;u++){var h=c[u];if(h.getAttribute("src")==r||h.getAttribute("data-webpack")==t+s){o=h;break}}o||(l=!0,(o=document.createElement("script")).charset="utf-8",o.timeout=120,n.nc&&o.setAttribute("nonce",n.nc),o.setAttribute("data-webpack",t+s),o.src=r),e[r]=[i];var d=(t,n)=>{o.onerror=o.onload=null,clearTimeout(f);var i=e[r];if(delete e[r],o.parentNode&&o.parentNode.removeChild(o),i&&i.forEach((e=>e(n))),t)return t(n)},f=setTimeout(d.bind(null,void 0,{type:"timeout",target:o}),12e4);o.onerror=d.bind(null,o.onerror),o.onload=d.bind(null,o.onload),l&&document.head.appendChild(o)}}})(),n.r=e=>{"undefined"!==typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.p="/Friendly-Betting/",(()=>{var e={179:0};n.f.j=(t,r)=>{var i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{var s=new Promise(((n,r)=>i=e[t]=[n,r]));r.push(i[2]=s);var a=n.p+n.u(t),o=new Error;n.l(a,(r=>{if(n.o(e,t)&&(0!==(i=e[t])&&(e[t]=void 0),i)){var s=r&&("load"===r.type?"missing":r.type),a=r&&r.target&&r.target.src;o.message="Loading chunk "+t+" failed.\n("+s+": "+a+")",o.name="ChunkLoadError",o.type=s,o.request=a,i[1](o)}}),"chunk-"+t,t)}};var t=(t,r)=>{var i,s,a=r[0],o=r[1],l=r[2],c=0;if(a.some((t=>0!==e[t]))){for(i in o)n.o(o,i)&&(n.m[i]=o[i]);if(l)l(n)}for(t&&t(r);c<a.length;c++)s=a[c],n.o(e,s)&&e[s]&&e[s][0](),e[s]=0},r=self.webpackChunkfriendlybetting=self.webpackChunkfriendlybetting||[];r.forEach(t.bind(null,0)),r.push=t.bind(null,r.push.bind(r))})(),(()=>{var e=n(791),t=n.t(e,2),r=n(250);const i=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):55296===(64512&i)&&r+1<e.length&&56320===(64512&e.charCodeAt(r+1))?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++r)),t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128)}return t},s={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"===typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let i=0;i<e.length;i+=3){const t=e[i],s=i+1<e.length,a=s?e[i+1]:0,o=i+2<e.length,l=o?e[i+2]:0,c=t>>2,u=(3&t)<<4|a>>4;let h=(15&a)<<2|l>>6,d=63&l;o||(d=64,s||(h=64)),r.push(n[c],n[u],n[h],n[d])}return r.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(i(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){const i=e[n++];if(i<128)t[r++]=String.fromCharCode(i);else if(i>191&&i<224){const s=e[n++];t[r++]=String.fromCharCode((31&i)<<6|63&s)}else if(i>239&&i<365){const s=((7&i)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))}else{const s=e[n++],a=e[n++];t[r++]=String.fromCharCode((15&i)<<12|(63&s)<<6|63&a)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let i=0;i<e.length;){const t=n[e.charAt(i++)],s=i<e.length?n[e.charAt(i)]:0;++i;const o=i<e.length?n[e.charAt(i)]:64;++i;const l=i<e.length?n[e.charAt(i)]:64;if(++i,null==t||null==s||null==o||null==l)throw new a;const c=t<<2|s>>4;if(r.push(c),64!==o){const e=s<<4&240|o>>2;if(r.push(e),64!==l){const e=o<<6&192|l;r.push(e)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class a extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const o=function(e){return function(e){const t=i(e);return s.encodeByteArray(t,!0)}(e).replace(/\./g,"")},l=function(e){try{return s.decodeString(e,!0)}catch(t){console.error("base64Decode failed: ",t)}return null};const c=()=>function(){if("undefined"!==typeof self)return self;if("undefined"!==typeof window)return window;if("undefined"!==typeof n.g)return n.g;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,u=()=>{try{return c()||(()=>{if("undefined"===typeof process)return;const e={NODE_ENV:"production",PUBLIC_URL:"/Friendly-Betting",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0}.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if("undefined"===typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(n){return}const t=e&&l(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info("Unable to get __FIREBASE_DEFAULTS__ due to: ".concat(e))}},h=e=>{var t,n;return null===(n=null===(t=u())||void 0===t?void 0:t.emulatorHosts)||void 0===n?void 0:n[e]},d=()=>{var e;return null===(e=u())||void 0===e?void 0:e.config},f=e=>{var t;return null===(t=u())||void 0===t?void 0:t["_".concat(e)]};class p{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,n)=>{t?this.reject(t):this.resolve(n),"function"===typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,n))}}}function m(){return"undefined"!==typeof navigator&&"string"===typeof navigator.userAgent?navigator.userAgent:""}function g(){const e="object"===typeof chrome?chrome.runtime:"object"===typeof browser?browser.runtime:void 0;return"object"===typeof e&&void 0!==e.id}function v(){try{return"object"===typeof indexedDB}catch(e){return!1}}function y(){return new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{var e;t((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(n){t(n)}}))}class w extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,w.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,b.prototype.create)}}class b{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e){const t=(arguments.length<=1?void 0:arguments[1])||{},n="".concat(this.service,"/").concat(e),r=this.errors[e],i=r?function(e,t){return e.replace(_,((e,n)=>{const r=t[n];return null!=r?String(r):"<".concat(n,"?>")}))}(r,t):"Error",s="".concat(this.serviceName,": ").concat(i," (").concat(n,").");return new w(n,s,t)}}const _=/\{\$([^}]+)}/g;function E(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const i of n){if(!r.includes(i))return!1;const n=e[i],s=t[i];if(S(n)&&S(s)){if(!E(n,s))return!1}else if(n!==s)return!1}for(const i of r)if(!n.includes(i))return!1;return!0}function S(e){return null!==e&&"object"===typeof e}function k(e){const t=[];for(const[n,r]of Object.entries(e))Array.isArray(r)?r.forEach((e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))})):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""}function I(e){const t={};return e.replace(/^\?/,"").split("&").forEach((e=>{if(e){const[n,r]=e.split("=");t[decodeURIComponent(n)]=decodeURIComponent(r)}})),t}function T(e){const t=e.indexOf("?");if(!t)return"";const n=e.indexOf("#",t);return e.substring(t,n>0?n:void 0)}class C{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then((()=>{e(this)})).catch((e=>{this.error(e)}))}next(e){this.forEachObserver((t=>{t.next(e)}))}error(e){this.forEachObserver((t=>{t.error(e)})),this.close(e)}complete(){this.forEachObserver((e=>{e.complete()})),this.close()}subscribe(e,t,n){let r;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");r=function(e,t){if("object"!==typeof e||null===e)return!1;for(const n of t)if(n in e&&"function"===typeof e[n])return!0;return!1}(e,["next","error","complete"])?e:{next:e,error:t,complete:n},void 0===r.next&&(r.next=x),void 0===r.error&&(r.error=x),void 0===r.complete&&(r.complete=x);const i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then((()=>{try{this.finalError?r.error(this.finalError):r.complete()}catch(e){}})),this.observers.push(r),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t<this.observers.length;t++)this.sendOne(t,e)}sendOne(e,t){this.task.then((()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(n){"undefined"!==typeof console&&console.error&&console.error(n)}}))}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then((()=>{this.observers=void 0,this.onNoObservers=void 0})))}}function x(){}const N=1e3,A=2,P=144e5,R=.5;function O(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:A;const n=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:N)*Math.pow(t,e),r=Math.round(R*n*(Math.random()-.5)*2);return Math.min(P,n+r)}function D(e){return e&&e._delegate?e._delegate:e}class L{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const M="[DEFAULT]";class j{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){const t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const e=new p;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{const n=this.getOrInitializeService({instanceIdentifier:t});n&&e.resolve(n)}catch(n){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t;const n=this.normalizeInstanceIdentifier(null===e||void 0===e?void 0:e.identifier),r=null!==(t=null===e||void 0===e?void 0:e.optional)&&void 0!==t&&t;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(r)return null;throw Error("Service ".concat(this.name," is not available"))}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(i){if(r)return null;throw i}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error("Mismatching Component ".concat(e.name," for Provider ").concat(this.name,"."));if(this.component)throw Error("Component for ".concat(this.name," has already been provided"));if(this.component=e,this.shouldAutoInitialize()){if(function(e){return"EAGER"===e.instantiationMode}(e))try{this.getOrInitializeService({instanceIdentifier:M})}catch(t){}for(const[e,n]of this.instancesDeferred.entries()){const r=this.normalizeInstanceIdentifier(e);try{const e=this.getOrInitializeService({instanceIdentifier:r});n.resolve(e)}catch(t){}}}}clearInstance(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:M;this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter((e=>"INTERNAL"in e)).map((e=>e.INTERNAL.delete())),...e.filter((e=>"_delete"in e)).map((e=>e._delete()))])}isComponentSet(){return null!=this.component}isInitialized(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:M;return this.instances.has(e)}getOptions(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:M;return this.instancesOptions.get(e)||{}}initialize(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error("".concat(this.name,"(").concat(n,") has already been initialized"));if(!this.isComponentSet())throw Error("Component ".concat(this.name," has not been registered yet"));const r=this.getOrInitializeService({instanceIdentifier:n,options:t});for(const[i,s]of this.instancesDeferred.entries()){n===this.normalizeInstanceIdentifier(i)&&s.resolve(r)}return r}onInit(e,t){var n;const r=this.normalizeInstanceIdentifier(t),i=null!==(n=this.onInitCallbacks.get(r))&&void 0!==n?n:new Set;i.add(e),this.onInitCallbacks.set(r,i);const s=this.instances.get(r);return s&&e(s,r),()=>{i.delete(e)}}invokeOnInitCallbacks(e,t){const n=this.onInitCallbacks.get(t);if(n)for(const i of n)try{i(e,t)}catch(r){}}getOrInitializeService(e){let{instanceIdentifier:t,options:n={}}=e,r=this.instances.get(t);if(!r&&this.component&&(r=this.component.instanceFactory(this.container,{instanceIdentifier:(i=t,i===M?void 0:i),options:n}),this.instances.set(t,r),this.instancesOptions.set(t,n),this.invokeOnInitCallbacks(r,t),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,t,r)}catch(s){}var i;return r||null}normalizeInstanceIdentifier(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:M;return this.component?this.component.multipleInstances?e:M:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class F{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error("Component ".concat(e.name," has already been registered with ").concat(this.name));t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const t=new j(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const U=[];var V;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(V||(V={}));const B={debug:V.DEBUG,verbose:V.VERBOSE,info:V.INFO,warn:V.WARN,error:V.ERROR,silent:V.SILENT},z=V.INFO,q={[V.DEBUG]:"log",[V.VERBOSE]:"log",[V.INFO]:"info",[V.WARN]:"warn",[V.ERROR]:"error"},H=function(e,t){if(t<e.logLevel)return;const n=(new Date).toISOString(),r=q[t];if(!r)throw new Error("Attempted to log a message with an invalid logType (value: ".concat(t,")"));for(var i=arguments.length,s=new Array(i>2?i-2:0),a=2;a<i;a++)s[a-2]=arguments[a];console[r]("[".concat(n,"] ").concat(e.name,":"),...s)};class W{constructor(e){this.name=e,this._logLevel=z,this._logHandler=H,this._userLogHandler=null,U.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in V))throw new TypeError('Invalid value "'.concat(e,'" assigned to `logLevel`'));this._logLevel=e}setLogLevel(e){this._logLevel="string"===typeof e?B[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!==typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this._userLogHandler&&this._userLogHandler(this,V.DEBUG,...t),this._logHandler(this,V.DEBUG,...t)}log(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this._userLogHandler&&this._userLogHandler(this,V.VERBOSE,...t),this._logHandler(this,V.VERBOSE,...t)}info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this._userLogHandler&&this._userLogHandler(this,V.INFO,...t),this._logHandler(this,V.INFO,...t)}warn(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this._userLogHandler&&this._userLogHandler(this,V.WARN,...t),this._logHandler(this,V.WARN,...t)}error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this._userLogHandler&&this._userLogHandler(this,V.ERROR,...t),this._logHandler(this,V.ERROR,...t)}}const K=(e,t)=>t.some((t=>e instanceof t));let G,Q;const $=new WeakMap,Y=new WeakMap,X=new WeakMap,J=new WeakMap,Z=new WeakMap;let ee={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return Y.get(e);if("objectStoreNames"===t)return e.objectStoreNames||X.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return re(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function te(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(Q||(Q=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return e.apply(ie(this),n),re($.get(this))}:function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return re(e.apply(ie(this),n))}:function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];const s=e.call(ie(this),t,...r);return X.set(s,t.sort?t.sort():[t]),re(s)}}function ne(e){return"function"===typeof e?te(e):(e instanceof IDBTransaction&&function(e){if(Y.has(e))return;const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",s),e.removeEventListener("abort",s)},i=()=>{t(),r()},s=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",i),e.addEventListener("error",s),e.addEventListener("abort",s)}));Y.set(e,t)}(e),K(e,G||(G=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,ee):e)}function re(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{t(re(e.result)),r()},s=()=>{n(e.error),r()};e.addEventListener("success",i),e.addEventListener("error",s)}));return t.then((t=>{t instanceof IDBCursor&&$.set(t,e)})).catch((()=>{})),Z.set(t,e),t}(e);if(J.has(e))return J.get(e);const t=ne(e);return t!==e&&(J.set(e,t),Z.set(t,e)),t}const ie=e=>Z.get(e);const se=["get","getKey","getAll","getAllKeys","count"],ae=["put","add","delete","clear"],oe=new Map;function le(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!==typeof t)return;if(oe.get(t))return oe.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=ae.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!se.includes(n))return;const s=async function(e){const t=this.transaction(e,i?"readwrite":"readonly");let s=t.store;for(var a=arguments.length,o=new Array(a>1?a-1:0),l=1;l<a;l++)o[l-1]=arguments[l];return r&&(s=s.index(o.shift())),(await Promise.all([s[n](...o),i&&t.done]))[0]};return oe.set(t,s),s}ee=(e=>({...e,get:(t,n,r)=>le(t,n)||e.get(t,n,r),has:(t,n)=>!!le(t,n)||e.has(t,n)}))(ee);class ce{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map((e=>{if(function(e){const t=e.getComponent();return"VERSION"===(null===t||void 0===t?void 0:t.type)}(e)){const t=e.getImmediate();return"".concat(t.library,"/").concat(t.version)}return null})).filter((e=>e)).join(" ")}}const ue="@firebase/app",he="0.9.23",de=new W("@firebase/app"),fe="[DEFAULT]",pe={[ue]:"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","fire-js":"fire-js",firebase:"fire-js-all"},me=new Map,ge=new Map;function ve(e,t){try{e.container.addComponent(t)}catch(n){de.debug("Component ".concat(t.name," failed to register with FirebaseApp ").concat(e.name),n)}}function ye(e){const t=e.name;if(ge.has(t))return de.debug("There were multiple attempts to register component ".concat(t,".")),!1;ge.set(t,e);for(const n of me.values())ve(n,e);return!0}function we(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}const be=new b("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}."});class _e{constructor(e,t,n){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new L("app",(()=>this),"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw be.create("app-deleted",{appName:this._name})}}const Ee="10.6.0";function Se(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e;if("object"!==typeof t){t={name:t}}const r=Object.assign({name:fe,automaticDataCollectionEnabled:!1},t),i=r.name;if("string"!==typeof i||!i)throw be.create("bad-app-name",{appName:String(i)});if(n||(n=d()),!n)throw be.create("no-options");const s=me.get(i);if(s){if(E(n,s.options)&&E(r,s.config))return s;throw be.create("duplicate-app",{appName:i})}const a=new F(i);for(const l of ge.values())a.addComponent(l);const o=new _e(n,r,a);return me.set(i,o),o}function ke(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:fe;const t=me.get(e);if(!t&&e===fe&&d())return Se();if(!t)throw be.create("no-app",{appName:e});return t}function Ie(e,t,n){var r;let i=null!==(r=pe[e])&&void 0!==r?r:e;n&&(i+="-".concat(n));const s=i.match(/\s|\//),a=t.match(/\s|\//);if(s||a){const e=['Unable to register library "'.concat(i,'" with version "').concat(t,'":')];return s&&e.push('library name "'.concat(i,'" contains illegal characters (whitespace or "/")')),s&&a&&e.push("and"),a&&e.push('version name "'.concat(t,'" contains illegal characters (whitespace or "/")')),void de.warn(e.join(" "))}ye(new L("".concat(i,"-version"),(()=>({library:i,version:t})),"VERSION"))}const Te="firebase-heartbeat-database",Ce=1,xe="firebase-heartbeat-store";let Ne=null;function Ae(){return Ne||(Ne=function(e,t){let{blocked:n,upgrade:r,blocking:i,terminated:s}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const a=indexedDB.open(e,t),o=re(a);return r&&a.addEventListener("upgradeneeded",(e=>{r(re(a.result),e.oldVersion,e.newVersion,re(a.transaction),e)})),n&&a.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),o.then((e=>{s&&e.addEventListener("close",(()=>s())),i&&e.addEventListener("versionchange",(e=>i(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),o}(Te,Ce,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(xe)}}).catch((e=>{throw be.create("idb-open",{originalErrorMessage:e.message})}))),Ne}async function Pe(e,t){try{const n=(await Ae()).transaction(xe,"readwrite"),r=n.objectStore(xe);await r.put(t,Re(e)),await n.done}catch(n){if(n instanceof w)de.warn(n.message);else{const e=be.create("idb-set",{originalErrorMessage:null===n||void 0===n?void 0:n.message});de.warn(e.message)}}}function Re(e){return"".concat(e.name,"!").concat(e.options.appId)}class Oe{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new Le(t),this._heartbeatsCachePromise=this._storage.read().then((e=>(this._heartbeatsCache=e,e)))}async triggerHeartbeat(){var e;const t=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),n=De();if(null==(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)&&(this._heartbeatsCache=await this._heartbeatsCachePromise),this._heartbeatsCache.lastSentHeartbeatDate!==n&&!this._heartbeatsCache.heartbeats.some((e=>e.date===n)))return this._heartbeatsCache.heartbeats.push({date:n,agent:t}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter((e=>{const t=new Date(e.date).valueOf();return Date.now()-t<=2592e6})),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){var e;if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null==(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)||0===this._heartbeatsCache.heartbeats.length)return"";const t=De(),{heartbeatsToSend:n,unsentEntries:r}=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1024;const n=[];let r=e.slice();for(const i of e){const e=n.find((e=>e.agent===i.agent));if(e){if(e.dates.push(i.date),Me(n)>t){e.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),Me(n)>t){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}(this._heartbeatsCache.heartbeats),i=o(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=t,r.length>0?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i}}function De(){return(new Date).toISOString().substring(0,10)}class Le{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!v()&&y().then((()=>!0)).catch((()=>!1))}async read(){if(await this._canUseIndexedDBPromise){const e=await async function(e){try{const t=await Ae();return await t.transaction(xe).objectStore(xe).get(Re(e))}catch(t){if(t instanceof w)de.warn(t.message);else{const e=be.create("idb-get",{originalErrorMessage:null===t||void 0===t?void 0:t.message});de.warn(e.message)}}}(this.app);return e||{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return Pe(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return Pe(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function Me(e){return o(JSON.stringify({version:2,heartbeats:e})).length}var je;je="",ye(new L("platform-logger",(e=>new ce(e)),"PRIVATE")),ye(new L("heartbeat",(e=>new Oe(e)),"PRIVATE")),Ie(ue,he,je),Ie(ue,he,"esm2017"),Ie("fire-js","");Ie("firebase","10.6.0","app");const Fe=(e,t)=>t.some((t=>e instanceof t));let Ue,Ve;const Be=new WeakMap,ze=new WeakMap,qe=new WeakMap,He=new WeakMap,We=new WeakMap;let Ke={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return ze.get(e);if("objectStoreNames"===t)return e.objectStoreNames||qe.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return $e(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function Ge(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(Ve||(Ve=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return e.apply(Ye(this),n),$e(Be.get(this))}:function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return $e(e.apply(Ye(this),n))}:function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];const s=e.call(Ye(this),t,...r);return qe.set(s,t.sort?t.sort():[t]),$e(s)}}function Qe(e){return"function"===typeof e?Ge(e):(e instanceof IDBTransaction&&function(e){if(ze.has(e))return;const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",s),e.removeEventListener("abort",s)},i=()=>{t(),r()},s=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",i),e.addEventListener("error",s),e.addEventListener("abort",s)}));ze.set(e,t)}(e),Fe(e,Ue||(Ue=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,Ke):e)}function $e(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{t($e(e.result)),r()},s=()=>{n(e.error),r()};e.addEventListener("success",i),e.addEventListener("error",s)}));return t.then((t=>{t instanceof IDBCursor&&Be.set(t,e)})).catch((()=>{})),We.set(t,e),t}(e);if(He.has(e))return He.get(e);const t=Qe(e);return t!==e&&(He.set(e,t),We.set(t,e)),t}const Ye=e=>We.get(e);const Xe=["get","getKey","getAll","getAllKeys","count"],Je=["put","add","delete","clear"],Ze=new Map;function et(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!==typeof t)return;if(Ze.get(t))return Ze.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=Je.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!Xe.includes(n))return;const s=async function(e){const t=this.transaction(e,i?"readwrite":"readonly");let s=t.store;for(var a=arguments.length,o=new Array(a>1?a-1:0),l=1;l<a;l++)o[l-1]=arguments[l];return r&&(s=s.index(o.shift())),(await Promise.all([s[n](...o),i&&t.done]))[0]};return Ze.set(t,s),s}!function(e){Ke=e(Ke)}((e=>({...e,get:(t,n,r)=>et(t,n)||e.get(t,n,r),has:(t,n)=>!!et(t,n)||e.has(t,n)})));const tt="@firebase/installations",nt="0.6.4",rt=1e4,it="w:".concat(nt),st="FIS_v2",at="https://firebaseinstallations.googleapis.com/v1",ot=36e5,lt=new b("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function ct(e){return e instanceof w&&e.code.includes("request-failed")}function ut(e){let{projectId:t}=e;return"".concat(at,"/projects/").concat(t,"/installations")}function ht(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function dt(e,t){const n=(await t.json()).error;return lt.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function ft(e){let{apiKey:t}=e;return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":t})}function pt(e,t){let{refreshToken:n}=t;const r=ft(e);return r.append("Authorization",function(e){return"".concat(st," ").concat(e)}(n)),r}async function mt(e){const t=await e();return t.status>=500&&t.status<600?e():t}function gt(e){return new Promise((t=>{setTimeout(t,e)}))}const vt=/^[cdef][\w-]{21}$/,yt="";function wt(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function(e){const t=(n=e,btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_"));var n;return t.substr(0,22)}(e);return vt.test(t)?t:yt}catch(e){return yt}}function bt(e){return"".concat(e.appName,"!").concat(e.appId)}const _t=new Map;function Et(e,t){const n=bt(e);St(n,t),function(e,t){const n=It();n&&n.postMessage({key:e,fid:t});Tt()}(n,t)}function St(e,t){const n=_t.get(e);if(n)for(const r of n)r(t)}let kt=null;function It(){return!kt&&"BroadcastChannel"in self&&(kt=new BroadcastChannel("[Firebase] FID Change"),kt.onmessage=e=>{St(e.data.key,e.data.fid)}),kt}function Tt(){0===_t.size&&kt&&(kt.close(),kt=null)}const Ct="firebase-installations-database",xt=1,Nt="firebase-installations-store";let At=null;function Pt(){return At||(At=function(e,t){let{blocked:n,upgrade:r,blocking:i,terminated:s}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const a=indexedDB.open(e,t),o=$e(a);return r&&a.addEventListener("upgradeneeded",(e=>{r($e(a.result),e.oldVersion,e.newVersion,$e(a.transaction))})),n&&a.addEventListener("blocked",(()=>n())),o.then((e=>{s&&e.addEventListener("close",(()=>s())),i&&e.addEventListener("versionchange",(()=>i()))})).catch((()=>{})),o}(Ct,xt,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(Nt)}})),At}async function Rt(e,t){const n=bt(e),r=(await Pt()).transaction(Nt,"readwrite"),i=r.objectStore(Nt),s=await i.get(n);return await i.put(t,n),await r.done,s&&s.fid===t.fid||Et(e,t.fid),t}async function Ot(e){const t=bt(e),n=(await Pt()).transaction(Nt,"readwrite");await n.objectStore(Nt).delete(t),await n.done}async function Dt(e,t){const n=bt(e),r=(await Pt()).transaction(Nt,"readwrite"),i=r.objectStore(Nt),s=await i.get(n),a=t(s);return void 0===a?await i.delete(n):await i.put(a,n),await r.done,!a||s&&s.fid===a.fid||Et(e,a.fid),a}async function Lt(e){let t;const n=await Dt(e.appConfig,(n=>{const r=function(e){const t=e||{fid:wt(),registrationStatus:0};return Ft(t)}(n),i=function(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(lt.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function(e,t){try{const n=await async function(e,t){let{appConfig:n,heartbeatServiceProvider:r}=e,{fid:i}=t;const s=ut(n),a=ft(n),o=r.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const l={fid:i,authVersion:st,appId:n.appId,sdkVersion:it},c={method:"POST",headers:a,body:JSON.stringify(l)},u=await mt((()=>fetch(s,c)));if(u.ok){const e=await u.json();return{fid:e.fid||i,registrationStatus:2,refreshToken:e.refreshToken,authToken:ht(e.authToken)}}throw await dt("Create Installation",u)}(e,t);return Rt(e.appConfig,n)}catch(n){throw ct(n)&&409===n.customData.serverCode?await Ot(e.appConfig):await Rt(e.appConfig,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:Mt(e)}:{installationEntry:t}}(e,r);return t=i.registrationPromise,i.installationEntry}));return n.fid===yt?{installationEntry:await t}:{installationEntry:n,registrationPromise:t}}async function Mt(e){let t=await jt(e.appConfig);for(;1===t.registrationStatus;)await gt(100),t=await jt(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:n}=await Lt(e);return n||t}return t}function jt(e){return Dt(e,(e=>{if(!e)throw lt.create("installation-not-found");return Ft(e)}))}function Ft(e){return 1===(t=e).registrationStatus&&t.registrationTime+rt<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t}async function Ut(e,t){let{appConfig:n,heartbeatServiceProvider:r}=e;const i=function(e,t){let{fid:n}=t;return"".concat(ut(e),"/").concat(n,"/authTokens:generate")}(n,t),s=pt(n,t),a=r.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&s.append("x-firebase-client",e)}const o={installation:{sdkVersion:it,appId:n.appId}},l={method:"POST",headers:s,body:JSON.stringify(o)},c=await mt((()=>fetch(i,l)));if(c.ok){return ht(await c.json())}throw await dt("Generate Auth Token",c)}async function Vt(e){let t,n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const r=await Dt(e.appConfig,(r=>{if(!zt(r))throw lt.create("not-registered");const i=r.authToken;if(!n&&function(e){return 2===e.requestStatus&&!function(e){const t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+ot}(e)}(i))return r;if(1===i.requestStatus)return t=async function(e,t){let n=await Bt(e.appConfig);for(;1===n.authToken.requestStatus;)await gt(100),n=await Bt(e.appConfig);const r=n.authToken;return 0===r.requestStatus?Vt(e,t):r}(e,n),r;{if(!navigator.onLine)throw lt.create("app-offline");const n=function(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(r);return t=async function(e,t){try{const n=await Ut(e,t),r=Object.assign(Object.assign({},t),{authToken:n});return await Rt(e.appConfig,r),n}catch(n){if(!ct(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await Rt(e.appConfig,n)}else await Ot(e.appConfig);throw n}}(e,n),n}}));return t?await t:r.authToken}function Bt(e){return Dt(e,(e=>{if(!zt(e))throw lt.create("not-registered");const t=e.authToken;return 1===(n=t).requestStatus&&n.requestTime+rt<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e;var n}))}function zt(e){return void 0!==e&&2===e.registrationStatus}async function qt(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=e;await async function(e){const{registrationPromise:t}=await Lt(e);t&&await t}(n);return(await Vt(n,t)).token}function Ht(e){return lt.create("missing-app-config-values",{valueName:e})}const Wt="installations",Kt=e=>{const t=e.getProvider("app").getImmediate(),n=function(e){if(!e||!e.options)throw Ht("App Configuration");if(!e.name)throw Ht("App Name");const t=["projectId","apiKey","appId"];for(const n of t)if(!e.options[n])throw Ht(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,heartbeatServiceProvider:we(t,"heartbeat"),_delete:()=>Promise.resolve()}},Gt=e=>{const t=we(e.getProvider("app").getImmediate(),Wt).getImmediate();return{getId:()=>async function(e){const t=e,{installationEntry:n,registrationPromise:r}=await Lt(t);return r?r.catch(console.error):Vt(t).catch(console.error),n.fid}(t),getToken:e=>qt(t,e)}};ye(new L(Wt,Kt,"PUBLIC")),ye(new L("installations-internal",Gt,"PRIVATE")),Ie(tt,nt),Ie(tt,nt,"esm2017");const Qt="analytics",$t="firebase_id",Yt="origin",Xt=6e4,Jt="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",Zt="https://www.googletagmanager.com/gtag/js",en=new W("@firebase/analytics"),tn=new b("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-intialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.',"no-client-id":'The "client_id" field is empty.',"invalid-gtag-resource":"Trusted Types detected an invalid gtag resource: {$gtagURL}."});function nn(e){if(!e.startsWith(Zt)){const t=tn.create("invalid-gtag-resource",{gtagURL:e});return en.warn(t.message),""}return e}function rn(e){return Promise.all(e.map((e=>e.catch((e=>e)))))}function sn(e,t){const n=function(e,t){let n;return window.trustedTypes&&(n=window.trustedTypes.createPolicy(e,t)),n}("firebase-js-sdk-policy",{createScriptURL:nn}),r=document.createElement("script"),i="".concat(Zt,"?l=").concat(e,"&id=").concat(t);r.src=n?null===n||void 0===n?void 0:n.createScriptURL(i):i,r.async=!0,document.head.appendChild(r)}function an(e,t,n,r){return async function(i){try{for(var s=arguments.length,a=new Array(s>1?s-1:0),o=1;o<s;o++)a[o-1]=arguments[o];if("event"===i){const[r,i]=a;await async function(e,t,n,r,i){try{let s=[];if(i&&i.send_to){let e=i.send_to;Array.isArray(e)||(e=[e]);const r=await rn(n);for(const n of e){const e=r.find((e=>e.measurementId===n)),i=e&&t[e.appId];if(!i){s=[];break}s.push(i)}}0===s.length&&(s=Object.values(t)),await Promise.all(s),e("event",r,i||{})}catch(s){en.error(s)}}(e,t,n,r,i)}else if("config"===i){const[i,s]=a;await async function(e,t,n,r,i,s){const a=r[i];try{if(a)await t[a];else{const e=(await rn(n)).find((e=>e.measurementId===i));e&&await t[e.appId]}}catch(o){en.error(o)}e("config",i,s)}(e,t,n,r,i,s)}else if("consent"===i){const[t]=a;e("consent","update",t)}else if("get"===i){const[t,n,r]=a;e("get",t,n,r)}else if("set"===i){const[t]=a;e("set",t)}else e(i,...a)}catch(l){en.error(l)}}}const on=30;const ln=new class{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3;this.throttleMetadata=e,this.intervalMillis=t}getThrottleMetadata(e){return this.throttleMetadata[e]}setThrottleMetadata(e,t){this.throttleMetadata[e]=t}deleteThrottleMetadata(e){delete this.throttleMetadata[e]}};function cn(e){return new Headers({Accept:"application/json","x-goog-api-key":e})}async function un(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ln,n=arguments.length>2?arguments[2]:void 0;const{appId:r,apiKey:i,measurementId:s}=e.options;if(!r)throw tn.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:r};throw tn.create("no-api-key")}const a=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()},o=new dn;return setTimeout((async()=>{o.abort()}),void 0!==n?n:Xt),hn({appId:r,apiKey:i,measurementId:s},a,o,t)}async function hn(e,t,n){let{throttleEndTimeMillis:r,backoffCount:i}=t,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:ln;var a;const{appId:o,measurementId:l}=e;try{await function(e,t){return new Promise(((n,r)=>{const i=Math.max(t-Date.now(),0),s=setTimeout(n,i);e.addEventListener((()=>{clearTimeout(s),r(tn.create("fetch-throttle",{throttleEndTimeMillis:t}))}))}))}(n,r)}catch(c){if(l)return en.warn("Timed out fetching this Firebase app's measurement ID from the server."+" Falling back to the measurement ID ".concat(l)+' provided in the "measurementId" field in the local Firebase config. ['.concat(null===c||void 0===c?void 0:c.message,"]")),{appId:o,measurementId:l};throw c}try{const t=await async function(e){var t;const{appId:n,apiKey:r}=e,i={method:"GET",headers:cn(r)},s=Jt.replace("{app-id}",n),a=await fetch(s,i);if(200!==a.status&&304!==a.status){let e="";try{const n=await a.json();(null===(t=n.error)||void 0===t?void 0:t.message)&&(e=n.error.message)}catch(o){}throw tn.create("config-fetch-failed",{httpStatus:a.status,responseMessage:e})}return a.json()}(e);return s.deleteThrottleMetadata(o),t}catch(c){const t=c;if(!function(e){if(!(e instanceof w)||!e.customData)return!1;const t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}(t)){if(s.deleteThrottleMetadata(o),l)return en.warn("Failed to fetch this Firebase app's measurement ID from the server."+" Falling back to the measurement ID ".concat(l)+' provided in the "measurementId" field in the local Firebase config. ['.concat(null===t||void 0===t?void 0:t.message,"]")),{appId:o,measurementId:l};throw c}const r=503===Number(null===(a=null===t||void 0===t?void 0:t.customData)||void 0===a?void 0:a.httpStatus)?O(i,s.intervalMillis,on):O(i,s.intervalMillis),u={throttleEndTimeMillis:Date.now()+r,backoffCount:i+1};return s.setThrottleMetadata(o,u),en.debug("Calling attemptFetch again in ".concat(r," millis")),hn(e,u,n,s)}}class dn{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}let fn,pn;function mn(e){pn=e}function gn(e){fn=e}async function vn(e,t,n,r,i,s,a){var o;const l=un(e);l.then((t=>{n[t.measurementId]=t.appId,e.options.measurementId&&t.measurementId!==e.options.measurementId&&en.warn("The measurement ID in the local Firebase config (".concat(e.options.measurementId,")")+" does not match the measurement ID fetched from the server (".concat(t.measurementId,").")+" To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.")})).catch((e=>en.error(e))),t.push(l);const c=async function(){if(!v())return en.warn(tn.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await y()}catch(e){return en.warn(tn.create("indexeddb-unavailable",{errorInfo:null===e||void 0===e?void 0:e.toString()}).message),!1}return!0}().then((e=>e?r.getId():void 0)),[u,h]=await Promise.all([l,c]);(function(e){const t=window.document.getElementsByTagName("script");for(const n of Object.values(t))if(n.src&&n.src.includes(Zt)&&n.src.includes(e))return n;return null})(s)||sn(s,u.measurementId),pn&&(i("consent","default",pn),mn(void 0)),i("js",new Date);const d=null!==(o=null===a||void 0===a?void 0:a.config)&&void 0!==o?o:{};return d[Yt]="firebase",d.update=!0,null!=h&&(d[$t]=h),i("config",u.measurementId,d),fn&&(i("set",fn),gn(void 0)),u.measurementId}class yn{constructor(e){this.app=e}_delete(){return delete wn[this.app.options.appId],Promise.resolve()}}let wn={},bn=[];const _n={};let En,Sn,kn="dataLayer",In="gtag",Tn=!1;function Cn(){const e=[];if(g()&&e.push("This is a browser extension environment."),"undefined"!==typeof navigator&&navigator.cookieEnabled||e.push("Cookies are not available."),e.length>0){const t=e.map(((e,t)=>"(".concat(t+1,") ").concat(e))).join(" "),n=tn.create("invalid-analytics-context",{errorInfo:t});en.warn(n.message)}}function xn(e,t,n){Cn();const r=e.options.appId;if(!r)throw tn.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw tn.create("no-api-key");en.warn('The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest'+" measurement ID for this Firebase app. Falling back to the measurement ID ".concat(e.options.measurementId)+' provided in the "measurementId" field in the local Firebase config.')}if(null!=wn[r])throw tn.create("already-exists",{id:r});if(!Tn){!function(e){let t=[];Array.isArray(window[e])?t=window[e]:window[e]=t}(kn);const{wrappedGtag:e,gtagCore:t}=function(e,t,n,r,i){let s=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];window[r].push(arguments)};return window[i]&&"function"===typeof window[i]&&(s=window[i]),window[i]=an(s,e,t,n),{gtagCore:s,wrappedGtag:window[i]}}(wn,bn,_n,kn,In);Sn=e,En=t,Tn=!0}wn[r]=vn(e,bn,_n,t,En,kn,n);return new yn(e)}function Nn(e,t,n,r){e=D(e),async function(e,t,n,r,i){if(i&&i.global)e("event",n,r);else{const i=await t;e("event",n,Object.assign(Object.assign({},r),{send_to:i}))}}(Sn,wn[e.app.options.appId],t,n,r).catch((e=>en.error(e)))}const An="@firebase/analytics",Pn="0.10.0";ye(new L(Qt,((e,t)=>{let{options:n}=t;return xn(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),n)}),"PUBLIC")),ye(new L("analytics-internal",(function(e){try{const t=e.getProvider(Qt).getImmediate();return{logEvent:(e,n,r)=>Nn(t,e,n,r)}}catch(t){throw tn.create("interop-component-reg-failed",{reason:t})}}),"PRIVATE")),Ie(An,Pn),Ie(An,Pn,"esm2017");function Rn(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"===typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}Object.create;Object.create;"function"===typeof SuppressedError&&SuppressedError;function On(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}const Dn=On,Ln=new b("auth","Firebase",{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}),Mn=new W("@firebase/auth");function jn(e){if(Mn.logLevel<=V.ERROR){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];Mn.error("Auth (".concat(Ee,"): ").concat(e),...n)}}function Fn(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];throw Bn(e,...n)}function Un(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return Bn(e,...n)}function Vn(e,t,n){const r=Object.assign(Object.assign({},Dn()),{[t]:n});return new b("auth","Firebase",r).create(t,{appName:e.name})}function Bn(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];if("string"!==typeof e){const t=n[0],r=[...n.slice(1)];return r[0]&&(r[0].appName=e.name),e._errorFactory.create(t,...r)}return Ln.create(e,...n)}function zn(e,t){if(!e){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i<n;i++)r[i-2]=arguments[i];throw Bn(t,...r)}}function qn(e){const t="INTERNAL ASSERTION FAILED: "+e;throw jn(t),new Error(t)}function Hn(e,t){e||qn(t)}function Wn(){var e;return"undefined"!==typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function Kn(){return"http:"===Gn()||"https:"===Gn()}function Gn(){var e;return"undefined"!==typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}class Qn{constructor(e,t){this.shortDelay=e,this.longDelay=t,Hn(t>e,"Short delay should be less than long delay!"),this.isMobile="undefined"!==typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(m())||"object"===typeof navigator&&"ReactNative"===navigator.product}get(){return"undefined"!==typeof navigator&&navigator&&"onLine"in navigator&&"boolean"===typeof navigator.onLine&&(Kn()||g()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function $n(e,t){Hn(e.emulator,"Emulator should always be set here");const{url:n}=e.emulator;return t?"".concat(n).concat(t.startsWith("/")?t.slice(1):t):n}class Yn{static initialize(e,t,n){this.fetchImpl=e,t&&(this.headersImpl=t),n&&(this.responseImpl=n)}static fetch(){return this.fetchImpl?this.fetchImpl:"undefined"!==typeof self&&"fetch"in self?self.fetch:"undefined"!==typeof globalThis&&globalThis.fetch?globalThis.fetch:"undefined"!==typeof fetch?fetch:void qn("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){return this.headersImpl?this.headersImpl:"undefined"!==typeof self&&"Headers"in self?self.Headers:"undefined"!==typeof globalThis&&globalThis.Headers?globalThis.Headers:"undefined"!==typeof Headers?Headers:void qn("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){return this.responseImpl?this.responseImpl:"undefined"!==typeof self&&"Response"in self?self.Response:"undefined"!==typeof globalThis&&globalThis.Response?globalThis.Response:"undefined"!==typeof Response?Response:void qn("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const Xn={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"},Jn=new Qn(3e4,6e4);function Zn(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function er(e,t,n,r){return tr(e,arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},(async()=>{let i={},s={};r&&("GET"===t?s=r:i={body:JSON.stringify(r)});const a=k(Object.assign({key:e.config.apiKey},s)).slice(1),o=await e._getAdditionalHeaders();return o["Content-Type"]="application/json",e.languageCode&&(o["X-Firebase-Locale"]=e.languageCode),Yn.fetch()(rr(e,e.config.apiHost,n,a),Object.assign({method:t,headers:o,referrerPolicy:"no-referrer"},i))}))}async function tr(e,t,n){e._canInitEmulator=!1;const r=Object.assign(Object.assign({},Xn),t);try{const t=new sr(e),i=await Promise.race([n(),t.promise]);t.clearNetworkTimeout();const s=await i.json();if("needConfirmation"in s)throw ar(e,"account-exists-with-different-credential",s);if(i.ok&&!("errorMessage"in s))return s;{const t=i.ok?s.errorMessage:s.error.message,[n,a]=t.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===n)throw ar(e,"credential-already-in-use",s);if("EMAIL_EXISTS"===n)throw ar(e,"email-already-in-use",s);if("USER_DISABLED"===n)throw ar(e,"user-disabled",s);const o=r[n]||n.toLowerCase().replace(/[_\s]+/g,"-");if(a)throw Vn(e,o,a);Fn(e,o)}}catch(i){if(i instanceof w)throw i;Fn(e,"network-request-failed",{message:String(i)})}}async function nr(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};const s=await er(e,t,n,r,i);return"mfaPendingCredential"in s&&Fn(e,"multi-factor-auth-required",{_serverResponse:s}),s}function rr(e,t,n,r){const i="".concat(t).concat(n,"?").concat(r);return e.config.emulator?$n(e.config,i):"".concat(e.config.apiScheme,"://").concat(i)}function ir(e){switch(e){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}class sr{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise(((e,t)=>{this.timer=setTimeout((()=>t(Un(this.auth,"network-request-failed"))),Jn.get())}))}clearNetworkTimeout(){clearTimeout(this.timer)}}function ar(e,t,n){const r={appName:e.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);const i=Un(e,t,r);return i.customData._tokenResponse=n,i}function or(e){return void 0!==e&&void 0!==e.enterprise}class lr{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],void 0===e.recaptchaKey)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||0===this.recaptchaEnforcementState.length)return null;for(const t of this.recaptchaEnforcementState)if(t.provider&&t.provider===e)return ir(t.enforcementState);return null}isProviderEnabled(e){return"ENFORCE"===this.getProviderEnforcementState(e)||"AUDIT"===this.getProviderEnforcementState(e)}}async function cr(e,t){return er(e,"GET","/v2/recaptchaConfig",Zn(e,t))}function ur(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(t){}}function hr(e){return 1e3*Number(e)}function dr(e){const[t,n,r]=e.split(".");if(void 0===t||void 0===n||void 0===r)return jn("JWT malformed, contained fewer than 3 sections"),null;try{const e=l(n);return e?JSON.parse(e):(jn("Failed to decode base64 JWT payload"),null)}catch(i){return jn("Caught error parsing JWT payload as JSON",null===i||void 0===i?void 0:i.toString()),null}}async function fr(e,t){if(arguments.length>2&&void 0!==arguments[2]&&arguments[2])return t;try{return await t}catch(n){throw n instanceof w&&function(e){let{code:t}=e;return t==="auth/".concat("user-disabled")||t==="auth/".concat("user-token-expired")}(n)&&e.auth.currentUser===e&&await e.auth.signOut(),n}}class pr{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){var t;if(e){const e=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),e}{this.errorBackoff=3e4;const e=(null!==(t=this.user.stsTokenManager.expirationTime)&&void 0!==t?t:0)-Date.now()-3e5;return Math.max(0,e)}}schedule(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!this.isRunning)return;const t=this.getInterval(e);this.timerId=setTimeout((async()=>{await this.iteration()}),t)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){return void((null===e||void 0===e?void 0:e.code)==="auth/".concat("network-request-failed")&&this.schedule(!0))}this.schedule()}}class mr{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=ur(this.lastLoginAt),this.creationTime=ur(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function gr(e){var t;const n=e.auth,r=await e.getIdToken(),i=await fr(e,async function(e,t){return er(e,"POST","/v1/accounts:lookup",t)}(n,{idToken:r}));zn(null===i||void 0===i?void 0:i.users.length,n,"internal-error");const s=i.users[0];e._notifyReloadListener(s);const a=(null===(t=s.providerUserInfo)||void 0===t?void 0:t.length)?s.providerUserInfo.map((e=>{var{providerId:t}=e,n=Rn(e,["providerId"]);return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}})):[];const o=(l=e.providerData,c=a,[...l.filter((e=>!c.some((t=>t.providerId===e.providerId)))),...c]);var l,c;const u=e.isAnonymous,h=!(e.email&&s.passwordHash)&&!(null===o||void 0===o?void 0:o.length),d=!!u&&h,f={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:o,metadata:new mr(s.createdAt,s.lastLoginAt),isAnonymous:d};Object.assign(e,f)}class vr{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){zn(e.idToken,"internal-error"),zn("undefined"!==typeof e.idToken,"internal-error"),zn("undefined"!==typeof e.refreshToken,"internal-error");const t="expiresIn"in e&&"undefined"!==typeof e.expiresIn?Number(e.expiresIn):function(e){const t=dr(e);return zn(t,"internal-error"),zn("undefined"!==typeof t.exp,"internal-error"),zn("undefined"!==typeof t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}async getToken(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return zn(!this.accessToken||this.refreshToken,e,"user-token-expired"),t||!this.accessToken||this.isExpired?this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null:this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){const{accessToken:n,refreshToken:r,expiresIn:i}=await async function(e,t){const n=await tr(e,{},(async()=>{const n=k({grant_type:"refresh_token",refresh_token:t}).slice(1),{tokenApiHost:r,apiKey:i}=e.config,s=rr(e,r,"/v1/token","key=".concat(i)),a=await e._getAdditionalHeaders();return a["Content-Type"]="application/x-www-form-urlencoded",Yn.fetch()(s,{method:"POST",headers:a,body:n})}));return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}(e,t);this.updateTokensAndExpiration(n,r,Number(i))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(e,t){const{refreshToken:n,accessToken:r,expirationTime:i}=t,s=new vr;return n&&(zn("string"===typeof n,"internal-error",{appName:e}),s.refreshToken=n),r&&(zn("string"===typeof r,"internal-error",{appName:e}),s.accessToken=r),i&&(zn("number"===typeof i,"internal-error",{appName:e}),s.expirationTime=i),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new vr,this.toJSON())}_performRefresh(){return qn("not implemented")}}function yr(e,t){zn("string"===typeof e||"undefined"===typeof e,"internal-error",{appName:t})}class wr{constructor(e){var{uid:t,auth:n,stsTokenManager:r}=e,i=Rn(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new pr(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[...i.providerData]:[],this.metadata=new mr(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){const t=await fr(this,this.stsTokenManager.getToken(this.auth,e));return zn(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return async function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=D(e),r=await n.getIdToken(t),i=dr(r);zn(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");const s="object"===typeof i.firebase?i.firebase:void 0,a=null===s||void 0===s?void 0:s.sign_in_provider;return{claims:i,token:r,authTime:ur(hr(i.auth_time)),issuedAtTime:ur(hr(i.iat)),expirationTime:ur(hr(i.exp)),signInProvider:a||null,signInSecondFactor:(null===s||void 0===s?void 0:s.sign_in_second_factor)||null}}(this,e)}reload(){return async function(e){const t=D(e);await gr(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}(this)}_assign(e){this!==e&&(zn(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map((e=>Object.assign({},e))),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){const t=new wr(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}));return t.metadata._copy(this.metadata),t}_onReload(e){zn(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),n=!0),t&&await gr(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){const e=await this.getIdToken();return await fr(this,async function(e,t){return er(e,"POST","/v1/accounts:delete",t)}(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return Object.assign(Object.assign({uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map((e=>Object.assign({},e))),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId},this.metadata.toJSON()),{apiKey:this.auth.config.apiKey,appName:this.auth.name})}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){var n,r,i,s,a,o,l,c;const u=null!==(n=t.displayName)&&void 0!==n?n:void 0,h=null!==(r=t.email)&&void 0!==r?r:void 0,d=null!==(i=t.phoneNumber)&&void 0!==i?i:void 0,f=null!==(s=t.photoURL)&&void 0!==s?s:void 0,p=null!==(a=t.tenantId)&&void 0!==a?a:void 0,m=null!==(o=t._redirectEventId)&&void 0!==o?o:void 0,g=null!==(l=t.createdAt)&&void 0!==l?l:void 0,v=null!==(c=t.lastLoginAt)&&void 0!==c?c:void 0,{uid:y,emailVerified:w,isAnonymous:b,providerData:_,stsTokenManager:E}=t;zn(y&&E,e,"internal-error");const S=vr.fromJSON(this.name,E);zn("string"===typeof y,e,"internal-error"),yr(u,e.name),yr(h,e.name),zn("boolean"===typeof w,e,"internal-error"),zn("boolean"===typeof b,e,"internal-error"),yr(d,e.name),yr(f,e.name),yr(p,e.name),yr(m,e.name),yr(g,e.name),yr(v,e.name);const k=new wr({uid:y,auth:e,email:h,emailVerified:w,displayName:u,isAnonymous:b,photoURL:f,phoneNumber:d,tenantId:p,stsTokenManager:S,createdAt:g,lastLoginAt:v});return _&&Array.isArray(_)&&(k.providerData=_.map((e=>Object.assign({},e)))),m&&(k._redirectEventId=m),k}static async _fromIdTokenResponse(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const r=new vr;r.updateFromServerResponse(t);const i=new wr({uid:t.localId,auth:e,stsTokenManager:r,isAnonymous:n});return await gr(i),i}}const br=new Map;function _r(e){Hn(e instanceof Function,"Expected a class definition");let t=br.get(e);return t?(Hn(t instanceof e,"Instance stored in cache mismatched with class"),t):(t=new e,br.set(e,t),t)}class Er{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){const t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}Er.type="NONE";const Sr=Er;function kr(e,t,n){return"firebase".concat(":",e,":").concat(t,":").concat(n)}class Ir{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;const{config:r,name:i}=this.auth;this.fullUserKey=kr(this.userKey,r.apiKey,i),this.fullPersistenceKey=kr("persistence",r.apiKey,i),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){const e=await this.persistence._get(this.fullUserKey);return e?wr._fromJSON(this.auth,e):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;const t=await this.getCurrentUser();return await this.removeCurrentUser(),this.persistence=e,t?this.setCurrentUser(t):void 0}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"authUser";if(!t.length)return new Ir(_r(Sr),e,n);const r=(await Promise.all(t.map((async e=>{if(await e._isAvailable())return e})))).filter((e=>e));let i=r[0]||_r(Sr);const s=kr(n,e.config.apiKey,e.name);let a=null;for(const c of t)try{const t=await c._get(s);if(t){const n=wr._fromJSON(e,t);c!==i&&(a=n),i=c;break}}catch(l){}const o=r.filter((e=>e._shouldAllowMigration));return i._shouldAllowMigration&&o.length?(i=o[0],a&&await i._set(s,a.toJSON()),await Promise.all(t.map((async e=>{if(e!==i)try{await e._remove(s)}catch(l){}}))),new Ir(i,e,n)):new Ir(i,e,n)}}function Tr(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(Ar(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(Cr(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(Rr(t))return"Blackberry";if(Or(t))return"Webos";if(xr(t))return"Safari";if((t.includes("chrome/")||Nr(t))&&!t.includes("edge/"))return"Chrome";if(Pr(t))return"Android";{const t=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,n=e.match(t);if(2===(null===n||void 0===n?void 0:n.length))return n[1]}return"Other"}function Cr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m();return/firefox\//i.test(e)}function xr(){const e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:m()).toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function Nr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m();return/crios\//i.test(e)}function Ar(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m();return/iemobile/i.test(e)}function Pr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m();return/android/i.test(e)}function Rr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m();return/blackberry/i.test(e)}function Or(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m();return/webos/i.test(e)}function Dr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m();return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function Lr(){return function(){const e=m();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0}()&&10===document.documentMode}function Mr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m();return Dr(e)||Pr(e)||Or(e)||Rr(e)||/windows phone/i.test(e)||Ar(e)}function jr(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];switch(e){case"Browser":t=Tr(m());break;case"Worker":t="".concat(Tr(m()),"-").concat(e);break;default:t=e}const r=n.length?n.join(","):"FirebaseCore-web";return"".concat(t,"/","JsCore","/").concat(Ee,"/").concat(r)}class Fr{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){const n=t=>new Promise(((n,r)=>{try{n(e(t))}catch(i){r(i)}}));n.onAbort=t,this.queue.push(n);const r=this.queue.length-1;return()=>{this.queue[r]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;const t=[];try{for(const n of this.queue)await n(e),n.onAbort&&t.push(n.onAbort)}catch(n){t.reverse();for(const e of t)try{e()}catch(r){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:null===n||void 0===n?void 0:n.message})}}}class Ur{constructor(e){var t,n,r,i;const s=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=null!==(t=s.minPasswordLength)&&void 0!==t?t:6,s.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=s.maxPasswordLength),void 0!==s.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=s.containsLowercaseCharacter),void 0!==s.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=s.containsUppercaseCharacter),void 0!==s.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=s.containsNumericCharacter),void 0!==s.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=s.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=null!==(r=null===(n=e.allowedNonAlphanumericCharacters)||void 0===n?void 0:n.join(""))&&void 0!==r?r:"",this.forceUpgradeOnSignin=null!==(i=e.forceUpgradeOnSignin)&&void 0!==i&&i,this.schemaVersion=e.schemaVersion}validatePassword(e){var t,n,r,i,s,a;const o={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,o),this.validatePasswordCharacterOptions(e,o),o.isValid&&(o.isValid=null===(t=o.meetsMinPasswordLength)||void 0===t||t),o.isValid&&(o.isValid=null===(n=o.meetsMaxPasswordLength)||void 0===n||n),o.isValid&&(o.isValid=null===(r=o.containsLowercaseLetter)||void 0===r||r),o.isValid&&(o.isValid=null===(i=o.containsUppercaseLetter)||void 0===i||i),o.isValid&&(o.isValid=null===(s=o.containsNumericCharacter)||void 0===s||s),o.isValid&&(o.isValid=null===(a=o.containsNonAlphanumericCharacter)||void 0===a||a),o}validatePasswordLengthOptions(e,t){const n=this.customStrengthOptions.minPasswordLength,r=this.customStrengthOptions.maxPasswordLength;n&&(t.meetsMinPasswordLength=e.length>=n),r&&(t.meetsMaxPasswordLength=e.length<=r)}validatePasswordCharacterOptions(e,t){let n;this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);for(let r=0;r<e.length;r++)n=e.charAt(r),this.updatePasswordCharacterOptionsStatuses(t,n>="a"&&n<="z",n>="A"&&n<="Z",n>="0"&&n<="9",this.allowedNonAlphanumericCharacters.includes(n))}updatePasswordCharacterOptionsStatuses(e,t,n,r,i){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=n)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=r)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=i))}}class Vr{constructor(e,t,n,r){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=n,this.config=r,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new zr(this),this.idTokenSubscription=new zr(this),this.beforeStateQueue=new Fr(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=Ln,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=r.sdkClientVersion}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=_r(t)),this._initializationPromise=this.queue((async()=>{var n,r;if(!this._deleted&&(this.persistenceManager=await Ir.create(this,e),!this._deleted)){if(null===(n=this._popupRedirectResolver)||void 0===n?void 0:n._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(i){}await this.initializeCurrentUser(t),this.lastNotifiedUid=(null===(r=this.currentUser)||void 0===r?void 0:r.uid)||null,this._deleted||(this._isInitialized=!0)}})),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();return this.currentUser||e?this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(e,!0):void 0}async initializeCurrentUser(e){var t;const n=await this.assertedPersistence.getCurrentUser();let r=n,i=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const n=null===(t=this.redirectUser)||void 0===t?void 0:t._redirectEventId,s=null===r||void 0===r?void 0:r._redirectEventId,a=await this.tryRedirectSignIn(e);n&&n!==s||!(null===a||void 0===a?void 0:a.user)||(r=a.user,i=!0)}if(!r)return this.directlySetCurrentUser(null);if(!r._redirectEventId){if(i)try{await this.beforeStateQueue.runMiddleware(r)}catch(s){r=n,this._popupRedirectResolver._overrideRedirectResult(this,(()=>Promise.reject(s)))}return r?this.reloadAndSetCurrentUserOrClear(r):this.directlySetCurrentUser(null)}return zn(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===r._redirectEventId?this.directlySetCurrentUser(r):this.reloadAndSetCurrentUserOrClear(r)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(n){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await gr(e)}catch(t){if((null===t||void 0===t?void 0:t.code)!=="auth/".concat("network-request-failed"))return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function(){if("undefined"===typeof navigator)return null;const e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(e){const t=e?D(e):null;return t&&zn(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!this._deleted)return e&&zn(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),t||await this.beforeStateQueue.runMiddleware(e),this.queue((async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()}))}async signOut(){return await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0)}setPersistence(e){return this.queue((async()=>{await this.assertedPersistence.setPersistence(_r(e))}))}_getRecaptchaConfig(){return null==this.tenantId?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();const t=this._getPasswordPolicyInternal();return t.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):t.validatePassword(e)}_getPasswordPolicyInternal(){return null===this.tenantId?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){const e=await async function(e){return er(e,"GET","/v2/passwordPolicy",Zn(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}))}(this),t=new Ur(e);null===this.tenantId?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new b("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}authStateReady(){return new Promise(((e,t)=>{if(this.currentUser)e();else{const n=this.onAuthStateChanged((()=>{n(),e()}),t)}}))}async revokeAccessToken(e){if(this.currentUser){const t={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:await this.currentUser.getIdToken()};null!=this.tenantId&&(t.tenantId=this.tenantId),await async function(e,t){return er(e,"POST","/v2/accounts:revokeToken",Zn(e,t))}(this,t)}}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?void 0:e.toJSON()}}async _setRedirectUser(e,t){const n=await this.getOrInitRedirectPersistenceManager(t);return null===e?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&_r(e)||this._popupRedirectResolver;zn(t,this,"argument-error"),this.redirectPersistenceManager=await Ir.create(this,[_r(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){var t,n;return this._isInitialized&&await this.queue((async()=>{})),(null===(t=this._currentUser)||void 0===t?void 0:t._redirectEventId)===e?this._currentUser:(null===(n=this.redirectUser)||void 0===n?void 0:n._redirectEventId)===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue((async()=>this.directlySetCurrentUser(e)))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return"".concat(this.config.authDomain,":").concat(this.config.apiKey,":").concat(this.name)}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){var e,t;if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const n=null!==(t=null===(e=this.currentUser)||void 0===e?void 0:e.uid)&&void 0!==t?t:null;this.lastNotifiedUid!==n&&(this.lastNotifiedUid=n,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,n,r){if(this._deleted)return()=>{};const i="function"===typeof t?t:t.next.bind(t);let s=!1;const a=this._isInitialized?Promise.resolve():this._initializationPromise;if(zn(a,this,"internal-error"),a.then((()=>{s||i(this.currentUser)})),"function"===typeof t){const i=e.addObserver(t,n,r);return()=>{s=!0,i()}}{const n=e.addObserver(t);return()=>{s=!0,n()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return zn(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=jr(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var e;const t={"X-Client-Version":this.clientVersion};this.app.options.appId&&(t["X-Firebase-gmpid"]=this.app.options.appId);const n=await(null===(e=this.heartbeatServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getHeartbeatsHeader());n&&(t["X-Firebase-Client"]=n);const r=await this._getAppCheckToken();return r&&(t["X-Firebase-AppCheck"]=r),t}async _getAppCheckToken(){var e;const t=await(null===(e=this.appCheckServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getToken());return(null===t||void 0===t?void 0:t.error)&&function(e){if(Mn.logLevel<=V.WARN){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];Mn.warn("Auth (".concat(Ee,"): ").concat(e),...n)}}("Error while retrieving App Check token: ".concat(t.error)),null===t||void 0===t?void 0:t.token}}function Br(e){return D(e)}class zr{constructor(e){this.auth=e,this.observer=null,this.addObserver=function(e,t){const n=new C(e,t);return n.subscribe.bind(n)}((e=>this.observer=e))}get next(){return zn(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}function qr(e){return new Promise(((t,n)=>{const r=document.createElement("script");r.setAttribute("src",e),r.onload=t,r.onerror=e=>{const t=Un("internal-error");t.customData=e,n(t)},r.type="text/javascript",r.charset="UTF-8",function(){var e,t;return null!==(t=null===(e=document.getElementsByTagName("head"))||void 0===e?void 0:e[0])&&void 0!==t?t:document}().appendChild(r)}))}function Hr(e){return"__".concat(e).concat(Math.floor(1e6*Math.random()))}class Wr{constructor(e){this.type="recaptcha-enterprise",this.auth=Br(e)}async verify(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"verify",t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];function n(t,n,r){const i=window.grecaptcha;or(i)?i.enterprise.ready((()=>{i.enterprise.execute(t,{action:e}).then((e=>{n(e)})).catch((()=>{n("NO_RECAPTCHA")}))})):r(Error("No reCAPTCHA enterprise script loaded."))}return new Promise(((e,r)=>{(async function(e){if(!t){if(null==e.tenantId&&null!=e._agentRecaptchaConfig)return e._agentRecaptchaConfig.siteKey;if(null!=e.tenantId&&void 0!==e._tenantRecaptchaConfigs[e.tenantId])return e._tenantRecaptchaConfigs[e.tenantId].siteKey}return new Promise((async(t,n)=>{cr(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then((r=>{if(void 0!==r.recaptchaKey){const n=new lr(r);return null==e.tenantId?e._agentRecaptchaConfig=n:e._tenantRecaptchaConfigs[e.tenantId]=n,t(n.siteKey)}n(new Error("recaptcha Enterprise site key undefined"))})).catch((e=>{n(e)}))}))})(this.auth).then((i=>{if(!t&&or(window.grecaptcha))n(i,e,r);else{if("undefined"===typeof window)return void r(new Error("RecaptchaVerifier is only supported in browser"));qr("https://www.google.com/recaptcha/enterprise.js?render="+i).then((()=>{n(i,e,r)})).catch((e=>{r(e)}))}})).catch((e=>{r(e)}))}))}}async function Kr(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const i=new Wr(e);let s;try{s=await i.verify(n)}catch(o){s=await i.verify(n,!0)}const a=Object.assign({},t);return r?Object.assign(a,{captchaResp:s}):Object.assign(a,{captchaResponse:s}),Object.assign(a,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(a,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),a}async function Gr(e,t,n,r){var i;if(null===(i=e._getRecaptchaConfig())||void 0===i?void 0:i.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){const i=await Kr(e,t,n,"getOobCode"===n);return r(e,i)}return r(e,t).catch((async i=>{if(i.code==="auth/".concat("missing-recaptcha-token")){console.log("".concat(n," is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow."));const i=await Kr(e,t,n,"getOobCode"===n);return r(e,i)}return Promise.reject(i)}))}function Qr(e,t,n){const r=Br(e);zn(r._canInitEmulator,r,"emulator-config-failed"),zn(/^https?:\/\//.test(t),r,"invalid-emulator-scheme");const i=!!(null===n||void 0===n?void 0:n.disableWarnings),s=$r(t),{host:a,port:o}=function(e){const t=$r(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:"",port:null};const r=n[2].split("@").pop()||"",i=/^(\[[^\]]+\])(:|$)/.exec(r);if(i){const e=i[1];return{host:e,port:Yr(r.substr(e.length+1))}}{const[e,t]=r.split(":");return{host:e,port:Yr(t)}}}(t),l=null===o?"":":".concat(o);r.config.emulator={url:"".concat(s,"//").concat(a).concat(l,"/")},r.settings.appVerificationDisabledForTesting=!0,r.emulatorConfig=Object.freeze({host:a,port:o,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})}),i||function(){function e(){const e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}"undefined"!==typeof console&&"function"===typeof console.info&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials.");"undefined"!==typeof window&&"undefined"!==typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",e):e())}()}function $r(e){const t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function Yr(e){if(!e)return null;const t=Number(e);return isNaN(t)?null:t}class Xr{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return qn("not implemented")}_getIdTokenResponse(e){return qn("not implemented")}_linkToIdToken(e,t){return qn("not implemented")}_getReauthenticationResolver(e){return qn("not implemented")}}async function Jr(e,t){return er(e,"POST","/v1/accounts:signUp",t)}async function Zr(e,t){return nr(e,"POST","/v1/accounts:signInWithPassword",Zn(e,t))}class ei extends Xr{constructor(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;super("password",n),this._email=e,this._password=t,this._tenantId=r}static _fromEmailAndPassword(e,t){return new ei(e,t,"password")}static _fromEmailAndCode(e,t){return new ei(e,t,"emailLink",arguments.length>2&&void 0!==arguments[2]?arguments[2]:null)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){const t="string"===typeof e?JSON.parse(e):e;if((null===t||void 0===t?void 0:t.email)&&(null===t||void 0===t?void 0:t.password)){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return Gr(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",Zr);case"emailLink":return async function(e,t){return nr(e,"POST","/v1/accounts:signInWithEmailLink",Zn(e,t))}(e,{email:this._email,oobCode:this._password});default:Fn(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return Gr(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",Jr);case"emailLink":return async function(e,t){return nr(e,"POST","/v1/accounts:signInWithEmailLink",Zn(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:Fn(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function ti(e,t){return nr(e,"POST","/v1/accounts:signInWithIdp",Zn(e,t))}class ni extends Xr{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new ni(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):Fn("argument-error"),t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){const t="string"===typeof e?JSON.parse(e):e,{providerId:n,signInMethod:r}=t,i=Rn(t,["providerId","signInMethod"]);if(!n||!r)return null;const s=new ni(n,r);return s.idToken=i.idToken||void 0,s.accessToken=i.accessToken||void 0,s.secret=i.secret,s.nonce=i.nonce,s.pendingToken=i.pendingToken||null,s}_getIdTokenResponse(e){return ti(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,ti(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,ti(e,t)}buildRequest(){const e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=k(t)}return e}}const ri={USER_NOT_FOUND:"user-not-found"};class ii extends Xr{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new ii({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new ii({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function(e,t){return nr(e,"POST","/v1/accounts:signInWithPhoneNumber",Zn(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){const n=await nr(e,"POST","/v1/accounts:signInWithPhoneNumber",Zn(e,t));if(n.temporaryProof)throw ar(e,"account-exists-with-different-credential",n);return n}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function(e,t){return nr(e,"POST","/v1/accounts:signInWithPhoneNumber",Zn(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),ri)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:r}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:r}}toJSON(){const e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){"string"===typeof e&&(e=JSON.parse(e));const{verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}=e;return n||t||r||i?new ii({verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}):null}}class si{constructor(e){var t,n,r,i,s,a;const o=I(T(e)),l=null!==(t=o.apiKey)&&void 0!==t?t:null,c=null!==(n=o.oobCode)&&void 0!==n?n:null,u=function(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(null!==(r=o.mode)&&void 0!==r?r:null);zn(l&&c&&u,"argument-error"),this.apiKey=l,this.operation=u,this.code=c,this.continueUrl=null!==(i=o.continueUrl)&&void 0!==i?i:null,this.languageCode=null!==(s=o.languageCode)&&void 0!==s?s:null,this.tenantId=null!==(a=o.tenantId)&&void 0!==a?a:null}static parseLink(e){const t=function(e){const t=I(T(e)).link,n=t?I(T(t)).deep_link_id:null,r=I(T(e)).deep_link_id;return(r?I(T(r)).link:null)||r||n||t||e}(e);try{return new si(t)}catch(n){return null}}}class ai{constructor(){this.providerId=ai.PROVIDER_ID}static credential(e,t){return ei._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const n=si.parseLink(t);return zn(n,"argument-error"),ei._fromEmailAndCode(e,n.code,n.tenantId)}}ai.PROVIDER_ID="password",ai.EMAIL_PASSWORD_SIGN_IN_METHOD="password",ai.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class oi{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}}class li extends oi{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class ci extends li{constructor(){super("facebook.com")}static credential(e){return ni._fromParams({providerId:ci.PROVIDER_ID,signInMethod:ci.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return ci.credentialFromTaggedObject(e)}static credentialFromError(e){return ci.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject(e){let{_tokenResponse:t}=e;if(!t||!("oauthAccessToken"in t))return null;if(!t.oauthAccessToken)return null;try{return ci.credential(t.oauthAccessToken)}catch(n){return null}}}ci.FACEBOOK_SIGN_IN_METHOD="facebook.com",ci.PROVIDER_ID="facebook.com";class ui extends li{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return ni._fromParams({providerId:ui.PROVIDER_ID,signInMethod:ui.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return ui.credentialFromTaggedObject(e)}static credentialFromError(e){return ui.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject(e){let{_tokenResponse:t}=e;if(!t)return null;const{oauthIdToken:n,oauthAccessToken:r}=t;if(!n&&!r)return null;try{return ui.credential(n,r)}catch(i){return null}}}ui.GOOGLE_SIGN_IN_METHOD="google.com",ui.PROVIDER_ID="google.com";class hi extends li{constructor(){super("github.com")}static credential(e){return ni._fromParams({providerId:hi.PROVIDER_ID,signInMethod:hi.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return hi.credentialFromTaggedObject(e)}static credentialFromError(e){return hi.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject(e){let{_tokenResponse:t}=e;if(!t||!("oauthAccessToken"in t))return null;if(!t.oauthAccessToken)return null;try{return hi.credential(t.oauthAccessToken)}catch(n){return null}}}hi.GITHUB_SIGN_IN_METHOD="github.com",hi.PROVIDER_ID="github.com";class di extends li{constructor(){super("twitter.com")}static credential(e,t){return ni._fromParams({providerId:di.PROVIDER_ID,signInMethod:di.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return di.credentialFromTaggedObject(e)}static credentialFromError(e){return di.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject(e){let{_tokenResponse:t}=e;if(!t)return null;const{oauthAccessToken:n,oauthTokenSecret:r}=t;if(!n||!r)return null;try{return di.credential(n,r)}catch(i){return null}}}async function fi(e,t){return nr(e,"POST","/v1/accounts:signUp",Zn(e,t))}di.TWITTER_SIGN_IN_METHOD="twitter.com",di.PROVIDER_ID="twitter.com";class pi{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const i=await wr._fromIdTokenResponse(e,n,r),s=mi(n);return new pi({user:i,providerId:s,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);const r=mi(n);return new pi({user:e,providerId:r,_tokenResponse:n,operationType:t})}}function mi(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}class gi extends w{constructor(e,t,n,r){var i;super(t.code,t.message),this.operationType=n,this.user=r,Object.setPrototypeOf(this,gi.prototype),this.customData={appName:e.name,tenantId:null!==(i=e.tenantId)&&void 0!==i?i:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,r){return new gi(e,t,n,r)}}function vi(e,t,n,r){return("reauthenticate"===t?n._getReauthenticationResolver(e):n._getIdTokenResponse(e)).catch((n=>{if(n.code==="auth/".concat("multi-factor-auth-required"))throw gi._fromErrorAndOperation(e,n,t,r);throw n}))}async function yi(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const r=await fr(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return pi._forOperation(e,"link",r)}async function wi(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const{auth:r}=e,i="reauthenticate";try{const s=await fr(e,vi(r,i,t,e),n);zn(s.idToken,r,"internal-error");const a=dr(s.idToken);zn(a,r,"internal-error");const{sub:o}=a;return zn(e.uid===o,r,"user-mismatch"),pi._forOperation(e,i,s)}catch(s){throw(null===s||void 0===s?void 0:s.code)==="auth/".concat("user-not-found")&&Fn(r,"user-mismatch"),s}}async function bi(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const r="signIn",i=await vi(e,r,t),s=await pi._fromIdTokenResponse(e,r,i);return n||await e._updateCurrentUser(s.user),s}async function _i(e){const t=Br(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}new WeakMap;const Ei="__sak";class Si{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(Ei,"1"),this.storage.removeItem(Ei),Promise.resolve(!0)):Promise.resolve(!1)}catch(e){return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){const t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}class ki extends Si{constructor(){super((()=>window.localStorage),"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=function(){const e=m();return xr(e)||Dr(e)}()&&function(){try{return!(!window||window===window.top)}catch(e){return!1}}(),this.fallbackToPolling=Mr(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const n=this.storage.getItem(t),r=this.localCache[t];n!==r&&e(t,r,n)}}onStorageEvent(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!e.key)return void this.forAllChangedKeys(((e,t,n)=>{this.notifyListeners(e,n)}));const n=e.key;if(t?this.detachListener():this.stopPolling(),this.safariLocalStorageNotSynced){const r=this.storage.getItem(n);if(e.newValue!==r)null!==e.newValue?this.storage.setItem(n,e.newValue):this.storage.removeItem(n);else if(this.localCache[n]===e.newValue&&!t)return}const r=()=>{const e=this.storage.getItem(n);(t||this.localCache[n]!==e)&&this.notifyListeners(n,e)},i=this.storage.getItem(n);Lr()&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(r,10):r()}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n)for(const r of Array.from(n))r(t?JSON.parse(t):t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((()=>{this.forAllChangedKeys(((e,t,n)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:n}),!0)}))}),1e3)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){const t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}ki.type="LOCAL";const Ii=ki;class Ti extends Si{constructor(){super((()=>window.sessionStorage),"SESSION")}_addListener(e,t){}_removeListener(e,t){}}Ti.type="SESSION";const Ci=Ti;class xi{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const t=this.receivers.find((t=>t.isListeningto(e)));if(t)return t;const n=new xi(e);return this.receivers.push(n),n}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:n,eventType:r,data:i}=t.data,s=this.handlersMap[r];if(!(null===s||void 0===s?void 0:s.size))return;t.ports[0].postMessage({status:"ack",eventId:n,eventType:r});const a=Array.from(s).map((async e=>e(t.origin,i))),o=await function(e){return Promise.all(e.map((async e=>{try{return{fulfilled:!0,value:await e}}catch(t){return{fulfilled:!1,reason:t}}})))}(a);t.ports[0].postMessage({status:"done",eventId:n,eventType:r,response:o})}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function Ni(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10,n="";for(let r=0;r<t;r++)n+=Math.floor(10*Math.random());return e+n}xi.receivers=[];class Ai{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:50;const r="undefined"!==typeof MessageChannel?new MessageChannel:null;if(!r)throw new Error("connection_unavailable");let i,s;return new Promise(((a,o)=>{const l=Ni("",20);r.port1.start();const c=setTimeout((()=>{o(new Error("unsupported_event"))}),n);s={messageChannel:r,onMessage(e){const t=e;if(t.data.eventId===l)switch(t.data.status){case"ack":clearTimeout(c),i=setTimeout((()=>{o(new Error("timeout"))}),3e3);break;case"done":clearTimeout(i),a(t.data.response);break;default:clearTimeout(c),clearTimeout(i),o(new Error("invalid_response"))}}},this.handlers.add(s),r.port1.addEventListener("message",s.onMessage),this.target.postMessage({eventType:e,eventId:l,data:t},[r.port2])})).finally((()=>{s&&this.removeMessageHandler(s)}))}}function Pi(){return window}function Ri(){return"undefined"!==typeof Pi().WorkerGlobalScope&&"function"===typeof Pi().importScripts}const Oi="firebaseLocalStorageDb",Di="firebaseLocalStorage",Li="fbase_key";class Mi{constructor(e){this.request=e}toPromise(){return new Promise(((e,t)=>{this.request.addEventListener("success",(()=>{e(this.request.result)})),this.request.addEventListener("error",(()=>{t(this.request.error)}))}))}}function ji(e,t){return e.transaction([Di],t?"readwrite":"readonly").objectStore(Di)}function Fi(){const e=indexedDB.open(Oi,1);return new Promise(((t,n)=>{e.addEventListener("error",(()=>{n(e.error)})),e.addEventListener("upgradeneeded",(()=>{const t=e.result;try{t.createObjectStore(Di,{keyPath:Li})}catch(r){n(r)}})),e.addEventListener("success",(async()=>{const n=e.result;n.objectStoreNames.contains(Di)?t(n):(n.close(),await function(){const e=indexedDB.deleteDatabase(Oi);return new Mi(e).toPromise()}(),t(await Fi()))}))}))}async function Ui(e,t,n){const r=ji(e,!0).put({[Li]:t,value:n});return new Mi(r).toPromise()}function Vi(e,t){const n=ji(e,!0).delete(t);return new Mi(n).toPromise()}class Bi{constructor(){this.type="LOCAL",this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then((()=>{}),(()=>{}))}async _openDb(){return this.db||(this.db=await Fi()),this.db}async _withRetries(e){let t=0;for(;;)try{const t=await this._openDb();return await e(t)}catch(n){if(t++>3)throw n;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return Ri()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=xi._getInstance(Ri()?self:null),this.receiver._subscribe("keyChanged",(async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)}))),this.receiver._subscribe("ping",(async(e,t)=>["keyChanged"]))}async initializeSender(){var e,t;if(this.activeServiceWorker=await async function(){if(!(null===navigator||void 0===navigator?void 0:navigator.serviceWorker))return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}}(),!this.activeServiceWorker)return;this.sender=new Ai(this.activeServiceWorker);const n=await this.sender._send("ping",{},800);n&&(null===(e=n[0])||void 0===e?void 0:e.fulfilled)&&(null===(t=n[0])||void 0===t?void 0:t.value.includes("keyChanged"))&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(this.sender&&this.activeServiceWorker&&function(){var e;return(null===(e=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===e?void 0:e.controller)||null}()===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(t){}}async _isAvailable(){try{if(!indexedDB)return!1;const e=await Fi();return await Ui(e,Ei,"1"),await Vi(e,Ei),!0}catch(e){}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite((async()=>(await this._withRetries((n=>Ui(n,e,t))),this.localCache[e]=t,this.notifyServiceWorker(e))))}async _get(e){const t=await this._withRetries((t=>async function(e,t){const n=ji(e,!1).get(t),r=await new Mi(n).toPromise();return void 0===r?null:r.value}(t,e)));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite((async()=>(await this._withRetries((t=>Vi(t,e))),delete this.localCache[e],this.notifyServiceWorker(e))))}async _poll(){const e=await this._withRetries((e=>{const t=ji(e,!1).getAll();return new Mi(t).toPromise()}));if(!e)return[];if(0!==this.pendingWrites)return[];const t=[],n=new Set;for(const{fbase_key:r,value:i}of e)n.add(r),JSON.stringify(this.localCache[r])!==JSON.stringify(i)&&(this.notifyListeners(r,i),t.push(r));for(const r of Object.keys(this.localCache))this.localCache[r]&&!n.has(r)&&(this.notifyListeners(r,null),t.push(r));return t}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n)for(const r of Array.from(n))r(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((async()=>this._poll()),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&this.stopPolling()}}Bi.type="LOCAL";const zi=Bi;Hr("rcb"),new Qn(3e4,6e4);const qi="recaptcha";async function Hi(e,t,n){var r;const i=await n.verify();try{let s;if(zn("string"===typeof i,e,"argument-error"),zn(n.type===qi,e,"argument-error"),s="string"===typeof t?{phoneNumber:t}:t,"session"in s){const t=s.session;if("phoneNumber"in s){zn("enroll"===t.type,e,"internal-error");const n=await function(e,t){return er(e,"POST","/v2/accounts/mfaEnrollment:start",Zn(e,t))}(e,{idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:s.phoneNumber,recaptchaToken:i}});return n.phoneSessionInfo.sessionInfo}{zn("signin"===t.type,e,"internal-error");const n=(null===(r=s.multiFactorHint)||void 0===r?void 0:r.uid)||s.multiFactorUid;zn(n,e,"missing-multi-factor-info");const a=await function(e,t){return er(e,"POST","/v2/accounts/mfaSignIn:start",Zn(e,t))}(e,{mfaPendingCredential:t.credential,mfaEnrollmentId:n,phoneSignInInfo:{recaptchaToken:i}});return a.phoneResponseInfo.sessionInfo}}{const{sessionInfo:t}=await async function(e,t){return er(e,"POST","/v1/accounts:sendVerificationCode",Zn(e,t))}(e,{phoneNumber:s.phoneNumber,recaptchaToken:i});return t}}finally{n._reset()}}class Wi{constructor(e){this.providerId=Wi.PROVIDER_ID,this.auth=Br(e)}verifyPhoneNumber(e,t){return Hi(this.auth,e,D(t))}static credential(e,t){return ii._fromVerification(e,t)}static credentialFromResult(e){const t=e;return Wi.credentialFromTaggedObject(t)}static credentialFromError(e){return Wi.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject(e){let{_tokenResponse:t}=e;if(!t)return null;const{phoneNumber:n,temporaryProof:r}=t;return n&&r?ii._fromTokenResponse(n,r):null}}function Ki(e,t){return t?_r(t):(zn(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}Wi.PROVIDER_ID="phone",Wi.PHONE_SIGN_IN_METHOD="phone";class Gi extends Xr{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return ti(e,this._buildIdpRequest())}_linkToIdToken(e,t){return ti(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return ti(e,this._buildIdpRequest())}_buildIdpRequest(e){const t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function Qi(e){return bi(e.auth,new Gi(e),e.bypassAuthState)}function $i(e){const{auth:t,user:n}=e;return zn(n,t,"internal-error"),wi(n,new Gi(e),e.bypassAuthState)}async function Yi(e){const{auth:t,user:n}=e;return zn(n,t,"internal-error"),yi(n,new Gi(e),e.bypassAuthState)}class Xi{constructor(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]&&arguments[4];this.auth=e,this.resolver=n,this.user=r,this.bypassAuthState=i,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise((async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(n){this.reject(n)}}))}async onAuthEvent(e){const{urlResponse:t,sessionId:n,postBody:r,tenantId:i,error:s,type:a}=e;if(s)return void this.reject(s);const o={auth:this.auth,requestUri:t,sessionId:n,tenantId:i||void 0,postBody:r||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(a)(o))}catch(l){this.reject(l)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return Qi;case"linkViaPopup":case"linkViaRedirect":return Yi;case"reauthViaPopup":case"reauthViaRedirect":return $i;default:Fn(this.auth,"internal-error")}}resolve(e){Hn(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){Hn(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}const Ji=new Qn(2e3,1e4);class Zi extends Xi{constructor(e,t,n,r,i){super(e,t,r,i),this.provider=n,this.authWindow=null,this.pollId=null,Zi.currentPopupAction&&Zi.currentPopupAction.cancel(),Zi.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return zn(e,this.auth,"internal-error"),e}async onExecution(){Hn(1===this.filter.length,"Popup operations only handle one event");const e=Ni();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch((e=>{this.reject(e)})),this.resolver._isIframeWebStorageSupported(this.auth,(e=>{e||this.reject(Un(this.auth,"web-storage-unsupported"))})),this.pollUserCancellation()}get eventId(){var e;return(null===(e=this.authWindow)||void 0===e?void 0:e.associatedEvent)||null}cancel(){this.reject(Un(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,Zi.currentPopupAction=null}pollUserCancellation(){const e=()=>{var t,n;(null===(n=null===(t=this.authWindow)||void 0===t?void 0:t.window)||void 0===n?void 0:n.closed)?this.pollId=window.setTimeout((()=>{this.pollId=null,this.reject(Un(this.auth,"popup-closed-by-user"))}),8e3):this.pollId=window.setTimeout(e,Ji.get())};e()}}Zi.currentPopupAction=null;const es="pendingRedirect",ts=new Map;class ns extends Xi{constructor(e,t){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,arguments.length>2&&void 0!==arguments[2]&&arguments[2]),this.eventId=null}async execute(){let e=ts.get(this.auth._key());if(!e){try{const t=await async function(e,t){const n=ss(t),r=is(e);if(!await r._isAvailable())return!1;const i="true"===await r._get(n);return await r._remove(n),i}(this.resolver,this.auth),n=t?await super.execute():null;e=()=>Promise.resolve(n)}catch(t){e=()=>Promise.reject(t)}ts.set(this.auth._key(),e)}return this.bypassAuthState||ts.set(this.auth._key(),(()=>Promise.resolve(null))),e()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"!==e.type){if(e.eventId){const t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}else this.resolve(null)}async onExecution(){}cleanUp(){}}function rs(e,t){ts.set(e._key(),t)}function is(e){return _r(e._redirectPersistence)}function ss(e){return kr(es,e.config.apiKey,e.name)}async function as(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const r=Br(e),i=Ki(r,t),s=new ns(r,i,n),a=await s.execute();return a&&!n&&(delete a.user._redirectEventId,await r._persistUserIfCurrent(a.user),await r._setRedirectUser(null,t)),a}class os{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(e){if(this.hasEventBeenHandled(e))return!1;let t=!1;return this.consumers.forEach((n=>{this.isEventForConsumer(e,n)&&(t=!0,this.sendToConsumer(e,n),this.saveEventToCache(e))})),this.hasHandledPotentialRedirect||!function(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return cs(e);default:return!1}}(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){var n;if(e.error&&!cs(e)){const r=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error";t.onError(Un(this.auth,r))}else t.onAuthEvent(e)}isEventForConsumer(e,t){const n=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=6e5&&this.cachedEventUids.clear(),this.cachedEventUids.has(ls(e))}saveEventToCache(e){this.cachedEventUids.add(ls(e)),this.lastProcessedEventTime=Date.now()}}function ls(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter((e=>e)).join("-")}function cs(e){let{type:t,error:n}=e;return"unknown"===t&&(null===n||void 0===n?void 0:n.code)==="auth/".concat("no-auth-event")}const us=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,hs=/^https?/;async function ds(e){if(e.config.emulator)return;const{authorizedDomains:t}=await async function(e){return er(e,"GET","/v1/projects",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}(e);for(const r of t)try{if(fs(r))return}catch(n){}Fn(e,"unauthorized-domain")}function fs(e){const t=Wn(),{protocol:n,hostname:r}=new URL(t);if(e.startsWith("chrome-extension://")){const i=new URL(e);return""===i.hostname&&""===r?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&i.hostname===r}if(!hs.test(n))return!1;if(us.test(e))return r===e;const i=e.replace(/\./g,"\\.");return new RegExp("^(.+\\."+i+"|"+i+")$","i").test(r)}const ps=new Qn(3e4,6e4);function ms(){const e=Pi().___jsl;if(null===e||void 0===e?void 0:e.H)for(const t of Object.keys(e.H))if(e.H[t].r=e.H[t].r||[],e.H[t].L=e.H[t].L||[],e.H[t].r=[...e.H[t].L],e.CP)for(let n=0;n<e.CP.length;n++)e.CP[n]=null}let gs=null;function vs(e){return gs=gs||function(e){return new Promise(((t,n)=>{var r,i,s;function a(){ms(),gapi.load("gapi.iframes",{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{ms(),n(Un(e,"network-request-failed"))},timeout:ps.get()})}if(null===(i=null===(r=Pi().gapi)||void 0===r?void 0:r.iframes)||void 0===i?void 0:i.Iframe)t(gapi.iframes.getContext());else{if(!(null===(s=Pi().gapi)||void 0===s?void 0:s.load)){const t=Hr("iframefcb");return Pi()[t]=()=>{gapi.load?a():n(Un(e,"network-request-failed"))},qr("https://apis.google.com/js/api.js?onload=".concat(t)).catch((e=>n(e)))}a()}})).catch((e=>{throw gs=null,e}))}(e),gs}const ys=new Qn(5e3,15e3),ws="__/auth/iframe",bs="emulator/auth/iframe",_s={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},Es=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function Ss(e){const t=e.config;zn(t.authDomain,e,"auth-domain-config-required");const n=t.emulator?$n(t,bs):"https://".concat(e.config.authDomain,"/").concat(ws),r={apiKey:t.apiKey,appName:e.name,v:Ee},i=Es.get(e.config.apiHost);i&&(r.eid=i);const s=e._getFrameworks();return s.length&&(r.fw=s.join(",")),"".concat(n,"?").concat(k(r).slice(1))}const ks={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class Is{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function Ts(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:500,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:600;const s=Math.max((window.screen.availHeight-i)/2,0).toString(),a=Math.max((window.screen.availWidth-r)/2,0).toString();let o="";const l=Object.assign(Object.assign({},ks),{width:r.toString(),height:i.toString(),top:s,left:a}),c=m().toLowerCase();n&&(o=Nr(c)?"_blank":n),Cr(c)&&(t=t||"http://localhost",l.scrollbars="yes");const u=Object.entries(l).reduce(((e,t)=>{let[n,r]=t;return"".concat(e).concat(n,"=").concat(r,",")}),"");if(function(){var e;return Dr(arguments.length>0&&void 0!==arguments[0]?arguments[0]:m())&&!!(null===(e=window.navigator)||void 0===e?void 0:e.standalone)}(c)&&"_self"!==o)return function(e,t){const n=document.createElement("a");n.href=e,n.target=t;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(r)}(t||"",o),new Is(null);const h=window.open(t||"",o,u);zn(h,e,"popup-blocked");try{h.focus()}catch(d){}return new Is(h)}const Cs="__/auth/handler",xs="emulator/auth/handler",Ns=encodeURIComponent("fac");async function As(e,t,n,r,i,s){zn(e.config.authDomain,e,"auth-domain-config-required"),zn(e.config.apiKey,e,"invalid-api-key");const a={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:r,v:Ee,eventId:i};if(t instanceof oi){t.setDefaultLanguage(e.languageCode),a.providerId=t.providerId||"",function(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}(t.getCustomParameters())||(a.customParameters=JSON.stringify(t.getCustomParameters()));for(const[e,t]of Object.entries(s||{}))a[e]=t}if(t instanceof li){const e=t.getScopes().filter((e=>""!==e));e.length>0&&(a.scopes=e.join(","))}e.tenantId&&(a.tid=e.tenantId);const o=a;for(const u of Object.keys(o))void 0===o[u]&&delete o[u];const l=await e._getAppCheckToken(),c=l?"#".concat(Ns,"=").concat(encodeURIComponent(l)):"";return"".concat(function(e){let{config:t}=e;if(!t.emulator)return"https://".concat(t.authDomain,"/").concat(Cs);return $n(t,xs)}(e),"?").concat(k(o).slice(1)).concat(c)}const Ps="webStorageSupport";const Rs=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=Ci,this._completeRedirectFn=as,this._overrideRedirectResult=rs}async _openPopup(e,t,n,r){var i;Hn(null===(i=this.eventManagers[e._key()])||void 0===i?void 0:i.manager,"_initialize() not called before _openPopup()");return Ts(e,await As(e,t,n,Wn(),r),Ni())}async _openRedirect(e,t,n,r){await this._originValidation(e);return function(e){Pi().location.href=e}(await As(e,t,n,Wn(),r)),new Promise((()=>{}))}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:e,promise:n}=this.eventManagers[t];return e?Promise.resolve(e):(Hn(n,"If manager is not set, promise should be"),n)}const n=this.initAndGetManager(e);return this.eventManagers[t]={promise:n},n.catch((()=>{delete this.eventManagers[t]})),n}async initAndGetManager(e){const t=await async function(e){const t=await vs(e),n=Pi().gapi;return zn(n,e,"internal-error"),t.open({where:document.body,url:Ss(e),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:_s,dontclear:!0},(t=>new Promise((async(n,r)=>{await t.restyle({setHideOnLeave:!1});const i=Un(e,"network-request-failed"),s=Pi().setTimeout((()=>{r(i)}),ys.get());function a(){Pi().clearTimeout(s),n(t)}t.ping(a).then(a,(()=>{r(i)}))}))))}(e),n=new os(e);return t.register("authEvent",(t=>{zn(null===t||void 0===t?void 0:t.authEvent,e,"invalid-auth-event");return{status:n.onEvent(t.authEvent)?"ACK":"ERROR"}}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:n},this.iframes[e._key()]=t,n}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(Ps,{type:Ps},(n=>{var r;const i=null===(r=null===n||void 0===n?void 0:n[0])||void 0===r?void 0:r[Ps];void 0!==i&&t(!!i),Fn(e,"internal-error")}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=ds(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return Mr()||xr()||Dr()}};var Os="@firebase/auth",Ds="1.4.0";class Ls{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),(null===(e=this.auth.currentUser)||void 0===e?void 0:e.uid)||null}async getToken(e){if(this.assertAuthConfigured(),await this.auth._initializationPromise,!this.auth.currentUser)return null;return{accessToken:await this.auth.currentUser.getIdToken(e)}}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const t=this.auth.onIdTokenChanged((t=>{e((null===t||void 0===t?void 0:t.stsTokenManager.accessToken)||null)}));this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){zn(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}const Ms=f("authIdTokenMaxAge")||300;let js=null;var Fs;Fs="Browser",ye(new L("auth",((e,t)=>{let{options:n}=t;const r=e.getProvider("app").getImmediate(),i=e.getProvider("heartbeat"),s=e.getProvider("app-check-internal"),{apiKey:a,authDomain:o}=r.options;zn(a&&!a.includes(":"),"invalid-api-key",{appName:r.name});const l={apiKey:a,authDomain:o,clientPlatform:Fs,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:jr(Fs)},c=new Vr(r,i,s,l);return function(e,t){const n=(null===t||void 0===t?void 0:t.persistence)||[],r=(Array.isArray(n)?n:[n]).map(_r);(null===t||void 0===t?void 0:t.errorMap)&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,null===t||void 0===t?void 0:t.popupRedirectResolver)}(c,n),c}),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,n)=>{e.getProvider("auth-internal").initialize()}))),ye(new L("auth-internal",(e=>(e=>new Ls(e))(Br(e.getProvider("auth").getImmediate()))),"PRIVATE").setInstantiationMode("EXPLICIT")),Ie(Os,Ds,function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";default:return}}(Fs)),Ie(Os,Ds,"esm2017");var Us,Vs="undefined"!==typeof globalThis?globalThis:"undefined"!==typeof window?window:"undefined"!==typeof global?global:"undefined"!==typeof self?self:{},Bs={},zs=zs||{},qs=Vs||self;function Hs(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function Ws(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var Ks="closure_uid_"+(1e9*Math.random()>>>0),Gs=0;function Qs(e,t,n){return e.call.apply(e.bind,arguments)}function $s(e,t,n){if(!e)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var n=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(n,r),e.apply(t,n)}}return function(){return e.apply(t,arguments)}}function Ys(e,t,n){return(Ys=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?Qs:$s).apply(null,arguments)}function Xs(e,t){var n=Array.prototype.slice.call(arguments,1);return function(){var t=n.slice();return t.push.apply(t,arguments),e.apply(this,t)}}function Js(e,t){function n(){}n.prototype=t.prototype,e.$=t.prototype,e.prototype=new n,e.prototype.constructor=e,e.ac=function(e,n,r){for(var i=Array(arguments.length-2),s=2;s<arguments.length;s++)i[s-2]=arguments[s];return t.prototype[n].apply(e,i)}}function Zs(){this.s=this.s,this.o=this.o}Zs.prototype.s=!1,Zs.prototype.sa=function(){var e;!this.s&&(this.s=!0,this.N(),0)&&(e=this,Object.prototype.hasOwnProperty.call(e,Ks)&&e[Ks]||(e[Ks]=++Gs))},Zs.prototype.N=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const ea=Array.prototype.indexOf?function(e,t){return Array.prototype.indexOf.call(e,t,void 0)}:function(e,t){if("string"===typeof e)return"string"!==typeof t||1!=t.length?-1:e.indexOf(t,0);for(let n=0;n<e.length;n++)if(n in e&&e[n]===t)return n;return-1};function ta(e){const t=e.length;if(0<t){const n=Array(t);for(let r=0;r<t;r++)n[r]=e[r];return n}return[]}function na(e,t){for(let n=1;n<arguments.length;n++){const t=arguments[n];if(Hs(t)){const n=e.length||0,r=t.length||0;e.length=n+r;for(let i=0;i<r;i++)e[n+i]=t[i]}else e.push(t)}}function ra(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}ra.prototype.h=function(){this.defaultPrevented=!0};var ia=function(){if(!qs.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{qs.addEventListener("test",(()=>{}),t),qs.removeEventListener("test",(()=>{}),t)}catch(n){}return e}();function sa(e){return/^[\s\xa0]*$/.test(e)}function aa(){var e=qs.navigator;return e&&(e=e.userAgent)?e:""}function oa(e){return-1!=aa().indexOf(e)}function la(e){return la[" "](e),e}la[" "]=function(){};var ca,ua,ha=oa("Opera"),da=oa("Trident")||oa("MSIE"),fa=oa("Edge"),pa=fa||da,ma=oa("Gecko")&&!(-1!=aa().toLowerCase().indexOf("webkit")&&!oa("Edge"))&&!(oa("Trident")||oa("MSIE"))&&!oa("Edge"),ga=-1!=aa().toLowerCase().indexOf("webkit")&&!oa("Edge");function va(){var e=qs.document;return e?e.documentMode:void 0}e:{var ya="",wa=function(){var e=aa();return ma?/rv:([^\);]+)(\)|;)/.exec(e):fa?/Edge\/([\d\.]+)/.exec(e):da?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(e):ga?/WebKit\/(\S+)/.exec(e):ha?/(?:Version)[ \/]?(\S+)/.exec(e):void 0}();if(wa&&(ya=wa?wa[1]:""),da){var ba=va();if(null!=ba&&ba>parseFloat(ya)){ca=String(ba);break e}}ca=ya}if(qs.document&&da){var _a=va();ua=_a||(parseInt(ca,10)||void 0)}else ua=void 0;var Ea=ua;function Sa(e,t){if(ra.call(this,e?e.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,e){var n=this.type=e.type,r=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(ma){e:{try{la(t.nodeName);var i=!0;break e}catch(s){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType="string"===typeof e.pointerType?e.pointerType:ka[e.pointerType]||"",this.state=e.state,this.i=e,e.defaultPrevented&&Sa.$.h.call(this)}}Js(Sa,ra);var ka={2:"touch",3:"pen",4:"mouse"};Sa.prototype.h=function(){Sa.$.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var Ia="closure_listenable_"+(1e6*Math.random()|0),Ta=0;function Ca(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.la=i,this.key=++Ta,this.fa=this.ia=!1}function xa(e){e.fa=!0,e.listener=null,e.proxy=null,e.src=null,e.la=null}function Na(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function Aa(e){const t={};for(const n in e)t[n]=e[n];return t}const Pa="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function Ra(e,t){let n,r;for(let i=1;i<arguments.length;i++){for(n in r=arguments[i],r)e[n]=r[n];for(let t=0;t<Pa.length;t++)n=Pa[t],Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}}function Oa(e){this.src=e,this.g={},this.h=0}function Da(e,t){var n=t.type;if(n in e.g){var r,i=e.g[n],s=ea(i,t);(r=0<=s)&&Array.prototype.splice.call(i,s,1),r&&(xa(t),0==e.g[n].length&&(delete e.g[n],e.h--))}}function La(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.fa&&s.listener==t&&s.capture==!!n&&s.la==r)return i}return-1}Oa.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var a=La(e,t,r,i);return-1<a?(t=e[a],n||(t.ia=!1)):((t=new Ca(t,this.src,s,!!r,i)).ia=n,e.push(t)),t};var Ma="closure_lm_"+(1e6*Math.random()|0),ja={};function Fa(e,t,n,r,i){if(r&&r.once)return Va(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)Fa(e,t[s],n,r,i);return null}return n=Ga(n),e&&e[Ia]?e.O(t,n,Ws(r)?!!r.capture:!!r,i):Ua(e,t,n,!1,r,i)}function Ua(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var a=Ws(i)?!!i.capture:!!i,o=Wa(e);if(o||(e[Ma]=o=new Oa(e)),(n=o.add(t,n,r,a,s)).proxy)return n;if(r=function(){function e(n){return t.call(e.src,e.listener,n)}const t=Ha;return e}(),n.proxy=r,r.src=e,r.listener=n,e.addEventListener)ia||(i=a),void 0===i&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(qa(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function Va(e,t,n,r,i){if(Array.isArray(t)){for(var s=0;s<t.length;s++)Va(e,t[s],n,r,i);return null}return n=Ga(n),e&&e[Ia]?e.P(t,n,Ws(r)?!!r.capture:!!r,i):Ua(e,t,n,!0,r,i)}function Ba(e,t,n,r,i){if(Array.isArray(t))for(var s=0;s<t.length;s++)Ba(e,t[s],n,r,i);else r=Ws(r)?!!r.capture:!!r,n=Ga(n),e&&e[Ia]?(e=e.i,(t=String(t).toString())in e.g&&(-1<(n=La(s=e.g[t],n,r,i))&&(xa(s[n]),Array.prototype.splice.call(s,n,1),0==s.length&&(delete e.g[t],e.h--)))):e&&(e=Wa(e))&&(t=e.g[t.toString()],e=-1,t&&(e=La(t,n,r,i)),(n=-1<e?t[e]:null)&&za(n))}function za(e){if("number"!==typeof e&&e&&!e.fa){var t=e.src;if(t&&t[Ia])Da(t.i,e);else{var n=e.type,r=e.proxy;t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(qa(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=Wa(t))?(Da(n,e),0==n.h&&(n.src=null,t[Ma]=null)):xa(e)}}}function qa(e){return e in ja?ja[e]:ja[e]="on"+e}function Ha(e,t){if(e.fa)e=!0;else{t=new Sa(t,this);var n=e.listener,r=e.la||e.src;e.ia&&za(e),e=n.call(r,t)}return e}function Wa(e){return(e=e[Ma])instanceof Oa?e:null}var Ka="__closure_events_fn_"+(1e9*Math.random()>>>0);function Ga(e){return"function"===typeof e?e:(e[Ka]||(e[Ka]=function(t){return e.handleEvent(t)}),e[Ka])}function Qa(){Zs.call(this),this.i=new Oa(this),this.S=this,this.J=null}function $a(e,t){var n,r=e.J;if(r)for(n=[];r;r=r.J)n.push(r);if(e=e.S,r=t.type||t,"string"===typeof t)t=new ra(t,e);else if(t instanceof ra)t.target=t.target||e;else{var i=t;Ra(t=new ra(r,e),i)}if(i=!0,n)for(var s=n.length-1;0<=s;s--){var a=t.g=n[s];i=Ya(a,r,!0,t)&&i}if(i=Ya(a=t.g=e,r,!0,t)&&i,i=Ya(a,r,!1,t)&&i,n)for(s=0;s<n.length;s++)i=Ya(a=t.g=n[s],r,!1,t)&&i}function Ya(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var i=!0,s=0;s<t.length;++s){var a=t[s];if(a&&!a.fa&&a.capture==n){var o=a.listener,l=a.la||a.src;a.ia&&Da(e.i,a),i=!1!==o.call(l,r)&&i}}return i&&!r.defaultPrevented}Js(Qa,Zs),Qa.prototype[Ia]=!0,Qa.prototype.removeEventListener=function(e,t,n,r){Ba(this,e,t,n,r)},Qa.prototype.N=function(){if(Qa.$.N.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)xa(n[r]);delete t.g[e],t.h--}}this.J=null},Qa.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},Qa.prototype.P=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var Xa=qs.JSON.stringify;function Ja(){var e=so;let t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t}var Za=new class{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}((()=>new eo),(e=>e.reset()));class eo{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}function to(e){var t=1;e=e.split(":");const n=[];for(;0<t&&e.length;)n.push(e.shift()),t--;return e.length&&n.push(e.join(":")),n}function no(e){qs.setTimeout((()=>{throw e}),0)}let ro,io=!1,so=new class{constructor(){this.h=this.g=null}add(e,t){const n=Za.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}},ao=()=>{const e=qs.Promise.resolve(void 0);ro=()=>{e.then(oo)}};var oo=()=>{for(var e;e=Ja();){try{e.h.call(e.g)}catch(n){no(n)}var t=Za;t.j(e),100>t.h&&(t.h++,e.next=t.g,t.g=e)}io=!1};function lo(e,t){Qa.call(this),this.h=e||1,this.g=t||qs,this.j=Ys(this.qb,this),this.l=Date.now()}function co(e){e.ga=!1,e.T&&(e.g.clearTimeout(e.T),e.T=null)}function uo(e,t,n){if("function"===typeof e)n&&(e=Ys(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=Ys(e.handleEvent,e)}return 2147483647<Number(t)?-1:qs.setTimeout(e,t||0)}function ho(e){e.g=uo((()=>{e.g=null,e.i&&(e.i=!1,ho(e))}),e.j);const t=e.h;e.h=null,e.m.apply(null,t)}Js(lo,Qa),(Us=lo.prototype).ga=!1,Us.T=null,Us.qb=function(){if(this.ga){var e=Date.now()-this.l;0<e&&e<.8*this.h?this.T=this.g.setTimeout(this.j,this.h-e):(this.T&&(this.g.clearTimeout(this.T),this.T=null),$a(this,"tick"),this.ga&&(co(this),this.start()))}},Us.start=function(){this.ga=!0,this.T||(this.T=this.g.setTimeout(this.j,this.h),this.l=Date.now())},Us.N=function(){lo.$.N.call(this),co(this),delete this.g};class fo extends Zs{constructor(e,t){super(),this.m=e,this.j=t,this.h=null,this.i=!1,this.g=null}l(e){this.h=arguments,this.g?this.i=!0:ho(this)}N(){super.N(),this.g&&(qs.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function po(e){Zs.call(this),this.h=e,this.g={}}Js(po,Zs);var mo=[];function go(e,t,n,r){Array.isArray(n)||(n&&(mo[0]=n.toString()),n=mo);for(var i=0;i<n.length;i++){var s=Fa(t,n[i],r||e.handleEvent,!1,e.h||e);if(!s)break;e.g[s.key]=s}}function vo(e){Na(e.g,(function(e,t){this.g.hasOwnProperty(t)&&za(e)}),e),e.g={}}function yo(){this.g=!0}function wo(e,t,n,r){e.info((function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{var n=JSON.parse(t);if(n)for(e=0;e<n.length;e++)if(Array.isArray(n[e])){var r=n[e];if(!(2>r.length)){var i=r[1];if(Array.isArray(i)&&!(1>i.length)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var a=1;a<i.length;a++)i[a]=""}}}return Xa(n)}catch(o){return t}}(e,n)+(r?" "+r:"")}))}po.prototype.N=function(){po.$.N.call(this),vo(this)},po.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},yo.prototype.Ea=function(){this.g=!1},yo.prototype.info=function(){};var bo={},_o=null;function Eo(){return _o=_o||new Qa}function So(e){ra.call(this,bo.Ta,e)}function ko(e){const t=Eo();$a(t,new So(t))}function Io(e,t){ra.call(this,bo.STAT_EVENT,e),this.stat=t}function To(e){const t=Eo();$a(t,new Io(t,e))}function Co(e,t){ra.call(this,bo.Ua,e),this.size=t}function xo(e,t){if("function"!==typeof e)throw Error("Fn must not be null and must be a function");return qs.setTimeout((function(){e()}),t)}bo.Ta="serverreachability",Js(So,ra),bo.STAT_EVENT="statevent",Js(Io,ra),bo.Ua="timingevent",Js(Co,ra);var No={NO_ERROR:0,rb:1,Eb:2,Db:3,yb:4,Cb:5,Fb:6,Qa:7,TIMEOUT:8,Ib:9},Ao={wb:"complete",Sb:"success",Ra:"error",Qa:"abort",Kb:"ready",Lb:"readystatechange",TIMEOUT:"timeout",Gb:"incrementaldata",Jb:"progress",zb:"downloadprogress",$b:"uploadprogress"};function Po(){}function Ro(e){return e.h||(e.h=e.i())}function Oo(){}Po.prototype.h=null;var Do,Lo={OPEN:"a",vb:"b",Ra:"c",Hb:"d"};function Mo(){ra.call(this,"d")}function jo(){ra.call(this,"c")}function Fo(){}function Uo(e,t,n,r){this.l=e,this.j=t,this.m=n,this.W=r||1,this.U=new po(this),this.P=Bo,e=pa?125:void 0,this.V=new lo(e),this.I=null,this.i=!1,this.s=this.A=this.v=this.L=this.G=this.Y=this.B=null,this.F=[],this.g=null,this.C=0,this.o=this.u=null,this.ca=-1,this.J=!1,this.O=0,this.M=null,this.ba=this.K=this.aa=this.S=!1,this.h=new Vo}function Vo(){this.i=null,this.g="",this.h=!1}Js(Mo,ra),Js(jo,ra),Js(Fo,Po),Fo.prototype.g=function(){return new XMLHttpRequest},Fo.prototype.i=function(){return{}},Do=new Fo;var Bo=45e3,zo={},qo={};function Ho(e,t,n){e.L=1,e.v=cl(il(t)),e.s=n,e.S=!0,Wo(e,null)}function Wo(e,t){e.G=Date.now(),$o(e),e.A=il(e.v);var n=e.A,r=e.W;Array.isArray(r)||(r=[String(r)]),El(n.i,"t",r),e.C=0,n=e.l.J,e.h=new Vo,e.g=Sc(e.l,n?t:null,!e.s),0<e.O&&(e.M=new fo(Ys(e.Pa,e,e.g),e.O)),go(e.U,e.g,"readystatechange",e.nb),t=e.I?Aa(e.I):{},e.s?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ha(e.A,e.u,e.s,t)):(e.u="GET",e.g.ha(e.A,e.u,null,t)),ko(),function(e,t,n,r,i,s){e.info((function(){if(e.g)if(s)for(var a="",o=s.split("&"),l=0;l<o.length;l++){var c=o[l].split("=");if(1<c.length){var u=c[0];c=c[1];var h=u.split("_");a=2<=h.length&&"type"==h[1]?a+(u+"=")+c+"&":a+(u+"=redacted&")}}else a=null;else a=s;return"XMLHTTP REQ ("+r+") [attempt "+i+"]: "+t+"\n"+n+"\n"+a}))}(e.j,e.u,e.A,e.m,e.W,e.s)}function Ko(e){return!!e.g&&("GET"==e.u&&2!=e.L&&e.l.Ha)}function Go(e,t,n){let r,i=!0;for(;!e.J&&e.C<n.length;){if(r=Qo(e,n),r==qo){4==t&&(e.o=4,To(14),i=!1),wo(e.j,e.m,null,"[Incomplete Response]");break}if(r==zo){e.o=4,To(15),wo(e.j,e.m,n,"[Invalid Chunk]"),i=!1;break}wo(e.j,e.m,r,null),el(e,r)}Ko(e)&&r!=qo&&r!=zo&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,To(16),i=!1),e.i=e.i&&i,i?0<n.length&&!e.ba&&(e.ba=!0,(t=e.l).g==e&&t.ca&&!t.M&&(t.l.info("Great, no buffering proxy detected. Bytes received: "+n.length),mc(t),t.M=!0,To(11))):(wo(e.j,e.m,n,"[Invalid Chunked Response]"),Zo(e),Jo(e))}function Qo(e,t){var n=e.C,r=t.indexOf("\n",n);return-1==r?qo:(n=Number(t.substring(n,r)),isNaN(n)?zo:(r+=1)+n>t.length?qo:(t=t.slice(r,r+n),e.C=r+n,t))}function $o(e){e.Y=Date.now()+e.P,Yo(e,e.P)}function Yo(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=xo(Ys(e.lb,e),t)}function Xo(e){e.B&&(qs.clearTimeout(e.B),e.B=null)}function Jo(e){0==e.l.H||e.J||yc(e.l,e)}function Zo(e){Xo(e);var t=e.M;t&&"function"==typeof t.sa&&t.sa(),e.M=null,co(e.V),vo(e.U),e.g&&(t=e.g,e.g=null,t.abort(),t.sa())}function el(e,t){try{var n=e.l;if(0!=n.H&&(n.g==e||Nl(n.i,e)))if(!e.K&&Nl(n.i,e)&&3==n.H){try{var r=n.Ja.g.parse(t)}catch(c){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.G+3e3<e.G))break e;vc(n),oc(n)}pc(n),To(18)}}else n.Fa=i[1],0<n.Fa-n.V&&37500>i[2]&&n.G&&0==n.A&&!n.v&&(n.v=xo(Ys(n.ib,n),6e3));if(1>=xl(n.i)&&n.oa){try{n.oa()}catch(c){}n.oa=void 0}}else bc(n,11)}else if((e.K||n.g==e)&&vc(n),!sa(t))for(i=n.Ja.g.parse(t),t=0;t<i.length;t++){let c=i[t];if(n.V=c[0],c=c[1],2==n.H)if("c"==c[0]){n.K=c[1],n.pa=c[2];const t=c[3];null!=t&&(n.ra=t,n.l.info("VER="+n.ra));const i=c[4];null!=i&&(n.Ga=i,n.l.info("SVER="+n.Ga));const u=c[5];null!=u&&"number"===typeof u&&0<u&&(r=1.5*u,n.L=r,n.l.info("backChannelRequestTimeoutMs_="+r)),r=n;const h=e.g;if(h){const e=h.g?h.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(e){var s=r.i;s.g||-1==e.indexOf("spdy")&&-1==e.indexOf("quic")&&-1==e.indexOf("h2")||(s.j=s.l,s.g=new Set,s.h&&(Al(s,s.h),s.h=null))}if(r.F){const e=h.g?h.g.getResponseHeader("X-HTTP-Session-Id"):null;e&&(r.Da=e,ll(r.I,r.F,e))}}n.H=3,n.h&&n.h.Ba(),n.ca&&(n.S=Date.now()-e.G,n.l.info("Handshake RTT: "+n.S+"ms"));var a=e;if((r=n).wa=Ec(r,r.J?r.pa:null,r.Y),a.K){Pl(r.i,a);var o=a,l=r.L;l&&o.setTimeout(l),o.B&&(Xo(o),$o(o)),r.g=a}else fc(r);0<n.j.length&&cc(n)}else"stop"!=c[0]&&"close"!=c[0]||bc(n,7);else 3==n.H&&("stop"==c[0]||"close"==c[0]?"stop"==c[0]?bc(n,7):ac(n):"noop"!=c[0]&&n.h&&n.h.Aa(c),n.A=0)}ko()}catch(c){}}function tl(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(Hs(e)||"string"===typeof e)Array.prototype.forEach.call(e,t,void 0);else for(var n=function(e){if(e.ta&&"function"==typeof e.ta)return e.ta();if(!e.Z||"function"!=typeof e.Z){if("undefined"!==typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!==typeof Set&&e instanceof Set)){if(Hs(e)||"string"===typeof e){var t=[];e=e.length;for(var n=0;n<e;n++)t.push(n);return t}t=[],n=0;for(const r in e)t[n++]=r;return t}}}(e),r=function(e){if(e.Z&&"function"==typeof e.Z)return e.Z();if("undefined"!==typeof Map&&e instanceof Map||"undefined"!==typeof Set&&e instanceof Set)return Array.from(e.values());if("string"===typeof e)return e.split("");if(Hs(e)){for(var t=[],n=e.length,r=0;r<n;r++)t.push(e[r]);return t}for(r in t=[],n=0,e)t[n++]=e[r];return t}(e),i=r.length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}(Us=Uo.prototype).setTimeout=function(e){this.P=e},Us.nb=function(e){e=e.target;const t=this.M;t&&3==ec(e)?t.l():this.Pa(e)},Us.Pa=function(e){try{if(e==this.g)e:{const u=ec(this.g);var t=this.g.Ia();this.g.da();if(!(3>u)&&(3!=u||pa||this.g&&(this.h.h||this.g.ja()||tc(this.g)))){this.J||4!=u||7==t||ko(),Xo(this);var n=this.g.da();this.ca=n;t:if(Ko(this)){var r=tc(this.g);e="";var i=r.length,s=4==ec(this.g);if(!this.h.i){if("undefined"===typeof TextDecoder){Zo(this),Jo(this);var a="";break t}this.h.i=new qs.TextDecoder}for(t=0;t<i;t++)this.h.h=!0,e+=this.h.i.decode(r[t],{stream:s&&t==i-1});r.splice(0,i),this.h.g+=e,this.C=0,a=this.h.g}else a=this.g.ja();if(this.i=200==n,function(e,t,n,r,i,s,a){e.info((function(){return"XMLHTTP RESP ("+r+") [ attempt "+i+"]: "+t+"\n"+n+"\n"+s+" "+a}))}(this.j,this.u,this.A,this.m,this.W,u,n),this.i){if(this.aa&&!this.K){t:{if(this.g){var o,l=this.g;if((o=l.g?l.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!sa(o)){var c=o;break t}}c=null}if(!(n=c)){this.i=!1,this.o=3,To(12),Zo(this),Jo(this);break e}wo(this.j,this.m,n,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,el(this,n)}this.S?(Go(this,u,a),pa&&this.i&&3==u&&(go(this.U,this.V,"tick",this.mb),this.V.start())):(wo(this.j,this.m,a,null),el(this,a)),4==u&&Zo(this),this.i&&!this.J&&(4==u?yc(this.l,this):(this.i=!1,$o(this)))}else(function(e){const t={};e=(e.g&&2<=ec(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let r=0;r<e.length;r++){if(sa(e[r]))continue;var n=to(e[r]);const i=n[0];if("string"!==typeof(n=n[1]))continue;n=n.trim();const s=t[i]||[];t[i]=s,s.push(n)}!function(e,t){for(const n in e)t.call(void 0,e[n],n,e)}(t,(function(e){return e.join(", ")}))})(this.g),400==n&&0<a.indexOf("Unknown SID")?(this.o=3,To(12)):(this.o=0,To(13)),Zo(this),Jo(this)}}}catch(u){}},Us.mb=function(){if(this.g){var e=ec(this.g),t=this.g.ja();this.C<t.length&&(Xo(this),Go(this,e,t),this.i&&4!=e&&$o(this))}},Us.cancel=function(){this.J=!0,Zo(this)},Us.lb=function(){this.B=null;const e=Date.now();0<=e-this.Y?(function(e,t){e.info((function(){return"TIMEOUT: "+t}))}(this.j,this.A),2!=this.L&&(ko(),To(17)),Zo(this),this.o=2,Jo(this)):Yo(this,this.Y-e)};var nl=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function rl(e){if(this.g=this.s=this.j="",this.m=null,this.o=this.l="",this.h=!1,e instanceof rl){this.h=e.h,sl(this,e.j),this.s=e.s,this.g=e.g,al(this,e.m),this.l=e.l;var t=e.i,n=new yl;n.i=t.i,t.g&&(n.g=new Map(t.g),n.h=t.h),ol(this,n),this.o=e.o}else e&&(t=String(e).match(nl))?(this.h=!1,sl(this,t[1]||"",!0),this.s=ul(t[2]||""),this.g=ul(t[3]||"",!0),al(this,t[4]),this.l=ul(t[5]||"",!0),ol(this,t[6]||"",!0),this.o=ul(t[7]||"")):(this.h=!1,this.i=new yl(null,this.h))}function il(e){return new rl(e)}function sl(e,t,n){e.j=n?ul(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function al(e,t){if(t){if(t=Number(t),isNaN(t)||0>t)throw Error("Bad port number "+t);e.m=t}else e.m=null}function ol(e,t,n){t instanceof yl?(e.i=t,function(e,t){t&&!e.j&&(wl(e),e.i=null,e.g.forEach((function(e,t){var n=t.toLowerCase();t!=n&&(bl(this,t),El(this,n,e))}),e)),e.j=t}(e.i,e.h)):(n||(t=hl(t,gl)),e.i=new yl(t,e.h))}function ll(e,t,n){e.i.set(t,n)}function cl(e){return ll(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function ul(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function hl(e,t,n){return"string"===typeof e?(e=encodeURI(e).replace(t,dl),n&&(e=e.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),e):null}function dl(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}rl.prototype.toString=function(){var e=[],t=this.j;t&&e.push(hl(t,fl,!0),":");var n=this.g;return(n||"file"==t)&&(e.push("//"),(t=this.s)&&e.push(hl(t,fl,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&e.push(":",String(n))),(n=this.l)&&(this.g&&"/"!=n.charAt(0)&&e.push("/"),e.push(hl(n,"/"==n.charAt(0)?ml:pl,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.o)&&e.push("#",hl(n,vl)),e.join("")};var fl=/[#\/\?@]/g,pl=/[#\?:]/g,ml=/[#\?]/g,gl=/[#\?@]/g,vl=/#/g;function yl(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function wl(e){e.g||(e.g=new Map,e.h=0,e.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r=e[n].indexOf("="),i=null;if(0<=r){var s=e[n].substring(0,r);i=e[n].substring(r+1)}else s=e[n];t(s,i?decodeURIComponent(i.replace(/\+/g," ")):"")}}}(e.i,(function(t,n){e.add(decodeURIComponent(t.replace(/\+/g," ")),n)})))}function bl(e,t){wl(e),t=Sl(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function _l(e,t){return wl(e),t=Sl(e,t),e.g.has(t)}function El(e,t,n){bl(e,t),0<n.length&&(e.i=null,e.g.set(Sl(e,t),ta(n)),e.h+=n.length)}function Sl(e,t){return t=String(t),e.j&&(t=t.toLowerCase()),t}(Us=yl.prototype).add=function(e,t){wl(this),this.i=null,e=Sl(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},Us.forEach=function(e,t){wl(this),this.g.forEach((function(n,r){n.forEach((function(n){e.call(t,n,r,this)}),this)}),this)},Us.ta=function(){wl(this);const e=Array.from(this.g.values()),t=Array.from(this.g.keys()),n=[];for(let r=0;r<t.length;r++){const i=e[r];for(let e=0;e<i.length;e++)n.push(t[r])}return n},Us.Z=function(e){wl(this);let t=[];if("string"===typeof e)_l(this,e)&&(t=t.concat(this.g.get(Sl(this,e))));else{e=Array.from(this.g.values());for(let n=0;n<e.length;n++)t=t.concat(e[n])}return t},Us.set=function(e,t){return wl(this),this.i=null,_l(this,e=Sl(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},Us.get=function(e,t){return e&&0<(e=this.Z(e)).length?String(e[0]):t},Us.toString=function(){if(this.i)return this.i;if(!this.g)return"";const e=[],t=Array.from(this.g.keys());for(var n=0;n<t.length;n++){var r=t[n];const s=encodeURIComponent(String(r)),a=this.Z(r);for(r=0;r<a.length;r++){var i=s;""!==a[r]&&(i+="="+encodeURIComponent(String(a[r]))),e.push(i)}}return this.i=e.join("&")};var kl=class{constructor(e,t){this.g=e,this.map=t}};function Il(e){this.l=e||Tl,qs.PerformanceNavigationTiming?e=0<(e=qs.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):e=!!(qs.g&&qs.g.Ka&&qs.g.Ka()&&qs.g.Ka().dc),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}var Tl=10;function Cl(e){return!!e.h||!!e.g&&e.g.size>=e.j}function xl(e){return e.h?1:e.g?e.g.size:0}function Nl(e,t){return e.h?e.h==t:!!e.g&&e.g.has(t)}function Al(e,t){e.g?e.g.add(t):e.h=t}function Pl(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function Rl(e){if(null!=e.h)return e.i.concat(e.h.F);if(null!=e.g&&0!==e.g.size){let t=e.i;for(const n of e.g.values())t=t.concat(n.F);return t}return ta(e.i)}Il.prototype.cancel=function(){if(this.i=Rl(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}};var Ol,Dl=class{stringify(e){return qs.JSON.stringify(e,void 0)}parse(e){return qs.JSON.parse(e,void 0)}};function Ll(){this.g=new Dl}function Ml(e,t,n){const r=n||"";try{tl(e,(function(e,n){let i=e;Ws(e)&&(i=Xa(e)),t.push(r+n+"="+encodeURIComponent(i))}))}catch(i){throw t.push(r+"type="+encodeURIComponent("_badmap")),i}}function jl(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(s){}}function Fl(e){this.l=e.ec||null,this.j=e.ob||!1}function Ul(e,t){Qa.call(this),this.F=e,this.u=t,this.m=void 0,this.readyState=Vl,this.status=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.v=new Headers,this.h=null,this.C="GET",this.B="",this.g=!1,this.A=this.j=this.l=null}Js(Fl,Po),Fl.prototype.g=function(){return new Ul(this.l,this.j)},Fl.prototype.i=(Ol={},function(){return Ol}),Js(Ul,Qa);var Vl=0;function Bl(e){e.j.read().then(e.Xa.bind(e)).catch(e.ka.bind(e))}function zl(e){e.readyState=4,e.l=null,e.j=null,e.A=null,ql(e)}function ql(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(Us=Ul.prototype).open=function(e,t){if(this.readyState!=Vl)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,ql(this)},Us.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.F||qs).fetch(new Request(this.B,t)).then(this.$a.bind(this),this.ka.bind(this))},Us.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch((()=>{})),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,zl(this)),this.readyState=Vl},Us.$a=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,ql(this)),this.g&&(this.readyState=3,ql(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ya.bind(this),this.ka.bind(this));else if("undefined"!==typeof qs.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.u){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.A=new TextDecoder;Bl(this)}else e.text().then(this.Za.bind(this),this.ka.bind(this))},Us.Xa=function(e){if(this.g){if(this.u&&e.value)this.response.push(e.value);else if(!this.u){var t=e.value?e.value:new Uint8Array(0);(t=this.A.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)}e.done?zl(this):ql(this),3==this.readyState&&Bl(this)}},Us.Za=function(e){this.g&&(this.response=this.responseText=e,zl(this))},Us.Ya=function(e){this.g&&(this.response=e,zl(this))},Us.ka=function(){this.g&&zl(this)},Us.setRequestHeader=function(e,t){this.v.append(e,t)},Us.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},Us.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(Ul.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var Hl=qs.JSON.parse;function Wl(e){Qa.call(this),this.headers=new Map,this.u=e||null,this.h=!1,this.C=this.g=null,this.I="",this.m=0,this.j="",this.l=this.G=this.v=this.F=!1,this.B=0,this.A=null,this.K=Kl,this.L=this.M=!1}Js(Wl,Qa);var Kl="",Gl=/^https?$/i,Ql=["POST","PUT"];function $l(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,Yl(e),Jl(e)}function Yl(e){e.F||(e.F=!0,$a(e,"complete"),$a(e,"error"))}function Xl(e){if(e.h&&"undefined"!=typeof zs&&(!e.C[1]||4!=ec(e)||2!=e.da()))if(e.v&&4==ec(e))uo(e.La,0,e);else if($a(e,"readystatechange"),4==ec(e)){e.h=!1;try{const o=e.da();e:switch(o){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var t=!0;break e;default:t=!1}var n;if(!(n=t)){var r;if(r=0===o){var i=String(e.I).match(nl)[1]||null;!i&&qs.self&&qs.self.location&&(i=qs.self.location.protocol.slice(0,-1)),r=!Gl.test(i?i.toLowerCase():"")}n=r}if(n)$a(e,"complete"),$a(e,"success");else{e.m=6;try{var s=2<ec(e)?e.g.statusText:""}catch(a){s=""}e.j=s+" ["+e.da()+"]",Yl(e)}}finally{Jl(e)}}}function Jl(e,t){if(e.g){Zl(e);const r=e.g,i=e.C[0]?()=>{}:null;e.g=null,e.C=null,t||$a(e,"ready");try{r.onreadystatechange=i}catch(n){}}}function Zl(e){e.g&&e.L&&(e.g.ontimeout=null),e.A&&(qs.clearTimeout(e.A),e.A=null)}function ec(e){return e.g?e.g.readyState:0}function tc(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.K){case Kl:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(lu){return null}}function nc(e){let t="";return Na(e,(function(e,n){t+=n,t+=":",t+=e,t+="\r\n"})),t}function rc(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=nc(n),"string"===typeof e?null!=n&&encodeURIComponent(String(n)):ll(e,t,n))}function ic(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function sc(e){this.Ga=0,this.j=[],this.l=new yo,this.pa=this.wa=this.I=this.Y=this.g=this.Da=this.F=this.na=this.o=this.U=this.s=null,this.fb=this.W=0,this.cb=ic("failFast",!1,e),this.G=this.v=this.u=this.m=this.h=null,this.aa=!0,this.Fa=this.V=-1,this.ba=this.A=this.C=0,this.ab=ic("baseRetryDelayMs",5e3,e),this.hb=ic("retryDelaySeedMs",1e4,e),this.eb=ic("forwardChannelMaxRetries",2,e),this.xa=ic("forwardChannelRequestTimeoutMs",2e4,e),this.va=e&&e.xmlHttpFactory||void 0,this.Ha=e&&e.useFetchStreams||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.i=new Il(e&&e.concurrentRequestLimit),this.Ja=new Ll,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.bb=e&&e.bc||!1,e&&e.Ea&&this.l.Ea(),e&&e.forceLongPolling&&(this.aa=!1),this.ca=!this.P&&this.aa&&e&&e.detectBufferingProxy||!1,this.qa=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.qa=e.longPollingTimeout),this.oa=void 0,this.S=0,this.M=!1,this.ma=this.B=null}function ac(e){if(lc(e),3==e.H){var t=e.W++,n=il(e.I);if(ll(n,"SID",e.K),ll(n,"RID",t),ll(n,"TYPE","terminate"),hc(e,n),(t=new Uo(e,e.l,t)).L=2,t.v=cl(il(n)),n=!1,qs.navigator&&qs.navigator.sendBeacon)try{n=qs.navigator.sendBeacon(t.v.toString(),"")}catch(r){}!n&&qs.Image&&((new Image).src=t.v,n=!0),n||(t.g=Sc(t.l,null),t.g.ha(t.v)),t.G=Date.now(),$o(t)}_c(e)}function oc(e){e.g&&(mc(e),e.g.cancel(),e.g=null)}function lc(e){oc(e),e.u&&(qs.clearTimeout(e.u),e.u=null),vc(e),e.i.cancel(),e.m&&("number"===typeof e.m&&qs.clearTimeout(e.m),e.m=null)}function cc(e){if(!Cl(e.i)&&!e.m){e.m=!0;var t=e.Na;ro||ao(),io||(ro(),io=!0),so.add(t,e),e.C=0}}function uc(e,t){var n;n=t?t.m:e.W++;const r=il(e.I);ll(r,"SID",e.K),ll(r,"RID",n),ll(r,"AID",e.V),hc(e,r),e.o&&e.s&&rc(r,e.o,e.s),n=new Uo(e,e.l,n,e.C+1),null===e.o&&(n.I=e.s),t&&(e.j=t.F.concat(e.j)),t=dc(e,n,1e3),n.setTimeout(Math.round(.5*e.xa)+Math.round(.5*e.xa*Math.random())),Al(e.i,n),Ho(n,r,t)}function hc(e,t){e.na&&Na(e.na,(function(e,n){ll(t,n,e)})),e.h&&tl({},(function(e,n){ll(t,n,e)}))}function dc(e,t,n){n=Math.min(e.j.length,n);var r=e.h?Ys(e.h.Va,e.h,e):null;e:{var i=e.j;let t=-1;for(;;){const e=["count="+n];-1==t?0<n?(t=i[0].g,e.push("ofs="+t)):t=0:e.push("ofs="+t);let a=!0;for(let o=0;o<n;o++){let n=i[o].g;const l=i[o].map;if(n-=t,0>n)t=Math.max(0,i[o].g-100),a=!1;else try{Ml(l,e,"req"+n+"_")}catch(s){r&&r(l)}}if(a){r=e.join("&");break e}}}return e=e.j.splice(0,n),t.F=e,r}function fc(e){if(!e.g&&!e.u){e.ba=1;var t=e.Ma;ro||ao(),io||(ro(),io=!0),so.add(t,e),e.A=0}}function pc(e){return!(e.g||e.u||3<=e.A)&&(e.ba++,e.u=xo(Ys(e.Ma,e),wc(e,e.A)),e.A++,!0)}function mc(e){null!=e.B&&(qs.clearTimeout(e.B),e.B=null)}function gc(e){e.g=new Uo(e,e.l,"rpc",e.ba),null===e.o&&(e.g.I=e.s),e.g.O=0;var t=il(e.wa);ll(t,"RID","rpc"),ll(t,"SID",e.K),ll(t,"AID",e.V),ll(t,"CI",e.G?"0":"1"),!e.G&&e.qa&&ll(t,"TO",e.qa),ll(t,"TYPE","xmlhttp"),hc(e,t),e.o&&e.s&&rc(t,e.o,e.s),e.L&&e.g.setTimeout(e.L);var n=e.g;e=e.pa,n.L=1,n.v=cl(il(t)),n.s=null,n.S=!0,Wo(n,e)}function vc(e){null!=e.v&&(qs.clearTimeout(e.v),e.v=null)}function yc(e,t){var n=null;if(e.g==t){vc(e),mc(e),e.g=null;var r=2}else{if(!Nl(e.i,t))return;n=t.F,Pl(e.i,t),r=1}if(0!=e.H)if(t.i)if(1==r){n=t.s?t.s.length:0,t=Date.now()-t.G;var i=e.C;$a(r=Eo(),new Co(r,n)),cc(e)}else fc(e);else if(3==(i=t.o)||0==i&&0<t.ca||!(1==r&&function(e,t){return!(xl(e.i)>=e.i.j-(e.m?1:0))&&(e.m?(e.j=t.F.concat(e.j),!0):!(1==e.H||2==e.H||e.C>=(e.cb?0:e.eb))&&(e.m=xo(Ys(e.Na,e,t),wc(e,e.C)),e.C++,!0))}(e,t)||2==r&&pc(e)))switch(n&&0<n.length&&(t=e.i,t.i=t.i.concat(n)),i){case 1:bc(e,5);break;case 4:bc(e,10);break;case 3:bc(e,6);break;default:bc(e,2)}}function wc(e,t){let n=e.ab+Math.floor(Math.random()*e.hb);return e.isActive()||(n*=2),n*t}function bc(e,t){if(e.l.info("Error code "+t),2==t){var n=null;e.h&&(n=null);var r=Ys(e.pb,e);n||(n=new rl("//www.google.com/images/cleardot.gif"),qs.location&&"http"==qs.location.protocol||sl(n,"https"),cl(n)),function(e,t){const n=new yo;if(qs.Image){const r=new Image;r.onload=Xs(jl,n,r,"TestLoadImage: loaded",!0,t),r.onerror=Xs(jl,n,r,"TestLoadImage: error",!1,t),r.onabort=Xs(jl,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=Xs(jl,n,r,"TestLoadImage: timeout",!1,t),qs.setTimeout((function(){r.ontimeout&&r.ontimeout()}),1e4),r.src=e}else t(!1)}(n.toString(),r)}else To(2);e.H=0,e.h&&e.h.za(t),_c(e),lc(e)}function _c(e){if(e.H=0,e.ma=[],e.h){const t=Rl(e.i);0==t.length&&0==e.j.length||(na(e.ma,t),na(e.ma,e.j),e.i.i.length=0,ta(e.j),e.j.length=0),e.h.ya()}}function Ec(e,t,n){var r=n instanceof rl?il(n):new rl(n);if(""!=r.g)t&&(r.g=t+"."+r.g),al(r,r.m);else{var i=qs.location;r=i.protocol,t=t?t+"."+i.hostname:i.hostname,i=+i.port;var s=new rl(null);r&&sl(s,r),t&&(s.g=t),i&&al(s,i),n&&(s.l=n),r=s}return n=e.F,t=e.Da,n&&t&&ll(r,n,t),ll(r,"VER",e.ra),hc(e,r),r}function Sc(e,t,n){if(t&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(t=n&&e.Ha&&!e.va?new Wl(new Fl({ob:!0})):new Wl(e.va)).Oa(e.J),t}function kc(){}function Ic(){if(da&&!(10<=Number(Ea)))throw Error("Environmental error: no available transport.")}function Tc(e,t){Qa.call(this),this.g=new sc(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.s=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.Ca&&(e?e["X-WebChannel-Client-Profile"]=t.Ca:e={"X-WebChannel-Client-Profile":t.Ca}),this.g.U=e,(e=t&&t.cc)&&!sa(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!sa(t)&&(this.g.F=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new Nc(this)}function Cc(e){Mo.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);var t=e.__sm__;if(t){e:{for(const n in t){e=n;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function xc(){jo.call(this),this.status=1}function Nc(e){this.g=e}function Ac(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.m=Array(this.blockSize),this.i=this.h=0,this.reset()}function Pc(e,t,n){n||(n=0);var r=Array(16);if("string"===typeof t)for(var i=0;16>i;++i)r[i]=t.charCodeAt(n++)|t.charCodeAt(n++)<<8|t.charCodeAt(n++)<<16|t.charCodeAt(n++)<<24;else for(i=0;16>i;++i)r[i]=t[n++]|t[n++]<<8|t[n++]<<16|t[n++]<<24;t=e.g[0],n=e.g[1],i=e.g[2];var s=e.g[3],a=t+(s^n&(i^s))+r[0]+3614090360&4294967295;a=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=n+(a<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[1]+3905402710&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[2]+606105819&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[3]+3250441966&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[4]+4118548399&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[5]+1200080426&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[6]+2821735955&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[7]+4249261313&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[8]+1770035416&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[9]+2336552879&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[10]+4294925233&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[11]+2304563134&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[12]+1804603682&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[13]+4254626195&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[14]+2792965006&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[15]+1236535329&4294967295)<<22&4294967295|a>>>10))+((a=t+(i^s&(n^i))+r[1]+4129170786&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[6]+3225465664&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[11]+643717713&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[0]+3921069994&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[5]+3593408605&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[10]+38016083&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[15]+3634488961&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[4]+3889429448&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[9]+568446438&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[14]+3275163606&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[3]+4107603335&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[8]+1163531501&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[13]+2850285829&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[2]+4243563512&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[7]+1735328473&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[12]+2368359562&4294967295)<<20&4294967295|a>>>12))+((a=t+(n^i^s)+r[5]+4294588738&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[8]+2272392833&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[11]+1839030562&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[14]+4259657740&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[1]+2763975236&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[4]+1272893353&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[7]+4139469664&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[10]+3200236656&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[13]+681279174&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[0]+3936430074&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[3]+3572445317&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[6]+76029189&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[9]+3654602809&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[12]+3873151461&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[15]+530742520&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[2]+3299628645&4294967295)<<23&4294967295|a>>>9))+((a=t+(i^(n|~s))+r[0]+4096336452&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[7]+1126891415&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[14]+2878612391&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[5]+4237533241&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[12]+1700485571&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[3]+2399980690&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[10]+4293915773&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[1]+2240044497&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[8]+1873313359&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[15]+4264355552&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[6]+2734768916&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[13]+1309151649&4294967295)<<21&4294967295|a>>>11))+((s=(t=n+((a=t+(i^(n|~s))+r[4]+4149444226&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[11]+3174756917&4294967295)<<10&4294967295|a>>>22))^((i=s+((a=i+(t^(s|~n))+r[2]+718787259&4294967295)<<15&4294967295|a>>>17))|~t))+r[9]+3951481745&4294967295,e.g[0]=e.g[0]+t&4294967295,e.g[1]=e.g[1]+(i+(a<<21&4294967295|a>>>11))&4294967295,e.g[2]=e.g[2]+i&4294967295,e.g[3]=e.g[3]+s&4294967295}function Rc(e,t){this.h=t;for(var n=[],r=!0,i=e.length-1;0<=i;i--){var s=0|e[i];r&&s==t||(n[i]=s,r=!1)}this.g=n}(Us=Wl.prototype).Oa=function(e){this.M=e},Us.ha=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.I+"; newUri="+e);t=t?t.toUpperCase():"GET",this.I=e,this.j="",this.m=0,this.F=!1,this.h=!0,this.g=this.u?this.u.g():Do.g(),this.C=this.u?Ro(this.u):Ro(Do),this.g.onreadystatechange=Ys(this.La,this);try{this.G=!0,this.g.open(t,String(e),!0),this.G=!1}catch(s){return void $l(this,s)}if(e=n||"",n=new Map(this.headers),r)if(Object.getPrototypeOf(r)===Object.prototype)for(var i in r)n.set(i,r[i]);else{if("function"!==typeof r.keys||"function"!==typeof r.get)throw Error("Unknown input type for opt_headers: "+String(r));for(const e of r.keys())n.set(e,r.get(e))}r=Array.from(n.keys()).find((e=>"content-type"==e.toLowerCase())),i=qs.FormData&&e instanceof qs.FormData,!(0<=ea(Ql,t))||r||i||n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(const[a,o]of n)this.g.setRequestHeader(a,o);this.K&&(this.g.responseType=this.K),"withCredentials"in this.g&&this.g.withCredentials!==this.M&&(this.g.withCredentials=this.M);try{Zl(this),0<this.B&&((this.L=function(e){return da&&"number"===typeof e.timeout&&void 0!==e.ontimeout}(this.g))?(this.g.timeout=this.B,this.g.ontimeout=Ys(this.ua,this)):this.A=uo(this.ua,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(s){$l(this,s)}},Us.ua=function(){"undefined"!=typeof zs&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,$a(this,"timeout"),this.abort(8))},Us.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,$a(this,"complete"),$a(this,"abort"),Jl(this))},Us.N=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),Jl(this,!0)),Wl.$.N.call(this)},Us.La=function(){this.s||(this.G||this.v||this.l?Xl(this):this.kb())},Us.kb=function(){Xl(this)},Us.isActive=function(){return!!this.g},Us.da=function(){try{return 2<ec(this)?this.g.status:-1}catch(Ol){return-1}},Us.ja=function(){try{return this.g?this.g.responseText:""}catch(Ol){return""}},Us.Wa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),Hl(t)}},Us.Ia=function(){return this.m},Us.Sa=function(){return"string"===typeof this.j?this.j:String(this.j)},(Us=sc.prototype).ra=8,Us.H=1,Us.Na=function(e){if(this.m)if(this.m=null,1==this.H){if(!e){this.W=Math.floor(1e5*Math.random()),e=this.W++;const i=new Uo(this,this.l,e);let s=this.s;if(this.U&&(s?(s=Aa(s),Ra(s,this.U)):s=this.U),null!==this.o||this.O||(i.I=s,s=null),this.P)e:{for(var t=0,n=0;n<this.j.length;n++){var r=this.j[n];if(void 0===(r="__data__"in r.map&&"string"===typeof(r=r.map.__data__)?r.length:void 0))break;if(4096<(t+=r)){t=n;break e}if(4096===t||n===this.j.length-1){t=n+1;break e}}t=1e3}else t=1e3;t=dc(this,i,t),ll(n=il(this.I),"RID",e),ll(n,"CVER",22),this.F&&ll(n,"X-HTTP-Session-Id",this.F),hc(this,n),s&&(this.O?t="headers="+encodeURIComponent(String(nc(s)))+"&"+t:this.o&&rc(n,this.o,s)),Al(this.i,i),this.bb&&ll(n,"TYPE","init"),this.P?(ll(n,"$req",t),ll(n,"SID","null"),i.aa=!0,Ho(i,n,null)):Ho(i,n,t),this.H=2}}else 3==this.H&&(e?uc(this,e):0==this.j.length||Cl(this.i)||uc(this))},Us.Ma=function(){if(this.u=null,gc(this),this.ca&&!(this.M||null==this.g||0>=this.S)){var e=2*this.S;this.l.info("BP detection timer enabled: "+e),this.B=xo(Ys(this.jb,this),e)}},Us.jb=function(){this.B&&(this.B=null,this.l.info("BP detection timeout reached."),this.l.info("Buffering proxy detected and switch to long-polling!"),this.G=!1,this.M=!0,To(10),oc(this),gc(this))},Us.ib=function(){null!=this.v&&(this.v=null,oc(this),pc(this),To(19))},Us.pb=function(e){e?(this.l.info("Successfully pinged google.com"),To(2)):(this.l.info("Failed to ping google.com"),To(1))},Us.isActive=function(){return!!this.h&&this.h.isActive(this)},(Us=kc.prototype).Ba=function(){},Us.Aa=function(){},Us.za=function(){},Us.ya=function(){},Us.isActive=function(){return!0},Us.Va=function(){},Ic.prototype.g=function(e,t){return new Tc(e,t)},Js(Tc,Qa),Tc.prototype.m=function(){this.g.h=this.j,this.A&&(this.g.J=!0);var e=this.g,t=this.l,n=this.h||void 0;To(0),e.Y=t,e.na=n||{},e.G=e.aa,e.I=Ec(e,null,e.Y),cc(e)},Tc.prototype.close=function(){ac(this.g)},Tc.prototype.u=function(e){var t=this.g;if("string"===typeof e){var n={};n.__data__=e,e=n}else this.v&&((n={}).__data__=Xa(e),e=n);t.j.push(new kl(t.fb++,e)),3==t.H&&cc(t)},Tc.prototype.N=function(){this.g.h=null,delete this.j,ac(this.g),delete this.g,Tc.$.N.call(this)},Js(Cc,Mo),Js(xc,jo),Js(Nc,kc),Nc.prototype.Ba=function(){$a(this.g,"a")},Nc.prototype.Aa=function(e){$a(this.g,new Cc(e))},Nc.prototype.za=function(e){$a(this.g,new xc)},Nc.prototype.ya=function(){$a(this.g,"b")},Js(Ac,(function(){this.blockSize=-1})),Ac.prototype.reset=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.i=this.h=0},Ac.prototype.j=function(e,t){void 0===t&&(t=e.length);for(var n=t-this.blockSize,r=this.m,i=this.h,s=0;s<t;){if(0==i)for(;s<=n;)Pc(this,e,s),s+=this.blockSize;if("string"===typeof e){for(;s<t;)if(r[i++]=e.charCodeAt(s++),i==this.blockSize){Pc(this,r),i=0;break}}else for(;s<t;)if(r[i++]=e[s++],i==this.blockSize){Pc(this,r),i=0;break}}this.h=i,this.i+=t},Ac.prototype.l=function(){var e=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var t=1;t<e.length-8;++t)e[t]=0;var n=8*this.i;for(t=e.length-8;t<e.length;++t)e[t]=255&n,n/=256;for(this.j(e),e=Array(16),t=n=0;4>t;++t)for(var r=0;32>r;r+=8)e[n++]=this.g[t]>>>r&255;return e};var Oc={};function Dc(e){return-128<=e&&128>e?function(e,t){var n=Oc;return Object.prototype.hasOwnProperty.call(n,e)?n[e]:n[e]=t(e)}(e,(function(e){return new Rc([0|e],0>e?-1:0)})):new Rc([0|e],0>e?-1:0)}function Lc(e){if(isNaN(e)||!isFinite(e))return jc;if(0>e)return zc(Lc(-e));for(var t=[],n=1,r=0;e>=n;r++)t[r]=e/n|0,n*=Mc;return new Rc(t,0)}var Mc=4294967296,jc=Dc(0),Fc=Dc(1),Uc=Dc(16777216);function Vc(e){if(0!=e.h)return!1;for(var t=0;t<e.g.length;t++)if(0!=e.g[t])return!1;return!0}function Bc(e){return-1==e.h}function zc(e){for(var t=e.g.length,n=[],r=0;r<t;r++)n[r]=~e.g[r];return new Rc(n,~e.h).add(Fc)}function qc(e,t){return e.add(zc(t))}function Hc(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function Wc(e,t){this.g=e,this.h=t}function Kc(e,t){if(Vc(t))throw Error("division by zero");if(Vc(e))return new Wc(jc,jc);if(Bc(e))return t=Kc(zc(e),t),new Wc(zc(t.g),zc(t.h));if(Bc(t))return t=Kc(e,zc(t)),new Wc(zc(t.g),t.h);if(30<e.g.length){if(Bc(e)||Bc(t))throw Error("slowDivide_ only works with positive integers.");for(var n=Fc,r=t;0>=r.X(e);)n=Gc(n),r=Gc(r);var i=Qc(n,1),s=Qc(r,1);for(r=Qc(r,2),n=Qc(n,2);!Vc(r);){var a=s.add(r);0>=a.X(e)&&(i=i.add(n),s=a),r=Qc(r,1),n=Qc(n,1)}return t=qc(e,i.R(t)),new Wc(i,t)}for(i=jc;0<=e.X(t);){for(n=Math.max(1,Math.floor(e.ea()/t.ea())),r=48>=(r=Math.ceil(Math.log(n)/Math.LN2))?1:Math.pow(2,r-48),a=(s=Lc(n)).R(t);Bc(a)||0<a.X(e);)a=(s=Lc(n-=r)).R(t);Vc(s)&&(s=Fc),i=i.add(s),e=qc(e,a)}return new Wc(i,e)}function Gc(e){for(var t=e.g.length+1,n=[],r=0;r<t;r++)n[r]=e.D(r)<<1|e.D(r-1)>>>31;return new Rc(n,e.h)}function Qc(e,t){var n=t>>5;t%=32;for(var r=e.g.length-n,i=[],s=0;s<r;s++)i[s]=0<t?e.D(s+n)>>>t|e.D(s+n+1)<<32-t:e.D(s+n);return new Rc(i,e.h)}(Us=Rc.prototype).ea=function(){if(Bc(this))return-zc(this).ea();for(var e=0,t=1,n=0;n<this.g.length;n++){var r=this.D(n);e+=(0<=r?r:Mc+r)*t,t*=Mc}return e},Us.toString=function(e){if(2>(e=e||10)||36<e)throw Error("radix out of range: "+e);if(Vc(this))return"0";if(Bc(this))return"-"+zc(this).toString(e);for(var t=Lc(Math.pow(e,6)),n=this,r="";;){var i=Kc(n,t).g,s=((0<(n=qc(n,i.R(t))).g.length?n.g[0]:n.h)>>>0).toString(e);if(Vc(n=i))return s+r;for(;6>s.length;)s="0"+s;r=s+r}},Us.D=function(e){return 0>e?0:e<this.g.length?this.g[e]:this.h},Us.X=function(e){return Bc(e=qc(this,e))?-1:Vc(e)?0:1},Us.abs=function(){return Bc(this)?zc(this):this},Us.add=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0,i=0;i<=t;i++){var s=r+(65535&this.D(i))+(65535&e.D(i)),a=(s>>>16)+(this.D(i)>>>16)+(e.D(i)>>>16);r=a>>>16,s&=65535,a&=65535,n[i]=a<<16|s}return new Rc(n,-2147483648&n[n.length-1]?-1:0)},Us.R=function(e){if(Vc(this)||Vc(e))return jc;if(Bc(this))return Bc(e)?zc(this).R(zc(e)):zc(zc(this).R(e));if(Bc(e))return zc(this.R(zc(e)));if(0>this.X(Uc)&&0>e.X(Uc))return Lc(this.ea()*e.ea());for(var t=this.g.length+e.g.length,n=[],r=0;r<2*t;r++)n[r]=0;for(r=0;r<this.g.length;r++)for(var i=0;i<e.g.length;i++){var s=this.D(r)>>>16,a=65535&this.D(r),o=e.D(i)>>>16,l=65535&e.D(i);n[2*r+2*i]+=a*l,Hc(n,2*r+2*i),n[2*r+2*i+1]+=s*l,Hc(n,2*r+2*i+1),n[2*r+2*i+1]+=a*o,Hc(n,2*r+2*i+1),n[2*r+2*i+2]+=s*o,Hc(n,2*r+2*i+2)}for(r=0;r<t;r++)n[r]=n[2*r+1]<<16|n[2*r];for(r=t;r<2*t;r++)n[r]=0;return new Rc(n,0)},Us.gb=function(e){return Kc(this,e).h},Us.and=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)&e.D(r);return new Rc(n,this.h&e.h)},Us.or=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)|e.D(r);return new Rc(n,this.h|e.h)},Us.xor=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)^e.D(r);return new Rc(n,this.h^e.h)},Ic.prototype.createWebChannel=Ic.prototype.g,Tc.prototype.send=Tc.prototype.u,Tc.prototype.open=Tc.prototype.m,Tc.prototype.close=Tc.prototype.close,No.NO_ERROR=0,No.TIMEOUT=8,No.HTTP_ERROR=6,Ao.COMPLETE="complete",Oo.EventType=Lo,Lo.OPEN="a",Lo.CLOSE="b",Lo.ERROR="c",Lo.MESSAGE="d",Qa.prototype.listen=Qa.prototype.O,Wl.prototype.listenOnce=Wl.prototype.P,Wl.prototype.getLastError=Wl.prototype.Sa,Wl.prototype.getLastErrorCode=Wl.prototype.Ia,Wl.prototype.getStatus=Wl.prototype.da,Wl.prototype.getResponseJson=Wl.prototype.Wa,Wl.prototype.getResponseText=Wl.prototype.ja,Wl.prototype.send=Wl.prototype.ha,Wl.prototype.setWithCredentials=Wl.prototype.Oa,Ac.prototype.digest=Ac.prototype.l,Ac.prototype.reset=Ac.prototype.reset,Ac.prototype.update=Ac.prototype.j,Rc.prototype.add=Rc.prototype.add,Rc.prototype.multiply=Rc.prototype.R,Rc.prototype.modulo=Rc.prototype.gb,Rc.prototype.compare=Rc.prototype.X,Rc.prototype.toNumber=Rc.prototype.ea,Rc.prototype.toString=Rc.prototype.toString,Rc.prototype.getBits=Rc.prototype.D,Rc.fromNumber=Lc,Rc.fromString=function e(t,n){if(0==t.length)throw Error("number format error: empty string");if(2>(n=n||10)||36<n)throw Error("radix out of range: "+n);if("-"==t.charAt(0))return zc(e(t.substring(1),n));if(0<=t.indexOf("-"))throw Error('number format error: interior "-" character');for(var r=Lc(Math.pow(n,8)),i=jc,s=0;s<t.length;s+=8){var a=Math.min(8,t.length-s),o=parseInt(t.substring(s,s+a),n);8>a?(a=Lc(Math.pow(n,a)),i=i.R(a).add(Lc(o))):i=(i=i.R(r)).add(Lc(o))}return i};var $c=Bs.createWebChannelTransport=function(){return new Ic},Yc=Bs.getStatEventTarget=function(){return Eo()},Xc=Bs.ErrorCode=No,Jc=Bs.EventType=Ao,Zc=Bs.Event=bo,eu=Bs.Stat={xb:0,Ab:1,Bb:2,Ub:3,Zb:4,Wb:5,Xb:6,Vb:7,Tb:8,Yb:9,PROXY:10,NOPROXY:11,Rb:12,Nb:13,Ob:14,Mb:15,Pb:16,Qb:17,tb:18,sb:19,ub:20},tu=Bs.FetchXmlHttpFactory=Fl,nu=Bs.WebChannel=Oo,ru=Bs.XhrIo=Wl,iu=Bs.Md5=Ac,su=Bs.Integer=Rc;const au="@firebase/firestore";class ou{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}ou.UNAUTHENTICATED=new ou(null),ou.GOOGLE_CREDENTIALS=new ou("google-credentials-uid"),ou.FIRST_PARTY=new ou("first-party-uid"),ou.MOCK_USER=new ou("mock-user");let lu="10.5.2";const cu=new W("@firebase/firestore");function uu(){return cu.logLevel}function hu(e){if(cu.logLevel<=V.DEBUG){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];const i=n.map(pu);cu.debug("Firestore (".concat(lu,"): ").concat(e),...i)}}function du(e){if(cu.logLevel<=V.ERROR){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];const i=n.map(pu);cu.error("Firestore (".concat(lu,"): ").concat(e),...i)}}function fu(e){if(cu.logLevel<=V.WARN){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];const i=n.map(pu);cu.warn("Firestore (".concat(lu,"): ").concat(e),...i)}}function pu(e){if("string"==typeof e)return e;try{return function(e){return JSON.stringify(e)}(e)}catch(t){return e}}function mu(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unexpected state";const t="FIRESTORE (".concat(lu,") INTERNAL ASSERTION FAILED: ")+e;throw du(t),new Error(t)}function gu(e,t){e||mu()}function vu(e,t){return e}const yu={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class wu extends w{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>"".concat(this.name,": [code=").concat(this.code,"]: ").concat(this.message)}}class bu{constructor(){this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}class _u{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization","Bearer ".concat(e))}}class Eu{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable((()=>t(ou.UNAUTHENTICATED)))}shutdown(){}}class Su{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable((()=>t(this.token.user)))}shutdown(){this.changeListener=null}}class ku{constructor(e){this.t=e,this.currentUser=ou.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){let n=this.i;const r=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve();let i=new bu;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new bu,e.enqueueRetryable((()=>r(this.currentUser)))};const s=()=>{const t=i;e.enqueueRetryable((async()=>{await t.promise,await r(this.currentUser)}))},a=e=>{hu("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),s()};this.t.onInit((e=>a(e))),setTimeout((()=>{if(!this.auth){const e=this.t.getImmediate({optional:!0});e?a(e):(hu("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new bu)}}),0),s()}getToken(){const e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then((t=>this.i!==e?(hu("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(gu("string"==typeof t.accessToken),new _u(t.accessToken,this.currentUser)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){const e=this.auth&&this.auth.getUid();return gu(null===e||"string"==typeof e),new ou(e)}}class Iu{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=ou.FIRST_PARTY,this.I=new Map}T(){return this.P?this.P():null}get headers(){this.I.set("X-Goog-AuthUser",this.l);const e=this.T();return e&&this.I.set("Authorization",e),this.h&&this.I.set("X-Goog-Iam-Authorization-Token",this.h),this.I}}class Tu{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new Iu(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable((()=>t(ou.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class Cu{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class xu{constructor(e){this.A=e,this.forceRefresh=!1,this.appCheck=null,this.R=null}start(e,t){const n=e=>{null!=e.error&&hu("FirebaseAppCheckTokenProvider","Error getting App Check token; using placeholder token instead. Error: ".concat(e.error.message));const n=e.token!==this.R;return this.R=e.token,hu("FirebaseAppCheckTokenProvider","Received ".concat(n?"new":"existing"," token.")),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable((()=>n(t)))};const r=e=>{hu("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.A.onInit((e=>r(e))),setTimeout((()=>{if(!this.appCheck){const e=this.A.getImmediate({optional:!0});e?r(e):hu("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}}),0)}getToken(){const e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then((e=>e?(gu("string"==typeof e.token),this.R=e.token,new Cu(e.token)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}function Nu(e){const t="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(e);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(n);else for(let r=0;r<e;r++)n[r]=Math.floor(256*Math.random());return n}class Au{static newId(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=62*Math.floor(256/62);let n="";for(;n.length<20;){const r=Nu(40);for(let i=0;i<r.length;++i)n.length<20&&r[i]<t&&(n+=e.charAt(r[i]%62))}return n}}function Pu(e,t){return e<t?-1:e>t?1:0}function Ru(e,t,n){return e.length===t.length&&e.every(((e,r)=>n(e,t[r])))}class Ou{constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new wu(yu.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new wu(yu.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new wu(yu.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new wu(yu.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return Ou.fromMillis(Date.now())}static fromDate(e){return Ou.fromMillis(e.getTime())}static fromMillis(e){const t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new Ou(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Pu(this.nanoseconds,e.nanoseconds):Pu(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class Du{constructor(e){this.timestamp=e}static fromTimestamp(e){return new Du(e)}static min(){return new Du(new Ou(0,0))}static max(){return new Du(new Ou(253402300799,999999999))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}class Lu{constructor(e,t,n){void 0===t?t=0:t>e.length&&mu(),void 0===n?n=e.length-t:n>e.length-t&&mu(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===Lu.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof Lu?e.forEach((e=>{t.push(e)})):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return e=void 0===e?1:e,this.construct(this.segments,this.offset+e,this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),i=t.get(r);if(n<i)return-1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class Mu extends Lu{construct(e,t,n){return new Mu(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(){const e=[];for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];for(const i of n){if(i.indexOf("//")>=0)throw new wu(yu.INVALID_ARGUMENT,"Invalid segment (".concat(i,"). Paths must not contain // in them."));e.push(...i.split("/").filter((e=>e.length>0)))}return new Mu(e)}static emptyPath(){return new Mu([])}}const ju=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class Fu extends Lu{construct(e,t,n){return new Fu(e,t,n)}static isValidIdentifier(e){return ju.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),Fu.isValidIdentifier(e)||(e="`"+e+"`"),e))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new Fu(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;const i=()=>{if(0===n.length)throw new wu(yu.INVALID_ARGUMENT,"Invalid field path (".concat(e,"). Paths must not be empty, begin with '.', end with '.', or contain '..'"));t.push(n),n=""};let s=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new wu(yu.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new wu(yu.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?(s=!s,r++):"."!==t||s?(n+=t,r++):(i(),r++)}if(i(),s)throw new wu(yu.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new Fu(t)}static emptyPath(){return new Fu([])}}class Uu{constructor(e){this.path=e}static fromPath(e){return new Uu(Mu.fromString(e))}static fromName(e){return new Uu(Mu.fromString(e).popFirst(5))}static empty(){return new Uu(Mu.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return this.path.length>=2&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===Mu.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return Mu.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new Uu(new Mu(e.slice()))}}class Vu{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}Vu.UNKNOWN_ID=-1;function Bu(e,t){const n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,i=Du.fromTimestamp(1e9===r?new Ou(n+1,0):new Ou(n,r));return new qu(i,Uu.empty(),t)}function zu(e){return new qu(e.readTime,e.key,-1)}class qu{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new qu(Du.min(),Uu.empty(),-1)}static max(){return new qu(Du.max(),Uu.empty(),-1)}}function Hu(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=Uu.comparator(e.documentKey,t.documentKey),0!==n?n:Pu(e.largestBatchId,t.largestBatchId))}const Wu="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class Ku{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach((e=>e()))}}async function Gu(e){if(e.code!==yu.FAILED_PRECONDITION||e.message!==Wu)throw e;hu("LocalStore","Unexpectedly lost primary lease")}class Qu{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e((e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)}),(e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)}))}catch(e){return this.next(void 0,e)}next(e,t){return this.callbackAttached&&mu(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new Qu(((n,r)=>{this.nextCallback=t=>{this.wrapSuccess(e,t).next(n,r)},this.catchCallback=e=>{this.wrapFailure(t,e).next(n,r)}}))}toPromise(){return new Promise(((e,t)=>{this.next(e,t)}))}wrapUserFunction(e){try{const t=e();return t instanceof Qu?t:Qu.resolve(t)}catch(e){return Qu.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction((()=>e(t))):Qu.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction((()=>e(t))):Qu.reject(t)}static resolve(e){return new Qu(((t,n)=>{t(e)}))}static reject(e){return new Qu(((t,n)=>{n(e)}))}static waitFor(e){return new Qu(((t,n)=>{let r=0,i=0,s=!1;e.forEach((e=>{++r,e.next((()=>{++i,s&&i===r&&t()}),(e=>n(e)))})),s=!0,i===r&&t()}))}static or(e){let t=Qu.resolve(!1);for(const n of e)t=t.next((e=>e?Qu.resolve(e):n()));return t}static forEach(e,t){const n=[];return e.forEach(((e,r)=>{n.push(t.call(this,e,r))})),this.waitFor(n)}static mapArray(e,t){return new Qu(((n,r)=>{const i=e.length,s=new Array(i);let a=0;for(let o=0;o<i;o++){const l=o;t(e[l]).next((e=>{s[l]=e,++a,a===i&&n(s)}),(e=>r(e)))}}))}static doWhile(e,t){return new Qu(((n,r)=>{const i=()=>{!0===e()?t().next((()=>{i()}),r):n()};i()}))}}function $u(e){return"IndexedDbTransactionError"===e.name}class Yu{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.se(e),this.oe=e=>t.writeSequenceNumber(e))}se(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){const e=++this.previousValue;return this.oe&&this.oe(e),e}}function Xu(e){return null==e}function Ju(e){return 0===e&&1/e==-1/0}function Zu(e){return"number"==typeof e&&Number.isInteger(e)&&!Ju(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}Yu._e=-1;const eh=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],th=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],nh=th;function rh(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function ih(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function sh(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class ah{constructor(e,t){this.comparator=e,this.root=t||lh.EMPTY}insert(e,t){return new ah(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,lh.BLACK,null,null))}remove(e){return new ah(this.comparator,this.root.remove(e,this.comparator).copy(null,null,lh.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){const n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:n>0&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){const r=this.comparator(e,n.key);if(0===r)return t+n.left.size;r<0?n=n.left:(t+=n.left.size+1,n=n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal(((t,n)=>(e(t,n),!1)))}toString(){const e=[];return this.inorderTraversal(((t,n)=>(e.push("".concat(t,":").concat(n)),!1))),"{".concat(e.join(", "),"}")}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new oh(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new oh(this.root,e,this.comparator,!1)}getReverseIterator(){return new oh(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new oh(this.root,e,this.comparator,!0)}}class oh{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();const t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;const e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class lh{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:lh.RED,this.left=null!=r?r:lh.EMPTY,this.right=null!=i?i:lh.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new lh(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;const i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return lh.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return lh.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){const e=this.copy(null,null,lh.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,lh.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){const e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw mu();if(this.right.isRed())throw mu();const e=this.left.check();if(e!==this.right.check())throw mu();return e+(this.isRed()?0:1)}}lh.EMPTY=null,lh.RED=!0,lh.BLACK=!1,lh.EMPTY=new class{constructor(){this.size=0}get key(){throw mu()}get value(){throw mu()}get color(){throw mu()}get left(){throw mu()}get right(){throw mu()}copy(e,t,n,r,i){return this}insert(e,t,n){return new lh(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class ch{constructor(e){this.comparator=e,this.data=new ah(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(e){this.data.inorderTraversal(((t,n)=>(e(t),!1)))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){const r=n.getNext();if(this.comparator(r.key,e[1])>=0)return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new uh(this.data.getIterator())}getIteratorFrom(e){return new uh(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach((e=>{t=t.add(e)})),t}isEqual(e){if(!(e instanceof ch))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const e=[];return this.forEach((t=>{e.push(t)})),e}toString(){const e=[];return this.forEach((t=>e.push(t))),"SortedSet("+e.toString()+")"}copy(e){const t=new ch(this.comparator);return t.data=e,t}}class uh{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}class hh{constructor(e){this.fields=e,e.sort(Fu.comparator)}static empty(){return new hh([])}unionWith(e){let t=new ch(Fu.comparator);for(const n of this.fields)t=t.add(n);for(const n of e)t=t.add(n);return new hh(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Ru(this.fields,e.fields,((e,t)=>e.isEqual(t)))}}class dh extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class fh{constructor(e){this.binaryString=e}static fromBase64String(e){const t=function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new dh("Invalid base64 string: "+e):e}}(e);return new fh(t)}static fromUint8Array(e){const t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new fh(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return Pu(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}fh.EMPTY_BYTE_STRING=new fh("");const ph=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function mh(e){if(gu(!!e),"string"==typeof e){let t=0;const n=ph.exec(e);if(gu(!!n),n[1]){let e=n[1];e=(e+"000000000").substr(0,9),t=Number(e)}const r=new Date(e);return{seconds:Math.floor(r.getTime()/1e3),nanos:t}}return{seconds:gh(e.seconds),nanos:gh(e.nanos)}}function gh(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function vh(e){return"string"==typeof e?fh.fromBase64String(e):fh.fromUint8Array(e)}function yh(e){var t,n;return"server_timestamp"===(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===n?void 0:n.stringValue)}function wh(e){const t=e.mapValue.fields.__previous_value__;return yh(t)?wh(t):t}function bh(e){const t=mh(e.mapValue.fields.__local_write_time__.timestampValue);return new Ou(t.seconds,t.nanos)}class _h{constructor(e,t,n,r,i,s,a,o,l){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=l}}class Eh{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new Eh("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Eh&&e.projectId===this.projectId&&e.database===this.database}}const Sh={mapValue:{fields:{__type__:{stringValue:"__max__"}}}};function kh(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?yh(e)?4:Fh(e)?9007199254740991:10:mu()}function Ih(e,t){if(e===t)return!0;const n=kh(e);if(n!==kh(t))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return bh(e).isEqual(bh(t));case 3:return function(e,t){if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;const n=mh(e.timestampValue),r=mh(t.timestampValue);return n.seconds===r.seconds&&n.nanos===r.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return function(e,t){return vh(e.bytesValue).isEqual(vh(t.bytesValue))}(e,t);case 7:return e.referenceValue===t.referenceValue;case 8:return function(e,t){return gh(e.geoPointValue.latitude)===gh(t.geoPointValue.latitude)&&gh(e.geoPointValue.longitude)===gh(t.geoPointValue.longitude)}(e,t);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return gh(e.integerValue)===gh(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){const n=gh(e.doubleValue),r=gh(t.doubleValue);return n===r?Ju(n)===Ju(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return Ru(e.arrayValue.values||[],t.arrayValue.values||[],Ih);case 10:return function(e,t){const n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(rh(n)!==rh(r))return!1;for(const i in n)if(n.hasOwnProperty(i)&&(void 0===r[i]||!Ih(n[i],r[i])))return!1;return!0}(e,t);default:return mu()}}function Th(e,t){return void 0!==(e.values||[]).find((e=>Ih(e,t)))}function Ch(e,t){if(e===t)return 0;const n=kh(e),r=kh(t);if(n!==r)return Pu(n,r);switch(n){case 0:case 9007199254740991:return 0;case 1:return Pu(e.booleanValue,t.booleanValue);case 2:return function(e,t){const n=gh(e.integerValue||e.doubleValue),r=gh(t.integerValue||t.doubleValue);return n<r?-1:n>r?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1}(e,t);case 3:return xh(e.timestampValue,t.timestampValue);case 4:return xh(bh(e),bh(t));case 5:return Pu(e.stringValue,t.stringValue);case 6:return function(e,t){const n=vh(e),r=vh(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){const n=e.split("/"),r=t.split("/");for(let i=0;i<n.length&&i<r.length;i++){const e=Pu(n[i],r[i]);if(0!==e)return e}return Pu(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){const n=Pu(gh(e.latitude),gh(t.latitude));return 0!==n?n:Pu(gh(e.longitude),gh(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return function(e,t){const n=e.values||[],r=t.values||[];for(let i=0;i<n.length&&i<r.length;++i){const e=Ch(n[i],r[i]);if(e)return e}return Pu(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===Sh.mapValue&&t===Sh.mapValue)return 0;if(e===Sh.mapValue)return 1;if(t===Sh.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let a=0;a<r.length&&a<s.length;++a){const e=Pu(r[a],s[a]);if(0!==e)return e;const t=Ch(n[r[a]],i[s[a]]);if(0!==t)return t}return Pu(r.length,s.length)}(e.mapValue,t.mapValue);default:throw mu()}}function xh(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return Pu(e,t);const n=mh(e),r=mh(t),i=Pu(n.seconds,r.seconds);return 0!==i?i:Pu(n.nanos,r.nanos)}function Nh(e){return Ah(e)}function Ah(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=mh(e);return"time(".concat(t.seconds,",").concat(t.nanos,")")}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?function(e){return vh(e).toBase64()}(e.bytesValue):"referenceValue"in e?function(e){return Uu.fromName(e).toString()}(e.referenceValue):"geoPointValue"in e?function(e){return"geo(".concat(e.latitude,",").concat(e.longitude,")")}(e.geoPointValue):"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=Ah(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const i of t)r?r=!1:n+=",",n+="".concat(i,":").concat(Ah(e.fields[i]));return n+"}"}(e.mapValue):mu()}function Ph(e,t){return{referenceValue:"projects/".concat(e.projectId,"/databases/").concat(e.database,"/documents/").concat(t.path.canonicalString())}}function Rh(e){return!!e&&"integerValue"in e}function Oh(e){return!!e&&"arrayValue"in e}function Dh(e){return!!e&&"nullValue"in e}function Lh(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Mh(e){return!!e&&"mapValue"in e}function jh(e){if(e.geoPointValue)return{geoPointValue:Object.assign({},e.geoPointValue)};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:Object.assign({},e.timestampValue)};if(e.mapValue){const t={mapValue:{fields:{}}};return ih(e.mapValue.fields,((e,n)=>t.mapValue.fields[e]=jh(n))),t}if(e.arrayValue){const t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=jh(e.arrayValue.values[n]);return t}return Object.assign({},e)}function Fh(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}class Uh{constructor(e){this.value=e}static empty(){return new Uh({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(t=(t.mapValue.fields||{})[e.get(n)],!Mh(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=jh(t)}setAll(e){let t=Fu.emptyPath(),n={},r=[];e.forEach(((e,i)=>{if(!t.isImmediateParentOf(i)){const e=this.getFieldsMap(t);this.applyChanges(e,n,r),n={},r=[],t=i.popLast()}e?n[i.lastSegment()]=jh(e):r.push(i.lastSegment())}));const i=this.getFieldsMap(t);this.applyChanges(i,n,r)}delete(e){const t=this.field(e.popLast());Mh(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Ih(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let n=0;n<e.length;++n){let r=t.mapValue.fields[e.get(n)];Mh(r)&&r.mapValue.fields||(r={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=r),t=r}return t.mapValue.fields}applyChanges(e,t,n){ih(t,((t,n)=>e[t]=n));for(const r of n)delete e[r]}clone(){return new Uh(jh(this.value))}}function Vh(e){const t=[];return ih(e.fields,((e,n)=>{const r=new Fu([e]);if(Mh(n)){const e=Vh(n.mapValue).fields;if(0===e.length)t.push(r);else for(const n of e)t.push(r.child(n))}else t.push(r)})),new hh(t)}class Bh{constructor(e,t,n,r,i,s,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new Bh(e,0,Du.min(),Du.min(),Du.min(),Uh.empty(),0)}static newFoundDocument(e,t,n,r){return new Bh(e,1,t,Du.min(),n,r,0)}static newNoDocument(e,t){return new Bh(e,2,t,Du.min(),Du.min(),Uh.empty(),0)}static newUnknownDocument(e,t){return new Bh(e,3,t,Du.min(),Du.min(),Uh.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(Du.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Uh.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Uh.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=Du.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof Bh&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new Bh(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return"Document(".concat(this.key,", ").concat(this.version,", ").concat(JSON.stringify(this.data.value),", {createTime: ").concat(this.createTime,"}), {documentType: ").concat(this.documentType,"}), {documentState: ").concat(this.documentState,"})")}}class zh{constructor(e,t){this.position=e,this.inclusive=t}}function qh(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){const s=t[i],a=e.position[i];if(r=s.field.isKeyField()?Uu.comparator(Uu.fromName(a.referenceValue),n.key):Ch(a,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function Hh(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!Ih(e.position[n],t.position[n]))return!1;return!0}class Wh{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"asc";this.field=e,this.dir=t}}function Kh(e,t){return e.dir===t.dir&&e.field.isEqual(t.field)}class Gh{}class Qh extends Gh{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,n):new nd(e,t,n):"array-contains"===t?new ad(e,n):"in"===t?new od(e,n):"not-in"===t?new ld(e,n):"array-contains-any"===t?new cd(e,n):new Qh(e,t,n)}static createKeyFieldInFilter(e,t,n){return"in"===t?new rd(e,n):new id(e,n)}matches(e){const t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(Ch(t,this.value)):null!==t&&kh(this.value)===kh(t)&&this.matchesComparison(Ch(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return e>0;case">=":return e>=0;default:return mu()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class $h extends Gh{constructor(e,t){super(),this.filters=e,this.op=t,this.ue=null}static create(e,t){return new $h(e,t)}matches(e){return Yh(this)?void 0===this.filters.find((t=>!t.matches(e))):void 0!==this.filters.find((t=>t.matches(e)))}getFlattenedFilters(){return null!==this.ue||(this.ue=this.filters.reduce(((e,t)=>e.concat(t.getFlattenedFilters())),[])),this.ue}getFilters(){return Object.assign([],this.filters)}}function Yh(e){return"and"===e.op}function Xh(e){return Jh(e)&&Yh(e)}function Jh(e){for(const t of e.filters)if(t instanceof $h)return!1;return!0}function Zh(e){if(e instanceof Qh)return e.field.canonicalString()+e.op.toString()+Nh(e.value);if(Xh(e))return e.filters.map((e=>Zh(e))).join(",");{const t=e.filters.map((e=>Zh(e))).join(",");return"".concat(e.op,"(").concat(t,")")}}function ed(e,t){return e instanceof Qh?function(e,t){return t instanceof Qh&&e.op===t.op&&e.field.isEqual(t.field)&&Ih(e.value,t.value)}(e,t):e instanceof $h?function(e,t){return t instanceof $h&&e.op===t.op&&e.filters.length===t.filters.length&&e.filters.reduce(((e,n,r)=>e&&ed(n,t.filters[r])),!0)}(e,t):void mu()}function td(e){return e instanceof Qh?function(e){return"".concat(e.field.canonicalString()," ").concat(e.op," ").concat(Nh(e.value))}(e):e instanceof $h?function(e){return e.op.toString()+" {"+e.getFilters().map(td).join(" ,")+"}"}(e):"Filter"}class nd extends Qh{constructor(e,t,n){super(e,t,n),this.key=Uu.fromName(n.referenceValue)}matches(e){const t=Uu.comparator(e.key,this.key);return this.matchesComparison(t)}}class rd extends Qh{constructor(e,t){super(e,"in",t),this.keys=sd("in",t)}matches(e){return this.keys.some((t=>t.isEqual(e.key)))}}class id extends Qh{constructor(e,t){super(e,"not-in",t),this.keys=sd("not-in",t)}matches(e){return!this.keys.some((t=>t.isEqual(e.key)))}}function sd(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map((e=>Uu.fromName(e.referenceValue)))}class ad extends Qh{constructor(e,t){super(e,"array-contains",t)}matches(e){const t=e.data.field(this.field);return Oh(t)&&Th(t.arrayValue,this.value)}}class od extends Qh{constructor(e,t){super(e,"in",t)}matches(e){const t=e.data.field(this.field);return null!==t&&Th(this.value.arrayValue,t)}}class ld extends Qh{constructor(e,t){super(e,"not-in",t)}matches(e){if(Th(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return null!==t&&!Th(this.value.arrayValue,t)}}class cd extends Qh{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!Oh(t)||!t.arrayValue.values)&&t.arrayValue.values.some((e=>Th(this.value.arrayValue,e)))}}class ud{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null;this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=a,this.ce=null}}function hd(e){return new ud(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,arguments.length>6&&void 0!==arguments[6]?arguments[6]:null)}function dd(e){const t=vu(e);if(null===t.ce){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map((e=>Zh(e))).join(","),e+="|ob:",e+=t.orderBy.map((e=>function(e){return e.field.canonicalString()+e.dir}(e))).join(","),Xu(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map((e=>Nh(e))).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map((e=>Nh(e))).join(",")),t.ce=e}return t.ce}function fd(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let n=0;n<e.orderBy.length;n++)if(!Kh(e.orderBy[n],t.orderBy[n]))return!1;if(e.filters.length!==t.filters.length)return!1;for(let n=0;n<e.filters.length;n++)if(!ed(e.filters[n],t.filters[n]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!Hh(e.startAt,t.startAt)&&Hh(e.endAt,t.endAt)}function pd(e){return Uu.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}class md{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:"F",a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,o=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null;this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this.le=null,this.he=null,this.Pe=null,this.startAt,this.endAt}}function gd(e,t,n,r,i,s,a,o){return new md(e,t,n,r,i,s,a,o)}function vd(e){return new md(e)}function yd(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function wd(e){return null!==e.collectionGroup}function bd(e){const t=vu(e);if(null===t.le){t.le=[];const e=new Set;for(const i of t.explicitOrderBy)t.le.push(i),e.add(i.field.canonicalString());const n=t.explicitOrderBy.length>0?t.explicitOrderBy[t.explicitOrderBy.length-1].dir:"asc",r=function(e){let t=new ch(Fu.comparator);return e.filters.forEach((e=>{e.getFlattenedFilters().forEach((e=>{e.isInequality()&&(t=t.add(e.field))}))})),t}(t);r.forEach((r=>{e.has(r.canonicalString())||r.isKeyField()||t.le.push(new Wh(r,n))})),e.has(Fu.keyField().canonicalString())||t.le.push(new Wh(Fu.keyField(),n))}return t.le}function _d(e){const t=vu(e);return t.he||(t.he=Ed(t,bd(e))),t.he}function Ed(e,t){if("F"===e.limitType)return hd(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map((e=>{const t="desc"===e.dir?"asc":"desc";return new Wh(e.field,t)}));const n=e.endAt?new zh(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new zh(e.startAt.position,e.startAt.inclusive):null;return hd(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}function Sd(e,t){const n=e.filters.concat([t]);return new md(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function kd(e,t,n){return new md(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function Id(e,t){return fd(_d(e),_d(t))&&e.limitType===t.limitType}function Td(e){return"".concat(dd(_d(e)),"|lt:").concat(e.limitType)}function Cd(e){return"Query(target=".concat(function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),e.filters.length>0&&(t+=", filters: [".concat(e.filters.map((e=>td(e))).join(", "),"]")),Xu(e.limit)||(t+=", limit: "+e.limit),e.orderBy.length>0&&(t+=", orderBy: [".concat(e.orderBy.map((e=>function(e){return"".concat(e.field.canonicalString()," (").concat(e.dir,")")}(e))).join(", "),"]")),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map((e=>Nh(e))).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map((e=>Nh(e))).join(",")),"Target(".concat(t,")")}(_d(e)),"; limitType=").concat(e.limitType,")")}function xd(e,t){return t.isFoundDocument()&&function(e,t){const n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):Uu.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(const n of bd(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return!1;return!0}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return!1;return!0}(e,t)&&function(e,t){return!(e.startAt&&!function(e,t,n){const r=qh(e,t,n);return e.inclusive?r<=0:r<0}(e.startAt,bd(e),t))&&!(e.endAt&&!function(e,t,n){const r=qh(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,bd(e),t))}(e,t)}function Nd(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function Ad(e){return(t,n)=>{let r=!1;for(const i of bd(e)){const e=Pd(i,t,n);if(0!==e)return e;r=r||i.field.isKeyField()}return 0}}function Pd(e,t,n){const r=e.field.isKeyField()?Uu.comparator(t.key,n.key):function(e,t,n){const r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?Ch(r,i):mu()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return mu()}}class Rd{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[r,i]of n)if(this.equalsFn(r,e))return i}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let i=0;i<r.length;i++)if(this.equalsFn(r[i][0],e))return void(r[i]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(e){ih(this.inner,((t,n)=>{for(const[r,i]of n)e(r,i)}))}isEmpty(){return sh(this.inner)}size(){return this.innerSize}}const Od=new ah(Uu.comparator);function Dd(){return Od}const Ld=new ah(Uu.comparator);function Md(){let e=Ld;for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];for(const i of n)e=e.insert(i.key,i);return e}function jd(e){let t=Ld;return e.forEach(((e,n)=>t=t.insert(e,n.overlayedDocument))),t}function Fd(){return Vd()}function Ud(){return Vd()}function Vd(){return new Rd((e=>e.toString()),((e,t)=>e.isEqual(t)))}const Bd=new ah(Uu.comparator),zd=new ch(Uu.comparator);function qd(){let e=zd;for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];for(const i of n)e=e.add(i);return e}const Hd=new ch(Pu);function Wd(){return Hd}function Kd(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Ju(t)?"-0":t}}function Gd(e){return{integerValue:""+e}}function Qd(e,t){return Zu(t)?Gd(t):Kd(e,t)}class $d{constructor(){this._=void 0}}function Yd(e,t,n){return e instanceof Zd?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&yh(t)&&(t=wh(t)),t&&(n.fields.__previous_value__=t),{mapValue:n}}(n,t):e instanceof ef?tf(e,t):e instanceof nf?rf(e,t):function(e,t){const n=Jd(e,t),r=af(n)+af(e.Ie);return Rh(n)&&Rh(e.Ie)?Gd(r):Kd(e.serializer,r)}(e,t)}function Xd(e,t,n){return e instanceof ef?tf(e,t):e instanceof nf?rf(e,t):n}function Jd(e,t){return e instanceof sf?function(e){return Rh(e)||function(e){return!!e&&"doubleValue"in e}(e)}(t)?t:{integerValue:0}:null}class Zd extends $d{}class ef extends $d{constructor(e){super(),this.elements=e}}function tf(e,t){const n=of(t);for(const r of e.elements)n.some((e=>Ih(e,r)))||n.push(r);return{arrayValue:{values:n}}}class nf extends $d{constructor(e){super(),this.elements=e}}function rf(e,t){let n=of(t);for(const r of e.elements)n=n.filter((e=>!Ih(e,r)));return{arrayValue:{values:n}}}class sf extends $d{constructor(e,t){super(),this.serializer=e,this.Ie=t}}function af(e){return gh(e.integerValue||e.doubleValue)}function of(e){return Oh(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class lf{constructor(e,t){this.version=e,this.transformResults=t}}class cf{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new cf}static exists(e){return new cf(void 0,e)}static updateTime(e){return new cf(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function uf(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class hf{}function df(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new Ef(e.key,cf.none()):new vf(e.key,e.data,cf.none());{const n=e.data,r=Uh.empty();let i=new ch(Fu.comparator);for(let e of t.fields)if(!i.has(e)){let t=n.field(e);null===t&&e.length>1&&(e=e.popLast(),t=n.field(e)),null===t?r.delete(e):r.set(e,t),i=i.add(e)}return new yf(e.key,r,new hh(i.toArray()),cf.none())}}function ff(e,t,n){e instanceof vf?function(e,t,n){const r=e.value.clone(),i=bf(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof yf?function(e,t,n){if(!uf(e.precondition,t))return void t.convertToUnknownDocument(n.version);const r=bf(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(wf(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):function(e,t,n){t.convertToNoDocument(n.version).setHasCommittedMutations()}(0,t,n)}function pf(e,t,n,r){return e instanceof vf?function(e,t,n,r){if(!uf(e.precondition,t))return n;const i=e.value.clone(),s=_f(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof yf?function(e,t,n,r){if(!uf(e.precondition,t))return n;const i=_f(e.fieldTransforms,r,t),s=t.data;return s.setAll(wf(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map((e=>e.field)))}(e,t,n,r):function(e,t,n){return uf(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}(e,t,n)}function mf(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=Jd(r.transform,e||null);null!=i&&(null===n&&(n=Uh.empty()),n.set(r.field,i))}return n||null}function gf(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&!!function(e,t){return void 0===e&&void 0===t||!(!e||!t)&&Ru(e,t,((e,t)=>function(e,t){return e.field.isEqual(t.field)&&function(e,t){return e instanceof ef&&t instanceof ef||e instanceof nf&&t instanceof nf?Ru(e.elements,t.elements,Ih):e instanceof sf&&t instanceof sf?Ih(e.Ie,t.Ie):e instanceof Zd&&t instanceof Zd}(e.transform,t.transform)}(e,t)))}(e.fieldTransforms,t.fieldTransforms)&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class vf extends hf{constructor(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class yf extends hf{constructor(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[];super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function wf(e){const t=new Map;return e.fieldMask.fields.forEach((n=>{if(!n.isEmpty()){const r=e.data.field(n);t.set(n,r)}})),t}function bf(e,t,n){const r=new Map;gu(e.length===n.length);for(let i=0;i<n.length;i++){const s=e[i],a=s.transform,o=t.data.field(s.field);r.set(s.field,Xd(a,o,n[i]))}return r}function _f(e,t,n){const r=new Map;for(const i of e){const e=i.transform,s=n.data.field(i.field);r.set(i.field,Yd(e,s,t))}return r}class Ef extends hf{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Sf extends hf{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class kf{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){const n=t.mutationResults;for(let r=0;r<this.mutations.length;r++){const t=this.mutations[r];t.key.isEqual(e.key)&&ff(t,e,n[r])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=pf(n,e,t,this.localWriteTime));for(const n of this.mutations)n.key.isEqual(e.key)&&(t=pf(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){const n=Ud();return this.mutations.forEach((r=>{const i=e.get(r.key),s=i.overlayedDocument;let a=this.applyToLocalView(s,i.mutatedFields);a=t.has(r.key)?null:a;const o=df(s,a);null!==o&&n.set(r.key,o),s.isValidDocument()||s.convertToNoDocument(Du.min())})),n}keys(){return this.mutations.reduce(((e,t)=>e.add(t.key)),qd())}isEqual(e){return this.batchId===e.batchId&&Ru(this.mutations,e.mutations,((e,t)=>gf(e,t)))&&Ru(this.baseMutations,e.baseMutations,((e,t)=>gf(e,t)))}}class If{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){gu(e.mutations.length===n.length);let r=Bd;const i=e.mutations;for(let s=0;s<i.length;s++)r=r.insert(i[s].key,n[s].version);return new If(e,t,n,r)}}class Tf{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return"Overlay{\n largestBatchId: ".concat(this.largestBatchId,",\n mutation: ").concat(this.mutation.toString(),"\n }")}}class Cf{constructor(e,t){this.count=e,this.unchangedNames=t}}var xf,Nf;function Af(e){switch(e){default:return mu();case yu.CANCELLED:case yu.UNKNOWN:case yu.DEADLINE_EXCEEDED:case yu.RESOURCE_EXHAUSTED:case yu.INTERNAL:case yu.UNAVAILABLE:case yu.UNAUTHENTICATED:return!1;case yu.INVALID_ARGUMENT:case yu.NOT_FOUND:case yu.ALREADY_EXISTS:case yu.PERMISSION_DENIED:case yu.FAILED_PRECONDITION:case yu.ABORTED:case yu.OUT_OF_RANGE:case yu.UNIMPLEMENTED:case yu.DATA_LOSS:return!0}}function Pf(e){if(void 0===e)return du("GRPC error has no .code"),yu.UNKNOWN;switch(e){case xf.OK:return yu.OK;case xf.CANCELLED:return yu.CANCELLED;case xf.UNKNOWN:return yu.UNKNOWN;case xf.DEADLINE_EXCEEDED:return yu.DEADLINE_EXCEEDED;case xf.RESOURCE_EXHAUSTED:return yu.RESOURCE_EXHAUSTED;case xf.INTERNAL:return yu.INTERNAL;case xf.UNAVAILABLE:return yu.UNAVAILABLE;case xf.UNAUTHENTICATED:return yu.UNAUTHENTICATED;case xf.INVALID_ARGUMENT:return yu.INVALID_ARGUMENT;case xf.NOT_FOUND:return yu.NOT_FOUND;case xf.ALREADY_EXISTS:return yu.ALREADY_EXISTS;case xf.PERMISSION_DENIED:return yu.PERMISSION_DENIED;case xf.FAILED_PRECONDITION:return yu.FAILED_PRECONDITION;case xf.ABORTED:return yu.ABORTED;case xf.OUT_OF_RANGE:return yu.OUT_OF_RANGE;case xf.UNIMPLEMENTED:return yu.UNIMPLEMENTED;case xf.DATA_LOSS:return yu.DATA_LOSS;default:return mu()}}(Nf=xf||(xf={}))[Nf.OK=0]="OK",Nf[Nf.CANCELLED=1]="CANCELLED",Nf[Nf.UNKNOWN=2]="UNKNOWN",Nf[Nf.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",Nf[Nf.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",Nf[Nf.NOT_FOUND=5]="NOT_FOUND",Nf[Nf.ALREADY_EXISTS=6]="ALREADY_EXISTS",Nf[Nf.PERMISSION_DENIED=7]="PERMISSION_DENIED",Nf[Nf.UNAUTHENTICATED=16]="UNAUTHENTICATED",Nf[Nf.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",Nf[Nf.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",Nf[Nf.ABORTED=10]="ABORTED",Nf[Nf.OUT_OF_RANGE=11]="OUT_OF_RANGE",Nf[Nf.UNIMPLEMENTED=12]="UNIMPLEMENTED",Nf[Nf.INTERNAL=13]="INTERNAL",Nf[Nf.UNAVAILABLE=14]="UNAVAILABLE",Nf[Nf.DATA_LOSS=15]="DATA_LOSS";let Rf=null;function Of(){return new TextEncoder}const Df=new su([4294967295,4294967295],0);function Lf(e){const t=Of().encode(e),n=new iu;return n.update(t),new Uint8Array(n.digest())}function Mf(e){const t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new su([n,r],0),new su([i,s],0)]}class jf{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new Ff("Invalid padding: ".concat(t));if(n<0)throw new Ff("Invalid hash count: ".concat(n));if(e.length>0&&0===this.hashCount)throw new Ff("Invalid hash count: ".concat(n));if(0===e.length&&0!==t)throw new Ff("Invalid padding when bitmap length is 0: ".concat(t));this.Te=8*e.length-t,this.Ee=su.fromNumber(this.Te)}de(e,t,n){let r=e.add(t.multiply(su.fromNumber(n)));return 1===r.compare(Df)&&(r=new su([r.getBits(0),r.getBits(1)],0)),r.modulo(this.Ee).toNumber()}Ae(e){return 0!=(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.Te)return!1;const t=Lf(e),[n,r]=Mf(t);for(let i=0;i<this.hashCount;i++){const e=this.de(n,r,i);if(!this.Ae(e))return!1}return!0}static create(e,t,n){const r=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),s=new jf(i,r,t);return n.forEach((e=>s.insert(e))),s}insert(e){if(0===this.Te)return;const t=Lf(e),[n,r]=Mf(t);for(let i=0;i<this.hashCount;i++){const e=this.de(n,r,i);this.Re(e)}}Re(e){const t=Math.floor(e/8),n=e%8;this.bitmap[t]|=1<<n}}class Ff extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class Uf{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,Vf.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new Uf(Du.min(),r,new ah(Pu),Dd(),qd())}}class Vf{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new Vf(n,t,qd(),qd(),qd())}}class Bf{constructor(e,t,n,r){this.Ve=e,this.removedTargetIds=t,this.key=n,this.me=r}}class zf{constructor(e,t){this.targetId=e,this.fe=t}}class qf{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:fh.EMPTY_BYTE_STRING,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class Hf{constructor(){this.ge=0,this.pe=Gf(),this.ye=fh.EMPTY_BYTE_STRING,this.we=!1,this.Se=!0}get current(){return this.we}get resumeToken(){return this.ye}get be(){return 0!==this.ge}get De(){return this.Se}Ce(e){e.approximateByteSize()>0&&(this.Se=!0,this.ye=e)}ve(){let e=qd(),t=qd(),n=qd();return this.pe.forEach(((r,i)=>{switch(i){case 0:e=e.add(r);break;case 2:t=t.add(r);break;case 1:n=n.add(r);break;default:mu()}})),new Vf(this.ye,this.we,e,t,n)}Fe(){this.Se=!1,this.pe=Gf()}Me(e,t){this.Se=!0,this.pe=this.pe.insert(e,t)}xe(e){this.Se=!0,this.pe=this.pe.remove(e)}Oe(){this.ge+=1}Ne(){this.ge-=1}Be(){this.Se=!0,this.we=!0}}class Wf{constructor(e){this.Le=e,this.ke=new Map,this.qe=Dd(),this.Qe=Kf(),this.Ke=new ah(Pu)}$e(e){for(const t of e.Ve)e.me&&e.me.isFoundDocument()?this.Ue(t,e.me):this.We(t,e.key,e.me);for(const t of e.removedTargetIds)this.We(t,e.key,e.me)}Ge(e){this.forEachTarget(e,(t=>{const n=this.ze(t);switch(e.state){case 0:this.je(t)&&n.Ce(e.resumeToken);break;case 1:n.Ne(),n.be||n.Fe(),n.Ce(e.resumeToken);break;case 2:n.Ne(),n.be||this.removeTarget(t);break;case 3:this.je(t)&&(n.Be(),n.Ce(e.resumeToken));break;case 4:this.je(t)&&(this.He(t),n.Ce(e.resumeToken));break;default:mu()}}))}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.ke.forEach(((e,n)=>{this.je(n)&&t(n)}))}Je(e){const t=e.targetId,n=e.fe.count,r=this.Ye(t);if(r){const i=r.target;if(pd(i))if(0===n){const e=new Uu(i.path);this.We(t,e,Bh.newNoDocument(e,Du.min()))}else gu(1===n);else{const r=this.Ze(t);if(r!==n){const n=this.Xe(e),i=n?this.et(n,e,r):1;if(0!==i){this.He(t);const e=2===i?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ke=this.Ke.insert(t,e)}null==Rf||Rf.tt(function(e,t,n,r,i){var s,a,o,l,c,u;const h={localCacheCount:e,existenceFilterCount:t.count,databaseId:n.database,projectId:n.projectId},d=t.unchangedNames;return d&&(h.bloomFilter={applied:0===i,hashCount:null!==(s=null==d?void 0:d.hashCount)&&void 0!==s?s:0,bitmapLength:null!==(l=null===(o=null===(a=null==d?void 0:d.bits)||void 0===a?void 0:a.bitmap)||void 0===o?void 0:o.length)&&void 0!==l?l:0,padding:null!==(u=null===(c=null==d?void 0:d.bits)||void 0===c?void 0:c.padding)&&void 0!==u?u:0,mightContain:e=>{var t;return null!==(t=null==r?void 0:r.mightContain(e))&&void 0!==t&&t}}),h}(r,e.fe,this.Le.nt(),n,i))}}}}Xe(e){const t=e.fe.unchangedNames;if(!t||!t.bits)return null;const{bits:{bitmap:n="",padding:r=0},hashCount:i=0}=t;let s,a;try{s=vh(n).toUint8Array()}catch(e){if(e instanceof dh)return fu("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw e}try{a=new jf(s,r,i)}catch(e){return fu(e instanceof Ff?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===a.Te?null:a}et(e,t,n){return t.fe.count===n-this.rt(e,t.targetId)?0:2}rt(e,t){const n=this.Le.getRemoteKeysForTarget(t);let r=0;return n.forEach((n=>{const i=this.Le.nt(),s="projects/".concat(i.projectId,"/databases/").concat(i.database,"/documents/").concat(n.path.canonicalString());e.mightContain(s)||(this.We(t,n,null),r++)})),r}it(e){const t=new Map;this.ke.forEach(((n,r)=>{const i=this.Ye(r);if(i){if(n.current&&pd(i.target)){const t=new Uu(i.target.path);null!==this.qe.get(t)||this.st(r,t)||this.We(r,t,Bh.newNoDocument(t,e))}n.De&&(t.set(r,n.ve()),n.Fe())}}));let n=qd();this.Qe.forEach(((e,t)=>{let r=!0;t.forEachWhile((e=>{const t=this.Ye(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(r=!1,!1)})),r&&(n=n.add(e))})),this.qe.forEach(((t,n)=>n.setReadTime(e)));const r=new Uf(e,t,this.Ke,this.qe,n);return this.qe=Dd(),this.Qe=Kf(),this.Ke=new ah(Pu),r}Ue(e,t){if(!this.je(e))return;const n=this.st(e,t.key)?2:0;this.ze(e).Me(t.key,n),this.qe=this.qe.insert(t.key,t),this.Qe=this.Qe.insert(t.key,this.ot(t.key).add(e))}We(e,t,n){if(!this.je(e))return;const r=this.ze(e);this.st(e,t)?r.Me(t,1):r.xe(t),this.Qe=this.Qe.insert(t,this.ot(t).delete(e)),n&&(this.qe=this.qe.insert(t,n))}removeTarget(e){this.ke.delete(e)}Ze(e){const t=this.ze(e).ve();return this.Le.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Oe(e){this.ze(e).Oe()}ze(e){let t=this.ke.get(e);return t||(t=new Hf,this.ke.set(e,t)),t}ot(e){let t=this.Qe.get(e);return t||(t=new ch(Pu),this.Qe=this.Qe.insert(e,t)),t}je(e){const t=null!==this.Ye(e);return t||hu("WatchChangeAggregator","Detected inactive target",e),t}Ye(e){const t=this.ke.get(e);return t&&t.be?null:this.Le._t(e)}He(e){this.ke.set(e,new Hf),this.Le.getRemoteKeysForTarget(e).forEach((t=>{this.We(e,t,null)}))}st(e,t){return this.Le.getRemoteKeysForTarget(e).has(t)}}function Kf(){return new ah(Uu.comparator)}function Gf(){return new ah(Uu.comparator)}const Qf={asc:"ASCENDING",desc:"DESCENDING"},$f={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"},Yf={and:"AND",or:"OR"};class Xf{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function Jf(e,t){return e.useProto3Json||Xu(t)?t:{value:t}}function Zf(e,t){return e.useProto3Json?"".concat(new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z",""),".").concat(("000000000"+t.nanoseconds).slice(-9),"Z"):{seconds:""+t.seconds,nanos:t.nanoseconds}}function ep(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function tp(e,t){return Zf(e,t.toTimestamp())}function np(e){return gu(!!e),Du.fromTimestamp(function(e){const t=mh(e);return new Ou(t.seconds,t.nanos)}(e))}function rp(e,t){return function(e){return new Mu(["projects",e.projectId,"databases",e.database])}(e).child("documents").child(t).canonicalString()}function ip(e){const t=Mu.fromString(e);return gu(kp(t)),t}function sp(e,t){return rp(e.databaseId,t.path)}function ap(e,t){const n=ip(t);if(n.get(1)!==e.databaseId.projectId)throw new wu(yu.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new wu(yu.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new Uu(up(n))}function op(e,t){return rp(e.databaseId,t)}function lp(e){const t=ip(e);return 4===t.length?Mu.emptyPath():up(t)}function cp(e){return new Mu(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function up(e){return gu(e.length>4&&"documents"===e.get(4)),e.popFirst(5)}function hp(e,t,n){return{name:sp(e,t),fields:n.value.mapValue.fields}}function dp(e,t){let n;if(t instanceof vf)n={update:hp(e,t.key,t.value)};else if(t instanceof Ef)n={delete:sp(e,t.key)};else if(t instanceof yf)n={update:hp(e,t.key,t.data),updateMask:Sp(t.fieldMask)};else{if(!(t instanceof Sf))return mu();n={verify:sp(e,t.key)}}return t.fieldTransforms.length>0&&(n.updateTransforms=t.fieldTransforms.map((e=>function(e,t){const n=t.transform;if(n instanceof Zd)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof ef)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof nf)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof sf)return{fieldPath:t.field.canonicalString(),increment:n.Ie};throw mu()}(0,e)))),t.precondition.isNone||(n.currentDocument=function(e,t){return void 0!==t.updateTime?{updateTime:tp(e,t.updateTime)}:void 0!==t.exists?{exists:t.exists}:mu()}(e,t.precondition)),n}function fp(e,t){return{documents:[op(e,t.path)]}}function pp(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=op(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=op(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);const i=function(e){if(0!==e.length)return Ep($h.create(e,"and"))}(t.filters);i&&(n.structuredQuery.where=i);const s=function(e){if(0!==e.length)return e.map((e=>function(e){return{field:bp(e.field),direction:vp(e.dir)}}(e)))}(t.orderBy);s&&(n.structuredQuery.orderBy=s);const a=Jf(e,t.limit);return null!==a&&(n.structuredQuery.limit=a),t.startAt&&(n.structuredQuery.startAt=function(e){return{before:e.inclusive,values:e.position}}(t.startAt)),t.endAt&&(n.structuredQuery.endAt=function(e){return{before:!e.inclusive,values:e.position}}(t.endAt)),n}function mp(e){let t=lp(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let i=null;if(r>0){gu(1===r);const e=n.from[0];e.allDescendants?i=e.collectionId:t=t.child(e.collectionId)}let s=[];n.where&&(s=function(e){const t=gp(e);return t instanceof $h&&Xh(t)?t.getFilters():[t]}(n.where));let a=[];n.orderBy&&(a=function(e){return e.map((e=>function(e){return new Wh(_p(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)))}(n.orderBy));let o=null;n.limit&&(o=function(e){let t;return t="object"==typeof e?e.value:e,Xu(t)?null:t}(n.limit));let l=null;n.startAt&&(l=function(e){const t=!!e.before,n=e.values||[];return new zh(n,t)}(n.startAt));let c=null;return n.endAt&&(c=function(e){const t=!e.before,n=e.values||[];return new zh(n,t)}(n.endAt)),gd(t,i,a,s,o,"F",l,c)}function gp(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=_p(e.unaryFilter.field);return Qh.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=_p(e.unaryFilter.field);return Qh.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=_p(e.unaryFilter.field);return Qh.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const i=_p(e.unaryFilter.field);return Qh.create(i,"!=",{nullValue:"NULL_VALUE"});default:return mu()}}(e):void 0!==e.fieldFilter?function(e){return Qh.create(_p(e.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return mu()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return $h.create(e.compositeFilter.filters.map((e=>gp(e))),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return mu()}}(e.compositeFilter.op))}(e):mu()}function vp(e){return Qf[e]}function yp(e){return $f[e]}function wp(e){return Yf[e]}function bp(e){return{fieldPath:e.canonicalString()}}function _p(e){return Fu.fromServerFormat(e.fieldPath)}function Ep(e){return e instanceof Qh?function(e){if("=="===e.op){if(Lh(e.value))return{unaryFilter:{field:bp(e.field),op:"IS_NAN"}};if(Dh(e.value))return{unaryFilter:{field:bp(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Lh(e.value))return{unaryFilter:{field:bp(e.field),op:"IS_NOT_NAN"}};if(Dh(e.value))return{unaryFilter:{field:bp(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:bp(e.field),op:yp(e.op),value:e.value}}}(e):e instanceof $h?function(e){const t=e.getFilters().map((e=>Ep(e)));return 1===t.length?t[0]:{compositeFilter:{op:wp(e.op),filters:t}}}(e):mu()}function Sp(e){const t=[];return e.fields.forEach((e=>t.push(e.canonicalString()))),{fieldPaths:t}}function kp(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class Ip{constructor(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:Du.min(),s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:Du.min(),a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:fh.EMPTY_BYTE_STRING,o=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null;this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new Ip(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new Ip(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new Ip(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new Ip(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class Tp{constructor(e){this.ut=e}}function Cp(e){const t=mp({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?kd(t,t.limit,"L"):t}class xp{constructor(){}ht(e,t){this.Pt(e,t),t.It()}Pt(e,t){if("nullValue"in e)this.Tt(t,5);else if("booleanValue"in e)this.Tt(t,10),t.Et(e.booleanValue?1:0);else if("integerValue"in e)this.Tt(t,15),t.Et(gh(e.integerValue));else if("doubleValue"in e){const n=gh(e.doubleValue);isNaN(n)?this.Tt(t,13):(this.Tt(t,15),Ju(n)?t.Et(0):t.Et(n))}else if("timestampValue"in e){const n=e.timestampValue;this.Tt(t,20),"string"==typeof n?t.dt(n):(t.dt("".concat(n.seconds||"")),t.Et(n.nanos||0))}else if("stringValue"in e)this.At(e.stringValue,t),this.Rt(t);else if("bytesValue"in e)this.Tt(t,30),t.Vt(vh(e.bytesValue)),this.Rt(t);else if("referenceValue"in e)this.ft(e.referenceValue,t);else if("geoPointValue"in e){const n=e.geoPointValue;this.Tt(t,45),t.Et(n.latitude||0),t.Et(n.longitude||0)}else"mapValue"in e?Fh(e)?this.Tt(t,Number.MAX_SAFE_INTEGER):(this.gt(e.mapValue,t),this.Rt(t)):"arrayValue"in e?(this.yt(e.arrayValue,t),this.Rt(t)):mu()}At(e,t){this.Tt(t,25),this.wt(e,t)}wt(e,t){t.dt(e)}gt(e,t){const n=e.fields||{};this.Tt(t,55);for(const r of Object.keys(n))this.At(r,t),this.Pt(n[r],t)}yt(e,t){const n=e.values||[];this.Tt(t,50);for(const r of n)this.Pt(r,t)}ft(e,t){this.Tt(t,37),Uu.fromName(e).path.forEach((e=>{this.Tt(t,60),this.wt(e,t)}))}Tt(e,t){e.Et(t)}Rt(e){e.Et(2)}}xp.St=new xp;class Np{constructor(){this.on=new Ap}addToCollectionParentIndex(e,t){return this.on.add(t),Qu.resolve()}getCollectionParents(e,t){return Qu.resolve(this.on.getEntries(t))}addFieldIndex(e,t){return Qu.resolve()}deleteFieldIndex(e,t){return Qu.resolve()}deleteAllFieldIndexes(e){return Qu.resolve()}createTargetIndexes(e,t){return Qu.resolve()}getDocumentsMatchingTarget(e,t){return Qu.resolve(null)}getIndexType(e,t){return Qu.resolve(0)}getFieldIndexes(e,t){return Qu.resolve([])}getNextCollectionGroupToUpdate(e){return Qu.resolve(null)}getMinOffset(e,t){return Qu.resolve(qu.min())}getMinOffsetFromCollectionGroup(e,t){return Qu.resolve(qu.min())}updateCollectionGroup(e,t,n){return Qu.resolve()}updateIndexEntries(e,t){return Qu.resolve()}}class Ap{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new ch(Mu.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new ch(Mu.comparator)).toArray()}}new Uint8Array(0);class Pp{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new Pp(e,Pp.DEFAULT_COLLECTION_PERCENTILE,Pp.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}Pp.DEFAULT_COLLECTION_PERCENTILE=10,Pp.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Pp.DEFAULT=new Pp(41943040,Pp.DEFAULT_COLLECTION_PERCENTILE,Pp.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Pp.DISABLED=new Pp(-1,0,0);class Rp{constructor(e){this.xn=e}next(){return this.xn+=2,this.xn}static On(){return new Rp(0)}static Nn(){return new Rp(-1)}}class Op{constructor(){this.changes=new Rd((e=>e.toString()),((e,t)=>e.isEqual(t))),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,Bh.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();const n=this.changes.get(t);return void 0!==n?Qu.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class Dp{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class Lp{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(e,t){let n=null;return this.documentOverlayCache.getOverlay(e,t).next((r=>(n=r,this.remoteDocumentCache.getEntry(e,t)))).next((e=>(null!==n&&pf(n.mutation,e,hh.empty(),Ou.now()),e)))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next((t=>this.getLocalViewOfDocuments(e,t,qd()).next((()=>t))))}getLocalViewOfDocuments(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:qd();const r=Fd();return this.populateOverlays(e,r,t).next((()=>this.computeViews(e,t,r,n).next((e=>{let t=Md();return e.forEach(((e,n)=>{t=t.insert(e,n.overlayedDocument)})),t}))))}getOverlayedDocuments(e,t){const n=Fd();return this.populateOverlays(e,n,t).next((()=>this.computeViews(e,t,n,qd())))}populateOverlays(e,t,n){const r=[];return n.forEach((e=>{t.has(e)||r.push(e)})),this.documentOverlayCache.getOverlays(e,r).next((e=>{e.forEach(((e,n)=>{t.set(e,n)}))}))}computeViews(e,t,n,r){let i=Dd();const s=Vd(),a=Vd();return t.forEach(((e,t)=>{const a=n.get(t.key);r.has(t.key)&&(void 0===a||a.mutation instanceof yf)?i=i.insert(t.key,t):void 0!==a?(s.set(t.key,a.mutation.getFieldMask()),pf(a.mutation,t,a.mutation.getFieldMask(),Ou.now())):s.set(t.key,hh.empty())})),this.recalculateAndSaveOverlays(e,i).next((e=>(e.forEach(((e,t)=>s.set(e,t))),t.forEach(((e,t)=>{var n;return a.set(e,new Dp(t,null!==(n=s.get(e))&&void 0!==n?n:null))})),a)))}recalculateAndSaveOverlays(e,t){const n=Vd();let r=new ah(((e,t)=>e-t)),i=qd();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next((e=>{for(const i of e)i.keys().forEach((e=>{const s=t.get(e);if(null===s)return;let a=n.get(e)||hh.empty();a=i.applyToLocalView(s,a),n.set(e,a);const o=(r.get(i.batchId)||qd()).add(e);r=r.insert(i.batchId,o)}))})).next((()=>{const s=[],a=r.getReverseIterator();for(;a.hasNext();){const r=a.getNext(),o=r.key,l=r.value,c=Ud();l.forEach((e=>{if(!i.has(e)){const r=df(t.get(e),n.get(e));null!==r&&c.set(e,r),i=i.add(e)}})),s.push(this.documentOverlayCache.saveOverlays(e,o,c))}return Qu.waitFor(s)})).next((()=>n))}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next((t=>this.recalculateAndSaveOverlays(e,t)))}getDocumentsMatchingQuery(e,t,n,r){return function(e){return Uu.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):wd(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,r):this.getDocumentsMatchingCollectionQuery(e,t,n,r)}getNextDocuments(e,t,n,r){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,r).next((i=>{const s=r-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,r-i.size):Qu.resolve(Fd());let a=-1,o=i;return s.next((t=>Qu.forEach(t,((t,n)=>(a<n.largestBatchId&&(a=n.largestBatchId),i.get(t)?Qu.resolve():this.remoteDocumentCache.getEntry(e,t).next((e=>{o=o.insert(t,e)}))))).next((()=>this.populateOverlays(e,t,i))).next((()=>this.computeViews(e,o,t,qd()))).next((e=>({batchId:a,changes:jd(e)})))))}))}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new Uu(t)).next((e=>{let t=Md();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t}))}getDocumentsMatchingCollectionGroupQuery(e,t,n,r){const i=t.collectionGroup;let s=Md();return this.indexManager.getCollectionParents(e,i).next((a=>Qu.forEach(a,(a=>{const o=function(e,t){return new md(t,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(t,a.child(i));return this.getDocumentsMatchingCollectionQuery(e,o,n,r).next((e=>{e.forEach(((e,t)=>{s=s.insert(e,t)}))}))})).next((()=>s))))}getDocumentsMatchingCollectionQuery(e,t,n,r){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next((s=>(i=s,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,i,r)))).next((e=>{i.forEach(((t,n)=>{const r=n.getKey();null===e.get(r)&&(e=e.insert(r,Bh.newInvalidDocument(r)))}));let n=Md();return e.forEach(((e,r)=>{const s=i.get(e);void 0!==s&&pf(s.mutation,r,hh.empty(),Ou.now()),xd(t,r)&&(n=n.insert(e,r))})),n}))}}class Mp{constructor(e){this.serializer=e,this.ur=new Map,this.cr=new Map}getBundleMetadata(e,t){return Qu.resolve(this.ur.get(t))}saveBundleMetadata(e,t){return this.ur.set(t.id,function(e){return{id:e.id,version:e.version,createTime:np(e.createTime)}}(t)),Qu.resolve()}getNamedQuery(e,t){return Qu.resolve(this.cr.get(t))}saveNamedQuery(e,t){return this.cr.set(t.name,function(e){return{name:e.name,query:Cp(e.bundledQuery),readTime:np(e.readTime)}}(t)),Qu.resolve()}}class jp{constructor(){this.overlays=new ah(Uu.comparator),this.lr=new Map}getOverlay(e,t){return Qu.resolve(this.overlays.get(t))}getOverlays(e,t){const n=Fd();return Qu.forEach(t,(t=>this.getOverlay(e,t).next((e=>{null!==e&&n.set(t,e)})))).next((()=>n))}saveOverlays(e,t,n){return n.forEach(((n,r)=>{this.lt(e,t,r)})),Qu.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.lr.get(n);return void 0!==r&&(r.forEach((e=>this.overlays=this.overlays.remove(e))),this.lr.delete(n)),Qu.resolve()}getOverlaysForCollection(e,t,n){const r=Fd(),i=t.length+1,s=new Uu(t.child("")),a=this.overlays.getIteratorFrom(s);for(;a.hasNext();){const e=a.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return Qu.resolve(r)}getOverlaysForCollectionGroup(e,t,n,r){let i=new ah(((e,t)=>e-t));const s=this.overlays.getIterator();for(;s.hasNext();){const e=s.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>n){let t=i.get(e.largestBatchId);null===t&&(t=Fd(),i=i.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}const a=Fd(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach(((e,t)=>a.set(e,t))),!(a.size()>=r)););return Qu.resolve(a)}lt(e,t,n){const r=this.overlays.get(n.key);if(null!==r){const e=this.lr.get(r.largestBatchId).delete(n.key);this.lr.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new Tf(t,n));let i=this.lr.get(t);void 0===i&&(i=qd(),this.lr.set(t,i)),this.lr.set(t,i.add(n.key))}}class Fp{constructor(){this.hr=new ch(Up.Pr),this.Ir=new ch(Up.Tr)}isEmpty(){return this.hr.isEmpty()}addReference(e,t){const n=new Up(e,t);this.hr=this.hr.add(n),this.Ir=this.Ir.add(n)}Er(e,t){e.forEach((e=>this.addReference(e,t)))}removeReference(e,t){this.dr(new Up(e,t))}Ar(e,t){e.forEach((e=>this.removeReference(e,t)))}Rr(e){const t=new Uu(new Mu([])),n=new Up(t,e),r=new Up(t,e+1),i=[];return this.Ir.forEachInRange([n,r],(e=>{this.dr(e),i.push(e.key)})),i}Vr(){this.hr.forEach((e=>this.dr(e)))}dr(e){this.hr=this.hr.delete(e),this.Ir=this.Ir.delete(e)}mr(e){const t=new Uu(new Mu([])),n=new Up(t,e),r=new Up(t,e+1);let i=qd();return this.Ir.forEachInRange([n,r],(e=>{i=i.add(e.key)})),i}containsKey(e){const t=new Up(e,0),n=this.hr.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class Up{constructor(e,t){this.key=e,this.gr=t}static Pr(e,t){return Uu.comparator(e.key,t.key)||Pu(e.gr,t.gr)}static Tr(e,t){return Pu(e.gr,t.gr)||Uu.comparator(e.key,t.key)}}class Vp{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.pr=1,this.yr=new ch(Up.Pr)}checkEmpty(e){return Qu.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){const i=this.pr;this.pr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];const s=new kf(i,t,n,r);this.mutationQueue.push(s);for(const a of r)this.yr=this.yr.add(new Up(a.key,i)),this.indexManager.addToCollectionParentIndex(e,a.key.path.popLast());return Qu.resolve(s)}lookupMutationBatch(e,t){return Qu.resolve(this.wr(t))}getNextMutationBatchAfterBatchId(e,t){const n=t+1,r=this.Sr(n),i=r<0?0:r;return Qu.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)}getHighestUnacknowledgedBatchId(){return Qu.resolve(0===this.mutationQueue.length?-1:this.pr-1)}getAllMutationBatches(e){return Qu.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new Up(t,0),r=new Up(t,Number.POSITIVE_INFINITY),i=[];return this.yr.forEachInRange([n,r],(e=>{const t=this.wr(e.gr);i.push(t)})),Qu.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new ch(Pu);return t.forEach((e=>{const t=new Up(e,0),r=new Up(e,Number.POSITIVE_INFINITY);this.yr.forEachInRange([t,r],(e=>{n=n.add(e.gr)}))})),Qu.resolve(this.br(n))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;Uu.isDocumentKey(i)||(i=i.child(""));const s=new Up(new Uu(i),0);let a=new ch(Pu);return this.yr.forEachWhile((e=>{const t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.gr)),!0)}),s),Qu.resolve(this.br(a))}br(e){const t=[];return e.forEach((e=>{const n=this.wr(e);null!==n&&t.push(n)})),t}removeMutationBatch(e,t){gu(0===this.Dr(t.batchId,"removed")),this.mutationQueue.shift();let n=this.yr;return Qu.forEach(t.mutations,(r=>{const i=new Up(r.key,t.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,r.key)})).next((()=>{this.yr=n}))}Fn(e){}containsKey(e,t){const n=new Up(t,0),r=this.yr.firstAfterOrEqual(n);return Qu.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,Qu.resolve()}Dr(e,t){return this.Sr(e)}Sr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}wr(e){const t=this.Sr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class Bp{constructor(e){this.Cr=e,this.docs=new ah(Uu.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.Cr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){const t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return Qu.resolve(n?n.document.mutableCopy():Bh.newInvalidDocument(t))}getEntries(e,t){let n=Dd();return t.forEach((e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Bh.newInvalidDocument(e))})),Qu.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=Dd();const s=t.path,a=new Uu(s.child("")),o=this.docs.getIteratorFrom(a);for(;o.hasNext();){const{key:e,value:{document:a}}=o.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||Hu(zu(a),n)<=0||(r.has(a.key)||xd(t,a))&&(i=i.insert(a.key,a.mutableCopy()))}return Qu.resolve(i)}getAllFromCollectionGroup(e,t,n,r){mu()}vr(e,t){return Qu.forEach(this.docs,(e=>t(e)))}newChangeBuffer(e){return new zp(this)}getSize(e){return Qu.resolve(this.size)}}class zp extends Op{constructor(e){super(),this._r=e}applyChanges(e){const t=[];return this.changes.forEach(((n,r)=>{r.isValidDocument()?t.push(this._r.addEntry(e,r)):this._r.removeEntry(n)})),Qu.waitFor(t)}getFromCache(e,t){return this._r.getEntry(e,t)}getAllFromCache(e,t){return this._r.getEntries(e,t)}}class qp{constructor(e){this.persistence=e,this.Fr=new Rd((e=>dd(e)),fd),this.lastRemoteSnapshotVersion=Du.min(),this.highestTargetId=0,this.Mr=0,this.Or=new Fp,this.targetCount=0,this.Nr=Rp.On()}forEachTarget(e,t){return this.Fr.forEach(((e,n)=>t(n))),Qu.resolve()}getLastRemoteSnapshotVersion(e){return Qu.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return Qu.resolve(this.Mr)}allocateTargetId(e){return this.highestTargetId=this.Nr.next(),Qu.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Mr&&(this.Mr=t),Qu.resolve()}kn(e){this.Fr.set(e.target,e);const t=e.targetId;t>this.highestTargetId&&(this.Nr=new Rp(t),this.highestTargetId=t),e.sequenceNumber>this.Mr&&(this.Mr=e.sequenceNumber)}addTargetData(e,t){return this.kn(t),this.targetCount+=1,Qu.resolve()}updateTargetData(e,t){return this.kn(t),Qu.resolve()}removeTargetData(e,t){return this.Fr.delete(t.target),this.Or.Rr(t.targetId),this.targetCount-=1,Qu.resolve()}removeTargets(e,t,n){let r=0;const i=[];return this.Fr.forEach(((s,a)=>{a.sequenceNumber<=t&&null===n.get(a.targetId)&&(this.Fr.delete(s),i.push(this.removeMatchingKeysForTargetId(e,a.targetId)),r++)})),Qu.waitFor(i).next((()=>r))}getTargetCount(e){return Qu.resolve(this.targetCount)}getTargetData(e,t){const n=this.Fr.get(t)||null;return Qu.resolve(n)}addMatchingKeys(e,t,n){return this.Or.Er(t,n),Qu.resolve()}removeMatchingKeys(e,t,n){this.Or.Ar(t,n);const r=this.persistence.referenceDelegate,i=[];return r&&t.forEach((t=>{i.push(r.markPotentiallyOrphaned(e,t))})),Qu.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Or.Rr(t),Qu.resolve()}getMatchingKeysForTargetId(e,t){const n=this.Or.mr(t);return Qu.resolve(n)}containsKey(e,t){return Qu.resolve(this.Or.containsKey(t))}}class Hp{constructor(e,t){this.Br={},this.overlays={},this.Lr=new Yu(0),this.kr=!1,this.kr=!0,this.referenceDelegate=e(this),this.qr=new qp(this),this.indexManager=new Np,this.remoteDocumentCache=function(e){return new Bp(e)}((e=>this.referenceDelegate.Qr(e))),this.serializer=new Tp(t),this.Kr=new Mp(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.kr=!1,Promise.resolve()}get started(){return this.kr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new jp,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Br[e.toKey()];return n||(n=new Vp(t,this.referenceDelegate),this.Br[e.toKey()]=n),n}getTargetCache(){return this.qr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Kr}runTransaction(e,t,n){hu("MemoryPersistence","Starting transaction:",e);const r=new Wp(this.Lr.next());return this.referenceDelegate.$r(),n(r).next((e=>this.referenceDelegate.Ur(r).next((()=>e)))).toPromise().then((e=>(r.raiseOnCommittedEvent(),e)))}Wr(e,t){return Qu.or(Object.values(this.Br).map((n=>()=>n.containsKey(e,t))))}}class Wp extends Ku{constructor(e){super(),this.currentSequenceNumber=e}}class Kp{constructor(e){this.persistence=e,this.Gr=new Fp,this.zr=null}static jr(e){return new Kp(e)}get Hr(){if(this.zr)return this.zr;throw mu()}addReference(e,t,n){return this.Gr.addReference(n,t),this.Hr.delete(n.toString()),Qu.resolve()}removeReference(e,t,n){return this.Gr.removeReference(n,t),this.Hr.add(n.toString()),Qu.resolve()}markPotentiallyOrphaned(e,t){return this.Hr.add(t.toString()),Qu.resolve()}removeTarget(e,t){this.Gr.Rr(t.targetId).forEach((e=>this.Hr.add(e.toString())));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next((e=>{e.forEach((e=>this.Hr.add(e.toString())))})).next((()=>n.removeTargetData(e,t)))}$r(){this.zr=new Set}Ur(e){const t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return Qu.forEach(this.Hr,(n=>{const r=Uu.fromPath(n);return this.Jr(e,r).next((e=>{e||t.removeEntry(r,Du.min())}))})).next((()=>(this.zr=null,t.apply(e))))}updateLimboDocument(e,t){return this.Jr(e,t).next((e=>{e?this.Hr.delete(t.toString()):this.Hr.add(t.toString())}))}Qr(e){return 0}Jr(e,t){return Qu.or([()=>Qu.resolve(this.Gr.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Wr(e,t)])}}class Gp{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.ki=n,this.qi=r}static Qi(e,t){let n=qd(),r=qd();for(const i of t.docChanges)switch(i.type){case 0:n=n.add(i.doc.key);break;case 1:r=r.add(i.doc.key)}return new Gp(e,t.fromCache,n,r)}}class Qp{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class $p{constructor(){this.Ki=!1,this.$i=!1,this.Ui=100,this.Wi=8}initialize(e,t){this.Gi=e,this.indexManager=t,this.Ki=!0}getDocumentsMatchingQuery(e,t,n,r){const i={result:null};return this.zi(e,t).next((e=>{i.result=e})).next((()=>{if(!i.result)return this.ji(e,t,r,n).next((e=>{i.result=e}))})).next((()=>{if(i.result)return;const n=new Qp;return this.Hi(e,t,n).next((r=>{if(i.result=r,this.$i)return this.Ji(e,t,n,r.size)}))})).next((()=>i.result))}Ji(e,t,n,r){return n.documentReadCount<this.Ui?(uu()<=V.DEBUG&&hu("QueryEngine","SDK will not create cache indexes for query:",Cd(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Ui,"documents"),Qu.resolve()):(uu()<=V.DEBUG&&hu("QueryEngine","Query:",Cd(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.Wi*r?(uu()<=V.DEBUG&&hu("QueryEngine","The SDK decides to create cache indexes for query:",Cd(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,_d(t))):Qu.resolve())}zi(e,t){if(yd(t))return Qu.resolve(null);let n=_d(t);return this.indexManager.getIndexType(e,n).next((r=>0===r?null:(null!==t.limit&&1===r&&(t=kd(t,null,"F"),n=_d(t)),this.indexManager.getDocumentsMatchingTarget(e,n).next((r=>{const i=qd(...r);return this.Gi.getDocuments(e,i).next((r=>this.indexManager.getMinOffset(e,n).next((n=>{const s=this.Yi(t,r);return this.Zi(t,s,i,n.readTime)?this.zi(e,kd(t,null,"F")):this.Xi(e,s,t,n)}))))})))))}ji(e,t,n,r){return yd(t)||r.isEqual(Du.min())?Qu.resolve(null):this.Gi.getDocuments(e,n).next((i=>{const s=this.Yi(t,i);return this.Zi(t,s,n,r)?Qu.resolve(null):(uu()<=V.DEBUG&&hu("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),Cd(t)),this.Xi(e,s,t,Bu(r,-1)).next((e=>e)))}))}Yi(e,t){let n=new ch(Ad(e));return t.forEach(((t,r)=>{xd(e,r)&&(n=n.add(r))})),n}Zi(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(r)>0)}Hi(e,t,n){return uu()<=V.DEBUG&&hu("QueryEngine","Using full collection scan to execute query:",Cd(t)),this.Gi.getDocumentsMatchingQuery(e,t,qu.min(),n)}Xi(e,t,n,r){return this.Gi.getDocumentsMatchingQuery(e,n,r).next((e=>(t.forEach((t=>{e=e.insert(t.key,t)})),e)))}}class Yp{constructor(e,t,n,r){this.persistence=e,this.es=t,this.serializer=r,this.ts=new ah(Pu),this.ns=new Rd((e=>dd(e)),fd),this.rs=new Map,this.ss=e.getRemoteDocumentCache(),this.qr=e.getTargetCache(),this.Kr=e.getBundleCache(),this.os(n)}os(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new Lp(this.ss,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.ss.setIndexManager(this.indexManager),this.es.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",(t=>e.collect(t,this.ts)))}}function Xp(e,t,n,r){return new Yp(e,t,n,r)}async function Jp(e,t){const n=vu(e);return await n.persistence.runTransaction("Handle user change","readonly",(e=>{let r;return n.mutationQueue.getAllMutationBatches(e).next((i=>(r=i,n.os(t),n.mutationQueue.getAllMutationBatches(e)))).next((t=>{const i=[],s=[];let a=qd();for(const e of r){i.push(e.batchId);for(const t of e.mutations)a=a.add(t.key)}for(const e of t){s.push(e.batchId);for(const t of e.mutations)a=a.add(t.key)}return n.localDocuments.getDocuments(e,a).next((e=>({_s:e,removedBatchIds:i,addedBatchIds:s})))}))}))}function Zp(e){const t=vu(e);return t.persistence.runTransaction("Get last remote snapshot version","readonly",(e=>t.qr.getLastRemoteSnapshotVersion(e)))}function em(e,t,n){let r=qd(),i=qd();return n.forEach((e=>r=r.add(e))),t.getEntries(e,r).next((e=>{let r=Dd();return n.forEach(((n,s)=>{const a=e.get(n);s.isFoundDocument()!==a.isFoundDocument()&&(i=i.add(n)),s.isNoDocument()&&s.version.isEqual(Du.min())?(t.removeEntry(n,s.readTime),r=r.insert(n,s)):!a.isValidDocument()||s.version.compareTo(a.version)>0||0===s.version.compareTo(a.version)&&a.hasPendingWrites?(t.addEntry(s),r=r.insert(n,s)):hu("LocalStore","Ignoring outdated watch update for ",n,". Current version:",a.version," Watch version:",s.version)})),{us:r,cs:i}}))}function tm(e,t){const n=vu(e);return n.persistence.runTransaction("Get next mutation batch","readonly",(e=>(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t))))}function nm(e,t){const n=vu(e);return n.persistence.runTransaction("Allocate target","readwrite",(e=>{let r;return n.qr.getTargetData(e,t).next((i=>i?(r=i,Qu.resolve(r)):n.qr.allocateTargetId(e).next((i=>(r=new Ip(t,i,"TargetPurposeListen",e.currentSequenceNumber),n.qr.addTargetData(e,r).next((()=>r)))))))})).then((e=>{const r=n.ts.get(e.targetId);return(null===r||e.snapshotVersion.compareTo(r.snapshotVersion)>0)&&(n.ts=n.ts.insert(e.targetId,e),n.ns.set(t,e.targetId)),e}))}async function rm(e,t,n){const r=vu(e),i=r.ts.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,(e=>r.persistence.referenceDelegate.removeTarget(e,i)))}catch(e){if(!$u(e))throw e;hu("LocalStore","Failed to update sequence numbers for target ".concat(t,": ").concat(e))}r.ts=r.ts.remove(t),r.ns.delete(i.target)}function im(e,t,n){const r=vu(e);let i=Du.min(),s=qd();return r.persistence.runTransaction("Execute query","readwrite",(e=>function(e,t,n){const r=vu(e),i=r.ns.get(n);return void 0!==i?Qu.resolve(r.ts.get(i)):r.qr.getTargetData(t,n)}(r,e,_d(t)).next((t=>{if(t)return i=t.lastLimboFreeSnapshotVersion,r.qr.getMatchingKeysForTargetId(e,t.targetId).next((e=>{s=e}))})).next((()=>r.es.getDocumentsMatchingQuery(e,t,n?i:Du.min(),n?s:qd()))).next((e=>(sm(r,Nd(t),e),{documents:e,ls:s})))))}function sm(e,t,n){let r=e.rs.get(t)||Du.min();n.forEach(((e,t)=>{t.readTime.compareTo(r)>0&&(r=t.readTime)})),e.rs.set(t,r)}class am{constructor(){this.activeTargetIds=Wd()}ds(e){this.activeTargetIds=this.activeTargetIds.add(e)}As(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Es(){const e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class om{constructor(){this.eo=new am,this.no={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.eo.ds(e),this.no[e]||"not-current"}updateQueryState(e,t,n){this.no[e]=t}removeLocalQueryTarget(e){this.eo.As(e)}isLocalQueryTarget(e){return this.eo.activeTargetIds.has(e)}clearQueryState(e){delete this.no[e]}getAllActiveQueryTargets(){return this.eo.activeTargetIds}isActiveQueryTarget(e){return this.eo.activeTargetIds.has(e)}start(){return this.eo=new am,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class lm{ro(e){}shutdown(){}}class cm{constructor(){this.io=()=>this.so(),this.oo=()=>this._o(),this.ao=[],this.uo()}ro(e){this.ao.push(e)}shutdown(){window.removeEventListener("online",this.io),window.removeEventListener("offline",this.oo)}uo(){window.addEventListener("online",this.io),window.addEventListener("offline",this.oo)}so(){hu("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.ao)e(0)}_o(){hu("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.ao)e(1)}static D(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let um=null;function hm(){return null===um?um=268435456+Math.round(2147483648*Math.random()):um++,"0x"+um.toString(16)}const dm={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class fm{constructor(e){this.co=e.co,this.lo=e.lo}ho(e){this.Po=e}Io(e){this.To=e}onMessage(e){this.Eo=e}close(){this.lo()}send(e){this.co(e)}Ao(){this.Po()}Ro(e){this.To(e)}Vo(e){this.Eo(e)}}const pm="WebChannelConnection";class mm extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),r=encodeURIComponent(this.databaseId.database);this.mo=t+"://"+e.host,this.fo="projects/".concat(n,"/databases/").concat(r),this.po="(default)"===this.databaseId.database?"project_id=".concat(n):"project_id=".concat(n,"&database_id=").concat(r)}get yo(){return!1}wo(e,t,n,r,i){const s=hm(),a=this.So(e,t);hu("RestConnection","Sending RPC '".concat(e,"' ").concat(s,":"),a,n);const o={"google-cloud-resource-prefix":this.fo,"x-goog-request-params":this.po};return this.bo(o,r,i),this.Do(e,a,o,n).then((t=>(hu("RestConnection","Received RPC '".concat(e,"' ").concat(s,": "),t),t)),(t=>{throw fu("RestConnection","RPC '".concat(e,"' ").concat(s," failed with error: "),t,"url: ",a,"request:",n),t}))}Co(e,t,n,r,i,s){return this.wo(e,t,n,r,i)}bo(e,t,n){e["X-Goog-Api-Client"]="gl-js/ fire/"+lu,e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach(((t,n)=>e[n]=t)),n&&n.headers.forEach(((t,n)=>e[n]=t))}So(e,t){const n=dm[e];return"".concat(this.mo,"/v1/").concat(t,":").concat(n)}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}Do(e,t,n,r){const i=hm();return new Promise(((s,a)=>{const o=new ru;o.setWithCredentials(!0),o.listenOnce(Jc.COMPLETE,(()=>{try{switch(o.getLastErrorCode()){case Xc.NO_ERROR:const t=o.getResponseJson();hu(pm,"XHR for RPC '".concat(e,"' ").concat(i," received:"),JSON.stringify(t)),s(t);break;case Xc.TIMEOUT:hu(pm,"RPC '".concat(e,"' ").concat(i," timed out")),a(new wu(yu.DEADLINE_EXCEEDED,"Request time out"));break;case Xc.HTTP_ERROR:const n=o.getStatus();if(hu(pm,"RPC '".concat(e,"' ").concat(i," failed with status:"),n,"response text:",o.getResponseText()),n>0){let e=o.getResponseJson();Array.isArray(e)&&(e=e[0]);const t=null==e?void 0:e.error;if(t&&t.status&&t.message){const e=function(e){const t=e.toLowerCase().replace(/_/g,"-");return Object.values(yu).indexOf(t)>=0?t:yu.UNKNOWN}(t.status);a(new wu(e,t.message))}else a(new wu(yu.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new wu(yu.UNAVAILABLE,"Connection failed."));break;default:mu()}}finally{hu(pm,"RPC '".concat(e,"' ").concat(i," completed."))}}));const l=JSON.stringify(r);hu(pm,"RPC '".concat(e,"' ").concat(i," sending request:"),r),o.send(t,"POST",l,n,15)}))}vo(e,t,n){const r=hm(),i=[this.mo,"/","google.firestore.v1.Firestore","/",e,"/channel"],s=$c(),a=Yc(),o={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:"projects/".concat(this.databaseId.projectId,"/databases/").concat(this.databaseId.database)},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},l=this.longPollingOptions.timeoutSeconds;void 0!==l&&(o.longPollingTimeout=Math.round(1e3*l)),this.useFetchStreams&&(o.xmlHttpFactory=new tu({})),this.bo(o.initMessageHeaders,t,n),o.encodeInitMessageHeaders=!0;const c=i.join("");hu(pm,"Creating RPC '".concat(e,"' stream ").concat(r,": ").concat(c),o);const u=s.createWebChannel(c,o);let h=!1,d=!1;const f=new fm({co:t=>{d?hu(pm,"Not sending because RPC '".concat(e,"' stream ").concat(r," is closed:"),t):(h||(hu(pm,"Opening RPC '".concat(e,"' stream ").concat(r," transport.")),u.open(),h=!0),hu(pm,"RPC '".concat(e,"' stream ").concat(r," sending:"),t),u.send(t))},lo:()=>u.close()}),p=(e,t,n)=>{e.listen(t,(e=>{try{n(e)}catch(e){setTimeout((()=>{throw e}),0)}}))};return p(u,nu.EventType.OPEN,(()=>{d||hu(pm,"RPC '".concat(e,"' stream ").concat(r," transport opened."))})),p(u,nu.EventType.CLOSE,(()=>{d||(d=!0,hu(pm,"RPC '".concat(e,"' stream ").concat(r," transport closed")),f.Ro())})),p(u,nu.EventType.ERROR,(t=>{d||(d=!0,fu(pm,"RPC '".concat(e,"' stream ").concat(r," transport errored:"),t),f.Ro(new wu(yu.UNAVAILABLE,"The operation could not be completed")))})),p(u,nu.EventType.MESSAGE,(t=>{var n;if(!d){const i=t.data[0];gu(!!i);const s=i,a=s.error||(null===(n=s[0])||void 0===n?void 0:n.error);if(a){hu(pm,"RPC '".concat(e,"' stream ").concat(r," received error:"),a);const t=a.status;let n=function(e){const t=xf[e];if(void 0!==t)return Pf(t)}(t),i=a.message;void 0===n&&(n=yu.INTERNAL,i="Unknown error status: "+t+" with message "+a.message),d=!0,f.Ro(new wu(n,i)),u.close()}else hu(pm,"RPC '".concat(e,"' stream ").concat(r," received:"),i),f.Vo(i)}})),p(a,Zc.STAT_EVENT,(t=>{t.stat===eu.PROXY?hu(pm,"RPC '".concat(e,"' stream ").concat(r," detected buffering proxy")):t.stat===eu.NOPROXY&&hu(pm,"RPC '".concat(e,"' stream ").concat(r," detected no buffering proxy"))})),setTimeout((()=>{f.Ao()}),0),f}}function gm(){return"undefined"!=typeof document?document:null}function vm(e){return new Xf(e,!0)}class ym{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1e3,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1.5,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:6e4;this.si=e,this.timerId=t,this.Fo=n,this.Mo=r,this.xo=i,this.Oo=0,this.No=null,this.Bo=Date.now(),this.reset()}reset(){this.Oo=0}Lo(){this.Oo=this.xo}ko(e){this.cancel();const t=Math.floor(this.Oo+this.qo()),n=Math.max(0,Date.now()-this.Bo),r=Math.max(0,t-n);r>0&&hu("ExponentialBackoff","Backing off for ".concat(r," ms (base delay: ").concat(this.Oo," ms, delay with jitter: ").concat(t," ms, last attempt: ").concat(n," ms ago)")),this.No=this.si.enqueueAfterDelay(this.timerId,r,(()=>(this.Bo=Date.now(),e()))),this.Oo*=this.Mo,this.Oo<this.Fo&&(this.Oo=this.Fo),this.Oo>this.xo&&(this.Oo=this.xo)}Qo(){null!==this.No&&(this.No.skipDelay(),this.No=null)}cancel(){null!==this.No&&(this.No.cancel(),this.No=null)}qo(){return(Math.random()-.5)*this.Oo}}class wm{constructor(e,t,n,r,i,s,a,o){this.si=e,this.Ko=n,this.$o=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.Uo=0,this.Wo=null,this.Go=null,this.stream=null,this.zo=new ym(e,t)}jo(){return 1===this.state||5===this.state||this.Ho()}Ho(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.Jo()}async stop(){this.jo()&&await this.close(0)}Yo(){this.state=0,this.zo.reset()}Zo(){this.Ho()&&null===this.Wo&&(this.Wo=this.si.enqueueAfterDelay(this.Ko,6e4,(()=>this.Xo())))}e_(e){this.t_(),this.stream.send(e)}async Xo(){if(this.Ho())return this.close(0)}t_(){this.Wo&&(this.Wo.cancel(),this.Wo=null)}n_(){this.Go&&(this.Go.cancel(),this.Go=null)}async close(e,t){this.t_(),this.n_(),this.zo.cancel(),this.Uo++,4!==e?this.zo.reset():t&&t.code===yu.RESOURCE_EXHAUSTED?(du(t.toString()),du("Using maximum backoff delay to prevent overloading the backend."),this.zo.Lo()):t&&t.code===yu.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.r_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Io(t)}r_(){}auth(){this.state=1;const e=this.i_(this.Uo),t=this.Uo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((e=>{let[n,r]=e;this.Uo===t&&this.s_(n,r)}),(t=>{e((()=>{const e=new wu(yu.UNKNOWN,"Fetching auth token failed: "+t.message);return this.o_(e)}))}))}s_(e,t){const n=this.i_(this.Uo);this.stream=this.__(e,t),this.stream.ho((()=>{n((()=>(this.state=2,this.Go=this.si.enqueueAfterDelay(this.$o,1e4,(()=>(this.Ho()&&(this.state=3),Promise.resolve()))),this.listener.ho())))})),this.stream.Io((e=>{n((()=>this.o_(e)))})),this.stream.onMessage((e=>{n((()=>this.onMessage(e)))}))}Jo(){this.state=5,this.zo.ko((async()=>{this.state=0,this.start()}))}o_(e){return hu("PersistentStream","close with error: ".concat(e)),this.stream=null,this.close(4,e)}i_(e){return t=>{this.si.enqueueAndForget((()=>this.Uo===e?t():(hu("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}}class bm extends wm{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}__(e,t){return this.connection.vo("Listen",e,t)}onMessage(e){this.zo.reset();const t=function(e,t){let n;if("targetChange"in t){t.targetChange;const r=function(e){return"NO_CHANGE"===e?0:"ADD"===e?1:"REMOVE"===e?2:"CURRENT"===e?3:"RESET"===e?4:mu()}(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],s=function(e,t){return e.useProto3Json?(gu(void 0===t||"string"==typeof t),fh.fromBase64String(t||"")):(gu(void 0===t||t instanceof Uint8Array),fh.fromUint8Array(t||new Uint8Array))}(e,t.targetChange.resumeToken),a=t.targetChange.cause,o=a&&function(e){const t=void 0===e.code?yu.UNKNOWN:Pf(e.code);return new wu(t,e.message||"")}(a);n=new qf(r,i,s,o||null)}else if("documentChange"in t){t.documentChange;const r=t.documentChange;r.document,r.document.name,r.document.updateTime;const i=ap(e,r.document.name),s=np(r.document.updateTime),a=r.document.createTime?np(r.document.createTime):Du.min(),o=new Uh({mapValue:{fields:r.document.fields}}),l=Bh.newFoundDocument(i,s,a,o),c=r.targetIds||[],u=r.removedTargetIds||[];n=new Bf(c,u,l.key,l)}else if("documentDelete"in t){t.documentDelete;const r=t.documentDelete;r.document;const i=ap(e,r.document),s=r.readTime?np(r.readTime):Du.min(),a=Bh.newNoDocument(i,s),o=r.removedTargetIds||[];n=new Bf([],o,a.key,a)}else if("documentRemove"in t){t.documentRemove;const r=t.documentRemove;r.document;const i=ap(e,r.document),s=r.removedTargetIds||[];n=new Bf([],s,i,null)}else{if(!("filter"in t))return mu();{t.filter;const e=t.filter;e.targetId;const{count:r=0,unchangedNames:i}=e,s=new Cf(r,i),a=e.targetId;n=new zf(a,s)}}return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return Du.min();const t=e.targetChange;return t.targetIds&&t.targetIds.length?Du.min():t.readTime?np(t.readTime):Du.min()}(e);return this.listener.a_(t,n)}u_(e){const t={};t.database=cp(this.serializer),t.addTarget=function(e,t){let n;const r=t.target;if(n=pd(r)?{documents:fp(e,r)}:{query:pp(e,r)},n.targetId=t.targetId,t.resumeToken.approximateByteSize()>0){n.resumeToken=ep(e,t.resumeToken);const r=Jf(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(t.snapshotVersion.compareTo(Du.min())>0){n.readTime=Zf(e,t.snapshotVersion.toTimestamp());const r=Jf(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);const n=function(e,t){const n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return mu()}}(t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.serializer,e);n&&(t.labels=n),this.e_(t)}c_(e){const t={};t.database=cp(this.serializer),t.removeTarget=e,this.e_(t)}}class _m extends wm{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i,this.l_=!1}get h_(){return this.l_}start(){this.l_=!1,this.lastStreamToken=void 0,super.start()}r_(){this.l_&&this.P_([])}__(e,t){return this.connection.vo("Write",e,t)}onMessage(e){if(gu(!!e.streamToken),this.lastStreamToken=e.streamToken,this.l_){this.zo.reset();const t=function(e,t){return e&&e.length>0?(gu(void 0!==t),e.map((e=>function(e,t){let n=e.updateTime?np(e.updateTime):np(t);return n.isEqual(Du.min())&&(n=np(t)),new lf(n,e.transformResults||[])}(e,t)))):[]}(e.writeResults,e.commitTime),n=np(e.commitTime);return this.listener.I_(n,t)}return gu(!e.writeResults||0===e.writeResults.length),this.l_=!0,this.listener.T_()}E_(){const e={};e.database=cp(this.serializer),this.e_(e)}P_(e){const t={streamToken:this.lastStreamToken,writes:e.map((e=>dp(this.serializer,e)))};this.e_(t)}}class Em extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.d_=!1}A_(){if(this.d_)throw new wu(yu.FAILED_PRECONDITION,"The client has already been terminated.")}wo(e,t,n){return this.A_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((r=>{let[i,s]=r;return this.connection.wo(e,t,n,i,s)})).catch((e=>{throw"FirebaseError"===e.name?(e.code===yu.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new wu(yu.UNKNOWN,e.toString())}))}Co(e,t,n,r){return this.A_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((i=>{let[s,a]=i;return this.connection.Co(e,t,n,s,a,r)})).catch((e=>{throw"FirebaseError"===e.name?(e.code===yu.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new wu(yu.UNKNOWN,e.toString())}))}terminate(){this.d_=!0}}class Sm{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.V_=0,this.m_=null,this.f_=!0}g_(){0===this.V_&&(this.p_("Unknown"),this.m_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,(()=>(this.m_=null,this.y_("Backend didn't respond within 10 seconds."),this.p_("Offline"),Promise.resolve()))))}w_(e){"Online"===this.state?this.p_("Unknown"):(this.V_++,this.V_>=1&&(this.S_(),this.y_("Connection failed 1 times. Most recent error: ".concat(e.toString())),this.p_("Offline")))}set(e){this.S_(),this.V_=0,"Online"===e&&(this.f_=!1),this.p_(e)}p_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}y_(e){const t="Could not reach Cloud Firestore backend. ".concat(e,"\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.");this.f_?(du(t),this.f_=!1):hu("OnlineStateTracker",t)}S_(){null!==this.m_&&(this.m_.cancel(),this.m_=null)}}class km{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.b_=[],this.D_=new Map,this.C_=new Set,this.v_=[],this.F_=i,this.F_.ro((e=>{n.enqueueAndForget((async()=>{Om(this)&&(hu("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=vu(e);t.C_.add(4),await Tm(t),t.M_.set("Unknown"),t.C_.delete(4),await Im(t)}(this))}))})),this.M_=new Sm(n,r)}}async function Im(e){if(Om(e))for(const t of e.v_)await t(!0)}async function Tm(e){for(const t of e.v_)await t(!1)}function Cm(e,t){const n=vu(e);n.D_.has(t.targetId)||(n.D_.set(t.targetId,t),Rm(n)?Pm(n):Xm(n).Ho()&&Nm(n,t))}function xm(e,t){const n=vu(e),r=Xm(n);n.D_.delete(t),r.Ho()&&Am(n,t),0===n.D_.size&&(r.Ho()?r.Zo():Om(n)&&n.M_.set("Unknown"))}function Nm(e,t){if(e.x_.Oe(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(Du.min())>0){const n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(n)}Xm(e).u_(t)}function Am(e,t){e.x_.Oe(t),Xm(e).c_(t)}function Pm(e){e.x_=new Wf({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),_t:t=>e.D_.get(t)||null,nt:()=>e.datastore.serializer.databaseId}),Xm(e).start(),e.M_.g_()}function Rm(e){return Om(e)&&!Xm(e).jo()&&e.D_.size>0}function Om(e){return 0===vu(e).C_.size}function Dm(e){e.x_=void 0}async function Lm(e){e.D_.forEach(((t,n)=>{Nm(e,t)}))}async function Mm(e,t){Dm(e),Rm(e)?(e.M_.w_(t),Pm(e)):e.M_.set("Unknown")}async function jm(e,t,n){if(e.M_.set("Online"),t instanceof qf&&2===t.state&&t.cause)try{await async function(e,t){const n=t.cause;for(const r of t.targetIds)e.D_.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.D_.delete(r),e.x_.removeTarget(r))}(e,t)}catch(n){hu("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await Fm(e,n)}else if(t instanceof Bf?e.x_.$e(t):t instanceof zf?e.x_.Je(t):e.x_.Ge(t),!n.isEqual(Du.min()))try{const t=await Zp(e.localStore);n.compareTo(t)>=0&&await function(e,t){const n=e.x_.it(t);return n.targetChanges.forEach(((n,r)=>{if(n.resumeToken.approximateByteSize()>0){const i=e.D_.get(r);i&&e.D_.set(r,i.withResumeToken(n.resumeToken,t))}})),n.targetMismatches.forEach(((t,n)=>{const r=e.D_.get(t);if(!r)return;e.D_.set(t,r.withResumeToken(fh.EMPTY_BYTE_STRING,r.snapshotVersion)),Am(e,t);const i=new Ip(r.target,t,n,r.sequenceNumber);Nm(e,i)})),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){hu("RemoteStore","Failed to raise snapshot:",t),await Fm(e,t)}}async function Fm(e,t,n){if(!$u(t))throw t;e.C_.add(1),await Tm(e),e.M_.set("Offline"),n||(n=()=>Zp(e.localStore)),e.asyncQueue.enqueueRetryable((async()=>{hu("RemoteStore","Retrying IndexedDB access"),await n(),e.C_.delete(1),await Im(e)}))}function Um(e,t){return t().catch((n=>Fm(e,n,t)))}async function Vm(e){const t=vu(e),n=Jm(t);let r=t.b_.length>0?t.b_[t.b_.length-1].batchId:-1;for(;Bm(t);)try{const e=await tm(t.localStore,r);if(null===e){0===t.b_.length&&n.Zo();break}r=e.batchId,zm(t,e)}catch(e){await Fm(t,e)}qm(t)&&Hm(t)}function Bm(e){return Om(e)&&e.b_.length<10}function zm(e,t){e.b_.push(t);const n=Jm(e);n.Ho()&&n.h_&&n.P_(t.mutations)}function qm(e){return Om(e)&&!Jm(e).jo()&&e.b_.length>0}function Hm(e){Jm(e).start()}async function Wm(e){Jm(e).E_()}async function Km(e){const t=Jm(e);for(const n of e.b_)t.P_(n.mutations)}async function Gm(e,t,n){const r=e.b_.shift(),i=If.from(r,t,n);await Um(e,(()=>e.remoteSyncer.applySuccessfulWrite(i))),await Vm(e)}async function Qm(e,t){t&&Jm(e).h_&&await async function(e,t){if(function(e){return Af(e)&&e!==yu.ABORTED}(t.code)){const n=e.b_.shift();Jm(e).Yo(),await Um(e,(()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t))),await Vm(e)}}(e,t),qm(e)&&Hm(e)}async function $m(e,t){const n=vu(e);n.asyncQueue.verifyOperationInProgress(),hu("RemoteStore","RemoteStore received new credentials");const r=Om(n);n.C_.add(3),await Tm(n),r&&n.M_.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.C_.delete(3),await Im(n)}async function Ym(e,t){const n=vu(e);t?(n.C_.delete(2),await Im(n)):t||(n.C_.add(2),await Tm(n),n.M_.set("Unknown"))}function Xm(e){return e.O_||(e.O_=function(e,t,n){const r=vu(e);return r.A_(),new bm(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(e.datastore,e.asyncQueue,{ho:Lm.bind(null,e),Io:Mm.bind(null,e),a_:jm.bind(null,e)}),e.v_.push((async t=>{t?(e.O_.Yo(),Rm(e)?Pm(e):e.M_.set("Unknown")):(await e.O_.stop(),Dm(e))}))),e.O_}function Jm(e){return e.N_||(e.N_=function(e,t,n){const r=vu(e);return r.A_(),new _m(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(e.datastore,e.asyncQueue,{ho:Wm.bind(null,e),Io:Qm.bind(null,e),T_:Km.bind(null,e),I_:Gm.bind(null,e)}),e.v_.push((async t=>{t?(e.N_.Yo(),await Vm(e)):(await e.N_.stop(),e.b_.length>0&&(hu("RemoteStore","Stopping write stream with ".concat(e.b_.length," pending writes")),e.b_=[]))}))),e.N_}class Zm{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new bu,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((e=>{}))}get promise(){return this.deferred.promise}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,a=new Zm(e,t,s,r,i);return a.start(n),a}start(e){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new wu(yu.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget((()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then((e=>this.deferred.resolve(e)))):Promise.resolve()))}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function eg(e,t){if(du("AsyncQueue","".concat(t,": ").concat(e)),$u(e))return new wu(yu.UNAVAILABLE,"".concat(t,": ").concat(e));throw e}class tg{constructor(e){this.comparator=e?(t,n)=>e(t,n)||Uu.comparator(t.key,n.key):(e,t)=>Uu.comparator(e.key,t.key),this.keyedMap=Md(),this.sortedSet=new ah(this.comparator)}static emptySet(e){return new tg(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){const t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal(((t,n)=>(e(t),!1)))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){const t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof tg))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const e=[];return this.forEach((t=>{e.push(t.toString())})),0===e.length?"DocumentSet ()":"DocumentSet (\n "+e.join(" \n")+"\n)"}copy(e,t){const n=new tg;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class ng{constructor(){this.B_=new ah(Uu.comparator)}track(e){const t=e.doc.key,n=this.B_.get(t);n?0!==e.type&&3===n.type?this.B_=this.B_.insert(t,e):3===e.type&&1!==n.type?this.B_=this.B_.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.B_=this.B_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.B_=this.B_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.B_=this.B_.remove(t):1===e.type&&2===n.type?this.B_=this.B_.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.B_=this.B_.insert(t,{type:2,doc:e.doc}):mu():this.B_=this.B_.insert(t,e)}L_(){const e=[];return this.B_.inorderTraversal(((t,n)=>{e.push(n)})),e}}class rg{constructor(e,t,n,r,i,s,a,o,l){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=l}static fromInitialDocuments(e,t,n,r,i){const s=[];return t.forEach((e=>{s.push({type:0,doc:e})})),new rg(e,t,tg.emptySet(t),s,n,r,!0,!1,i)}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)&&Id(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r].type!==n[r].type||!t[r].doc.isEqual(n[r].doc))return!1;return!0}}class ig{constructor(){this.k_=void 0,this.listeners=[]}}class sg{constructor(){this.queries=new Rd((e=>Td(e)),Id),this.onlineState="Unknown",this.q_=new Set}}async function ag(e,t){const n=vu(e),r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new ig),i)try{s.k_=await n.onListen(r)}catch(e){const n=eg(e,"Initialization of query '".concat(Cd(t.query),"' failed"));return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.Q_(n.onlineState),s.k_&&t.K_(s.k_)&&ug(n)}async function og(e,t){const n=vu(e),r=t.query;let i=!1;const s=n.queries.get(r);if(s){const e=s.listeners.indexOf(t);e>=0&&(s.listeners.splice(e,1),i=0===s.listeners.length)}if(i)return n.queries.delete(r),n.onUnlisten(r)}function lg(e,t){const n=vu(e);let r=!1;for(const i of t){const e=i.query,t=n.queries.get(e);if(t){for(const e of t.listeners)e.K_(i)&&(r=!0);t.k_=i}}r&&ug(n)}function cg(e,t,n){const r=vu(e),i=r.queries.get(t);if(i)for(const s of i.listeners)s.onError(n);r.queries.delete(t)}function ug(e){e.q_.forEach((e=>{e.next()}))}class hg{constructor(e,t,n){this.query=e,this.U_=t,this.W_=!1,this.G_=null,this.onlineState="Unknown",this.options=n||{}}K_(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new rg(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.W_?this.z_(e)&&(this.U_.next(e),t=!0):this.j_(e,this.onlineState)&&(this.H_(e),t=!0),this.G_=e,t}onError(e){this.U_.error(e)}Q_(e){this.onlineState=e;let t=!1;return this.G_&&!this.W_&&this.j_(this.G_,e)&&(this.H_(this.G_),t=!0),t}j_(e,t){if(!e.fromCache)return!0;const n="Offline"!==t;return(!this.options.J_||!n)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}z_(e){if(e.docChanges.length>0)return!0;const t=this.G_&&this.G_.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}H_(e){e=rg.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.W_=!0,this.U_.next(e)}}class dg{constructor(e){this.key=e}}class fg{constructor(e){this.key=e}}class pg{constructor(e,t){this.query=e,this.ia=t,this.sa=null,this.hasCachedResults=!1,this.current=!1,this.oa=qd(),this.mutatedKeys=qd(),this._a=Ad(e),this.aa=new tg(this._a)}get ua(){return this.ia}ca(e,t){const n=t?t.la:new ng,r=t?t.aa:this.aa;let i=t?t.mutatedKeys:this.mutatedKeys,s=r,a=!1;const o="F"===this.query.limitType&&r.size===this.query.limit?r.last():null,l="L"===this.query.limitType&&r.size===this.query.limit?r.first():null;if(e.inorderTraversal(((e,t)=>{const c=r.get(e),u=xd(this.query,t)?t:null,h=!!c&&this.mutatedKeys.has(c.key),d=!!u&&(u.hasLocalMutations||this.mutatedKeys.has(u.key)&&u.hasCommittedMutations);let f=!1;c&&u?c.data.isEqual(u.data)?h!==d&&(n.track({type:3,doc:u}),f=!0):this.ha(c,u)||(n.track({type:2,doc:u}),f=!0,(o&&this._a(u,o)>0||l&&this._a(u,l)<0)&&(a=!0)):!c&&u?(n.track({type:0,doc:u}),f=!0):c&&!u&&(n.track({type:1,doc:c}),f=!0,(o||l)&&(a=!0)),f&&(u?(s=s.add(u),i=d?i.add(e):i.delete(e)):(s=s.delete(e),i=i.delete(e)))})),null!==this.query.limit)for(;s.size>this.query.limit;){const e="F"===this.query.limitType?s.last():s.first();s=s.delete(e.key),i=i.delete(e.key),n.track({type:1,doc:e})}return{aa:s,la:n,Zi:a,mutatedKeys:i}}ha(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){const r=this.aa;this.aa=e.aa,this.mutatedKeys=e.mutatedKeys;const i=e.la.L_();i.sort(((e,t)=>function(e,t){const n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return mu()}};return n(e)-n(t)}(e.type,t.type)||this._a(e.doc,t.doc))),this.Pa(n);const s=t?this.Ia():[],a=0===this.oa.size&&this.current?1:0,o=a!==this.sa;return this.sa=a,0!==i.length||o?{snapshot:new rg(this.query,e.aa,r,i,e.mutatedKeys,0===a,o,!1,!!n&&n.resumeToken.approximateByteSize()>0),Ta:s}:{Ta:s}}Q_(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({aa:this.aa,la:new ng,mutatedKeys:this.mutatedKeys,Zi:!1},!1)):{Ta:[]}}Ea(e){return!this.ia.has(e)&&!!this.aa.has(e)&&!this.aa.get(e).hasLocalMutations}Pa(e){e&&(e.addedDocuments.forEach((e=>this.ia=this.ia.add(e))),e.modifiedDocuments.forEach((e=>{})),e.removedDocuments.forEach((e=>this.ia=this.ia.delete(e))),this.current=e.current)}Ia(){if(!this.current)return[];const e=this.oa;this.oa=qd(),this.aa.forEach((e=>{this.Ea(e.key)&&(this.oa=this.oa.add(e.key))}));const t=[];return e.forEach((e=>{this.oa.has(e)||t.push(new fg(e))})),this.oa.forEach((n=>{e.has(n)||t.push(new dg(n))})),t}da(e){this.ia=e.ls,this.oa=qd();const t=this.ca(e.documents);return this.applyChanges(t,!0)}Aa(){return rg.fromInitialDocuments(this.query,this.aa,this.mutatedKeys,0===this.sa,this.hasCachedResults)}}class mg{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class gg{constructor(e){this.key=e,this.Ra=!1}}class vg{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.Va={},this.ma=new Rd((e=>Td(e)),Id),this.fa=new Map,this.ga=new Set,this.pa=new ah(Uu.comparator),this.ya=new Map,this.wa=new Fp,this.Sa={},this.ba=new Map,this.Da=Rp.Nn(),this.onlineState="Unknown",this.Ca=void 0}get isPrimaryClient(){return!0===this.Ca}}async function yg(e,t){const n=Mg(e);let r,i;const s=n.ma.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.Aa();else{const e=await nm(n.localStore,_d(t)),s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await wg(n,t,r,"current"===s,e.resumeToken),n.isPrimaryClient&&Cm(n.remoteStore,e)}return i}async function wg(e,t,n,r,i){e.va=(t,n,r)=>async function(e,t,n,r){let i=t.view.ca(n);i.Zi&&(i=await im(e.localStore,t.query,!1).then((e=>{let{documents:n}=e;return t.view.ca(n,i)})));const s=r&&r.targetChanges.get(t.targetId),a=t.view.applyChanges(i,e.isPrimaryClient,s);return Ag(e,t.targetId,a.Ta),a.snapshot}(e,t,n,r);const s=await im(e.localStore,t,!0),a=new pg(t,s.ls),o=a.ca(s.documents),l=Vf.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,i),c=a.applyChanges(o,e.isPrimaryClient,l);Ag(e,n,c.Ta);const u=new mg(t,n,a);return e.ma.set(t,u),e.fa.has(n)?e.fa.get(n).push(t):e.fa.set(n,[t]),c.snapshot}async function bg(e,t){const n=vu(e),r=n.ma.get(t),i=n.fa.get(r.targetId);if(i.length>1)return n.fa.set(r.targetId,i.filter((e=>!Id(e,t)))),void n.ma.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await rm(n.localStore,r.targetId,!1).then((()=>{n.sharedClientState.clearQueryState(r.targetId),xm(n.remoteStore,r.targetId),xg(n,r.targetId)})).catch(Gu)):(xg(n,r.targetId),await rm(n.localStore,r.targetId,!0))}async function _g(e,t){const n=vu(e);try{const e=await function(e,t){const n=vu(e),r=t.snapshotVersion;let i=n.ts;return n.persistence.runTransaction("Apply remote event","readwrite-primary",(e=>{const s=n.ss.newChangeBuffer({trackRemovals:!0});i=n.ts;const a=[];t.targetChanges.forEach(((s,o)=>{const l=i.get(o);if(!l)return;a.push(n.qr.removeMatchingKeys(e,s.removedDocuments,o).next((()=>n.qr.addMatchingKeys(e,s.addedDocuments,o))));let c=l.withSequenceNumber(e.currentSequenceNumber);null!==t.targetMismatches.get(o)?c=c.withResumeToken(fh.EMPTY_BYTE_STRING,Du.min()).withLastLimboFreeSnapshotVersion(Du.min()):s.resumeToken.approximateByteSize()>0&&(c=c.withResumeToken(s.resumeToken,r)),i=i.insert(o,c),function(e,t,n){return 0===e.resumeToken.approximateByteSize()||t.snapshotVersion.toMicroseconds()-e.snapshotVersion.toMicroseconds()>=3e8||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0}(l,c,s)&&a.push(n.qr.updateTargetData(e,c))}));let o=Dd(),l=qd();if(t.documentUpdates.forEach((r=>{t.resolvedLimboDocuments.has(r)&&a.push(n.persistence.referenceDelegate.updateLimboDocument(e,r))})),a.push(em(e,s,t.documentUpdates).next((e=>{o=e.us,l=e.cs}))),!r.isEqual(Du.min())){const t=n.qr.getLastRemoteSnapshotVersion(e).next((t=>n.qr.setTargetsMetadata(e,e.currentSequenceNumber,r)));a.push(t)}return Qu.waitFor(a).next((()=>s.apply(e))).next((()=>n.localDocuments.getLocalViewOfDocuments(e,o,l))).next((()=>o))})).then((e=>(n.ts=i,e)))}(n.localStore,t);t.targetChanges.forEach(((e,t)=>{const r=n.ya.get(t);r&&(gu(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),e.addedDocuments.size>0?r.Ra=!0:e.modifiedDocuments.size>0?gu(r.Ra):e.removedDocuments.size>0&&(gu(r.Ra),r.Ra=!1))})),await Og(n,e,t)}catch(e){await Gu(e)}}function Eg(e,t,n){const r=vu(e);if(r.isPrimaryClient&&0===n||!r.isPrimaryClient&&1===n){const e=[];r.ma.forEach(((n,r)=>{const i=r.view.Q_(t);i.snapshot&&e.push(i.snapshot)})),function(e,t){const n=vu(e);n.onlineState=t;let r=!1;n.queries.forEach(((e,n)=>{for(const i of n.listeners)i.Q_(t)&&(r=!0)})),r&&ug(n)}(r.eventManager,t),e.length&&r.Va.a_(e),r.onlineState=t,r.isPrimaryClient&&r.sharedClientState.setOnlineState(t)}}async function Sg(e,t,n){const r=vu(e);r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.ya.get(t),s=i&&i.key;if(s){let e=new ah(Uu.comparator);e=e.insert(s,Bh.newNoDocument(s,Du.min()));const n=qd().add(s),i=new Uf(Du.min(),new Map,new ah(Pu),e,n);await _g(r,i),r.pa=r.pa.remove(s),r.ya.delete(t),Rg(r)}else await rm(r.localStore,t,!1).then((()=>xg(r,t,n))).catch(Gu)}async function kg(e,t){const n=vu(e),r=t.batch.batchId;try{const e=await function(e,t){const n=vu(e);return n.persistence.runTransaction("Acknowledge batch","readwrite-primary",(e=>{const r=t.batch.keys(),i=n.ss.newChangeBuffer({trackRemovals:!0});return function(e,t,n,r){const i=n.batch,s=i.keys();let a=Qu.resolve();return s.forEach((e=>{a=a.next((()=>r.getEntry(t,e))).next((t=>{const s=n.docVersions.get(e);gu(null!==s),t.version.compareTo(s)<0&&(i.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),r.addEntry(t)))}))})),a.next((()=>e.mutationQueue.removeMutationBatch(t,i)))}(n,e,t,i).next((()=>i.apply(e))).next((()=>n.mutationQueue.performConsistencyCheck(e))).next((()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t.batch.batchId))).next((()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=qd();for(let n=0;n<e.mutationResults.length;++n)e.mutationResults[n].transformResults.length>0&&(t=t.add(e.batch.mutations[n].key));return t}(t)))).next((()=>n.localDocuments.getDocuments(e,r)))}))}(n.localStore,t);Cg(n,r,null),Tg(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await Og(n,e)}catch(e){await Gu(e)}}async function Ig(e,t,n){const r=vu(e);try{const e=await function(e,t){const n=vu(e);return n.persistence.runTransaction("Reject batch","readwrite-primary",(e=>{let r;return n.mutationQueue.lookupMutationBatch(e,t).next((t=>(gu(null!==t),r=t.keys(),n.mutationQueue.removeMutationBatch(e,t)))).next((()=>n.mutationQueue.performConsistencyCheck(e))).next((()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t))).next((()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,r))).next((()=>n.localDocuments.getDocuments(e,r)))}))}(r.localStore,t);Cg(r,t,n),Tg(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await Og(r,e)}catch(n){await Gu(n)}}function Tg(e,t){(e.ba.get(t)||[]).forEach((e=>{e.resolve()})),e.ba.delete(t)}function Cg(e,t,n){const r=vu(e);let i=r.Sa[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.Sa[r.currentUser.toKey()]=i}}function xg(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;e.sharedClientState.removeLocalQueryTarget(t);for(const r of e.fa.get(t))e.ma.delete(r),n&&e.Va.Fa(r,n);e.fa.delete(t),e.isPrimaryClient&&e.wa.Rr(t).forEach((t=>{e.wa.containsKey(t)||Ng(e,t)}))}function Ng(e,t){e.ga.delete(t.path.canonicalString());const n=e.pa.get(t);null!==n&&(xm(e.remoteStore,n),e.pa=e.pa.remove(t),e.ya.delete(n),Rg(e))}function Ag(e,t,n){for(const r of n)r instanceof dg?(e.wa.addReference(r.key,t),Pg(e,r)):r instanceof fg?(hu("SyncEngine","Document no longer in limbo: "+r.key),e.wa.removeReference(r.key,t),e.wa.containsKey(r.key)||Ng(e,r.key)):mu()}function Pg(e,t){const n=t.key,r=n.path.canonicalString();e.pa.get(n)||e.ga.has(r)||(hu("SyncEngine","New document in limbo: "+n),e.ga.add(r),Rg(e))}function Rg(e){for(;e.ga.size>0&&e.pa.size<e.maxConcurrentLimboResolutions;){const t=e.ga.values().next().value;e.ga.delete(t);const n=new Uu(Mu.fromString(t)),r=e.Da.next();e.ya.set(r,new gg(n)),e.pa=e.pa.insert(n,r),Cm(e.remoteStore,new Ip(_d(vd(n.path)),r,"TargetPurposeLimboResolution",Yu._e))}}async function Og(e,t,n){const r=vu(e),i=[],s=[],a=[];r.ma.isEmpty()||(r.ma.forEach(((e,o)=>{a.push(r.va(o,t,n).then((e=>{if((e||n)&&r.isPrimaryClient&&r.sharedClientState.updateQueryState(o.targetId,(null==e?void 0:e.fromCache)?"not-current":"current"),e){i.push(e);const t=Gp.Qi(o.targetId,e);s.push(t)}})))})),await Promise.all(a),r.Va.a_(i),await async function(e,t){const n=vu(e);try{await n.persistence.runTransaction("notifyLocalViewChanges","readwrite",(e=>Qu.forEach(t,(t=>Qu.forEach(t.ki,(r=>n.persistence.referenceDelegate.addReference(e,t.targetId,r))).next((()=>Qu.forEach(t.qi,(r=>n.persistence.referenceDelegate.removeReference(e,t.targetId,r)))))))))}catch(e){if(!$u(e))throw e;hu("LocalStore","Failed to update sequence numbers: "+e)}for(const r of t){const e=r.targetId;if(!r.fromCache){const t=n.ts.get(e),r=t.snapshotVersion,i=t.withLastLimboFreeSnapshotVersion(r);n.ts=n.ts.insert(e,i)}}}(r.localStore,s))}async function Dg(e,t){const n=vu(e);if(!n.currentUser.isEqual(t)){hu("SyncEngine","User change. New user:",t.toKey());const e=await Jp(n.localStore,t);n.currentUser=t,function(e,t){e.ba.forEach((e=>{e.forEach((e=>{e.reject(new wu(yu.CANCELLED,t))}))})),e.ba.clear()}(n,"'waitForPendingWrites' promise is rejected due to a user change."),n.sharedClientState.handleUserChange(t,e.removedBatchIds,e.addedBatchIds),await Og(n,e._s)}}function Lg(e,t){const n=vu(e),r=n.ya.get(t);if(r&&r.Ra)return qd().add(r.key);{let e=qd();const r=n.fa.get(t);if(!r)return e;for(const t of r){const r=n.ma.get(t);e=e.unionWith(r.view.ua)}return e}}function Mg(e){const t=vu(e);return t.remoteStore.remoteSyncer.applyRemoteEvent=_g.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=Lg.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=Sg.bind(null,t),t.Va.a_=lg.bind(null,t.eventManager),t.Va.Fa=cg.bind(null,t.eventManager),t}function jg(e){const t=vu(e);return t.remoteStore.remoteSyncer.applySuccessfulWrite=kg.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=Ig.bind(null,t),t}class Fg{constructor(){this.synchronizeTabs=!1}async initialize(e){this.serializer=vm(e.databaseInfo.databaseId),this.sharedClientState=this.createSharedClientState(e),this.persistence=this.createPersistence(e),await this.persistence.start(),this.localStore=this.createLocalStore(e),this.gcScheduler=this.createGarbageCollectionScheduler(e,this.localStore),this.indexBackfillerScheduler=this.createIndexBackfillerScheduler(e,this.localStore)}createGarbageCollectionScheduler(e,t){return null}createIndexBackfillerScheduler(e,t){return null}createLocalStore(e){return Xp(this.persistence,new $p,e.initialUser,this.serializer)}createPersistence(e){return new Hp(Kp.jr,this.serializer)}createSharedClientState(e){return new om}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class Ug{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>Eg(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=Dg.bind(null,this.syncEngine),await Ym(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new sg}createDatastore(e){const t=vm(e.databaseInfo.databaseId),n=function(e){return new mm(e)}(e.databaseInfo);return function(e,t,n,r){return new Em(e,t,n,r)}(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return function(e,t,n,r,i){return new km(e,t,n,r,i)}(this.localStore,this.datastore,e.asyncQueue,(e=>Eg(this.syncEngine,e,0)),cm.D()?new cm:new lm)}createSyncEngine(e,t){return function(e,t,n,r,i,s,a){const o=new vg(e,t,n,r,i,s);return a&&(o.Ca=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=vu(e);hu("RemoteStore","RemoteStore shutting down."),t.C_.add(5),await Tm(t),t.F_.shutdown(),t.M_.set("Unknown")}(this.remoteStore)}}class Vg{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Oa(this.observer.next,e)}error(e){this.observer.error?this.Oa(this.observer.error,e):du("Uncaught Error in snapshot listener:",e.toString())}Na(){this.muted=!0}Oa(e,t){this.muted||setTimeout((()=>{this.muted||e(t)}),0)}}class Bg{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=ou.UNAUTHENTICATED,this.clientId=Au.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,(async e=>{hu("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e})),this.appCheckCredentials.start(n,(e=>(hu("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user))))}async getConfiguration(){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}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new wu(yu.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const e=new bu;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(t){const n=eg(t,"Failed to shutdown persistence");e.reject(n)}})),e.promise}}async function zg(e,t){e.asyncQueue.verifyOperationInProgress(),hu("FirestoreClient","Initializing OfflineComponentProvider");const n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener((async e=>{r.isEqual(e)||(await Jp(t.localStore,e),r=e)})),t.persistence.setDatabaseDeletedListener((()=>e.terminate())),e._offlineComponents=t}async function qg(e,t){e.asyncQueue.verifyOperationInProgress();const n=await Wg(e);hu("FirestoreClient","Initializing OnlineComponentProvider");const r=await e.getConfiguration();await t.initialize(n,r),e.setCredentialChangeListener((e=>$m(t.remoteStore,e))),e.setAppCheckTokenChangeListener(((e,n)=>$m(t.remoteStore,n))),e._onlineComponents=t}function Hg(e){return"FirebaseError"===e.name?e.code===yu.FAILED_PRECONDITION||e.code===yu.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}async function Wg(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){hu("FirestoreClient","Using user provided OfflineComponentProvider");try{await zg(e,e._uninitializedComponentsProvider._offline)}catch(t){const n=t;if(!Hg(n))throw n;fu("Error using user provided cache. Falling back to memory cache: "+n),await zg(e,new Fg)}}else hu("FirestoreClient","Using default OfflineComponentProvider"),await zg(e,new Fg);return e._offlineComponents}async function Kg(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(hu("FirestoreClient","Using user provided OnlineComponentProvider"),await qg(e,e._uninitializedComponentsProvider._online)):(hu("FirestoreClient","Using default OnlineComponentProvider"),await qg(e,new Ug))),e._onlineComponents}function Gg(e){return Kg(e).then((e=>e.syncEngine))}async function Qg(e){const t=await Kg(e),n=t.eventManager;return n.onListen=yg.bind(null,t.syncEngine),n.onUnlisten=bg.bind(null,t.syncEngine),n}function $g(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const r=new bu;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,i){const s=new Vg({next:n=>{t.enqueueAndForget((()=>og(e,a))),n.fromCache&&"server"===r.source?i.reject(new wu(yu.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.)')):i.resolve(n)},error:e=>i.reject(e)}),a=new hg(n,s,{includeMetadataChanges:!0,J_:!0});return ag(e,a)}(await Qg(e),e.asyncQueue,t,n,r))),r.promise}function Yg(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const Xg=new Map;function Jg(e,t,n){if(!n)throw new wu(yu.INVALID_ARGUMENT,"Function ".concat(e,"() cannot be called with an empty ").concat(t,"."))}function Zg(e){if(!Uu.isDocumentKey(e))throw new wu(yu.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but ".concat(e," has ").concat(e.length,"."))}function ev(e){if(Uu.isDocumentKey(e))throw new wu(yu.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but ".concat(e," has ").concat(e.length,"."))}function tv(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e="".concat(e.substring(0,20),"...")),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{const t=function(e){return e.constructor?e.constructor.name:null}(e);return t?"a custom ".concat(t," object"):"an object"}}return"function"==typeof e?"a function":mu()}function nv(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new wu(yu.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const n=tv(e);throw new wu(yu.INVALID_ARGUMENT,"Expected type '".concat(t.name,"', but it was: ").concat(n))}}return e}class rv{constructor(e){var t,n;if(void 0===e.host){if(void 0!==e.ssl)throw new wu(yu.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new wu(yu.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}(function(e,t,n,r){if(!0===t&&!0===r)throw new wu(yu.INVALID_ARGUMENT,"".concat(e," and ").concat(n," cannot be used together."))})("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=Yg(null!==(n=e.experimentalLongPollingOptions)&&void 0!==n?n:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new wu(yu.INVALID_ARGUMENT,"invalid long polling timeout: ".concat(e.timeoutSeconds," (must not be NaN)"));if(e.timeoutSeconds<5)throw new wu(yu.INVALID_ARGUMENT,"invalid long polling timeout: ".concat(e.timeoutSeconds," (minimum allowed value is 5)"));if(e.timeoutSeconds>30)throw new wu(yu.INVALID_ARGUMENT,"invalid long polling timeout: ".concat(e.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(e,t){return e.timeoutSeconds===t.timeoutSeconds}(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class iv{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new rv({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new wu(yu.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 void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new wu(yu.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 rv(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new Eu;switch(e.type){case"firstParty":return new Tu(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new wu(yu.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=Xg.get(e);t&&(hu("ComponentProvider","Removing Datastore"),Xg.delete(e),t.terminate())}(this),Promise.resolve()}}function sv(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};var i;const s=(e=nv(e,iv))._getSettings(),a="".concat(t,":").concat(n);if("firestore.googleapis.com"!==s.host&&s.host!==a&&fu("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),e._setSettings(Object.assign(Object.assign({},s),{host:a,ssl:!1})),r.mockUserToken){let t,n;if("string"==typeof r.mockUserToken)t=r.mockUserToken,n=ou.MOCK_USER;else{t=function(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const s=Object.assign({iss:"https://securetoken.google.com/".concat(n),aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e);return[o(JSON.stringify({alg:"none",type:"JWT"})),o(JSON.stringify(s)),""].join(".")}(r.mockUserToken,null===(i=e._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new wu(yu.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");n=new ou(s)}e._authCredentials=new Su(new _u(t,n))}}class av{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new av(this.firestore,e,this._query)}}class ov{constructor(e,t,n){this.converter=t,this._key=n,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 lv(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new ov(this.firestore,e,this._key)}}class lv extends av{constructor(e,t,n){super(e,t,vd(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new ov(this.firestore,null,new Uu(e))}withConverter(e){return new lv(this.firestore,e,this._path)}}function cv(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i<n;i++)r[i-2]=arguments[i];if(e=D(e),Jg("collection","path",t),e instanceof iv){const n=Mu.fromString(t,...r);return ev(n),new lv(e,null,n)}{if(!(e instanceof ov||e instanceof lv))throw new wu(yu.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const n=e._path.child(Mu.fromString(t,...r));return ev(n),new lv(e.firestore,null,n)}}class uv{constructor(){this.Ja=Promise.resolve(),this.Ya=[],this.Za=!1,this.Xa=[],this.eu=null,this.tu=!1,this.nu=!1,this.ru=[],this.zo=new ym(this,"async_queue_retry"),this.iu=()=>{const e=gm();e&&hu("AsyncQueue","Visibility state changed to "+e.visibilityState),this.zo.Qo()};const e=gm();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.iu)}get isShuttingDown(){return this.Za}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.su(),this.ou(e)}enterRestrictedMode(e){if(!this.Za){this.Za=!0,this.nu=e||!1;const t=gm();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.iu)}}enqueue(e){if(this.su(),this.Za)return new Promise((()=>{}));const t=new bu;return this.ou((()=>this.Za&&this.nu?Promise.resolve():(e().then(t.resolve,t.reject),t.promise))).then((()=>t.promise))}enqueueRetryable(e){this.enqueueAndForget((()=>(this.Ya.push(e),this._u())))}async _u(){if(0!==this.Ya.length){try{await this.Ya[0](),this.Ya.shift(),this.zo.reset()}catch(e){if(!$u(e))throw e;hu("AsyncQueue","Operation failed with retryable error: "+e)}this.Ya.length>0&&this.zo.ko((()=>this._u()))}}ou(e){const t=this.Ja.then((()=>(this.tu=!0,e().catch((e=>{this.eu=e,this.tu=!1;const t=function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e);throw du("INTERNAL UNHANDLED ERROR: ",t),e})).then((e=>(this.tu=!1,e))))));return this.Ja=t,t}enqueueAfterDelay(e,t,n){this.su(),this.ru.indexOf(e)>-1&&(t=0);const r=Zm.createAndSchedule(this,e,t,n,(e=>this.au(e)));return this.Xa.push(r),r}su(){this.eu&&mu()}verifyOperationInProgress(){}async uu(){let e;do{e=this.Ja,await e}while(e!==this.Ja)}cu(e){for(const t of this.Xa)if(t.timerId===e)return!0;return!1}lu(e){return this.uu().then((()=>{this.Xa.sort(((e,t)=>e.targetTimeMs-t.targetTimeMs));for(const t of this.Xa)if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.uu()}))}hu(e){this.ru.push(e)}au(e){const t=this.Xa.indexOf(e);this.Xa.splice(t,1)}}class hv extends iv{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new uv,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||fv(this),this._firestoreClient.terminate()}}function dv(e){return e._firestoreClient||fv(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function fv(e){var t,n,r;const i=e._freezeSettings(),s=function(e,t,n,r){return new _h(e,t,n,r.host,r.ssl,r.experimentalForceLongPolling,r.experimentalAutoDetectLongPolling,Yg(r.experimentalLongPollingOptions),r.useFetchStreams)}(e._databaseId,(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",e._persistenceKey,i);e._firestoreClient=new Bg(e._authCredentials,e._appCheckCredentials,e._queue,s),(null===(n=i.localCache)||void 0===n?void 0:n._offlineComponentProvider)&&(null===(r=i.localCache)||void 0===r?void 0:r._onlineComponentProvider)&&(e._firestoreClient._uninitializedComponentsProvider={_offlineKind:i.localCache.kind,_offline:i.localCache._offlineComponentProvider,_online:i.localCache._onlineComponentProvider})}class pv{constructor(e){this._byteString=e}static fromBase64String(e){try{return new pv(fh.fromBase64String(e))}catch(e){throw new wu(yu.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new pv(fh.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)}}class mv{constructor(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(let r=0;r<t.length;++r)if(0===t[r].length)throw new wu(yu.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Fu(t)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class gv{constructor(e){this._methodName=e}}class vv{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new wu(yu.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new wu(yu.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return Pu(this._lat,e._lat)||Pu(this._long,e._long)}}const yv=/^__.*__$/;class wv{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new yf(e,this.data,this.fieldMask,t,this.fieldTransforms):new vf(e,this.data,t,this.fieldTransforms)}}function bv(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw mu()}}class _v{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===i&&this.Pu(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Iu(){return this.settings.Iu}Tu(e){return new _v(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Eu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Tu({path:n,du:!1});return r.Au(e),r}Ru(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Tu({path:n,du:!1});return r.Pu(),r}Vu(e){return this.Tu({path:void 0,du:!0})}mu(e){return Ov(e,this.settings.methodName,this.settings.fu||!1,this.path,this.settings.gu)}contains(e){return void 0!==this.fieldMask.find((t=>e.isPrefixOf(t)))||void 0!==this.fieldTransforms.find((t=>e.isPrefixOf(t.field)))}Pu(){if(this.path)for(let e=0;e<this.path.length;e++)this.Au(this.path.get(e))}Au(e){if(0===e.length)throw this.mu("Document fields must not be empty");if(bv(this.Iu)&&yv.test(e))throw this.mu('Document fields cannot begin and end with "__"')}}class Ev{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||vm(e)}pu(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return new _v({Iu:e,methodName:t,gu:n,path:Fu.emptyPath(),du:!1,fu:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function Sv(e){const t=e._freezeSettings(),n=vm(e._databaseId);return new Ev(e._databaseId,!!t.ignoreUndefinedProperties,n)}function kv(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};const a=e.pu(s.merge||s.mergeFields?2:0,t,n,i);Nv("Data must be an object, but it was:",a,r);const o=Cv(r,a);let l,c;if(s.merge)l=new hh(a.fieldMask),c=a.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=Av(t,r,n);if(!a.contains(i))throw new wu(yu.INVALID_ARGUMENT,"Field '".concat(i,"' is specified in your field mask but missing from your input data."));Dv(e,i)||e.push(i)}l=new hh(e),c=a.fieldTransforms.filter((e=>l.covers(e.field)))}else l=null,c=a.fieldTransforms;return new wv(new Uh(o),l,c)}function Iv(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return Tv(n,e.pu(r?4:3,t))}function Tv(e,t){if(xv(e=D(e)))return Nv("Unsupported field value:",t,e),Cv(e,t);if(e instanceof gv)return function(e,t){if(!bv(t.Iu))throw t.mu("".concat(e._methodName,"() can only be used with update() and set()"));if(!t.path)throw t.mu("".concat(e._methodName,"() is not currently supported inside arrays"));const n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.du&&4!==t.Iu)throw t.mu("Nested arrays are not supported");return function(e,t){const n=[];let r=0;for(const i of e){let e=Tv(i,t.Vu(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=D(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return Qd(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){const n=Ou.fromDate(e);return{timestampValue:Zf(t.serializer,n)}}if(e instanceof Ou){const n=new Ou(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:Zf(t.serializer,n)}}if(e instanceof vv)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof pv)return{bytesValue:ep(t.serializer,e._byteString)};if(e instanceof ov){const n=t.databaseId,r=e.firestore._databaseId;if(!r.isEqual(n))throw t.mu("Document reference is for database ".concat(r.projectId,"/").concat(r.database," but should be for database ").concat(n.projectId,"/").concat(n.database));return{referenceValue:rp(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.mu("Unsupported field value: ".concat(tv(e)))}(e,t)}function Cv(e,t){const n={};return sh(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):ih(e,((e,r)=>{const i=Tv(r,t.Eu(e));null!=i&&(n[e]=i)})),{mapValue:{fields:n}}}function xv(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof Ou||e instanceof vv||e instanceof pv||e instanceof ov||e instanceof gv)}function Nv(e,t,n){if(!xv(n)||!function(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(n)){const r=tv(n);throw"an object"===r?t.mu(e+" a custom object"):t.mu(e+" "+r)}}function Av(e,t,n){if((t=D(t))instanceof mv)return t._internalPath;if("string"==typeof t)return Rv(e,t);throw Ov("Field path arguments must be of type string or ",e,!1,void 0,n)}const Pv=new RegExp("[~\\*/\\[\\]]");function Rv(e,t,n){if(t.search(Pv)>=0)throw Ov("Invalid field path (".concat(t,"). Paths must not contain '~', '*', '/', '[', or ']'"),e,!1,void 0,n);try{return new mv(...t.split("."))._internalPath}catch(Js){throw Ov("Invalid field path (".concat(t,"). Paths must not be empty, begin with '.', end with '.', or contain '..'"),e,!1,void 0,n)}}function Ov(e,t,n,r,i){const s=r&&!r.isEmpty(),a=void 0!==i;let o="Function ".concat(t,"() called with invalid data");n&&(o+=" (via `toFirestore()`)"),o+=". ";let l="";return(s||a)&&(l+=" (found",s&&(l+=" in field ".concat(r)),a&&(l+=" in document ".concat(i)),l+=")"),new wu(yu.INVALID_ARGUMENT,o+e+l)}function Dv(e,t){return e.some((e=>e.isEqual(t)))}class Lv{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new ov(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new Mv(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){const t=this._document.data.field(jv("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Mv extends Lv{data(){return super.data()}}function jv(e,t){return"string"==typeof t?Rv(e,t):t instanceof mv?t._internalPath:t._delegate._internalPath}function Fv(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new wu(yu.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class Uv{}class Vv extends Uv{}function Bv(e,t){let n=[];for(var r=arguments.length,i=new Array(r>2?r-2:0),s=2;s<r;s++)i[s-2]=arguments[s];t instanceof Uv&&n.push(t),n=n.concat(i),function(e){const t=e.filter((e=>e instanceof Hv)).length,n=e.filter((e=>e instanceof zv)).length;if(t>1||t>0&&n>0)throw new wu(yu.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(...)))`.")}(n);for(const a of n)e=a._apply(e);return e}class zv extends Vv{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new zv(e,t,n)}_apply(e){const t=this._parse(e);return Gv(e._query,t),new av(e.firestore,e.converter,Sd(e._query,t))}_parse(e){const t=Sv(e.firestore),n=function(e,t,n,r,i,s,a){let o;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new wu(yu.INVALID_ARGUMENT,"Invalid Query. You can't perform '".concat(s,"' queries on documentId()."));if("in"===s||"not-in"===s){Kv(a,s);const t=[];for(const n of a)t.push(Wv(r,e,n));o={arrayValue:{values:t}}}else o=Wv(r,e,a)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||Kv(a,s),o=Iv(n,t,a,"in"===s||"not-in"===s);return Qh.create(i,s,o)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value);return n}}function qv(e,t,n){const r=t,i=jv("where",e);return zv._create(i,r,n)}class Hv extends Uv{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new Hv(e,t)}_parse(e){const t=this._queryConstraints.map((t=>t._parse(e))).filter((e=>e.getFilters().length>0));return 1===t.length?t[0]:$h.create(t,this._getOperator())}_apply(e){const t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;const r=t.getFlattenedFilters();for(const i of r)Gv(n,i),n=Sd(n,i)}(e._query,t),new av(e.firestore,e.converter,Sd(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}function Wv(e,t,n){if("string"==typeof(n=D(n))){if(""===n)throw new wu(yu.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!wd(t)&&-1!==n.indexOf("/"))throw new wu(yu.INVALID_ARGUMENT,"Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '".concat(n,"' contains a '/' character."));const r=t.path.child(Mu.fromString(n));if(!Uu.isDocumentKey(r))throw new wu(yu.INVALID_ARGUMENT,"Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '".concat(r,"' is not because it has an odd number of segments (").concat(r.length,")."));return Ph(e,new Uu(r))}if(n instanceof ov)return Ph(e,n._key);throw new wu(yu.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ".concat(tv(n),"."))}function Kv(e,t){if(!Array.isArray(e)||0===e.length)throw new wu(yu.INVALID_ARGUMENT,"Invalid Query. A non-empty array is required for '".concat(t.toString(),"' filters."))}function Gv(e,t){const n=function(e,t){for(const n of e)for(const e of n.getFlattenedFilters())if(t.indexOf(e.op)>=0)return e.op;return null}(e.filters,function(e){switch(e){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[]}}(t.op));if(null!==n)throw n===t.op?new wu(yu.INVALID_ARGUMENT,"Invalid query. You cannot use more than one '".concat(t.op.toString(),"' filter.")):new wu(yu.INVALID_ARGUMENT,"Invalid query. You cannot use '".concat(t.op.toString(),"' filters with '").concat(n.toString(),"' filters."))}class Qv{convertValue(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"none";switch(kh(e)){case 0:return null;case 1:return e.booleanValue;case 2:return gh(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(vh(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 10:return this.convertObject(e.mapValue,t);default:throw mu()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"none";const n={};return ih(e,((e,r)=>{n[e]=this.convertValue(r,t)})),n}convertGeoPoint(e){return new vv(gh(e.latitude),gh(e.longitude))}convertArray(e,t){return(e.values||[]).map((e=>this.convertValue(e,t)))}convertServerTimestamp(e,t){switch(t){case"previous":const n=wh(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(bh(e));default:return null}}convertTimestamp(e){const t=mh(e);return new Ou(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=Mu.fromString(e);gu(kp(n));const r=new Eh(n.get(1),n.get(3)),i=new Uu(n.popFirst(5));return r.isEqual(t)||du("Document ".concat(i," contains a document reference within a different database (").concat(r.projectId,"/").concat(r.database,") which is not supported. It will be treated as a reference in the current database (").concat(t.projectId,"/").concat(t.database,") instead.")),i}}function $v(e,t,n){let r;return r=e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t,r}class Yv{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class Xv extends Lv{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this._document){if(this._converter){const t=new Jv(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this._document){const n=this._document.data.field(jv("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class Jv extends Xv{data(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return super.data(e)}}class Zv{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new Yv(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const e=[];return this.forEach((t=>e.push(t))),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,t){this._snapshot.docs.forEach((n=>{e.call(t,new Jv(this._firestore,this._userDataWriter,n.key,n,new Yv(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))}))}docChanges(){const e=!!(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).includeMetadataChanges;if(e&&this._snapshot.excludesMetadataChanges)throw new wu(yu.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===e||(this._cachedChanges=function(e,t){if(e._snapshot.oldDocs.isEmpty()){let t=0;return e._snapshot.docChanges.map((n=>{const r=new Jv(e._firestore,e._userDataWriter,n.doc.key,n.doc,new Yv(e._snapshot.mutatedKeys.has(n.doc.key),e._snapshot.fromCache),e.query.converter);return n.doc,{type:"added",doc:r,oldIndex:-1,newIndex:t++}}))}{let n=e._snapshot.oldDocs;return e._snapshot.docChanges.filter((e=>t||3!==e.type)).map((t=>{const r=new Jv(e._firestore,e._userDataWriter,t.doc.key,t.doc,new Yv(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter);let i=-1,s=-1;return 0!==t.type&&(i=n.indexOf(t.doc.key),n=n.delete(t.doc.key)),1!==t.type&&(n=n.add(t.doc),s=n.indexOf(t.doc.key)),{type:ey(t.type),doc:r,oldIndex:i,newIndex:s}}))}}(this,e),this._cachedChangesIncludeMetadataChanges=e),this._cachedChanges}}function ey(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return mu()}}class ty extends Qv{constructor(e){super(),this.firestore=e}convertBytes(e){return new pv(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new ov(this.firestore,null,t)}}function ny(e){e=nv(e,av);const t=nv(e.firestore,hv),n=dv(t),r=new ty(t);return Fv(e._query),$g(n,e._query).then((n=>new Zv(t,r,e,n)))}function ry(e,t){const n=nv(e.firestore,hv),r=function(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i<n;i++)r[i-2]=arguments[i];if(e=D(e),1===arguments.length&&(t=Au.newId()),Jg("doc","path",t),e instanceof iv){const n=Mu.fromString(t,...r);return Zg(n),new ov(e,null,new Uu(n))}{if(!(e instanceof ov||e instanceof lv))throw new wu(yu.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const n=e._path.child(Mu.fromString(t,...r));return Zg(n),new ov(e.firestore,e instanceof lv?e.converter:null,new Uu(n))}}(e),i=$v(e.converter,t);return iy(n,[kv(Sv(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,cf.exists(!1))]).then((()=>r))}function iy(e,t){return function(e,t){const n=new bu;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){const r=jg(e);try{const e=await function(e,t){const n=vu(e),r=Ou.now(),i=t.reduce(((e,t)=>e.add(t.key)),qd());let s,a;return n.persistence.runTransaction("Locally write mutations","readwrite",(e=>{let o=Dd(),l=qd();return n.ss.getEntries(e,i).next((e=>{o=e,o.forEach(((e,t)=>{t.isValidDocument()||(l=l.add(e))}))})).next((()=>n.localDocuments.getOverlayedDocuments(e,o))).next((i=>{s=i;const a=[];for(const e of t){const t=mf(e,s.get(e.key).overlayedDocument);null!=t&&a.push(new yf(e.key,t,Vh(t.value.mapValue),cf.exists(!0)))}return n.mutationQueue.addMutationBatch(e,r,a,t)})).next((t=>{a=t;const r=t.applyToLocalDocumentSet(s,l);return n.documentOverlayCache.saveOverlays(e,t.batchId,r)}))})).then((()=>({batchId:a.batchId,changes:jd(s)})))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.Sa[e.currentUser.toKey()];r||(r=new ah(Pu)),r=r.insert(t,n),e.Sa[e.currentUser.toKey()]=r}(r,e.batchId,n),await Og(r,e.changes),await Vm(r.remoteStore)}catch(e){const t=eg(e,"Failed to persist write");n.reject(t)}}(await Gg(e),t,n))),n.promise}(dv(e),t)}new WeakMap;!function(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];!function(e){lu=e}(Ee),ye(new L("firestore",((e,n)=>{let{instanceIdentifier:r,options:i}=n;const s=e.getProvider("app").getImmediate(),a=new hv(new ku(e.getProvider("auth-internal")),new xu(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new wu(yu.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Eh(e.options.projectId,t)}(s,r),s);return i=Object.assign({useFetchStreams:t},i),a._setSettings(i),a}),"PUBLIC").setMultipleInstances(!0)),Ie(au,"4.3.2",e),Ie(au,"4.3.2","esm2017")}();const sy=Se({apiKey:"AIzaSyDZjgosQcTQgNfvwAaFC_W6R5Sv0JjjxkM",authDomain:"friendly-betting-fb47e.firebaseapp.com",projectId:"friendly-betting-fb47e",storageBucket:"friendly-betting-fb47e.appspot.com",messagingSenderId:"897713635691",appId:"1:897713635691:web:70b530052a319f77e14c2e",measurementId:"G-74305KF5X4"}),ay=(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ke();e=D(e);const t=we(e,Qt);t.isInitialized()?t.getImmediate():function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=we(e,Qt);if(n.isInitialized()){const e=n.getImmediate();if(E(t,n.getOptions()))return e;throw tn.create("already-initialized")}const r=n.initialize({options:t})}(e)}(sy),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ke();const t=we(e,"auth");if(t.isInitialized())return t.getImmediate();const n=function(e,t){const n=we(e,"auth");if(n.isInitialized()){const e=n.getImmediate();if(E(n.getOptions(),null!==t&&void 0!==t?t:{}))return e;Fn(e,"already-initialized")}return n.initialize({options:t})}(e,{popupRedirectResolver:Rs,persistence:[zi,Ii,Ci]}),r=f("authTokenSyncURL");if(r){const e=(i=r,async e=>{const t=e&&await e.getIdTokenResult(),n=t&&((new Date).getTime()-Date.parse(t.issuedAtTime))/1e3;if(n&&n>Ms)return;const r=null===t||void 0===t?void 0:t.token;js!==r&&(js=r,await fetch(i,{method:r?"POST":"DELETE",headers:r?{Authorization:"Bearer ".concat(r)}:{}}))});!function(e,t,n){D(e).beforeAuthStateChanged(t,n)}(n,e,(()=>e(n.currentUser))),function(e,t,n,r){D(e).onIdTokenChanged(t,n,r)}(n,(t=>e(t)))}var i;const s=h("auth");return s&&Qr(n,"http://".concat(s)),n}(sy)),oy=function(e,t){const n="string"==typeof e?e:t||"(default)",r=we("object"==typeof e?e:ke(),"firestore").getImmediate({identifier:n});if(!r._initialized){const e=(e=>{const t=h(e);if(!t)return;const n=t.lastIndexOf(":");if(n<=0||n+1===t.length)throw new Error("Invalid host ".concat(t," with no separate hostname and port!"));const r=parseInt(t.substring(n+1),10);return"["===t[0]?[t.substring(1,n-1),r]:[t.substring(0,n),r]})("firestore");e&&sv(r,...e)}return r}(sy);function ly(){return ly=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},ly.apply(this,arguments)}var cy;!function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"}(cy||(cy={}));const uy="popstate";function hy(e,t){if(!1===e||null===e||"undefined"===typeof e)throw new Error(t)}function dy(e,t){if(!e){"undefined"!==typeof console&&console.warn(t);try{throw new Error(t)}catch(n){}}}function fy(e,t){return{usr:e.state,key:e.key,idx:t}}function py(e,t,n,r){return void 0===n&&(n=null),ly({pathname:"string"===typeof e?e:e.pathname,search:"",hash:""},"string"===typeof t?gy(t):t,{state:n,key:t&&t.key||r||Math.random().toString(36).substr(2,8)})}function my(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&"?"!==n&&(t+="?"===n.charAt(0)?n:"?"+n),r&&"#"!==r&&(t+="#"===r.charAt(0)?r:"#"+r),t}function gy(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function vy(e,t,n,r){void 0===r&&(r={});let{window:i=document.defaultView,v5Compat:s=!1}=r,a=i.history,o=cy.Pop,l=null,c=u();function u(){return(a.state||{idx:null}).idx}function h(){o=cy.Pop;let e=u(),t=null==e?null:e-c;c=e,l&&l({action:o,location:f.location,delta:t})}function d(e){let t="null"!==i.location.origin?i.location.origin:i.location.href,n="string"===typeof e?e:my(e);return hy(t,"No window.location.(origin|href) available to create URL for href: "+n),new URL(n,t)}null==c&&(c=0,a.replaceState(ly({},a.state,{idx:c}),""));let f={get action(){return o},get location(){return e(i,a)},listen(e){if(l)throw new Error("A history only accepts one active listener");return i.addEventListener(uy,h),l=e,()=>{i.removeEventListener(uy,h),l=null}},createHref:e=>t(i,e),createURL:d,encodeLocation(e){let t=d(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:function(e,t){o=cy.Push;let r=py(f.location,e,t);n&&n(r,e),c=u()+1;let h=fy(r,c),d=f.createHref(r);try{a.pushState(h,"",d)}catch(p){if(p instanceof DOMException&&"DataCloneError"===p.name)throw p;i.location.assign(d)}s&&l&&l({action:o,location:f.location,delta:1})},replace:function(e,t){o=cy.Replace;let r=py(f.location,e,t);n&&n(r,e),c=u();let i=fy(r,c),h=f.createHref(r);a.replaceState(i,"",h),s&&l&&l({action:o,location:f.location,delta:0})},go:e=>a.go(e)};return f}var yy;!function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"}(yy||(yy={}));new Set(["lazy","caseSensitive","path","id","index","children"]);function wy(e,t,n){void 0===n&&(n="/");let r=Oy(("string"===typeof t?gy(t):t).pathname||"/",n);if(null==r)return null;let i=by(e);!function(e){e.sort(((e,t)=>e.score!==t.score?t.score-e.score:function(e,t){let n=e.length===t.length&&e.slice(0,-1).every(((e,n)=>e===t[n]));return n?e[e.length-1]-t[t.length-1]:0}(e.routesMeta.map((e=>e.childrenIndex)),t.routesMeta.map((e=>e.childrenIndex)))))}(i);let s=null;for(let a=0;null==s&&a<i.length;++a)s=Ay(i[a],Ry(r));return s}function by(e,t,n,r){void 0===t&&(t=[]),void 0===n&&(n=[]),void 0===r&&(r="");let i=(e,i,s)=>{let a={relativePath:void 0===s?e.path||"":s,caseSensitive:!0===e.caseSensitive,childrenIndex:i,route:e};a.relativePath.startsWith("/")&&(hy(a.relativePath.startsWith(r),'Absolute route path "'+a.relativePath+'" nested under path "'+r+'" is not valid. An absolute child route path must start with the combined path of all its parent routes.'),a.relativePath=a.relativePath.slice(r.length));let o=Fy([r,a.relativePath]),l=n.concat(a);e.children&&e.children.length>0&&(hy(!0!==e.index,'Index routes must not have child routes. Please remove all child routes from route path "'+o+'".'),by(e.children,t,l,o)),(null!=e.path||e.index)&&t.push({path:o,score:Ny(o,e.index),routesMeta:l})};return e.forEach(((e,t)=>{var n;if(""!==e.path&&null!=(n=e.path)&&n.includes("?"))for(let r of _y(e.path))i(e,t,r);else i(e,t)})),t}function _y(e){let t=e.split("/");if(0===t.length)return[];let[n,...r]=t,i=n.endsWith("?"),s=n.replace(/\?$/,"");if(0===r.length)return i?[s,""]:[s];let a=_y(r.join("/")),o=[];return o.push(...a.map((e=>""===e?s:[s,e].join("/")))),i&&o.push(...a),o.map((t=>e.startsWith("/")&&""===t?"/":t))}const Ey=/^:\w+$/,Sy=3,ky=2,Iy=1,Ty=10,Cy=-2,xy=e=>"*"===e;function Ny(e,t){let n=e.split("/"),r=n.length;return n.some(xy)&&(r+=Cy),t&&(r+=ky),n.filter((e=>!xy(e))).reduce(((e,t)=>e+(Ey.test(t)?Sy:""===t?Iy:Ty)),r)}function Ay(e,t){let{routesMeta:n}=e,r={},i="/",s=[];for(let a=0;a<n.length;++a){let e=n[a],o=a===n.length-1,l="/"===i?t:t.slice(i.length)||"/",c=Py({path:e.relativePath,caseSensitive:e.caseSensitive,end:o},l);if(!c)return null;Object.assign(r,c.params);let u=e.route;s.push({params:r,pathname:Fy([i,c.pathname]),pathnameBase:Uy(Fy([i,c.pathnameBase])),route:u}),"/"!==c.pathnameBase&&(i=Fy([i,c.pathnameBase]))}return s}function Py(e,t){"string"===typeof e&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=function(e,t,n){void 0===t&&(t=!1);void 0===n&&(n=!0);dy("*"===e||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were "'+e.replace(/\*$/,"/*")+'" because the `*` character must always follow a `/` in the pattern. To get rid of this warning, please change the route path to "'+e.replace(/\*$/,"/*")+'".');let r=[],i="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:(\w+)(\?)?/g,((e,t,n)=>(r.push({paramName:t,isOptional:null!=n}),n?"/?([^\\/]+)?":"/([^\\/]+)")));e.endsWith("*")?(r.push({paramName:"*"}),i+="*"===e||"/*"===e?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?i+="\\/*$":""!==e&&"/"!==e&&(i+="(?:(?=\\/|$))");let s=new RegExp(i,t?void 0:"i");return[s,r]}(e.path,e.caseSensitive,e.end),i=t.match(n);if(!i)return null;let s=i[0],a=s.replace(/(.)\/+$/,"$1"),o=i.slice(1);return{params:r.reduce(((e,t,n)=>{let{paramName:r,isOptional:i}=t;if("*"===r){let e=o[n]||"";a=s.slice(0,s.length-e.length).replace(/(.)\/+$/,"$1")}const l=o[n];return e[r]=i&&!l?void 0:function(e,t){try{return decodeURIComponent(e)}catch(n){return dy(!1,'The value for the URL param "'+t+'" will not be decoded because the string "'+e+'" is a malformed URL segment. This is probably due to a bad percent encoding ('+n+")."),e}}(l||"",r),e}),{}),pathname:s,pathnameBase:a,pattern:e}}function Ry(e){try{return decodeURI(e)}catch(t){return dy(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent encoding ('+t+")."),e}}function Oy(e,t){if("/"===t)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&"/"!==r?null:e.slice(n)||"/"}function Dy(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified `to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the `to."+n+'` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.'}function Ly(e){return e.filter(((e,t)=>0===t||e.route.path&&e.route.path.length>0))}function My(e){return Ly(e).map(((t,n)=>n===e.length-1?t.pathname:t.pathnameBase))}function jy(e,t,n,r){let i;void 0===r&&(r=!1),"string"===typeof e?i=gy(e):(i=ly({},e),hy(!i.pathname||!i.pathname.includes("?"),Dy("?","pathname","search",i)),hy(!i.pathname||!i.pathname.includes("#"),Dy("#","pathname","hash",i)),hy(!i.search||!i.search.includes("#"),Dy("#","search","hash",i)));let s,a=""===e||""===i.pathname,o=a?"/":i.pathname;if(null==o)s=n;else if(r){let e=t[t.length-1].replace(/^\//,"").split("/");if(o.startsWith("..")){let t=o.split("/");for(;".."===t[0];)t.shift(),e.pop();i.pathname=t.join("/")}s="/"+e.join("/")}else{let e=t.length-1;if(o.startsWith("..")){let t=o.split("/");for(;".."===t[0];)t.shift(),e-=1;i.pathname=t.join("/")}s=e>=0?t[e]:"/"}let l=function(e,t){void 0===t&&(t="/");let{pathname:n,search:r="",hash:i=""}="string"===typeof e?gy(e):e,s=n?n.startsWith("/")?n:function(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach((e=>{".."===e?n.length>1&&n.pop():"."!==e&&n.push(e)})),n.length>1?n.join("/"):"/"}(n,t):t;return{pathname:s,search:Vy(r),hash:By(i)}}(i,s),c=o&&"/"!==o&&o.endsWith("/"),u=(a||"."===o)&&n.endsWith("/");return l.pathname.endsWith("/")||!c&&!u||(l.pathname+="/"),l}const Fy=e=>e.join("/").replace(/\/\/+/g,"/"),Uy=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),Vy=e=>e&&"?"!==e?e.startsWith("?")?e:"?"+e:"",By=e=>e&&"#"!==e?e.startsWith("#")?e:"#"+e:"";Error;function zy(e){return null!=e&&"number"===typeof e.status&&"string"===typeof e.statusText&&"boolean"===typeof e.internal&&"data"in e}const qy=["post","put","patch","delete"],Hy=(new Set(qy),["get",...qy]);new Set(Hy),new Set([301,302,303,307,308]),new Set([307,308]);Symbol("deferred");function Wy(){return Wy=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Wy.apply(this,arguments)}const Ky=e.createContext(null);const Gy=e.createContext(null);const Qy=e.createContext(null);const $y=e.createContext(null);const Yy=e.createContext({outlet:null,matches:[],isDataRoute:!1});const Xy=e.createContext(null);function Jy(){return null!=e.useContext($y)}function Zy(){return Jy()||hy(!1),e.useContext($y).location}function ew(t){e.useContext(Qy).static||e.useLayoutEffect(t)}function tw(){let{isDataRoute:t}=e.useContext(Yy);return t?function(){let{router:t}=hw(cw.UseNavigateStable),n=fw(uw.UseNavigateStable),r=e.useRef(!1);ew((()=>{r.current=!0}));let i=e.useCallback((function(e,i){void 0===i&&(i={}),r.current&&("number"===typeof e?t.navigate(e):t.navigate(e,Wy({fromRouteId:n},i)))}),[t,n]);return i}():function(){Jy()||hy(!1);let t=e.useContext(Ky),{basename:n,navigator:r}=e.useContext(Qy),{matches:i}=e.useContext(Yy),{pathname:s}=Zy(),a=JSON.stringify(My(i)),o=e.useRef(!1);return ew((()=>{o.current=!0})),e.useCallback((function(e,i){if(void 0===i&&(i={}),!o.current)return;if("number"===typeof e)return void r.go(e);let l=jy(e,JSON.parse(a),s,"path"===i.relative);null==t&&"/"!==n&&(l.pathname="/"===l.pathname?n:Fy([n,l.pathname])),(i.replace?r.replace:r.push)(l,i.state,i)}),[n,r,a,s,t])}()}function nw(t,n){let{relative:r}=void 0===n?{}:n,{matches:i}=e.useContext(Yy),{pathname:s}=Zy(),a=JSON.stringify(My(i));return e.useMemo((()=>jy(t,JSON.parse(a),s,"path"===r)),[t,a,s,r])}function rw(t,n,r){Jy()||hy(!1);let{navigator:i}=e.useContext(Qy),{matches:s}=e.useContext(Yy),a=s[s.length-1],o=a?a.params:{},l=(a&&a.pathname,a?a.pathnameBase:"/");a&&a.route;let c,u=Zy();if(n){var h;let e="string"===typeof n?gy(n):n;"/"===l||(null==(h=e.pathname)?void 0:h.startsWith(l))||hy(!1),c=e}else c=u;let d=c.pathname||"/",f=wy(t,{pathname:"/"===l?d:d.slice(l.length)||"/"});let p=lw(f&&f.map((e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:Fy([l,i.encodeLocation?i.encodeLocation(e.pathname).pathname:e.pathname]),pathnameBase:"/"===e.pathnameBase?l:Fy([l,i.encodeLocation?i.encodeLocation(e.pathnameBase).pathname:e.pathnameBase])}))),s,r);return n&&p?e.createElement($y.Provider,{value:{location:Wy({pathname:"/",search:"",hash:"",state:null,key:"default"},c),navigationType:cy.Pop}},p):p}function iw(){let t=function(){var t;let n=e.useContext(Xy),r=dw(uw.UseRouteError),i=fw(uw.UseRouteError);if(n)return n;return null==(t=r.errors)?void 0:t[i]}(),n=zy(t)?t.status+" "+t.statusText:t instanceof Error?t.message:JSON.stringify(t),r=t instanceof Error?t.stack:null,i="rgba(200,200,200, 0.5)",s={padding:"0.5rem",backgroundColor:i};return e.createElement(e.Fragment,null,e.createElement("h2",null,"Unexpected Application Error!"),e.createElement("h3",{style:{fontStyle:"italic"}},n),r?e.createElement("pre",{style:s},r):null,null)}const sw=e.createElement(iw,null);class aw extends e.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||"idle"!==t.revalidation&&"idle"===e.revalidation?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error||t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){console.error("React Router caught the following error during render",e,t)}render(){return this.state.error?e.createElement(Yy.Provider,{value:this.props.routeContext},e.createElement(Xy.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function ow(t){let{routeContext:n,match:r,children:i}=t,s=e.useContext(Ky);return s&&s.static&&s.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=r.route.id),e.createElement(Yy.Provider,{value:n},i)}function lw(t,n,r){var i;if(void 0===n&&(n=[]),void 0===r&&(r=null),null==t){var s;if(null==(s=r)||!s.errors)return null;t=r.matches}let a=t,o=null==(i=r)?void 0:i.errors;if(null!=o){let e=a.findIndex((e=>e.route.id&&(null==o?void 0:o[e.route.id])));e>=0||hy(!1),a=a.slice(0,Math.min(a.length,e+1))}return a.reduceRight(((t,i,s)=>{let l=i.route.id?null==o?void 0:o[i.route.id]:null,c=null;r&&(c=i.route.errorElement||sw);let u=n.concat(a.slice(0,s+1)),h=()=>{let n;return n=l?c:i.route.Component?e.createElement(i.route.Component,null):i.route.element?i.route.element:t,e.createElement(ow,{match:i,routeContext:{outlet:t,matches:u,isDataRoute:null!=r},children:n})};return r&&(i.route.ErrorBoundary||i.route.errorElement||0===s)?e.createElement(aw,{location:r.location,revalidation:r.revalidation,component:c,error:l,children:h(),routeContext:{outlet:null,matches:u,isDataRoute:!0}}):h()}),null)}var cw=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(cw||{}),uw=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(uw||{});function hw(t){let n=e.useContext(Ky);return n||hy(!1),n}function dw(t){let n=e.useContext(Gy);return n||hy(!1),n}function fw(t){let n=function(t){let n=e.useContext(Yy);return n||hy(!1),n}(),r=n.matches[n.matches.length-1];return r.route.id||hy(!1),r.route.id}t.startTransition;function pw(e){hy(!1)}function mw(t){let{basename:n="/",children:r=null,location:i,navigationType:s=cy.Pop,navigator:a,static:o=!1}=t;Jy()&&hy(!1);let l=n.replace(/^\/*/,"/"),c=e.useMemo((()=>({basename:l,navigator:a,static:o})),[l,a,o]);"string"===typeof i&&(i=gy(i));let{pathname:u="/",search:h="",hash:d="",state:f=null,key:p="default"}=i,m=e.useMemo((()=>{let e=Oy(u,l);return null==e?null:{location:{pathname:e,search:h,hash:d,state:f,key:p},navigationType:s}}),[l,u,h,d,f,p,s]);return null==m?null:e.createElement(Qy.Provider,{value:c},e.createElement($y.Provider,{children:r,value:m}))}function gw(e){let{children:t,location:n}=e;return rw(vw(t),n)}new Promise((()=>{}));e.Component;function vw(t,n){void 0===n&&(n=[]);let r=[];return e.Children.forEach(t,((t,i)=>{if(!e.isValidElement(t))return;let s=[...n,i];if(t.type===e.Fragment)return void r.push.apply(r,vw(t.props.children,s));t.type!==pw&&hy(!1),t.props.index&&t.props.children&&hy(!1);let a={id:t.props.id||s.join("-"),caseSensitive:t.props.caseSensitive,element:t.props.element,Component:t.props.Component,index:t.props.index,path:t.props.path,loader:t.props.loader,action:t.props.action,errorElement:t.props.errorElement,ErrorBoundary:t.props.ErrorBoundary,hasErrorBoundary:null!=t.props.ErrorBoundary||null!=t.props.errorElement,shouldRevalidate:t.props.shouldRevalidate,handle:t.props.handle,lazy:t.props.lazy};t.props.children&&(a.children=vw(t.props.children,s)),r.push(a)})),r}const yw="SignIn_signIn__3t4GY",ww="SignIn_signInTransition__DVaCC",bw="SignIn_signInLabel__6itNQ",_w="SignIn_swapSignIn__WlTGP";var Ew=n(184);const Sw=()=>{var t;const[n,r]=(0,e.useState)(""),[i,s]=(0,e.useState)(""),[a,o]=(0,e.useState)(!1);console.log(null===ay||void 0===ay||null===(t=ay.currentUser)||void 0===t?void 0:t.email);const l=tw();return(0,e.useEffect)((()=>{const e=setTimeout((()=>{o(!0)}),2);return()=>clearTimeout(e)}),[]),(0,Ew.jsxs)("div",{className:"".concat(yw," ").concat(a?"":ww),children:[(0,Ew.jsx)("div",{className:bw,children:"Sign in"}),(0,Ew.jsx)("input",{type:"text",placeholder:"Email or Number",onChange:e=>r(e.target.value)}),(0,Ew.jsx)("input",{type:"password",placeholder:"password",id:"",onChange:e=>s(e.target.value)}),(0,Ew.jsx)("button",{onClick:async()=>{try{await async function(e,t,n){const r=Br(e),i=Gr(r,{returnSecureToken:!0,email:t,password:n,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",fi),s=await i.catch((t=>{throw t.code==="auth/".concat("password-does-not-meet-requirements")&&_i(e),t})),a=await pi._fromIdTokenResponse(r,"signIn",s);return await r._updateCurrentUser(a.user),a}(ay,n,i)}catch(e){console.error(e)}},children:"Sign In"}),(0,Ew.jsx)("div",{children:(0,Ew.jsx)("div",{onClick:()=>{l("/Friendly-Betting/CreateAccount")},className:_w,children:"Don't have account? Create One!"})}),(0,Ew.jsx)("br",{}),(0,Ew.jsx)("br",{}),(0,Ew.jsx)("button",{onClick:async()=>{try{await function(e){return D(e).signOut()}(ay)}catch(e){console.error(e)}},children:"Log Out"})]})},kw=()=>{const[t,n]=(0,e.useState)(!1),r=tw();return(0,e.useEffect)((()=>{const e=setTimeout((()=>{n(!0)}),2);return()=>clearTimeout(e)}),[]),(0,Ew.jsxs)("div",{className:"".concat(yw," ").concat(t?"":ww),children:[(0,Ew.jsx)("div",{className:bw,children:"Create Account"}),(0,Ew.jsx)("input",{type:"text",placeholder:"Email"}),(0,Ew.jsx)("input",{type:"text",placeholder:"Phone"}),(0,Ew.jsx)("br",{}),(0,Ew.jsx)("input",{type:"password",placeholder:"password",name:"",id:""}),(0,Ew.jsx)("input",{type:"password",placeholder:"confirm password",name:"",id:""}),(0,Ew.jsx)("button",{children:"Create Account"}),(0,Ew.jsx)("div",{children:(0,Ew.jsx)("div",{onClick:()=>{r("/Friendly-Betting/SignIn")},className:_w,children:"Already have account? Sign in!"})})]})};var Iw=n(164),Tw=n.t(Iw,2);function Cw(){return Cw=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Cw.apply(this,arguments)}function xw(e,t){if(null==e)return{};var n,r,i={},s=Object.keys(e);for(r=0;r<s.length;r++)n=s[r],t.indexOf(n)>=0||(i[n]=e[n]);return i}new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);const Nw=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","unstable_viewTransition"];new Map;const Aw=t.startTransition;Tw.flushSync;function Pw(t){let{basename:n,children:r,future:i,window:s}=t,a=e.useRef();var o;null==a.current&&(a.current=(void 0===(o={window:s,v5Compat:!0})&&(o={}),vy((function(e,t){let{pathname:n,search:r,hash:i}=e.location;return py("",{pathname:n,search:r,hash:i},t.state&&t.state.usr||null,t.state&&t.state.key||"default")}),(function(e,t){return"string"===typeof t?t:my(t)}),null,o)));let l=a.current,[c,u]=e.useState({action:l.action,location:l.location}),{v7_startTransition:h}=i||{},d=e.useCallback((e=>{h&&Aw?Aw((()=>u(e))):u(e)}),[u,h]);return e.useLayoutEffect((()=>l.listen(d)),[l,d]),e.createElement(mw,{basename:n,children:r,location:c.location,navigationType:c.action,navigator:l})}const Rw="undefined"!==typeof window&&"undefined"!==typeof window.document&&"undefined"!==typeof window.document.createElement,Ow=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Dw=e.forwardRef((function(t,n){let r,{onClick:i,relative:s,reloadDocument:a,replace:o,state:l,target:c,to:u,preventScrollReset:h,unstable_viewTransition:d}=t,f=xw(t,Nw),{basename:p}=e.useContext(Qy),m=!1;if("string"===typeof u&&Ow.test(u)&&(r=u,Rw))try{let e=new URL(window.location.href),t=u.startsWith("//")?new URL(e.protocol+u):new URL(u),n=Oy(t.pathname,p);t.origin===e.origin&&null!=n?u=n+t.search+t.hash:m=!0}catch(y){}let g=function(t,n){let{relative:r}=void 0===n?{}:n;Jy()||hy(!1);let{basename:i,navigator:s}=e.useContext(Qy),{hash:a,pathname:o,search:l}=nw(t,{relative:r}),c=o;return"/"!==i&&(c="/"===o?i:Fy([i,o])),s.createHref({pathname:c,search:l,hash:a})}(u,{relative:s}),v=function(t,n){let{target:r,replace:i,state:s,preventScrollReset:a,relative:o,unstable_viewTransition:l}=void 0===n?{}:n,c=tw(),u=Zy(),h=nw(t,{relative:o});return e.useCallback((e=>{if(function(e,t){return 0===e.button&&(!t||"_self"===t)&&!function(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}(e)}(e,r)){e.preventDefault();let n=void 0!==i?i:my(u)===my(h);c(t,{replace:n,state:s,preventScrollReset:a,relative:o,unstable_viewTransition:l})}}),[u,c,h,i,s,r,t,a,o,l])}(u,{replace:o,state:l,target:c,preventScrollReset:h,relative:s,unstable_viewTransition:d});return e.createElement("a",Cw({},f,{href:r||g,onClick:m||a?i:function(e){i&&i(e),e.defaultPrevented||v(e)},ref:n,target:c}))}));var Lw,Mw;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(Lw||(Lw={})),function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"}(Mw||(Mw={}));const jw=()=>{const e=Zy();return(0,Ew.jsxs)("div",{className:"header",children:[(0,Ew.jsx)("div",{className:"x1",children:(0,Ew.jsx)("div",{className:"logo",children:(0,Ew.jsx)(Dw,{className:"Link",to:"Friendly-Betting/",children:"logo"})})}),(0,Ew.jsx)("div",{className:"x1",children:"Friendly Bets"}),(0,Ew.jsxs)("div",{className:"flex pages x1",children:["/SignIn"!==e.pathname?(0,Ew.jsx)(Dw,{className:"Link",to:"Friendly-Betting/SignIn",children:"Sign In"}):(0,Ew.jsx)(Dw,{className:"Link",to:"/",children:"Sign In"}),(0,Ew.jsx)(Dw,{className:"Link",to:"Friendly-Betting/Bet",children:"Bets"}),(0,Ew.jsx)(Dw,{className:"Link",to:"Friendly-Betting/Friends",children:"Friends"})]})]})},Fw=()=>(0,Ew.jsxs)("div",{children:[(0,Ew.jsx)("h1",{children:"404"}),(0,Ew.jsx)("p",{children:"Page not found!"})]}),Uw=()=>{var t;const[n,r]=(0,e.useState)(!0);console.log(null===ay||void 0===ay||null===(t=ay.currentUser)||void 0===t?void 0:t.email),(0,e.useEffect)((()=>{i()}),[]);const i=()=>{var e;const t=null===ay||void 0===ay||null===(e=ay.currentUser)||void 0===e?void 0:e.email;r(void 0!==t)};return(0,Ew.jsx)("div",{className:"pad",children:n?(0,Ew.jsxs)("div",{children:[(0,Ew.jsx)("h1",{children:"Welcome, User!"}),(0,Ew.jsx)("p",{children:"This is the authenticated content."})]}):(0,Ew.jsxs)("div",{children:[(0,Ew.jsx)("h1",{children:"Please sign in to access this content."}),(0,Ew.jsx)(Dw,{className:"Link",to:"Friendly-Betting/SignIn",children:"Sign In"})]})})},Vw="MoneyLine_MoneyLine__GZY-g",Bw="MoneyLine_betContainer__MPUkR",zw="MoneyLine_bet__iBwWG",qw="MoneyLine_contestant__VUCuJ",Hw="MoneyLine_contestantInput__RtHW6",Ww="MoneyLine_label__SXs1d",Kw="MoneyLine_odds__5UKBZ",Gw="MoneyLine_ViewLabel__dee3p",Qw="MoneyLine_betLabel__xK-Pn",$w={disable:"Players_disable__2Lrxc",friends:"Players_friends__S-rHI",addFiendForm:"Players_addFiendForm__No56b",x:"Players_x__50IpE",or:"Players_or__vxIC5",shareBet:"Players_shareBet__IEGN8",friendsLabel:"Players_friendsLabel__doMbx",container:"Players_container__wuYC4",checkmark:"Players_checkmark__OI0Ce"},Yw=t=>{const[n,r]=(0,e.useState)(""),[i,s]=(0,e.useState)(""),[a,o]=(0,e.useState)(""),[l,c]=(0,e.useState)("");return(0,Ew.jsxs)("form",{className:$w.addFiendForm,onSubmit:e=>{e.preventDefault(),""!==l&&""!==a&&""!==i&&t.addNewPlayers({name:l,email:a,phone:i})},children:[(0,Ew.jsx)("div",{className:$w.x,children:(0,Ew.jsx)("span",{onClick:t.disable,children:"x"})}),(0,Ew.jsxs)("label",{children:[(0,Ew.jsx)("span",{children:"Account Number:"}),(0,Ew.jsx)("input",{type:"text",value:n,onChange:e=>{r(e.target.value)}})]}),(0,Ew.jsx)("br",{}),(0,Ew.jsx)("br",{}),(0,Ew.jsx)("div",{className:$w.or,children:"or"}),(0,Ew.jsx)("br",{}),(0,Ew.jsxs)("label",{children:[(0,Ew.jsx)("span",{children:"Name:"}),(0,Ew.jsx)("input",{type:"text",value:l,onChange:e=>{c(e.target.value)}})]}),(0,Ew.jsx)("br",{}),(0,Ew.jsxs)("label",{children:["Email:",(0,Ew.jsx)("input",{type:"email",value:a,onChange:e=>{o(e.target.value)}})]}),(0,Ew.jsx)("br",{}),(0,Ew.jsxs)("label",{children:[(0,Ew.jsx)("span",{children:"Phone:"}),(0,Ew.jsx)("input",{type:"phone",value:i,onChange:e=>{s(e.target.value)}})]}),(0,Ew.jsx)("br",{}),(0,Ew.jsx)("button",{type:"submit",children:"Add Friend"})]})},Xw=()=>{const[t,n]=(0,e.useState)({friends:[{name:"John",email:"johnRyan@gmail.com",phone:"1234567890"},{name:"Jack",email:"JackRyan@gmail.com",phone:"1234567890"},{name:"Another Person",email:"Person@gmail.com",phone:"1234567890"}]}),[r,i]=(0,e.useState)(!1),s=()=>{i((e=>!e))};return(0,Ew.jsxs)("div",{className:$w.friends,children:[t.friends.map((e=>(0,Ew.jsxs)("div",{children:[(0,Ew.jsx)("h3",{children:e.name}),(0,Ew.jsxs)("p",{children:["Email: ",e.email]}),(0,Ew.jsxs)("p",{children:["Phone: ",e.phone]})]},e.id))),(0,Ew.jsx)("div",{children:r?(0,Ew.jsxs)("div",{children:[(0,Ew.jsx)(Yw,{addNewPlayers:e=>{n((t=>({...t,friends:[...t.friends,e]}))),s()},disable:s}),(0,Ew.jsx)("button",{className:$w.disable,children:"Add Friend"})]}):(0,Ew.jsx)("button",{onClick:s,children:"Add Friend"})})]})},Jw=t=>{const[n,r]=(0,e.useState)({friends:[{name:"John",email:"johnRyan@gmail.com",phone:"1234567890"},{name:"Jack",email:"JackRyan@gmail.com",phone:"1234567890"},{name:"Another Person",email:"Person@gmail.com",phone:"1234567890"}]});return(0,Ew.jsxs)("div",{className:$w.shareBet,children:[(0,Ew.jsx)("div",{className:$w.x,children:(0,Ew.jsx)("span",{onClick:t.display,children:"x"})}),(0,Ew.jsx)("div",{className:$w.friendsLabel,children:(0,Ew.jsx)("span",{children:"friends"})}),(0,Ew.jsxs)("form",{onSubmit:e=>{e.preventDefault(),console.log("Sharing bet")},children:[n.friends.map((e=>(0,Ew.jsxs)("label",{className:$w.container,children:[e.name,(0,Ew.jsx)("input",{className:$w.input,type:"checkbox",name:"",id:""}),(0,Ew.jsx)("span",{className:$w.checkmark})]}))),(0,Ew.jsx)("button",{type:"submit",children:"Send"})]})]})},Zw=()=>{const[t,n]=(0,e.useState)(""),[r,i]=(0,e.useState)(""),[s,a]=(0,e.useState)(""),[o,l]=(0,e.useState)(0),[c,u]=(0,e.useState)(0),[h,d]=(0,e.useState)(!1),f=()=>{d((e=>!e))};return(0,Ew.jsxs)("div",{className:"flex",children:[(0,Ew.jsx)("div",{className:"x2",children:(0,Ew.jsxs)("form",{className:Vw,onSubmit:async e=>{e.preventDefault(),f();try{await ry(cv(oy,"bets"),{type:"Money Line",bet:t}),await ry(cv(oy,"MoneyLineBets"),{bet:t,contestant1:r,contestant1Odds:o,contestant2:s,contestant2Odds:c})}catch(e){console.error(e)}console.log("Creating moneyline bet:")},children:[(0,Ew.jsxs)("div",{className:Bw,children:["Bet:",(0,Ew.jsx)("div",{className:zw,children:(0,Ew.jsx)("textarea",{type:"text",name:"",id:"",onChange:e=>n(e.target.value)})})]}),(0,Ew.jsxs)("div",{className:"flex",children:[(0,Ew.jsxs)("div",{className:qw,children:[(0,Ew.jsx)("div",{children:(0,Ew.jsx)("span",{className:Ww,children:"Contestant 1"})}),(0,Ew.jsx)("input",{type:"text",name:"",value:r,className:Hw,onChange:e=>i(e.target.value)}),(0,Ew.jsxs)("div",{className:Kw,children:[(0,Ew.jsx)("span",{children:"(+ or - odds)"}),(0,Ew.jsx)("input",{type:"number",onChange:e=>l(Number(e.target.value))})]})]}),(0,Ew.jsxs)("div",{className:qw,children:[(0,Ew.jsx)("div",{children:(0,Ew.jsx)("span",{className:Ww,children:"Contestant 2"})}),(0,Ew.jsx)("input",{type:"text",name:"",value:s,className:Hw,onChange:e=>a(e.target.value)}),(0,Ew.jsxs)("div",{className:Kw,children:[(0,Ew.jsx)("span",{children:"(+ or - odds)"}),(0,Ew.jsx)("input",{type:"number",onChange:e=>u(Number(e.target.value))})]})]})]}),(0,Ew.jsx)("button",{type:"submit",children:"Create Bet"})]})}),(0,Ew.jsx)("div",{className:"x1",children:(0,Ew.jsx)(Xw,{})}),(0,Ew.jsx)("div",{children:h?(0,Ew.jsx)(Jw,{display:f}):null})]})},eb=()=>(0,Ew.jsxs)("div",{className:"pad",children:[(0,Ew.jsx)("h1",{children:"Money Line Bets"}),(0,Ew.jsx)(Zw,{})]}),tb={OverUnder:"OverUnder_OverUnder__lZCyp",betContainer:"OverUnder_betContainer__GC+uq",bet:"OverUnder_bet__SUjBe",setting:"OverUnder_setting__o-g2F",input:"OverUnder_input__FR6oC",betLabel:"OverUnder_betLabel__fUG2h",lineLabel:"OverUnder_lineLabel__uLemh",line:"OverUnder_line__xiV+Z",actualLine:"OverUnder_actualLine__NevcO",remain:"OverUnder_remain__s69rd",section:"OverUnder_section__A+HHD",pad:"OverUnder_pad__Qx6VE"},nb=()=>{const[t,n]=(0,e.useState)(""),[r,i]=(0,e.useState)(0),[s,a]=(0,e.useState)(!1),o=()=>{a((e=>!e))};return(0,Ew.jsxs)("div",{className:"flex",children:[(0,Ew.jsx)("div",{className:tb.OverUnder,children:(0,Ew.jsxs)("form",{onSubmit:async e=>{e.preventDefault(),o();try{await ry(cv(oy,"bets"),{type:"Over Under",bet:t}),await ry(cv(oy,"OverUnderBets"),{bet:t,line:r})}catch(e){console.error(e)}console.log("Creating over under bet")},children:[(0,Ew.jsxs)("div",{className:tb.betContainer,children:["Proposition:",(0,Ew.jsx)("div",{className:tb.bet,children:(0,Ew.jsx)("textarea",{type:"text",onChange:e=>{n(e.target.value)}})})]}),(0,Ew.jsx)("div",{children:(0,Ew.jsxs)("div",{className:tb.setting,children:[(0,Ew.jsx)("span",{className:tb.label,children:"Line:"}),(0,Ew.jsx)("input",{className:tb.input,type:"number",step:"0.5",onChange:e=>{i(Number(e.target.value))}})]})}),(0,Ew.jsx)("button",{type:"submit",children:"Create bet"})]})}),(0,Ew.jsx)("div",{className:"x1",children:(0,Ew.jsx)(Xw,{})}),(0,Ew.jsx)("div",{children:s?(0,Ew.jsx)(Jw,{display:o}):null})]})},rb=()=>(0,Ew.jsxs)("div",{className:"pad",children:[(0,Ew.jsx)("h1",{children:"OverUnder Component"}),(0,Ew.jsx)(nb,{})]}),ib="Prop_prop__DRZFt",sb="Prop_betContainer__KSYFf",ab="Prop_bet__7E-T-",ob="Prop_PreSetBetting__MzpqW",lb="Prop_settings__9dmn0",cb="Prop_title__GEvyW",ub="Prop_label__zDU93",hb="Prop_x__tu9O2",db="Prop_option__nu2JJ",fb="Prop_optionInput__MuLBG",pb="Prop_options__EQ8Hr",mb=t=>{const[n,r]=(0,e.useState)(0),[i,s]=(0,e.useState)([]),[a,o]=(0,e.useState)([]);(0,e.useEffect)((()=>{let e=[];for(let t=0;t<n;t++)e.push(t);s(e)}),[n]);return(0,Ew.jsxs)("div",{className:ob,children:[(0,Ew.jsx)("div",{className:hb,children:(0,Ew.jsx)("span",{onClick:t.display,children:"x"})}),(0,Ew.jsx)("div",{className:cb,children:(0,Ew.jsx)("span",{children:"Preset Betting Options"})}),(0,Ew.jsxs)("form",{onSubmit:e=>{e.preventDefault(),t.setOptions(a),console.log("Saving preset betting options")},children:[i.map(((e,t)=>(0,Ew.jsxs)("div",{className:db,children:[(0,Ew.jsxs)("span",{className:ub,children:[e+1,":"]}),(0,Ew.jsx)("input",{className:fb,type:"text",onChange:e=>((e,t)=>{o((n=>(a[t]=e.target.value,a)))})(e,t),placeholder:"Who or what"})]},t))),(0,Ew.jsx)("button",{type:"submit",children:"Save"})]}),(0,Ew.jsx)("button",{onClick:()=>{r(n+1)},children:"Add Option"})]})},gb=()=>{const[t,n]=(0,e.useState)(""),[r,i]=(0,e.useState)([]),[s,a]=(0,e.useState)(!1),[o,l]=(0,e.useState)(!1),c=()=>{l((e=>!e))},u=e=>{a(e.target.checked)};return(0,Ew.jsxs)("div",{className:"flex",children:[(0,Ew.jsx)("div",{className:ib,children:(0,Ew.jsxs)("form",{onSubmit:async e=>{e.preventDefault(),c();try{await ry(cv(oy,"bets"),{type:"Prop",bet:t}),await ry(cv(oy,"PropBets"),{bet:t,options:r})}catch(e){console.error(e)}console.log("Creating prop bet")},children:[(0,Ew.jsxs)("div",{className:sb,children:["Proposition:",(0,Ew.jsx)("div",{className:ab,children:(0,Ew.jsx)("textarea",{type:"text",onChange:e=>{n(e.target.value)}})})]}),(0,Ew.jsxs)("div",{className:lb,children:[(0,Ew.jsx)("input",{type:"checkbox",id:"preSetBetting",checked:s,onChange:u}),(0,Ew.jsx)("label",{htmlFor:"preSetBetting",children:"Pre Set Betting Options"})]}),(0,Ew.jsx)("button",{type:"submit",children:"Create bet"})]})}),(0,Ew.jsx)("div",{children:s?(0,Ew.jsx)(mb,{setOptions:e=>{i(e)},display:u}):null}),(0,Ew.jsx)("div",{className:"x1",children:(0,Ew.jsx)(Xw,{})}),(0,Ew.jsx)("div",{children:o?(0,Ew.jsx)(Jw,{display:c}):null})]})},vb=()=>(0,Ew.jsxs)("div",{className:"pad",children:[(0,Ew.jsx)("h1",{children:"Prop Bets"}),(0,Ew.jsx)(gb,{})]}),yb=()=>{const[t,n]=(0,e.useState)([]),r=Zy(),{bet:i}=r.state;return(0,e.useEffect)((()=>{(async()=>{try{const e=Bv(cv(oy,"MoneyLineBets"),qv("bet","==",i.bet)),t=await ny(e);n(t.docs[0].data())}catch(e){console.error(e)}})()}),[]),(0,Ew.jsxs)("div",{className:"flex pad",children:[(0,Ew.jsx)("div",{className:"x2",children:(0,Ew.jsxs)("div",{children:[(0,Ew.jsx)("h1",{className:Qw,children:t.bet}),(0,Ew.jsxs)("div",{className:"blob",children:[(0,Ew.jsxs)("div",{className:Gw,children:[(0,Ew.jsx)("button",{className:"betButton",children:"Bet"}),(0,Ew.jsxs)("h2",{children:[t.contestant1," "]}),t.contestant1Odds>0?(0,Ew.jsxs)("p",{className:"green",children:["(+",t.contestant1Odds,")"]}):(0,Ew.jsxs)("p",{className:"red",children:["(",t.contestant1Odds,")"]})]}),(0,Ew.jsx)("hr",{}),(0,Ew.jsxs)("div",{className:Gw,children:[(0,Ew.jsx)("button",{className:"betButton",children:"Bet"}),(0,Ew.jsxs)("h2",{children:[t.contestant2," "]}),t.contestant2Odds>0?(0,Ew.jsxs)("p",{className:"green",children:["(+",t.contestant2Odds,")"]}):(0,Ew.jsxs)("p",{className:"red",children:["(",t.contestant2Odds,")"]})]})]})]})}),(0,Ew.jsx)("div",{className:"x1",children:(0,Ew.jsx)(Xw,{})})]})},wb=()=>{const[t,n]=(0,e.useState)([]),r=Zy(),{bet:i}=r.state;return(0,e.useEffect)((()=>{(async()=>{try{const e=Bv(cv(oy,"OverUnderBets"),qv("bet","==",i.bet)),t=await ny(e);n(t.docs[0].data())}catch(e){console.error(e)}})()}),[]),(0,Ew.jsxs)("div",{className:"flex pad",children:[(0,Ew.jsx)("div",{className:"x2",children:(0,Ew.jsxs)("div",{children:[(0,Ew.jsx)("h1",{className:tb.betLabel,children:t.bet}),(0,Ew.jsxs)("div",{className:"blob row ".concat(tb.pad),children:[(0,Ew.jsxs)("div",{className:tb.section,children:[(0,Ew.jsx)("button",{className:"betButton ".concat(tb.button),children:"Under"}),(0,Ew.jsx)("p",{children:"8 others have taken the under"})]}),(0,Ew.jsxs)("div",{className:tb.line,children:[(0,Ew.jsx)("div",{className:tb.lineLabel,children:(0,Ew.jsx)("span",{children:"Line"})}),(0,Ew.jsx)("div",{className:tb.actualLine,children:t.line}),(0,Ew.jsx)("div",{className:tb.remain,children:"3 people have not voted"})]}),(0,Ew.jsxs)("div",{className:tb.section,children:[(0,Ew.jsx)("button",{className:"betButton",children:"Over"}),(0,Ew.jsx)("p",{children:"12 others have taken the over"})]})]})]})}),(0,Ew.jsx)("div",{className:"x1",children:(0,Ew.jsx)(Xw,{})})]})},bb=()=>{const[t,n]=(0,e.useState)([]),[r,i]=(0,e.useState)(0),s=Zy(),{bet:a}=s.state;return(0,e.useEffect)((()=>{(async()=>{try{const e=Bv(cv(oy,"PropBets"),qv("bet","==",a.bet)),t=await ny(e);n(t.docs[0].data()),i(t.docs[0].data().options.length)}catch(e){console.error(e)}})()}),[]),(0,Ew.jsx)("div",{children:(0,Ew.jsxs)("div",{className:"flex pad",children:[(0,Ew.jsx)("div",{className:"x2",children:(0,Ew.jsxs)("div",{children:[(0,Ew.jsx)("h1",{children:t.bet}),r>0?(0,Ew.jsxs)("div",{children:[(0,Ew.jsx)("h4",{children:(0,Ew.jsx)("span",{children:"Betting"})}),(0,Ew.jsx)("div",{className:pb,children:t.options.map(((e,t)=>(0,Ew.jsx)("div",{children:(0,Ew.jsx)("p",{children:e})},t)))})]}):null]})}),(0,Ew.jsx)("div",{className:"x1",children:(0,Ew.jsx)(Xw,{})})]})})},_b="Bets_betNav__NdIy7",Eb="Bets_BettingLinks__UtSL7",Sb="Bets_x__IOVNi",kb="Bets_bet__pvKP6",Ib="Bets_link__ibFCG",Tb=e=>{const t=tw();return(0,Ew.jsxs)("div",{className:_b,children:[(0,Ew.jsx)("div",{className:Sb,children:(0,Ew.jsx)("span",{onClick:e.swap,children:"x"})}),(0,Ew.jsx)("h1",{children:(0,Ew.jsx)("span",{children:"Bets"})}),(0,Ew.jsxs)("div",{className:Eb,children:[(0,Ew.jsx)("div",{children:(0,Ew.jsx)("div",{onClick:()=>{t("/Friendly-Betting/MoneyLineBets")},className:"Link",children:"Money Line Bets"})}),(0,Ew.jsx)("div",{children:(0,Ew.jsx)("div",{onClick:()=>{t("/Friendly-Betting/OverUnderBets")},className:"Link",children:"Over / Under Bets"})}),(0,Ew.jsx)("div",{children:(0,Ew.jsx)("div",{onClick:()=>{t("/Friendly-Betting/PropBets")},className:"Link",children:"Prop Bets"})})]})]})},Cb=e=>{const t=()=>"Money Line"===e.bet.type?"MoneyLineBets/":"Over Under"===e.bet.type?"OverUnderBets/":"Prop"===e.bet.type?"PropBets/":void 0;return(0,Ew.jsx)("div",{onClick:t,children:(0,Ew.jsx)(Dw,{to:"/Friendly-Betting/Bet/".concat(t()),state:{bet:e.bet},x:!0,className:Ib,children:(0,Ew.jsxs)("div",{className:kb,children:[(0,Ew.jsx)("h4",{children:e.bet.type}),(0,Ew.jsx)("p",{children:e.bet.bet})]},e.bet.id)})})},xb=()=>{const[t,n]=(0,e.useState)(""),[r,i]=(0,e.useState)(!1),[s,a]=(0,e.useState)([]);(0,e.useEffect)((()=>{(async()=>{try{const e=(await ny(cv(oy,"bets"))).docs.map((e=>({...e.data(),id:e.id})));console.log(e),a(e)}catch(e){console.error(e)}})()}),[]);const o=()=>{i((e=>!e))};return(0,Ew.jsxs)("div",{className:"flex pad",children:[(0,Ew.jsx)("div",{className:"x2",children:" "===t?(0,Ew.jsxs)("div",{children:[(0,Ew.jsx)("h3",{children:"You are not in any bets yet"}),(0,Ew.jsx)("button",{onClick:o,children:"Create One!"}),r?(0,Ew.jsx)(Tb,{swap:o}):null]}):(0,Ew.jsxs)("div",{children:[s.map((e=>(0,Ew.jsx)(Cb,{bet:e}))),(0,Ew.jsx)("button",{onClick:o,children:"Create One!"}),r?(0,Ew.jsx)(Tb,{swap:o}):null]})}),(0,Ew.jsx)("div",{className:"x1",children:(0,Ew.jsx)(Xw,{})})]})};const Nb=function(){return(0,Ew.jsx)("div",{children:(0,Ew.jsx)("h1",{children:"Friends"})})};const Ab=function(){return(0,Ew.jsxs)(Pw,{children:[(0,Ew.jsx)(jw,{}),(0,Ew.jsxs)(gw,{children:[(0,Ew.jsx)(pw,{path:"Friendly-Betting/",element:(0,Ew.jsx)(Uw,{})}),(0,Ew.jsx)(pw,{path:"Friendly-Betting/SignIn",element:(0,Ew.jsx)(Sw,{})}),(0,Ew.jsx)(pw,{path:"Friendly-Betting/CreateAccount",element:(0,Ew.jsx)(kw,{})}),(0,Ew.jsx)(pw,{path:"Friendly-Betting/Bet",element:(0,Ew.jsx)(xb,{})}),(0,Ew.jsx)(pw,{path:"Friendly-Betting/Friends",element:(0,Ew.jsx)(Nb,{})}),(0,Ew.jsx)(pw,{path:"Friendly-Betting/MoneyLineBets",element:(0,Ew.jsx)(eb,{})}),(0,Ew.jsx)(pw,{path:"Friendly-Betting/OverUnderBets",element:(0,Ew.jsx)(rb,{})}),(0,Ew.jsx)(pw,{path:"Friendly-Betting/PropBets",element:(0,Ew.jsx)(vb,{})}),(0,Ew.jsx)(pw,{path:"/Friendly-Betting/Bet/MoneyLineBets/",element:(0,Ew.jsx)(yb,{})}),(0,Ew.jsx)(pw,{path:"/Friendly-Betting/Bet/OverUnderBets/",element:(0,Ew.jsx)(wb,{})}),(0,Ew.jsx)(pw,{path:"/Friendly-Betting/Bet/PropBets/",element:(0,Ew.jsx)(bb,{})}),(0,Ew.jsx)(pw,{path:"/*",element:(0,Ew.jsx)(Fw,{})})]})]})},Pb=e=>{e&&e instanceof Function&&n.e(787).then(n.bind(n,787)).then((t=>{let{getCLS:n,getFID:r,getFCP:i,getLCP:s,getTTFB:a}=t;n(e),r(e),i(e),s(e),a(e)}))};r.createRoot(document.getElementById("root")).render((0,Ew.jsx)(e.StrictMode,{children:(0,Ew.jsx)(Ab,{})})),Pb()})()})(); -//# sourceMappingURL=main.e9c9ba71.js.map \ No newline at end of file +/*! For license information please see main.fc2a7381.js.LICENSE.txt */ +(()=>{"use strict";var e={463:(e,t,n)=>{var r=n(791),i=n(296);function s(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var a=new Set,o={};function l(e,t){c(e,t),c(e+"Capture",t)}function c(e,t){for(o[e]=t,e=0;e<t.length;e++)a.add(t[e])}var u=!("undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement),h=Object.prototype.hasOwnProperty,d=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,f={},p={};function m(e,t,n,r,i,s,a){this.acceptsBooleans=2===t||3===t||4===t,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=a}var g={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach((function(e){g[e]=new m(e,0,!1,e,null,!1,!1)})),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach((function(e){var t=e[0];g[t]=new m(t,1,!1,e[1],null,!1,!1)})),["contentEditable","draggable","spellCheck","value"].forEach((function(e){g[e]=new m(e,2,!1,e.toLowerCase(),null,!1,!1)})),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach((function(e){g[e]=new m(e,2,!1,e,null,!1,!1)})),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach((function(e){g[e]=new m(e,3,!1,e.toLowerCase(),null,!1,!1)})),["checked","multiple","muted","selected"].forEach((function(e){g[e]=new m(e,3,!0,e,null,!1,!1)})),["capture","download"].forEach((function(e){g[e]=new m(e,4,!1,e,null,!1,!1)})),["cols","rows","size","span"].forEach((function(e){g[e]=new m(e,6,!1,e,null,!1,!1)})),["rowSpan","start"].forEach((function(e){g[e]=new m(e,5,!1,e.toLowerCase(),null,!1,!1)}));var v=/[\-:]([a-z])/g;function y(e){return e[1].toUpperCase()}function w(e,t,n,r){var i=g.hasOwnProperty(t)?g[t]:null;(null!==i?0!==i.type:r||!(2<t.length)||"o"!==t[0]&&"O"!==t[0]||"n"!==t[1]&&"N"!==t[1])&&(function(e,t,n,r){if(null===t||"undefined"===typeof t||function(e,t,n,r){if(null!==n&&0===n.type)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return!r&&(null!==n?!n.acceptsBooleans:"data-"!==(e=e.toLowerCase().slice(0,5))&&"aria-"!==e);default:return!1}}(e,t,n,r))return!0;if(r)return!1;if(null!==n)switch(n.type){case 3:return!t;case 4:return!1===t;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}(t,n,i,r)&&(n=null),r||null===i?function(e){return!!h.call(p,e)||!h.call(f,e)&&(d.test(e)?p[e]=!0:(f[e]=!0,!1))}(t)&&(null===n?e.removeAttribute(t):e.setAttribute(t,""+n)):i.mustUseProperty?e[i.propertyName]=null===n?3!==i.type&&"":n:(t=i.attributeName,r=i.attributeNamespace,null===n?e.removeAttribute(t):(n=3===(i=i.type)||4===i&&!0===n?"":""+n,r?e.setAttributeNS(r,t,n):e.setAttribute(t,n))))}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach((function(e){var t=e.replace(v,y);g[t]=new m(t,1,!1,e,null,!1,!1)})),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach((function(e){var t=e.replace(v,y);g[t]=new m(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)})),["xml:base","xml:lang","xml:space"].forEach((function(e){var t=e.replace(v,y);g[t]=new m(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)})),["tabIndex","crossOrigin"].forEach((function(e){g[e]=new m(e,1,!1,e.toLowerCase(),null,!1,!1)})),g.xlinkHref=new m("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach((function(e){g[e]=new m(e,1,!1,e.toLowerCase(),null,!0,!0)}));var b=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,_=Symbol.for("react.element"),E=Symbol.for("react.portal"),S=Symbol.for("react.fragment"),k=Symbol.for("react.strict_mode"),I=Symbol.for("react.profiler"),T=Symbol.for("react.provider"),C=Symbol.for("react.context"),x=Symbol.for("react.forward_ref"),N=Symbol.for("react.suspense"),A=Symbol.for("react.suspense_list"),P=Symbol.for("react.memo"),R=Symbol.for("react.lazy");Symbol.for("react.scope"),Symbol.for("react.debug_trace_mode");var D=Symbol.for("react.offscreen");Symbol.for("react.legacy_hidden"),Symbol.for("react.cache"),Symbol.for("react.tracing_marker");var O=Symbol.iterator;function L(e){return null===e||"object"!==typeof e?null:"function"===typeof(e=O&&e[O]||e["@@iterator"])?e:null}var M,j=Object.assign;function F(e){if(void 0===M)try{throw Error()}catch(n){var t=n.stack.trim().match(/\n( *(at )?)/);M=t&&t[1]||""}return"\n"+M+e}var U=!1;function V(e,t){if(!e||U)return"";U=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),"object"===typeof Reflect&&Reflect.construct){try{Reflect.construct(t,[])}catch(c){var r=c}Reflect.construct(e,[],t)}else{try{t.call()}catch(c){r=c}e.call(t.prototype)}else{try{throw Error()}catch(c){r=c}e()}}catch(c){if(c&&r&&"string"===typeof c.stack){for(var i=c.stack.split("\n"),s=r.stack.split("\n"),a=i.length-1,o=s.length-1;1<=a&&0<=o&&i[a]!==s[o];)o--;for(;1<=a&&0<=o;a--,o--)if(i[a]!==s[o]){if(1!==a||1!==o)do{if(a--,0>--o||i[a]!==s[o]){var l="\n"+i[a].replace(" at new "," at ");return e.displayName&&l.includes("<anonymous>")&&(l=l.replace("<anonymous>",e.displayName)),l}}while(1<=a&&0<=o);break}}}finally{U=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?F(e):""}function B(e){switch(e.tag){case 5:return F(e.type);case 16:return F("Lazy");case 13:return F("Suspense");case 19:return F("SuspenseList");case 0:case 2:case 15:return e=V(e.type,!1);case 11:return e=V(e.type.render,!1);case 1:return e=V(e.type,!0);default:return""}}function z(e){if(null==e)return null;if("function"===typeof e)return e.displayName||e.name||null;if("string"===typeof e)return e;switch(e){case S:return"Fragment";case E:return"Portal";case I:return"Profiler";case k:return"StrictMode";case N:return"Suspense";case A:return"SuspenseList"}if("object"===typeof e)switch(e.$$typeof){case C:return(e.displayName||"Context")+".Consumer";case T:return(e._context.displayName||"Context")+".Provider";case x:var t=e.render;return(e=e.displayName)||(e=""!==(e=t.displayName||t.name||"")?"ForwardRef("+e+")":"ForwardRef"),e;case P:return null!==(t=e.displayName||null)?t:z(e.type)||"Memo";case R:t=e._payload,e=e._init;try{return z(e(t))}catch(n){}}return null}function q(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=(e=t.render).displayName||e.name||"",t.displayName||(""!==e?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return z(t);case 8:return t===k?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"===typeof t)return t.displayName||t.name||null;if("string"===typeof t)return t}return null}function H(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":case"object":return e;default:return""}}function W(e){var t=e.type;return(e=e.nodeName)&&"input"===e.toLowerCase()&&("checkbox"===t||"radio"===t)}function K(e){e._valueTracker||(e._valueTracker=function(e){var t=W(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&"undefined"!==typeof n&&"function"===typeof n.get&&"function"===typeof n.set){var i=n.get,s=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(e){r=""+e,s.call(this,e)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(e){r=""+e},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}(e))}function G(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=W(e)?e.checked?"true":"false":e.value),(e=r)!==n&&(t.setValue(e),!0)}function Q(e){if("undefined"===typeof(e=e||("undefined"!==typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(t){return e.body}}function $(e,t){var n=t.checked;return j({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=n?n:e._wrapperState.initialChecked})}function Y(e,t){var n=null==t.defaultValue?"":t.defaultValue,r=null!=t.checked?t.checked:t.defaultChecked;n=H(null!=t.value?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:"checkbox"===t.type||"radio"===t.type?null!=t.checked:null!=t.value}}function X(e,t){null!=(t=t.checked)&&w(e,"checked",t,!1)}function J(e,t){X(e,t);var n=H(t.value),r=t.type;if(null!=n)"number"===r?(0===n&&""===e.value||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if("submit"===r||"reset"===r)return void e.removeAttribute("value");t.hasOwnProperty("value")?ee(e,t.type,n):t.hasOwnProperty("defaultValue")&&ee(e,t.type,H(t.defaultValue)),null==t.checked&&null!=t.defaultChecked&&(e.defaultChecked=!!t.defaultChecked)}function Z(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!("submit"!==r&&"reset"!==r||void 0!==t.value&&null!==t.value))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}""!==(n=e.name)&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,""!==n&&(e.name=n)}function ee(e,t,n){"number"===t&&Q(e.ownerDocument)===e||(null==n?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var te=Array.isArray;function ne(e,t,n,r){if(e=e.options,t){t={};for(var i=0;i<n.length;i++)t["$"+n[i]]=!0;for(n=0;n<e.length;n++)i=t.hasOwnProperty("$"+e[n].value),e[n].selected!==i&&(e[n].selected=i),i&&r&&(e[n].defaultSelected=!0)}else{for(n=""+H(n),t=null,i=0;i<e.length;i++){if(e[i].value===n)return e[i].selected=!0,void(r&&(e[i].defaultSelected=!0));null!==t||e[i].disabled||(t=e[i])}null!==t&&(t.selected=!0)}}function re(e,t){if(null!=t.dangerouslySetInnerHTML)throw Error(s(91));return j({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function ie(e,t){var n=t.value;if(null==n){if(n=t.children,t=t.defaultValue,null!=n){if(null!=t)throw Error(s(92));if(te(n)){if(1<n.length)throw Error(s(93));n=n[0]}t=n}null==t&&(t=""),n=t}e._wrapperState={initialValue:H(n)}}function se(e,t){var n=H(t.value),r=H(t.defaultValue);null!=n&&((n=""+n)!==e.value&&(e.value=n),null==t.defaultValue&&e.defaultValue!==n&&(e.defaultValue=n)),null!=r&&(e.defaultValue=""+r)}function ae(e){var t=e.textContent;t===e._wrapperState.initialValue&&""!==t&&null!==t&&(e.value=t)}function oe(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function le(e,t){return null==e||"http://www.w3.org/1999/xhtml"===e?oe(t):"http://www.w3.org/2000/svg"===e&&"foreignObject"===t?"http://www.w3.org/1999/xhtml":e}var ce,ue,he=(ue=function(e,t){if("http://www.w3.org/2000/svg"!==e.namespaceURI||"innerHTML"in e)e.innerHTML=t;else{for((ce=ce||document.createElement("div")).innerHTML="<svg>"+t.valueOf().toString()+"</svg>",t=ce.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}},"undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(e,t,n,r){MSApp.execUnsafeLocalFunction((function(){return ue(e,t)}))}:ue);function de(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&3===n.nodeType)return void(n.nodeValue=t)}e.textContent=t}var fe={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},pe=["Webkit","ms","Moz","O"];function me(e,t,n){return null==t||"boolean"===typeof t||""===t?"":n||"number"!==typeof t||0===t||fe.hasOwnProperty(e)&&fe[e]?(""+t).trim():t+"px"}function ge(e,t){for(var n in e=e.style,t)if(t.hasOwnProperty(n)){var r=0===n.indexOf("--"),i=me(n,t[n],r);"float"===n&&(n="cssFloat"),r?e.setProperty(n,i):e[n]=i}}Object.keys(fe).forEach((function(e){pe.forEach((function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),fe[t]=fe[e]}))}));var ve=j({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ye(e,t){if(t){if(ve[e]&&(null!=t.children||null!=t.dangerouslySetInnerHTML))throw Error(s(137,e));if(null!=t.dangerouslySetInnerHTML){if(null!=t.children)throw Error(s(60));if("object"!==typeof t.dangerouslySetInnerHTML||!("__html"in t.dangerouslySetInnerHTML))throw Error(s(61))}if(null!=t.style&&"object"!==typeof t.style)throw Error(s(62))}}function we(e,t){if(-1===e.indexOf("-"))return"string"===typeof t.is;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var be=null;function _e(e){return(e=e.target||e.srcElement||window).correspondingUseElement&&(e=e.correspondingUseElement),3===e.nodeType?e.parentNode:e}var Ee=null,Se=null,ke=null;function Ie(e){if(e=wi(e)){if("function"!==typeof Ee)throw Error(s(280));var t=e.stateNode;t&&(t=_i(t),Ee(e.stateNode,e.type,t))}}function Te(e){Se?ke?ke.push(e):ke=[e]:Se=e}function Ce(){if(Se){var e=Se,t=ke;if(ke=Se=null,Ie(e),t)for(e=0;e<t.length;e++)Ie(t[e])}}function xe(e,t){return e(t)}function Ne(){}var Ae=!1;function Pe(e,t,n){if(Ae)return e(t,n);Ae=!0;try{return xe(e,t,n)}finally{Ae=!1,(null!==Se||null!==ke)&&(Ne(),Ce())}}function Re(e,t){var n=e.stateNode;if(null===n)return null;var r=_i(n);if(null===r)return null;n=r[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(r=!r.disabled)||(r=!("button"===(e=e.type)||"input"===e||"select"===e||"textarea"===e)),e=!r;break e;default:e=!1}if(e)return null;if(n&&"function"!==typeof n)throw Error(s(231,t,typeof n));return n}var De=!1;if(u)try{var Oe={};Object.defineProperty(Oe,"passive",{get:function(){De=!0}}),window.addEventListener("test",Oe,Oe),window.removeEventListener("test",Oe,Oe)}catch(ue){De=!1}function Le(e,t,n,r,i,s,a,o,l){var c=Array.prototype.slice.call(arguments,3);try{t.apply(n,c)}catch(u){this.onError(u)}}var Me=!1,je=null,Fe=!1,Ue=null,Ve={onError:function(e){Me=!0,je=e}};function Be(e,t,n,r,i,s,a,o,l){Me=!1,je=null,Le.apply(Ve,arguments)}function ze(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do{0!==(4098&(t=e).flags)&&(n=t.return),e=t.return}while(e)}return 3===t.tag?n:null}function qe(e){if(13===e.tag){var t=e.memoizedState;if(null===t&&(null!==(e=e.alternate)&&(t=e.memoizedState)),null!==t)return t.dehydrated}return null}function He(e){if(ze(e)!==e)throw Error(s(188))}function We(e){return null!==(e=function(e){var t=e.alternate;if(!t){if(null===(t=ze(e)))throw Error(s(188));return t!==e?null:e}for(var n=e,r=t;;){var i=n.return;if(null===i)break;var a=i.alternate;if(null===a){if(null!==(r=i.return)){n=r;continue}break}if(i.child===a.child){for(a=i.child;a;){if(a===n)return He(i),e;if(a===r)return He(i),t;a=a.sibling}throw Error(s(188))}if(n.return!==r.return)n=i,r=a;else{for(var o=!1,l=i.child;l;){if(l===n){o=!0,n=i,r=a;break}if(l===r){o=!0,r=i,n=a;break}l=l.sibling}if(!o){for(l=a.child;l;){if(l===n){o=!0,n=a,r=i;break}if(l===r){o=!0,r=a,n=i;break}l=l.sibling}if(!o)throw Error(s(189))}}if(n.alternate!==r)throw Error(s(190))}if(3!==n.tag)throw Error(s(188));return n.stateNode.current===n?e:t}(e))?Ke(e):null}function Ke(e){if(5===e.tag||6===e.tag)return e;for(e=e.child;null!==e;){var t=Ke(e);if(null!==t)return t;e=e.sibling}return null}var Ge=i.unstable_scheduleCallback,Qe=i.unstable_cancelCallback,$e=i.unstable_shouldYield,Ye=i.unstable_requestPaint,Xe=i.unstable_now,Je=i.unstable_getCurrentPriorityLevel,Ze=i.unstable_ImmediatePriority,et=i.unstable_UserBlockingPriority,tt=i.unstable_NormalPriority,nt=i.unstable_LowPriority,rt=i.unstable_IdlePriority,it=null,st=null;var at=Math.clz32?Math.clz32:function(e){return e>>>=0,0===e?32:31-(ot(e)/lt|0)|0},ot=Math.log,lt=Math.LN2;var ct=64,ut=4194304;function ht(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return 4194240&e;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return 130023424&e;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function dt(e,t){var n=e.pendingLanes;if(0===n)return 0;var r=0,i=e.suspendedLanes,s=e.pingedLanes,a=268435455&n;if(0!==a){var o=a&~i;0!==o?r=ht(o):0!==(s&=a)&&(r=ht(s))}else 0!==(a=n&~i)?r=ht(a):0!==s&&(r=ht(s));if(0===r)return 0;if(0!==t&&t!==r&&0===(t&i)&&((i=r&-r)>=(s=t&-t)||16===i&&0!==(4194240&s)))return t;if(0!==(4&r)&&(r|=16&n),0!==(t=e.entangledLanes))for(e=e.entanglements,t&=r;0<t;)i=1<<(n=31-at(t)),r|=e[n],t&=~i;return r}function ft(e,t){switch(e){case 1:case 2:case 4:return t+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;default:return-1}}function pt(e){return 0!==(e=-1073741825&e.pendingLanes)?e:1073741824&e?1073741824:0}function mt(){var e=ct;return 0===(4194240&(ct<<=1))&&(ct=64),e}function gt(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function vt(e,t,n){e.pendingLanes|=t,536870912!==t&&(e.suspendedLanes=0,e.pingedLanes=0),(e=e.eventTimes)[t=31-at(t)]=n}function yt(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-at(n),i=1<<r;i&t|e[r]&t&&(e[r]|=t),n&=~i}}var wt=0;function bt(e){return 1<(e&=-e)?4<e?0!==(268435455&e)?16:536870912:4:1}var _t,Et,St,kt,It,Tt=!1,Ct=[],xt=null,Nt=null,At=null,Pt=new Map,Rt=new Map,Dt=[],Ot="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function Lt(e,t){switch(e){case"focusin":case"focusout":xt=null;break;case"dragenter":case"dragleave":Nt=null;break;case"mouseover":case"mouseout":At=null;break;case"pointerover":case"pointerout":Pt.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":Rt.delete(t.pointerId)}}function Mt(e,t,n,r,i,s){return null===e||e.nativeEvent!==s?(e={blockedOn:t,domEventName:n,eventSystemFlags:r,nativeEvent:s,targetContainers:[i]},null!==t&&(null!==(t=wi(t))&&Et(t)),e):(e.eventSystemFlags|=r,t=e.targetContainers,null!==i&&-1===t.indexOf(i)&&t.push(i),e)}function jt(e){var t=yi(e.target);if(null!==t){var n=ze(t);if(null!==n)if(13===(t=n.tag)){if(null!==(t=qe(n)))return e.blockedOn=t,void It(e.priority,(function(){St(n)}))}else if(3===t&&n.stateNode.current.memoizedState.isDehydrated)return void(e.blockedOn=3===n.tag?n.stateNode.containerInfo:null)}e.blockedOn=null}function Ft(e){if(null!==e.blockedOn)return!1;for(var t=e.targetContainers;0<t.length;){var n=$t(e.domEventName,e.eventSystemFlags,t[0],e.nativeEvent);if(null!==n)return null!==(t=wi(n))&&Et(t),e.blockedOn=n,!1;var r=new(n=e.nativeEvent).constructor(n.type,n);be=r,n.target.dispatchEvent(r),be=null,t.shift()}return!0}function Ut(e,t,n){Ft(e)&&n.delete(t)}function Vt(){Tt=!1,null!==xt&&Ft(xt)&&(xt=null),null!==Nt&&Ft(Nt)&&(Nt=null),null!==At&&Ft(At)&&(At=null),Pt.forEach(Ut),Rt.forEach(Ut)}function Bt(e,t){e.blockedOn===t&&(e.blockedOn=null,Tt||(Tt=!0,i.unstable_scheduleCallback(i.unstable_NormalPriority,Vt)))}function zt(e){function t(t){return Bt(t,e)}if(0<Ct.length){Bt(Ct[0],e);for(var n=1;n<Ct.length;n++){var r=Ct[n];r.blockedOn===e&&(r.blockedOn=null)}}for(null!==xt&&Bt(xt,e),null!==Nt&&Bt(Nt,e),null!==At&&Bt(At,e),Pt.forEach(t),Rt.forEach(t),n=0;n<Dt.length;n++)(r=Dt[n]).blockedOn===e&&(r.blockedOn=null);for(;0<Dt.length&&null===(n=Dt[0]).blockedOn;)jt(n),null===n.blockedOn&&Dt.shift()}var qt=b.ReactCurrentBatchConfig,Ht=!0;function Wt(e,t,n,r){var i=wt,s=qt.transition;qt.transition=null;try{wt=1,Gt(e,t,n,r)}finally{wt=i,qt.transition=s}}function Kt(e,t,n,r){var i=wt,s=qt.transition;qt.transition=null;try{wt=4,Gt(e,t,n,r)}finally{wt=i,qt.transition=s}}function Gt(e,t,n,r){if(Ht){var i=$t(e,t,n,r);if(null===i)Hr(e,t,r,Qt,n),Lt(e,r);else if(function(e,t,n,r,i){switch(t){case"focusin":return xt=Mt(xt,e,t,n,r,i),!0;case"dragenter":return Nt=Mt(Nt,e,t,n,r,i),!0;case"mouseover":return At=Mt(At,e,t,n,r,i),!0;case"pointerover":var s=i.pointerId;return Pt.set(s,Mt(Pt.get(s)||null,e,t,n,r,i)),!0;case"gotpointercapture":return s=i.pointerId,Rt.set(s,Mt(Rt.get(s)||null,e,t,n,r,i)),!0}return!1}(i,e,t,n,r))r.stopPropagation();else if(Lt(e,r),4&t&&-1<Ot.indexOf(e)){for(;null!==i;){var s=wi(i);if(null!==s&&_t(s),null===(s=$t(e,t,n,r))&&Hr(e,t,r,Qt,n),s===i)break;i=s}null!==i&&r.stopPropagation()}else Hr(e,t,r,null,n)}}var Qt=null;function $t(e,t,n,r){if(Qt=null,null!==(e=yi(e=_e(r))))if(null===(t=ze(e)))e=null;else if(13===(n=t.tag)){if(null!==(e=qe(t)))return e;e=null}else if(3===n){if(t.stateNode.current.memoizedState.isDehydrated)return 3===t.tag?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null);return Qt=e,null}function Yt(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(Je()){case Ze:return 1;case et:return 4;case tt:case nt:return 16;case rt:return 536870912;default:return 16}default:return 16}}var Xt=null,Jt=null,Zt=null;function en(){if(Zt)return Zt;var e,t,n=Jt,r=n.length,i="value"in Xt?Xt.value:Xt.textContent,s=i.length;for(e=0;e<r&&n[e]===i[e];e++);var a=r-e;for(t=1;t<=a&&n[r-t]===i[s-t];t++);return Zt=i.slice(e,1<t?1-t:void 0)}function tn(e){var t=e.keyCode;return"charCode"in e?0===(e=e.charCode)&&13===t&&(e=13):e=t,10===e&&(e=13),32<=e||13===e?e:0}function nn(){return!0}function rn(){return!1}function sn(e){function t(t,n,r,i,s){for(var a in this._reactName=t,this._targetInst=r,this.type=n,this.nativeEvent=i,this.target=s,this.currentTarget=null,e)e.hasOwnProperty(a)&&(t=e[a],this[a]=t?t(i):i[a]);return this.isDefaultPrevented=(null!=i.defaultPrevented?i.defaultPrevented:!1===i.returnValue)?nn:rn,this.isPropagationStopped=rn,this}return j(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!==typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=nn)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!==typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=nn)},persist:function(){},isPersistent:nn}),t}var an,on,ln,cn={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},un=sn(cn),hn=j({},cn,{view:0,detail:0}),dn=sn(hn),fn=j({},hn,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:In,button:0,buttons:0,relatedTarget:function(e){return void 0===e.relatedTarget?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==ln&&(ln&&"mousemove"===e.type?(an=e.screenX-ln.screenX,on=e.screenY-ln.screenY):on=an=0,ln=e),an)},movementY:function(e){return"movementY"in e?e.movementY:on}}),pn=sn(fn),mn=sn(j({},fn,{dataTransfer:0})),gn=sn(j({},hn,{relatedTarget:0})),vn=sn(j({},cn,{animationName:0,elapsedTime:0,pseudoElement:0})),yn=j({},cn,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),wn=sn(yn),bn=sn(j({},cn,{data:0})),_n={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},En={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},Sn={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function kn(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):!!(e=Sn[e])&&!!t[e]}function In(){return kn}var Tn=j({},hn,{key:function(e){if(e.key){var t=_n[e.key]||e.key;if("Unidentified"!==t)return t}return"keypress"===e.type?13===(e=tn(e))?"Enter":String.fromCharCode(e):"keydown"===e.type||"keyup"===e.type?En[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:In,charCode:function(e){return"keypress"===e.type?tn(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?tn(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}}),Cn=sn(Tn),xn=sn(j({},fn,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0})),Nn=sn(j({},hn,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:In})),An=sn(j({},cn,{propertyName:0,elapsedTime:0,pseudoElement:0})),Pn=j({},fn,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),Rn=sn(Pn),Dn=[9,13,27,32],On=u&&"CompositionEvent"in window,Ln=null;u&&"documentMode"in document&&(Ln=document.documentMode);var Mn=u&&"TextEvent"in window&&!Ln,jn=u&&(!On||Ln&&8<Ln&&11>=Ln),Fn=String.fromCharCode(32),Un=!1;function Vn(e,t){switch(e){case"keyup":return-1!==Dn.indexOf(t.keyCode);case"keydown":return 229!==t.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Bn(e){return"object"===typeof(e=e.detail)&&"data"in e?e.data:null}var zn=!1;var qn={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Hn(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!qn[e.type]:"textarea"===t}function Wn(e,t,n,r){Te(r),0<(t=Kr(t,"onChange")).length&&(n=new un("onChange","change",null,n,r),e.push({event:n,listeners:t}))}var Kn=null,Gn=null;function Qn(e){Fr(e,0)}function $n(e){if(G(bi(e)))return e}function Yn(e,t){if("change"===e)return t}var Xn=!1;if(u){var Jn;if(u){var Zn="oninput"in document;if(!Zn){var er=document.createElement("div");er.setAttribute("oninput","return;"),Zn="function"===typeof er.oninput}Jn=Zn}else Jn=!1;Xn=Jn&&(!document.documentMode||9<document.documentMode)}function tr(){Kn&&(Kn.detachEvent("onpropertychange",nr),Gn=Kn=null)}function nr(e){if("value"===e.propertyName&&$n(Gn)){var t=[];Wn(t,Gn,e,_e(e)),Pe(Qn,t)}}function rr(e,t,n){"focusin"===e?(tr(),Gn=n,(Kn=t).attachEvent("onpropertychange",nr)):"focusout"===e&&tr()}function ir(e){if("selectionchange"===e||"keyup"===e||"keydown"===e)return $n(Gn)}function sr(e,t){if("click"===e)return $n(t)}function ar(e,t){if("input"===e||"change"===e)return $n(t)}var or="function"===typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e===1/t)||e!==e&&t!==t};function lr(e,t){if(or(e,t))return!0;if("object"!==typeof e||null===e||"object"!==typeof t||null===t)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(r=0;r<n.length;r++){var i=n[r];if(!h.call(t,i)||!or(e[i],t[i]))return!1}return!0}function cr(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function ur(e,t){var n,r=cr(e);for(e=0;r;){if(3===r.nodeType){if(n=e+r.textContent.length,e<=t&&n>=t)return{node:r,offset:t-e};e=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=cr(r)}}function hr(e,t){return!(!e||!t)&&(e===t||(!e||3!==e.nodeType)&&(t&&3===t.nodeType?hr(e,t.parentNode):"contains"in e?e.contains(t):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(t))))}function dr(){for(var e=window,t=Q();t instanceof e.HTMLIFrameElement;){try{var n="string"===typeof t.contentWindow.location.href}catch(r){n=!1}if(!n)break;t=Q((e=t.contentWindow).document)}return t}function fr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===t||"true"===e.contentEditable)}function pr(e){var t=dr(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&hr(n.ownerDocument.documentElement,n)){if(null!==r&&fr(n))if(t=r.start,void 0===(e=r.end)&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if((e=(t=n.ownerDocument||document)&&t.defaultView||window).getSelection){e=e.getSelection();var i=n.textContent.length,s=Math.min(r.start,i);r=void 0===r.end?s:Math.min(r.end,i),!e.extend&&s>r&&(i=r,r=s,s=i),i=ur(n,s);var a=ur(n,r);i&&a&&(1!==e.rangeCount||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&((t=t.createRange()).setStart(i.node,i.offset),e.removeAllRanges(),s>r?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}for(t=[],e=n;e=e.parentNode;)1===e.nodeType&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for("function"===typeof n.focus&&n.focus(),n=0;n<t.length;n++)(e=t[n]).element.scrollLeft=e.left,e.element.scrollTop=e.top}}var mr=u&&"documentMode"in document&&11>=document.documentMode,gr=null,vr=null,yr=null,wr=!1;function br(e,t,n){var r=n.window===n?n.document:9===n.nodeType?n:n.ownerDocument;wr||null==gr||gr!==Q(r)||("selectionStart"in(r=gr)&&fr(r)?r={start:r.selectionStart,end:r.selectionEnd}:r={anchorNode:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset},yr&&lr(yr,r)||(yr=r,0<(r=Kr(vr,"onSelect")).length&&(t=new un("onSelect","select",null,t,n),e.push({event:t,listeners:r}),t.target=gr)))}function _r(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var Er={animationend:_r("Animation","AnimationEnd"),animationiteration:_r("Animation","AnimationIteration"),animationstart:_r("Animation","AnimationStart"),transitionend:_r("Transition","TransitionEnd")},Sr={},kr={};function Ir(e){if(Sr[e])return Sr[e];if(!Er[e])return e;var t,n=Er[e];for(t in n)if(n.hasOwnProperty(t)&&t in kr)return Sr[e]=n[t];return e}u&&(kr=document.createElement("div").style,"AnimationEvent"in window||(delete Er.animationend.animation,delete Er.animationiteration.animation,delete Er.animationstart.animation),"TransitionEvent"in window||delete Er.transitionend.transition);var Tr=Ir("animationend"),Cr=Ir("animationiteration"),xr=Ir("animationstart"),Nr=Ir("transitionend"),Ar=new Map,Pr="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function Rr(e,t){Ar.set(e,t),l(t,[e])}for(var Dr=0;Dr<Pr.length;Dr++){var Or=Pr[Dr];Rr(Or.toLowerCase(),"on"+(Or[0].toUpperCase()+Or.slice(1)))}Rr(Tr,"onAnimationEnd"),Rr(Cr,"onAnimationIteration"),Rr(xr,"onAnimationStart"),Rr("dblclick","onDoubleClick"),Rr("focusin","onFocus"),Rr("focusout","onBlur"),Rr(Nr,"onTransitionEnd"),c("onMouseEnter",["mouseout","mouseover"]),c("onMouseLeave",["mouseout","mouseover"]),c("onPointerEnter",["pointerout","pointerover"]),c("onPointerLeave",["pointerout","pointerover"]),l("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),l("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),l("onBeforeInput",["compositionend","keypress","textInput","paste"]),l("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Lr="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Mr=new Set("cancel close invalid load scroll toggle".split(" ").concat(Lr));function jr(e,t,n){var r=e.type||"unknown-event";e.currentTarget=n,function(e,t,n,r,i,a,o,l,c){if(Be.apply(this,arguments),Me){if(!Me)throw Error(s(198));var u=je;Me=!1,je=null,Fe||(Fe=!0,Ue=u)}}(r,t,void 0,e),e.currentTarget=null}function Fr(e,t){t=0!==(4&t);for(var n=0;n<e.length;n++){var r=e[n],i=r.event;r=r.listeners;e:{var s=void 0;if(t)for(var a=r.length-1;0<=a;a--){var o=r[a],l=o.instance,c=o.currentTarget;if(o=o.listener,l!==s&&i.isPropagationStopped())break e;jr(i,o,c),s=l}else for(a=0;a<r.length;a++){if(l=(o=r[a]).instance,c=o.currentTarget,o=o.listener,l!==s&&i.isPropagationStopped())break e;jr(i,o,c),s=l}}}if(Fe)throw e=Ue,Fe=!1,Ue=null,e}function Ur(e,t){var n=t[mi];void 0===n&&(n=t[mi]=new Set);var r=e+"__bubble";n.has(r)||(qr(t,e,2,!1),n.add(r))}function Vr(e,t,n){var r=0;t&&(r|=4),qr(n,e,r,t)}var Br="_reactListening"+Math.random().toString(36).slice(2);function zr(e){if(!e[Br]){e[Br]=!0,a.forEach((function(t){"selectionchange"!==t&&(Mr.has(t)||Vr(t,!1,e),Vr(t,!0,e))}));var t=9===e.nodeType?e:e.ownerDocument;null===t||t[Br]||(t[Br]=!0,Vr("selectionchange",!1,t))}}function qr(e,t,n,r){switch(Yt(t)){case 1:var i=Wt;break;case 4:i=Kt;break;default:i=Gt}n=i.bind(null,t,n,e),i=void 0,!De||"touchstart"!==t&&"touchmove"!==t&&"wheel"!==t||(i=!0),r?void 0!==i?e.addEventListener(t,n,{capture:!0,passive:i}):e.addEventListener(t,n,!0):void 0!==i?e.addEventListener(t,n,{passive:i}):e.addEventListener(t,n,!1)}function Hr(e,t,n,r,i){var s=r;if(0===(1&t)&&0===(2&t)&&null!==r)e:for(;;){if(null===r)return;var a=r.tag;if(3===a||4===a){var o=r.stateNode.containerInfo;if(o===i||8===o.nodeType&&o.parentNode===i)break;if(4===a)for(a=r.return;null!==a;){var l=a.tag;if((3===l||4===l)&&((l=a.stateNode.containerInfo)===i||8===l.nodeType&&l.parentNode===i))return;a=a.return}for(;null!==o;){if(null===(a=yi(o)))return;if(5===(l=a.tag)||6===l){r=s=a;continue e}o=o.parentNode}}r=r.return}Pe((function(){var r=s,i=_e(n),a=[];e:{var o=Ar.get(e);if(void 0!==o){var l=un,c=e;switch(e){case"keypress":if(0===tn(n))break e;case"keydown":case"keyup":l=Cn;break;case"focusin":c="focus",l=gn;break;case"focusout":c="blur",l=gn;break;case"beforeblur":case"afterblur":l=gn;break;case"click":if(2===n.button)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":l=pn;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":l=mn;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":l=Nn;break;case Tr:case Cr:case xr:l=vn;break;case Nr:l=An;break;case"scroll":l=dn;break;case"wheel":l=Rn;break;case"copy":case"cut":case"paste":l=wn;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":l=xn}var u=0!==(4&t),h=!u&&"scroll"===e,d=u?null!==o?o+"Capture":null:o;u=[];for(var f,p=r;null!==p;){var m=(f=p).stateNode;if(5===f.tag&&null!==m&&(f=m,null!==d&&(null!=(m=Re(p,d))&&u.push(Wr(p,m,f)))),h)break;p=p.return}0<u.length&&(o=new l(o,c,null,n,i),a.push({event:o,listeners:u}))}}if(0===(7&t)){if(l="mouseout"===e||"pointerout"===e,(!(o="mouseover"===e||"pointerover"===e)||n===be||!(c=n.relatedTarget||n.fromElement)||!yi(c)&&!c[pi])&&(l||o)&&(o=i.window===i?i:(o=i.ownerDocument)?o.defaultView||o.parentWindow:window,l?(l=r,null!==(c=(c=n.relatedTarget||n.toElement)?yi(c):null)&&(c!==(h=ze(c))||5!==c.tag&&6!==c.tag)&&(c=null)):(l=null,c=r),l!==c)){if(u=pn,m="onMouseLeave",d="onMouseEnter",p="mouse","pointerout"!==e&&"pointerover"!==e||(u=xn,m="onPointerLeave",d="onPointerEnter",p="pointer"),h=null==l?o:bi(l),f=null==c?o:bi(c),(o=new u(m,p+"leave",l,n,i)).target=h,o.relatedTarget=f,m=null,yi(i)===r&&((u=new u(d,p+"enter",c,n,i)).target=f,u.relatedTarget=h,m=u),h=m,l&&c)e:{for(d=c,p=0,f=u=l;f;f=Gr(f))p++;for(f=0,m=d;m;m=Gr(m))f++;for(;0<p-f;)u=Gr(u),p--;for(;0<f-p;)d=Gr(d),f--;for(;p--;){if(u===d||null!==d&&u===d.alternate)break e;u=Gr(u),d=Gr(d)}u=null}else u=null;null!==l&&Qr(a,o,l,u,!1),null!==c&&null!==h&&Qr(a,h,c,u,!0)}if("select"===(l=(o=r?bi(r):window).nodeName&&o.nodeName.toLowerCase())||"input"===l&&"file"===o.type)var g=Yn;else if(Hn(o))if(Xn)g=ar;else{g=ir;var v=rr}else(l=o.nodeName)&&"input"===l.toLowerCase()&&("checkbox"===o.type||"radio"===o.type)&&(g=sr);switch(g&&(g=g(e,r))?Wn(a,g,n,i):(v&&v(e,o,r),"focusout"===e&&(v=o._wrapperState)&&v.controlled&&"number"===o.type&&ee(o,"number",o.value)),v=r?bi(r):window,e){case"focusin":(Hn(v)||"true"===v.contentEditable)&&(gr=v,vr=r,yr=null);break;case"focusout":yr=vr=gr=null;break;case"mousedown":wr=!0;break;case"contextmenu":case"mouseup":case"dragend":wr=!1,br(a,n,i);break;case"selectionchange":if(mr)break;case"keydown":case"keyup":br(a,n,i)}var y;if(On)e:{switch(e){case"compositionstart":var w="onCompositionStart";break e;case"compositionend":w="onCompositionEnd";break e;case"compositionupdate":w="onCompositionUpdate";break e}w=void 0}else zn?Vn(e,n)&&(w="onCompositionEnd"):"keydown"===e&&229===n.keyCode&&(w="onCompositionStart");w&&(jn&&"ko"!==n.locale&&(zn||"onCompositionStart"!==w?"onCompositionEnd"===w&&zn&&(y=en()):(Jt="value"in(Xt=i)?Xt.value:Xt.textContent,zn=!0)),0<(v=Kr(r,w)).length&&(w=new bn(w,e,null,n,i),a.push({event:w,listeners:v}),y?w.data=y:null!==(y=Bn(n))&&(w.data=y))),(y=Mn?function(e,t){switch(e){case"compositionend":return Bn(t);case"keypress":return 32!==t.which?null:(Un=!0,Fn);case"textInput":return(e=t.data)===Fn&&Un?null:e;default:return null}}(e,n):function(e,t){if(zn)return"compositionend"===e||!On&&Vn(e,t)?(e=en(),Zt=Jt=Xt=null,zn=!1,e):null;switch(e){case"paste":default:return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return jn&&"ko"!==t.locale?null:t.data}}(e,n))&&(0<(r=Kr(r,"onBeforeInput")).length&&(i=new bn("onBeforeInput","beforeinput",null,n,i),a.push({event:i,listeners:r}),i.data=y))}Fr(a,t)}))}function Wr(e,t,n){return{instance:e,listener:t,currentTarget:n}}function Kr(e,t){for(var n=t+"Capture",r=[];null!==e;){var i=e,s=i.stateNode;5===i.tag&&null!==s&&(i=s,null!=(s=Re(e,n))&&r.unshift(Wr(e,s,i)),null!=(s=Re(e,t))&&r.push(Wr(e,s,i))),e=e.return}return r}function Gr(e){if(null===e)return null;do{e=e.return}while(e&&5!==e.tag);return e||null}function Qr(e,t,n,r,i){for(var s=t._reactName,a=[];null!==n&&n!==r;){var o=n,l=o.alternate,c=o.stateNode;if(null!==l&&l===r)break;5===o.tag&&null!==c&&(o=c,i?null!=(l=Re(n,s))&&a.unshift(Wr(n,l,o)):i||null!=(l=Re(n,s))&&a.push(Wr(n,l,o))),n=n.return}0!==a.length&&e.push({event:t,listeners:a})}var $r=/\r\n?/g,Yr=/\u0000|\uFFFD/g;function Xr(e){return("string"===typeof e?e:""+e).replace($r,"\n").replace(Yr,"")}function Jr(e,t,n){if(t=Xr(t),Xr(e)!==t&&n)throw Error(s(425))}function Zr(){}var ei=null,ti=null;function ni(e,t){return"textarea"===e||"noscript"===e||"string"===typeof t.children||"number"===typeof t.children||"object"===typeof t.dangerouslySetInnerHTML&&null!==t.dangerouslySetInnerHTML&&null!=t.dangerouslySetInnerHTML.__html}var ri="function"===typeof setTimeout?setTimeout:void 0,ii="function"===typeof clearTimeout?clearTimeout:void 0,si="function"===typeof Promise?Promise:void 0,ai="function"===typeof queueMicrotask?queueMicrotask:"undefined"!==typeof si?function(e){return si.resolve(null).then(e).catch(oi)}:ri;function oi(e){setTimeout((function(){throw e}))}function li(e,t){var n=t,r=0;do{var i=n.nextSibling;if(e.removeChild(n),i&&8===i.nodeType)if("/$"===(n=i.data)){if(0===r)return e.removeChild(i),void zt(t);r--}else"$"!==n&&"$?"!==n&&"$!"!==n||r++;n=i}while(n);zt(t)}function ci(e){for(;null!=e;e=e.nextSibling){var t=e.nodeType;if(1===t||3===t)break;if(8===t){if("$"===(t=e.data)||"$!"===t||"$?"===t)break;if("/$"===t)return null}}return e}function ui(e){e=e.previousSibling;for(var t=0;e;){if(8===e.nodeType){var n=e.data;if("$"===n||"$!"===n||"$?"===n){if(0===t)return e;t--}else"/$"===n&&t++}e=e.previousSibling}return null}var hi=Math.random().toString(36).slice(2),di="__reactFiber$"+hi,fi="__reactProps$"+hi,pi="__reactContainer$"+hi,mi="__reactEvents$"+hi,gi="__reactListeners$"+hi,vi="__reactHandles$"+hi;function yi(e){var t=e[di];if(t)return t;for(var n=e.parentNode;n;){if(t=n[pi]||n[di]){if(n=t.alternate,null!==t.child||null!==n&&null!==n.child)for(e=ui(e);null!==e;){if(n=e[di])return n;e=ui(e)}return t}n=(e=n).parentNode}return null}function wi(e){return!(e=e[di]||e[pi])||5!==e.tag&&6!==e.tag&&13!==e.tag&&3!==e.tag?null:e}function bi(e){if(5===e.tag||6===e.tag)return e.stateNode;throw Error(s(33))}function _i(e){return e[fi]||null}var Ei=[],Si=-1;function ki(e){return{current:e}}function Ii(e){0>Si||(e.current=Ei[Si],Ei[Si]=null,Si--)}function Ti(e,t){Si++,Ei[Si]=e.current,e.current=t}var Ci={},xi=ki(Ci),Ni=ki(!1),Ai=Ci;function Pi(e,t){var n=e.type.contextTypes;if(!n)return Ci;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var i,s={};for(i in n)s[i]=t[i];return r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function Ri(e){return null!==(e=e.childContextTypes)&&void 0!==e}function Di(){Ii(Ni),Ii(xi)}function Oi(e,t,n){if(xi.current!==Ci)throw Error(s(168));Ti(xi,t),Ti(Ni,n)}function Li(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,"function"!==typeof r.getChildContext)return n;for(var i in r=r.getChildContext())if(!(i in t))throw Error(s(108,q(e)||"Unknown",i));return j({},n,r)}function Mi(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Ci,Ai=xi.current,Ti(xi,e),Ti(Ni,Ni.current),!0}function ji(e,t,n){var r=e.stateNode;if(!r)throw Error(s(169));n?(e=Li(e,t,Ai),r.__reactInternalMemoizedMergedChildContext=e,Ii(Ni),Ii(xi),Ti(xi,e)):Ii(Ni),Ti(Ni,n)}var Fi=null,Ui=!1,Vi=!1;function Bi(e){null===Fi?Fi=[e]:Fi.push(e)}function zi(){if(!Vi&&null!==Fi){Vi=!0;var e=0,t=wt;try{var n=Fi;for(wt=1;e<n.length;e++){var r=n[e];do{r=r(!0)}while(null!==r)}Fi=null,Ui=!1}catch(i){throw null!==Fi&&(Fi=Fi.slice(e+1)),Ge(Ze,zi),i}finally{wt=t,Vi=!1}}return null}var qi=[],Hi=0,Wi=null,Ki=0,Gi=[],Qi=0,$i=null,Yi=1,Xi="";function Ji(e,t){qi[Hi++]=Ki,qi[Hi++]=Wi,Wi=e,Ki=t}function Zi(e,t,n){Gi[Qi++]=Yi,Gi[Qi++]=Xi,Gi[Qi++]=$i,$i=e;var r=Yi;e=Xi;var i=32-at(r)-1;r&=~(1<<i),n+=1;var s=32-at(t)+i;if(30<s){var a=i-i%5;s=(r&(1<<a)-1).toString(32),r>>=a,i-=a,Yi=1<<32-at(t)+i|n<<i|r,Xi=s+e}else Yi=1<<s|n<<i|r,Xi=e}function es(e){null!==e.return&&(Ji(e,1),Zi(e,1,0))}function ts(e){for(;e===Wi;)Wi=qi[--Hi],qi[Hi]=null,Ki=qi[--Hi],qi[Hi]=null;for(;e===$i;)$i=Gi[--Qi],Gi[Qi]=null,Xi=Gi[--Qi],Gi[Qi]=null,Yi=Gi[--Qi],Gi[Qi]=null}var ns=null,rs=null,is=!1,ss=null;function as(e,t){var n=Rc(5,null,null,0);n.elementType="DELETED",n.stateNode=t,n.return=e,null===(t=e.deletions)?(e.deletions=[n],e.flags|=16):t.push(n)}function os(e,t){switch(e.tag){case 5:var n=e.type;return null!==(t=1!==t.nodeType||n.toLowerCase()!==t.nodeName.toLowerCase()?null:t)&&(e.stateNode=t,ns=e,rs=ci(t.firstChild),!0);case 6:return null!==(t=""===e.pendingProps||3!==t.nodeType?null:t)&&(e.stateNode=t,ns=e,rs=null,!0);case 13:return null!==(t=8!==t.nodeType?null:t)&&(n=null!==$i?{id:Yi,overflow:Xi}:null,e.memoizedState={dehydrated:t,treeContext:n,retryLane:1073741824},(n=Rc(18,null,null,0)).stateNode=t,n.return=e,e.child=n,ns=e,rs=null,!0);default:return!1}}function ls(e){return 0!==(1&e.mode)&&0===(128&e.flags)}function cs(e){if(is){var t=rs;if(t){var n=t;if(!os(e,t)){if(ls(e))throw Error(s(418));t=ci(n.nextSibling);var r=ns;t&&os(e,t)?as(r,n):(e.flags=-4097&e.flags|2,is=!1,ns=e)}}else{if(ls(e))throw Error(s(418));e.flags=-4097&e.flags|2,is=!1,ns=e}}}function us(e){for(e=e.return;null!==e&&5!==e.tag&&3!==e.tag&&13!==e.tag;)e=e.return;ns=e}function hs(e){if(e!==ns)return!1;if(!is)return us(e),is=!0,!1;var t;if((t=3!==e.tag)&&!(t=5!==e.tag)&&(t="head"!==(t=e.type)&&"body"!==t&&!ni(e.type,e.memoizedProps)),t&&(t=rs)){if(ls(e))throw ds(),Error(s(418));for(;t;)as(e,t),t=ci(t.nextSibling)}if(us(e),13===e.tag){if(!(e=null!==(e=e.memoizedState)?e.dehydrated:null))throw Error(s(317));e:{for(e=e.nextSibling,t=0;e;){if(8===e.nodeType){var n=e.data;if("/$"===n){if(0===t){rs=ci(e.nextSibling);break e}t--}else"$"!==n&&"$!"!==n&&"$?"!==n||t++}e=e.nextSibling}rs=null}}else rs=ns?ci(e.stateNode.nextSibling):null;return!0}function ds(){for(var e=rs;e;)e=ci(e.nextSibling)}function fs(){rs=ns=null,is=!1}function ps(e){null===ss?ss=[e]:ss.push(e)}var ms=b.ReactCurrentBatchConfig;function gs(e,t){if(e&&e.defaultProps){for(var n in t=j({},t),e=e.defaultProps)void 0===t[n]&&(t[n]=e[n]);return t}return t}var vs=ki(null),ys=null,ws=null,bs=null;function _s(){bs=ws=ys=null}function Es(e){var t=vs.current;Ii(vs),e._currentValue=t}function Ss(e,t,n){for(;null!==e;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,null!==r&&(r.childLanes|=t)):null!==r&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function ks(e,t){ys=e,bs=ws=null,null!==(e=e.dependencies)&&null!==e.firstContext&&(0!==(e.lanes&t)&&(bo=!0),e.firstContext=null)}function Is(e){var t=e._currentValue;if(bs!==e)if(e={context:e,memoizedValue:t,next:null},null===ws){if(null===ys)throw Error(s(308));ws=e,ys.dependencies={lanes:0,firstContext:e}}else ws=ws.next=e;return t}var Ts=null;function Cs(e){null===Ts?Ts=[e]:Ts.push(e)}function xs(e,t,n,r){var i=t.interleaved;return null===i?(n.next=n,Cs(t)):(n.next=i.next,i.next=n),t.interleaved=n,Ns(e,r)}function Ns(e,t){e.lanes|=t;var n=e.alternate;for(null!==n&&(n.lanes|=t),n=e,e=e.return;null!==e;)e.childLanes|=t,null!==(n=e.alternate)&&(n.childLanes|=t),n=e,e=e.return;return 3===n.tag?n.stateNode:null}var As=!1;function Ps(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Rs(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Ds(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Os(e,t,n){var r=e.updateQueue;if(null===r)return null;if(r=r.shared,0!==(2&Nl)){var i=r.pending;return null===i?t.next=t:(t.next=i.next,i.next=t),r.pending=t,Ns(e,n)}return null===(i=r.interleaved)?(t.next=t,Cs(r)):(t.next=i.next,i.next=t),r.interleaved=t,Ns(e,n)}function Ls(e,t,n){if(null!==(t=t.updateQueue)&&(t=t.shared,0!==(4194240&n))){var r=t.lanes;n|=r&=e.pendingLanes,t.lanes=n,yt(e,n)}}function Ms(e,t){var n=e.updateQueue,r=e.alternate;if(null!==r&&n===(r=r.updateQueue)){var i=null,s=null;if(null!==(n=n.firstBaseUpdate)){do{var a={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};null===s?i=s=a:s=s.next=a,n=n.next}while(null!==n);null===s?i=s=t:s=s.next=t}else i=s=t;return n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:s,shared:r.shared,effects:r.effects},void(e.updateQueue=n)}null===(e=n.lastBaseUpdate)?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function js(e,t,n,r){var i=e.updateQueue;As=!1;var s=i.firstBaseUpdate,a=i.lastBaseUpdate,o=i.shared.pending;if(null!==o){i.shared.pending=null;var l=o,c=l.next;l.next=null,null===a?s=c:a.next=c,a=l;var u=e.alternate;null!==u&&((o=(u=u.updateQueue).lastBaseUpdate)!==a&&(null===o?u.firstBaseUpdate=c:o.next=c,u.lastBaseUpdate=l))}if(null!==s){var h=i.baseState;for(a=0,u=c=l=null,o=s;;){var d=o.lane,f=o.eventTime;if((r&d)===d){null!==u&&(u=u.next={eventTime:f,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var p=e,m=o;switch(d=t,f=n,m.tag){case 1:if("function"===typeof(p=m.payload)){h=p.call(f,h,d);break e}h=p;break e;case 3:p.flags=-65537&p.flags|128;case 0:if(null===(d="function"===typeof(p=m.payload)?p.call(f,h,d):p)||void 0===d)break e;h=j({},h,d);break e;case 2:As=!0}}null!==o.callback&&0!==o.lane&&(e.flags|=64,null===(d=i.effects)?i.effects=[o]:d.push(o))}else f={eventTime:f,lane:d,tag:o.tag,payload:o.payload,callback:o.callback,next:null},null===u?(c=u=f,l=h):u=u.next=f,a|=d;if(null===(o=o.next)){if(null===(o=i.shared.pending))break;o=(d=o).next,d.next=null,i.lastBaseUpdate=d,i.shared.pending=null}}if(null===u&&(l=h),i.baseState=l,i.firstBaseUpdate=c,i.lastBaseUpdate=u,null!==(t=i.shared.interleaved)){i=t;do{a|=i.lane,i=i.next}while(i!==t)}else null===s&&(i.shared.lanes=0);jl|=a,e.lanes=a,e.memoizedState=h}}function Fs(e,t,n){if(e=t.effects,t.effects=null,null!==e)for(t=0;t<e.length;t++){var r=e[t],i=r.callback;if(null!==i){if(r.callback=null,r=n,"function"!==typeof i)throw Error(s(191,i));i.call(r)}}}var Us=(new r.Component).refs;function Vs(e,t,n,r){n=null===(n=n(r,t=e.memoizedState))||void 0===n?t:j({},t,n),e.memoizedState=n,0===e.lanes&&(e.updateQueue.baseState=n)}var Bs={isMounted:function(e){return!!(e=e._reactInternals)&&ze(e)===e},enqueueSetState:function(e,t,n){e=e._reactInternals;var r=tc(),i=nc(e),s=Ds(r,i);s.payload=t,void 0!==n&&null!==n&&(s.callback=n),null!==(t=Os(e,s,i))&&(rc(t,e,i,r),Ls(t,e,i))},enqueueReplaceState:function(e,t,n){e=e._reactInternals;var r=tc(),i=nc(e),s=Ds(r,i);s.tag=1,s.payload=t,void 0!==n&&null!==n&&(s.callback=n),null!==(t=Os(e,s,i))&&(rc(t,e,i,r),Ls(t,e,i))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var n=tc(),r=nc(e),i=Ds(n,r);i.tag=2,void 0!==t&&null!==t&&(i.callback=t),null!==(t=Os(e,i,r))&&(rc(t,e,r,n),Ls(t,e,r))}};function zs(e,t,n,r,i,s,a){return"function"===typeof(e=e.stateNode).shouldComponentUpdate?e.shouldComponentUpdate(r,s,a):!t.prototype||!t.prototype.isPureReactComponent||(!lr(n,r)||!lr(i,s))}function qs(e,t,n){var r=!1,i=Ci,s=t.contextType;return"object"===typeof s&&null!==s?s=Is(s):(i=Ri(t)?Ai:xi.current,s=(r=null!==(r=t.contextTypes)&&void 0!==r)?Pi(e,i):Ci),t=new t(n,s),e.memoizedState=null!==t.state&&void 0!==t.state?t.state:null,t.updater=Bs,e.stateNode=t,t._reactInternals=e,r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=i,e.__reactInternalMemoizedMaskedChildContext=s),t}function Hs(e,t,n,r){e=t.state,"function"===typeof t.componentWillReceiveProps&&t.componentWillReceiveProps(n,r),"function"===typeof t.UNSAFE_componentWillReceiveProps&&t.UNSAFE_componentWillReceiveProps(n,r),t.state!==e&&Bs.enqueueReplaceState(t,t.state,null)}function Ws(e,t,n,r){var i=e.stateNode;i.props=n,i.state=e.memoizedState,i.refs=Us,Ps(e);var s=t.contextType;"object"===typeof s&&null!==s?i.context=Is(s):(s=Ri(t)?Ai:xi.current,i.context=Pi(e,s)),i.state=e.memoizedState,"function"===typeof(s=t.getDerivedStateFromProps)&&(Vs(e,t,s,n),i.state=e.memoizedState),"function"===typeof t.getDerivedStateFromProps||"function"===typeof i.getSnapshotBeforeUpdate||"function"!==typeof i.UNSAFE_componentWillMount&&"function"!==typeof i.componentWillMount||(t=i.state,"function"===typeof i.componentWillMount&&i.componentWillMount(),"function"===typeof i.UNSAFE_componentWillMount&&i.UNSAFE_componentWillMount(),t!==i.state&&Bs.enqueueReplaceState(i,i.state,null),js(e,n,i,r),i.state=e.memoizedState),"function"===typeof i.componentDidMount&&(e.flags|=4194308)}function Ks(e,t,n){if(null!==(e=n.ref)&&"function"!==typeof e&&"object"!==typeof e){if(n._owner){if(n=n._owner){if(1!==n.tag)throw Error(s(309));var r=n.stateNode}if(!r)throw Error(s(147,e));var i=r,a=""+e;return null!==t&&null!==t.ref&&"function"===typeof t.ref&&t.ref._stringRef===a?t.ref:(t=function(e){var t=i.refs;t===Us&&(t=i.refs={}),null===e?delete t[a]:t[a]=e},t._stringRef=a,t)}if("string"!==typeof e)throw Error(s(284));if(!n._owner)throw Error(s(290,e))}return e}function Gs(e,t){throw e=Object.prototype.toString.call(t),Error(s(31,"[object Object]"===e?"object with keys {"+Object.keys(t).join(", ")+"}":e))}function Qs(e){return(0,e._init)(e._payload)}function $s(e){function t(t,n){if(e){var r=t.deletions;null===r?(t.deletions=[n],t.flags|=16):r.push(n)}}function n(n,r){if(!e)return null;for(;null!==r;)t(n,r),r=r.sibling;return null}function r(e,t){for(e=new Map;null!==t;)null!==t.key?e.set(t.key,t):e.set(t.index,t),t=t.sibling;return e}function i(e,t){return(e=Oc(e,t)).index=0,e.sibling=null,e}function a(t,n,r){return t.index=r,e?null!==(r=t.alternate)?(r=r.index)<n?(t.flags|=2,n):r:(t.flags|=2,n):(t.flags|=1048576,n)}function o(t){return e&&null===t.alternate&&(t.flags|=2),t}function l(e,t,n,r){return null===t||6!==t.tag?((t=Fc(n,e.mode,r)).return=e,t):((t=i(t,n)).return=e,t)}function c(e,t,n,r){var s=n.type;return s===S?h(e,t,n.props.children,r,n.key):null!==t&&(t.elementType===s||"object"===typeof s&&null!==s&&s.$$typeof===R&&Qs(s)===t.type)?((r=i(t,n.props)).ref=Ks(e,t,n),r.return=e,r):((r=Lc(n.type,n.key,n.props,null,e.mode,r)).ref=Ks(e,t,n),r.return=e,r)}function u(e,t,n,r){return null===t||4!==t.tag||t.stateNode.containerInfo!==n.containerInfo||t.stateNode.implementation!==n.implementation?((t=Uc(n,e.mode,r)).return=e,t):((t=i(t,n.children||[])).return=e,t)}function h(e,t,n,r,s){return null===t||7!==t.tag?((t=Mc(n,e.mode,r,s)).return=e,t):((t=i(t,n)).return=e,t)}function d(e,t,n){if("string"===typeof t&&""!==t||"number"===typeof t)return(t=Fc(""+t,e.mode,n)).return=e,t;if("object"===typeof t&&null!==t){switch(t.$$typeof){case _:return(n=Lc(t.type,t.key,t.props,null,e.mode,n)).ref=Ks(e,null,t),n.return=e,n;case E:return(t=Uc(t,e.mode,n)).return=e,t;case R:return d(e,(0,t._init)(t._payload),n)}if(te(t)||L(t))return(t=Mc(t,e.mode,n,null)).return=e,t;Gs(e,t)}return null}function f(e,t,n,r){var i=null!==t?t.key:null;if("string"===typeof n&&""!==n||"number"===typeof n)return null!==i?null:l(e,t,""+n,r);if("object"===typeof n&&null!==n){switch(n.$$typeof){case _:return n.key===i?c(e,t,n,r):null;case E:return n.key===i?u(e,t,n,r):null;case R:return f(e,t,(i=n._init)(n._payload),r)}if(te(n)||L(n))return null!==i?null:h(e,t,n,r,null);Gs(e,n)}return null}function p(e,t,n,r,i){if("string"===typeof r&&""!==r||"number"===typeof r)return l(t,e=e.get(n)||null,""+r,i);if("object"===typeof r&&null!==r){switch(r.$$typeof){case _:return c(t,e=e.get(null===r.key?n:r.key)||null,r,i);case E:return u(t,e=e.get(null===r.key?n:r.key)||null,r,i);case R:return p(e,t,n,(0,r._init)(r._payload),i)}if(te(r)||L(r))return h(t,e=e.get(n)||null,r,i,null);Gs(t,r)}return null}function m(i,s,o,l){for(var c=null,u=null,h=s,m=s=0,g=null;null!==h&&m<o.length;m++){h.index>m?(g=h,h=null):g=h.sibling;var v=f(i,h,o[m],l);if(null===v){null===h&&(h=g);break}e&&h&&null===v.alternate&&t(i,h),s=a(v,s,m),null===u?c=v:u.sibling=v,u=v,h=g}if(m===o.length)return n(i,h),is&&Ji(i,m),c;if(null===h){for(;m<o.length;m++)null!==(h=d(i,o[m],l))&&(s=a(h,s,m),null===u?c=h:u.sibling=h,u=h);return is&&Ji(i,m),c}for(h=r(i,h);m<o.length;m++)null!==(g=p(h,i,m,o[m],l))&&(e&&null!==g.alternate&&h.delete(null===g.key?m:g.key),s=a(g,s,m),null===u?c=g:u.sibling=g,u=g);return e&&h.forEach((function(e){return t(i,e)})),is&&Ji(i,m),c}function g(i,o,l,c){var u=L(l);if("function"!==typeof u)throw Error(s(150));if(null==(l=u.call(l)))throw Error(s(151));for(var h=u=null,m=o,g=o=0,v=null,y=l.next();null!==m&&!y.done;g++,y=l.next()){m.index>g?(v=m,m=null):v=m.sibling;var w=f(i,m,y.value,c);if(null===w){null===m&&(m=v);break}e&&m&&null===w.alternate&&t(i,m),o=a(w,o,g),null===h?u=w:h.sibling=w,h=w,m=v}if(y.done)return n(i,m),is&&Ji(i,g),u;if(null===m){for(;!y.done;g++,y=l.next())null!==(y=d(i,y.value,c))&&(o=a(y,o,g),null===h?u=y:h.sibling=y,h=y);return is&&Ji(i,g),u}for(m=r(i,m);!y.done;g++,y=l.next())null!==(y=p(m,i,g,y.value,c))&&(e&&null!==y.alternate&&m.delete(null===y.key?g:y.key),o=a(y,o,g),null===h?u=y:h.sibling=y,h=y);return e&&m.forEach((function(e){return t(i,e)})),is&&Ji(i,g),u}return function e(r,s,a,l){if("object"===typeof a&&null!==a&&a.type===S&&null===a.key&&(a=a.props.children),"object"===typeof a&&null!==a){switch(a.$$typeof){case _:e:{for(var c=a.key,u=s;null!==u;){if(u.key===c){if((c=a.type)===S){if(7===u.tag){n(r,u.sibling),(s=i(u,a.props.children)).return=r,r=s;break e}}else if(u.elementType===c||"object"===typeof c&&null!==c&&c.$$typeof===R&&Qs(c)===u.type){n(r,u.sibling),(s=i(u,a.props)).ref=Ks(r,u,a),s.return=r,r=s;break e}n(r,u);break}t(r,u),u=u.sibling}a.type===S?((s=Mc(a.props.children,r.mode,l,a.key)).return=r,r=s):((l=Lc(a.type,a.key,a.props,null,r.mode,l)).ref=Ks(r,s,a),l.return=r,r=l)}return o(r);case E:e:{for(u=a.key;null!==s;){if(s.key===u){if(4===s.tag&&s.stateNode.containerInfo===a.containerInfo&&s.stateNode.implementation===a.implementation){n(r,s.sibling),(s=i(s,a.children||[])).return=r,r=s;break e}n(r,s);break}t(r,s),s=s.sibling}(s=Uc(a,r.mode,l)).return=r,r=s}return o(r);case R:return e(r,s,(u=a._init)(a._payload),l)}if(te(a))return m(r,s,a,l);if(L(a))return g(r,s,a,l);Gs(r,a)}return"string"===typeof a&&""!==a||"number"===typeof a?(a=""+a,null!==s&&6===s.tag?(n(r,s.sibling),(s=i(s,a)).return=r,r=s):(n(r,s),(s=Fc(a,r.mode,l)).return=r,r=s),o(r)):n(r,s)}}var Ys=$s(!0),Xs=$s(!1),Js={},Zs=ki(Js),ea=ki(Js),ta=ki(Js);function na(e){if(e===Js)throw Error(s(174));return e}function ra(e,t){switch(Ti(ta,t),Ti(ea,e),Ti(Zs,Js),e=t.nodeType){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:le(null,"");break;default:t=le(t=(e=8===e?t.parentNode:t).namespaceURI||null,e=e.tagName)}Ii(Zs),Ti(Zs,t)}function ia(){Ii(Zs),Ii(ea),Ii(ta)}function sa(e){na(ta.current);var t=na(Zs.current),n=le(t,e.type);t!==n&&(Ti(ea,e),Ti(Zs,n))}function aa(e){ea.current===e&&(Ii(Zs),Ii(ea))}var oa=ki(0);function la(e){for(var t=e;null!==t;){if(13===t.tag){var n=t.memoizedState;if(null!==n&&(null===(n=n.dehydrated)||"$?"===n.data||"$!"===n.data))return t}else if(19===t.tag&&void 0!==t.memoizedProps.revealOrder){if(0!==(128&t.flags))return t}else if(null!==t.child){t.child.return=t,t=t.child;continue}if(t===e)break;for(;null===t.sibling;){if(null===t.return||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var ca=[];function ua(){for(var e=0;e<ca.length;e++)ca[e]._workInProgressVersionPrimary=null;ca.length=0}var ha=b.ReactCurrentDispatcher,da=b.ReactCurrentBatchConfig,fa=0,pa=null,ma=null,ga=null,va=!1,ya=!1,wa=0,ba=0;function _a(){throw Error(s(321))}function Ea(e,t){if(null===t)return!1;for(var n=0;n<t.length&&n<e.length;n++)if(!or(e[n],t[n]))return!1;return!0}function Sa(e,t,n,r,i,a){if(fa=a,pa=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,ha.current=null===e||null===e.memoizedState?ao:oo,e=n(r,i),ya){a=0;do{if(ya=!1,wa=0,25<=a)throw Error(s(301));a+=1,ga=ma=null,t.updateQueue=null,ha.current=lo,e=n(r,i)}while(ya)}if(ha.current=so,t=null!==ma&&null!==ma.next,fa=0,ga=ma=pa=null,va=!1,t)throw Error(s(300));return e}function ka(){var e=0!==wa;return wa=0,e}function Ia(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return null===ga?pa.memoizedState=ga=e:ga=ga.next=e,ga}function Ta(){if(null===ma){var e=pa.alternate;e=null!==e?e.memoizedState:null}else e=ma.next;var t=null===ga?pa.memoizedState:ga.next;if(null!==t)ga=t,ma=e;else{if(null===e)throw Error(s(310));e={memoizedState:(ma=e).memoizedState,baseState:ma.baseState,baseQueue:ma.baseQueue,queue:ma.queue,next:null},null===ga?pa.memoizedState=ga=e:ga=ga.next=e}return ga}function Ca(e,t){return"function"===typeof t?t(e):t}function xa(e){var t=Ta(),n=t.queue;if(null===n)throw Error(s(311));n.lastRenderedReducer=e;var r=ma,i=r.baseQueue,a=n.pending;if(null!==a){if(null!==i){var o=i.next;i.next=a.next,a.next=o}r.baseQueue=i=a,n.pending=null}if(null!==i){a=i.next,r=r.baseState;var l=o=null,c=null,u=a;do{var h=u.lane;if((fa&h)===h)null!==c&&(c=c.next={lane:0,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null}),r=u.hasEagerState?u.eagerState:e(r,u.action);else{var d={lane:h,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null};null===c?(l=c=d,o=r):c=c.next=d,pa.lanes|=h,jl|=h}u=u.next}while(null!==u&&u!==a);null===c?o=r:c.next=l,or(r,t.memoizedState)||(bo=!0),t.memoizedState=r,t.baseState=o,t.baseQueue=c,n.lastRenderedState=r}if(null!==(e=n.interleaved)){i=e;do{a=i.lane,pa.lanes|=a,jl|=a,i=i.next}while(i!==e)}else null===i&&(n.lanes=0);return[t.memoizedState,n.dispatch]}function Na(e){var t=Ta(),n=t.queue;if(null===n)throw Error(s(311));n.lastRenderedReducer=e;var r=n.dispatch,i=n.pending,a=t.memoizedState;if(null!==i){n.pending=null;var o=i=i.next;do{a=e(a,o.action),o=o.next}while(o!==i);or(a,t.memoizedState)||(bo=!0),t.memoizedState=a,null===t.baseQueue&&(t.baseState=a),n.lastRenderedState=a}return[a,r]}function Aa(){}function Pa(e,t){var n=pa,r=Ta(),i=t(),a=!or(r.memoizedState,i);if(a&&(r.memoizedState=i,bo=!0),r=r.queue,qa(Oa.bind(null,n,r,e),[e]),r.getSnapshot!==t||a||null!==ga&&1&ga.memoizedState.tag){if(n.flags|=2048,Fa(9,Da.bind(null,n,r,i,t),void 0,null),null===Al)throw Error(s(349));0!==(30&fa)||Ra(n,t,i)}return i}function Ra(e,t,n){e.flags|=16384,e={getSnapshot:t,value:n},null===(t=pa.updateQueue)?(t={lastEffect:null,stores:null},pa.updateQueue=t,t.stores=[e]):null===(n=t.stores)?t.stores=[e]:n.push(e)}function Da(e,t,n,r){t.value=n,t.getSnapshot=r,La(t)&&Ma(e)}function Oa(e,t,n){return n((function(){La(t)&&Ma(e)}))}function La(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!or(e,n)}catch(r){return!0}}function Ma(e){var t=Ns(e,1);null!==t&&rc(t,e,1,-1)}function ja(e){var t=Ia();return"function"===typeof e&&(e=e()),t.memoizedState=t.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Ca,lastRenderedState:e},t.queue=e,e=e.dispatch=to.bind(null,pa,e),[t.memoizedState,e]}function Fa(e,t,n,r){return e={tag:e,create:t,destroy:n,deps:r,next:null},null===(t=pa.updateQueue)?(t={lastEffect:null,stores:null},pa.updateQueue=t,t.lastEffect=e.next=e):null===(n=t.lastEffect)?t.lastEffect=e.next=e:(r=n.next,n.next=e,e.next=r,t.lastEffect=e),e}function Ua(){return Ta().memoizedState}function Va(e,t,n,r){var i=Ia();pa.flags|=e,i.memoizedState=Fa(1|t,n,void 0,void 0===r?null:r)}function Ba(e,t,n,r){var i=Ta();r=void 0===r?null:r;var s=void 0;if(null!==ma){var a=ma.memoizedState;if(s=a.destroy,null!==r&&Ea(r,a.deps))return void(i.memoizedState=Fa(t,n,s,r))}pa.flags|=e,i.memoizedState=Fa(1|t,n,s,r)}function za(e,t){return Va(8390656,8,e,t)}function qa(e,t){return Ba(2048,8,e,t)}function Ha(e,t){return Ba(4,2,e,t)}function Wa(e,t){return Ba(4,4,e,t)}function Ka(e,t){return"function"===typeof t?(e=e(),t(e),function(){t(null)}):null!==t&&void 0!==t?(e=e(),t.current=e,function(){t.current=null}):void 0}function Ga(e,t,n){return n=null!==n&&void 0!==n?n.concat([e]):null,Ba(4,4,Ka.bind(null,t,e),n)}function Qa(){}function $a(e,t){var n=Ta();t=void 0===t?null:t;var r=n.memoizedState;return null!==r&&null!==t&&Ea(t,r[1])?r[0]:(n.memoizedState=[e,t],e)}function Ya(e,t){var n=Ta();t=void 0===t?null:t;var r=n.memoizedState;return null!==r&&null!==t&&Ea(t,r[1])?r[0]:(e=e(),n.memoizedState=[e,t],e)}function Xa(e,t,n){return 0===(21&fa)?(e.baseState&&(e.baseState=!1,bo=!0),e.memoizedState=n):(or(n,t)||(n=mt(),pa.lanes|=n,jl|=n,e.baseState=!0),t)}function Ja(e,t){var n=wt;wt=0!==n&&4>n?n:4,e(!0);var r=da.transition;da.transition={};try{e(!1),t()}finally{wt=n,da.transition=r}}function Za(){return Ta().memoizedState}function eo(e,t,n){var r=nc(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},no(e))ro(t,n);else if(null!==(n=xs(e,t,n,r))){rc(n,e,r,tc()),io(n,t,r)}}function to(e,t,n){var r=nc(e),i={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(no(e))ro(t,i);else{var s=e.alternate;if(0===e.lanes&&(null===s||0===s.lanes)&&null!==(s=t.lastRenderedReducer))try{var a=t.lastRenderedState,o=s(a,n);if(i.hasEagerState=!0,i.eagerState=o,or(o,a)){var l=t.interleaved;return null===l?(i.next=i,Cs(t)):(i.next=l.next,l.next=i),void(t.interleaved=i)}}catch(c){}null!==(n=xs(e,t,i,r))&&(rc(n,e,r,i=tc()),io(n,t,r))}}function no(e){var t=e.alternate;return e===pa||null!==t&&t===pa}function ro(e,t){ya=va=!0;var n=e.pending;null===n?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function io(e,t,n){if(0!==(4194240&n)){var r=t.lanes;n|=r&=e.pendingLanes,t.lanes=n,yt(e,n)}}var so={readContext:Is,useCallback:_a,useContext:_a,useEffect:_a,useImperativeHandle:_a,useInsertionEffect:_a,useLayoutEffect:_a,useMemo:_a,useReducer:_a,useRef:_a,useState:_a,useDebugValue:_a,useDeferredValue:_a,useTransition:_a,useMutableSource:_a,useSyncExternalStore:_a,useId:_a,unstable_isNewReconciler:!1},ao={readContext:Is,useCallback:function(e,t){return Ia().memoizedState=[e,void 0===t?null:t],e},useContext:Is,useEffect:za,useImperativeHandle:function(e,t,n){return n=null!==n&&void 0!==n?n.concat([e]):null,Va(4194308,4,Ka.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Va(4194308,4,e,t)},useInsertionEffect:function(e,t){return Va(4,2,e,t)},useMemo:function(e,t){var n=Ia();return t=void 0===t?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Ia();return t=void 0!==n?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=eo.bind(null,pa,e),[r.memoizedState,e]},useRef:function(e){return e={current:e},Ia().memoizedState=e},useState:ja,useDebugValue:Qa,useDeferredValue:function(e){return Ia().memoizedState=e},useTransition:function(){var e=ja(!1),t=e[0];return e=Ja.bind(null,e[1]),Ia().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=pa,i=Ia();if(is){if(void 0===n)throw Error(s(407));n=n()}else{if(n=t(),null===Al)throw Error(s(349));0!==(30&fa)||Ra(r,t,n)}i.memoizedState=n;var a={value:n,getSnapshot:t};return i.queue=a,za(Oa.bind(null,r,a,e),[e]),r.flags|=2048,Fa(9,Da.bind(null,r,a,n,t),void 0,null),n},useId:function(){var e=Ia(),t=Al.identifierPrefix;if(is){var n=Xi;t=":"+t+"R"+(n=(Yi&~(1<<32-at(Yi)-1)).toString(32)+n),0<(n=wa++)&&(t+="H"+n.toString(32)),t+=":"}else t=":"+t+"r"+(n=ba++).toString(32)+":";return e.memoizedState=t},unstable_isNewReconciler:!1},oo={readContext:Is,useCallback:$a,useContext:Is,useEffect:qa,useImperativeHandle:Ga,useInsertionEffect:Ha,useLayoutEffect:Wa,useMemo:Ya,useReducer:xa,useRef:Ua,useState:function(){return xa(Ca)},useDebugValue:Qa,useDeferredValue:function(e){return Xa(Ta(),ma.memoizedState,e)},useTransition:function(){return[xa(Ca)[0],Ta().memoizedState]},useMutableSource:Aa,useSyncExternalStore:Pa,useId:Za,unstable_isNewReconciler:!1},lo={readContext:Is,useCallback:$a,useContext:Is,useEffect:qa,useImperativeHandle:Ga,useInsertionEffect:Ha,useLayoutEffect:Wa,useMemo:Ya,useReducer:Na,useRef:Ua,useState:function(){return Na(Ca)},useDebugValue:Qa,useDeferredValue:function(e){var t=Ta();return null===ma?t.memoizedState=e:Xa(t,ma.memoizedState,e)},useTransition:function(){return[Na(Ca)[0],Ta().memoizedState]},useMutableSource:Aa,useSyncExternalStore:Pa,useId:Za,unstable_isNewReconciler:!1};function co(e,t){try{var n="",r=t;do{n+=B(r),r=r.return}while(r);var i=n}catch(s){i="\nError generating stack: "+s.message+"\n"+s.stack}return{value:e,source:t,stack:i,digest:null}}function uo(e,t,n){return{value:e,source:null,stack:null!=n?n:null,digest:null!=t?t:null}}function ho(e,t){try{console.error(t.value)}catch(n){setTimeout((function(){throw n}))}}var fo="function"===typeof WeakMap?WeakMap:Map;function po(e,t,n){(n=Ds(-1,n)).tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){Wl||(Wl=!0,Kl=r),ho(0,t)},n}function mo(e,t,n){(n=Ds(-1,n)).tag=3;var r=e.type.getDerivedStateFromError;if("function"===typeof r){var i=t.value;n.payload=function(){return r(i)},n.callback=function(){ho(0,t)}}var s=e.stateNode;return null!==s&&"function"===typeof s.componentDidCatch&&(n.callback=function(){ho(0,t),"function"!==typeof r&&(null===Gl?Gl=new Set([this]):Gl.add(this));var e=t.stack;this.componentDidCatch(t.value,{componentStack:null!==e?e:""})}),n}function go(e,t,n){var r=e.pingCache;if(null===r){r=e.pingCache=new fo;var i=new Set;r.set(t,i)}else void 0===(i=r.get(t))&&(i=new Set,r.set(t,i));i.has(n)||(i.add(n),e=Tc.bind(null,e,t,n),t.then(e,e))}function vo(e){do{var t;if((t=13===e.tag)&&(t=null===(t=e.memoizedState)||null!==t.dehydrated),t)return e;e=e.return}while(null!==e);return null}function yo(e,t,n,r,i){return 0===(1&e.mode)?(e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,1===n.tag&&(null===n.alternate?n.tag=17:((t=Ds(-1,1)).tag=2,Os(n,t,1))),n.lanes|=1),e):(e.flags|=65536,e.lanes=i,e)}var wo=b.ReactCurrentOwner,bo=!1;function _o(e,t,n,r){t.child=null===e?Xs(t,null,n,r):Ys(t,e.child,n,r)}function Eo(e,t,n,r,i){n=n.render;var s=t.ref;return ks(t,i),r=Sa(e,t,n,r,s,i),n=ka(),null===e||bo?(is&&n&&es(t),t.flags|=1,_o(e,t,r,i),t.child):(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,Wo(e,t,i))}function So(e,t,n,r,i){if(null===e){var s=n.type;return"function"!==typeof s||Dc(s)||void 0!==s.defaultProps||null!==n.compare||void 0!==n.defaultProps?((e=Lc(n.type,null,r,t,t.mode,i)).ref=t.ref,e.return=t,t.child=e):(t.tag=15,t.type=s,ko(e,t,s,r,i))}if(s=e.child,0===(e.lanes&i)){var a=s.memoizedProps;if((n=null!==(n=n.compare)?n:lr)(a,r)&&e.ref===t.ref)return Wo(e,t,i)}return t.flags|=1,(e=Oc(s,r)).ref=t.ref,e.return=t,t.child=e}function ko(e,t,n,r,i){if(null!==e){var s=e.memoizedProps;if(lr(s,r)&&e.ref===t.ref){if(bo=!1,t.pendingProps=r=s,0===(e.lanes&i))return t.lanes=e.lanes,Wo(e,t,i);0!==(131072&e.flags)&&(bo=!0)}}return Co(e,t,n,r,i)}function Io(e,t,n){var r=t.pendingProps,i=r.children,s=null!==e?e.memoizedState:null;if("hidden"===r.mode)if(0===(1&t.mode))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},Ti(Ol,Dl),Dl|=n;else{if(0===(1073741824&n))return e=null!==s?s.baseLanes|n:n,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,Ti(Ol,Dl),Dl|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=null!==s?s.baseLanes:n,Ti(Ol,Dl),Dl|=r}else null!==s?(r=s.baseLanes|n,t.memoizedState=null):r=n,Ti(Ol,Dl),Dl|=r;return _o(e,t,i,n),t.child}function To(e,t){var n=t.ref;(null===e&&null!==n||null!==e&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function Co(e,t,n,r,i){var s=Ri(n)?Ai:xi.current;return s=Pi(t,s),ks(t,i),n=Sa(e,t,n,r,s,i),r=ka(),null===e||bo?(is&&r&&es(t),t.flags|=1,_o(e,t,n,i),t.child):(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,Wo(e,t,i))}function xo(e,t,n,r,i){if(Ri(n)){var s=!0;Mi(t)}else s=!1;if(ks(t,i),null===t.stateNode)Ho(e,t),qs(t,n,r),Ws(t,n,r,i),r=!0;else if(null===e){var a=t.stateNode,o=t.memoizedProps;a.props=o;var l=a.context,c=n.contextType;"object"===typeof c&&null!==c?c=Is(c):c=Pi(t,c=Ri(n)?Ai:xi.current);var u=n.getDerivedStateFromProps,h="function"===typeof u||"function"===typeof a.getSnapshotBeforeUpdate;h||"function"!==typeof a.UNSAFE_componentWillReceiveProps&&"function"!==typeof a.componentWillReceiveProps||(o!==r||l!==c)&&Hs(t,a,r,c),As=!1;var d=t.memoizedState;a.state=d,js(t,r,a,i),l=t.memoizedState,o!==r||d!==l||Ni.current||As?("function"===typeof u&&(Vs(t,n,u,r),l=t.memoizedState),(o=As||zs(t,n,o,r,d,l,c))?(h||"function"!==typeof a.UNSAFE_componentWillMount&&"function"!==typeof a.componentWillMount||("function"===typeof a.componentWillMount&&a.componentWillMount(),"function"===typeof a.UNSAFE_componentWillMount&&a.UNSAFE_componentWillMount()),"function"===typeof a.componentDidMount&&(t.flags|=4194308)):("function"===typeof a.componentDidMount&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=l),a.props=r,a.state=l,a.context=c,r=o):("function"===typeof a.componentDidMount&&(t.flags|=4194308),r=!1)}else{a=t.stateNode,Rs(e,t),o=t.memoizedProps,c=t.type===t.elementType?o:gs(t.type,o),a.props=c,h=t.pendingProps,d=a.context,"object"===typeof(l=n.contextType)&&null!==l?l=Is(l):l=Pi(t,l=Ri(n)?Ai:xi.current);var f=n.getDerivedStateFromProps;(u="function"===typeof f||"function"===typeof a.getSnapshotBeforeUpdate)||"function"!==typeof a.UNSAFE_componentWillReceiveProps&&"function"!==typeof a.componentWillReceiveProps||(o!==h||d!==l)&&Hs(t,a,r,l),As=!1,d=t.memoizedState,a.state=d,js(t,r,a,i);var p=t.memoizedState;o!==h||d!==p||Ni.current||As?("function"===typeof f&&(Vs(t,n,f,r),p=t.memoizedState),(c=As||zs(t,n,c,r,d,p,l)||!1)?(u||"function"!==typeof a.UNSAFE_componentWillUpdate&&"function"!==typeof a.componentWillUpdate||("function"===typeof a.componentWillUpdate&&a.componentWillUpdate(r,p,l),"function"===typeof a.UNSAFE_componentWillUpdate&&a.UNSAFE_componentWillUpdate(r,p,l)),"function"===typeof a.componentDidUpdate&&(t.flags|=4),"function"===typeof a.getSnapshotBeforeUpdate&&(t.flags|=1024)):("function"!==typeof a.componentDidUpdate||o===e.memoizedProps&&d===e.memoizedState||(t.flags|=4),"function"!==typeof a.getSnapshotBeforeUpdate||o===e.memoizedProps&&d===e.memoizedState||(t.flags|=1024),t.memoizedProps=r,t.memoizedState=p),a.props=r,a.state=p,a.context=l,r=c):("function"!==typeof a.componentDidUpdate||o===e.memoizedProps&&d===e.memoizedState||(t.flags|=4),"function"!==typeof a.getSnapshotBeforeUpdate||o===e.memoizedProps&&d===e.memoizedState||(t.flags|=1024),r=!1)}return No(e,t,n,r,s,i)}function No(e,t,n,r,i,s){To(e,t);var a=0!==(128&t.flags);if(!r&&!a)return i&&ji(t,n,!1),Wo(e,t,s);r=t.stateNode,wo.current=t;var o=a&&"function"!==typeof n.getDerivedStateFromError?null:r.render();return t.flags|=1,null!==e&&a?(t.child=Ys(t,e.child,null,s),t.child=Ys(t,null,o,s)):_o(e,t,o,s),t.memoizedState=r.state,i&&ji(t,n,!0),t.child}function Ao(e){var t=e.stateNode;t.pendingContext?Oi(0,t.pendingContext,t.pendingContext!==t.context):t.context&&Oi(0,t.context,!1),ra(e,t.containerInfo)}function Po(e,t,n,r,i){return fs(),ps(i),t.flags|=256,_o(e,t,n,r),t.child}var Ro,Do,Oo,Lo,Mo={dehydrated:null,treeContext:null,retryLane:0};function jo(e){return{baseLanes:e,cachePool:null,transitions:null}}function Fo(e,t,n){var r,i=t.pendingProps,a=oa.current,o=!1,l=0!==(128&t.flags);if((r=l)||(r=(null===e||null!==e.memoizedState)&&0!==(2&a)),r?(o=!0,t.flags&=-129):null!==e&&null===e.memoizedState||(a|=1),Ti(oa,1&a),null===e)return cs(t),null!==(e=t.memoizedState)&&null!==(e=e.dehydrated)?(0===(1&t.mode)?t.lanes=1:"$!"===e.data?t.lanes=8:t.lanes=1073741824,null):(l=i.children,e=i.fallback,o?(i=t.mode,o=t.child,l={mode:"hidden",children:l},0===(1&i)&&null!==o?(o.childLanes=0,o.pendingProps=l):o=jc(l,i,0,null),e=Mc(e,i,n,null),o.return=t,e.return=t,o.sibling=e,t.child=o,t.child.memoizedState=jo(n),t.memoizedState=Mo,e):Uo(t,l));if(null!==(a=e.memoizedState)&&null!==(r=a.dehydrated))return function(e,t,n,r,i,a,o){if(n)return 256&t.flags?(t.flags&=-257,Vo(e,t,o,r=uo(Error(s(422))))):null!==t.memoizedState?(t.child=e.child,t.flags|=128,null):(a=r.fallback,i=t.mode,r=jc({mode:"visible",children:r.children},i,0,null),(a=Mc(a,i,o,null)).flags|=2,r.return=t,a.return=t,r.sibling=a,t.child=r,0!==(1&t.mode)&&Ys(t,e.child,null,o),t.child.memoizedState=jo(o),t.memoizedState=Mo,a);if(0===(1&t.mode))return Vo(e,t,o,null);if("$!"===i.data){if(r=i.nextSibling&&i.nextSibling.dataset)var l=r.dgst;return r=l,Vo(e,t,o,r=uo(a=Error(s(419)),r,void 0))}if(l=0!==(o&e.childLanes),bo||l){if(null!==(r=Al)){switch(o&-o){case 4:i=2;break;case 16:i=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:i=32;break;case 536870912:i=268435456;break;default:i=0}0!==(i=0!==(i&(r.suspendedLanes|o))?0:i)&&i!==a.retryLane&&(a.retryLane=i,Ns(e,i),rc(r,e,i,-1))}return gc(),Vo(e,t,o,r=uo(Error(s(421))))}return"$?"===i.data?(t.flags|=128,t.child=e.child,t=xc.bind(null,e),i._reactRetry=t,null):(e=a.treeContext,rs=ci(i.nextSibling),ns=t,is=!0,ss=null,null!==e&&(Gi[Qi++]=Yi,Gi[Qi++]=Xi,Gi[Qi++]=$i,Yi=e.id,Xi=e.overflow,$i=t),t=Uo(t,r.children),t.flags|=4096,t)}(e,t,l,i,r,a,n);if(o){o=i.fallback,l=t.mode,r=(a=e.child).sibling;var c={mode:"hidden",children:i.children};return 0===(1&l)&&t.child!==a?((i=t.child).childLanes=0,i.pendingProps=c,t.deletions=null):(i=Oc(a,c)).subtreeFlags=14680064&a.subtreeFlags,null!==r?o=Oc(r,o):(o=Mc(o,l,n,null)).flags|=2,o.return=t,i.return=t,i.sibling=o,t.child=i,i=o,o=t.child,l=null===(l=e.child.memoizedState)?jo(n):{baseLanes:l.baseLanes|n,cachePool:null,transitions:l.transitions},o.memoizedState=l,o.childLanes=e.childLanes&~n,t.memoizedState=Mo,i}return e=(o=e.child).sibling,i=Oc(o,{mode:"visible",children:i.children}),0===(1&t.mode)&&(i.lanes=n),i.return=t,i.sibling=null,null!==e&&(null===(n=t.deletions)?(t.deletions=[e],t.flags|=16):n.push(e)),t.child=i,t.memoizedState=null,i}function Uo(e,t){return(t=jc({mode:"visible",children:t},e.mode,0,null)).return=e,e.child=t}function Vo(e,t,n,r){return null!==r&&ps(r),Ys(t,e.child,null,n),(e=Uo(t,t.pendingProps.children)).flags|=2,t.memoizedState=null,e}function Bo(e,t,n){e.lanes|=t;var r=e.alternate;null!==r&&(r.lanes|=t),Ss(e.return,t,n)}function zo(e,t,n,r,i){var s=e.memoizedState;null===s?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:i}:(s.isBackwards=t,s.rendering=null,s.renderingStartTime=0,s.last=r,s.tail=n,s.tailMode=i)}function qo(e,t,n){var r=t.pendingProps,i=r.revealOrder,s=r.tail;if(_o(e,t,r.children,n),0!==(2&(r=oa.current)))r=1&r|2,t.flags|=128;else{if(null!==e&&0!==(128&e.flags))e:for(e=t.child;null!==e;){if(13===e.tag)null!==e.memoizedState&&Bo(e,n,t);else if(19===e.tag)Bo(e,n,t);else if(null!==e.child){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;null===e.sibling;){if(null===e.return||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(Ti(oa,r),0===(1&t.mode))t.memoizedState=null;else switch(i){case"forwards":for(n=t.child,i=null;null!==n;)null!==(e=n.alternate)&&null===la(e)&&(i=n),n=n.sibling;null===(n=i)?(i=t.child,t.child=null):(i=n.sibling,n.sibling=null),zo(t,!1,i,n,s);break;case"backwards":for(n=null,i=t.child,t.child=null;null!==i;){if(null!==(e=i.alternate)&&null===la(e)){t.child=i;break}e=i.sibling,i.sibling=n,n=i,i=e}zo(t,!0,n,null,s);break;case"together":zo(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function Ho(e,t){0===(1&t.mode)&&null!==e&&(e.alternate=null,t.alternate=null,t.flags|=2)}function Wo(e,t,n){if(null!==e&&(t.dependencies=e.dependencies),jl|=t.lanes,0===(n&t.childLanes))return null;if(null!==e&&t.child!==e.child)throw Error(s(153));if(null!==t.child){for(n=Oc(e=t.child,e.pendingProps),t.child=n,n.return=t;null!==e.sibling;)e=e.sibling,(n=n.sibling=Oc(e,e.pendingProps)).return=t;n.sibling=null}return t.child}function Ko(e,t){if(!is)switch(e.tailMode){case"hidden":t=e.tail;for(var n=null;null!==t;)null!==t.alternate&&(n=t),t=t.sibling;null===n?e.tail=null:n.sibling=null;break;case"collapsed":n=e.tail;for(var r=null;null!==n;)null!==n.alternate&&(r=n),n=n.sibling;null===r?t||null===e.tail?e.tail=null:e.tail.sibling=null:r.sibling=null}}function Go(e){var t=null!==e.alternate&&e.alternate.child===e.child,n=0,r=0;if(t)for(var i=e.child;null!==i;)n|=i.lanes|i.childLanes,r|=14680064&i.subtreeFlags,r|=14680064&i.flags,i.return=e,i=i.sibling;else for(i=e.child;null!==i;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags,r|=i.flags,i.return=e,i=i.sibling;return e.subtreeFlags|=r,e.childLanes=n,t}function Qo(e,t,n){var r=t.pendingProps;switch(ts(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Go(t),null;case 1:case 17:return Ri(t.type)&&Di(),Go(t),null;case 3:return r=t.stateNode,ia(),Ii(Ni),Ii(xi),ua(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),null!==e&&null!==e.child||(hs(t)?t.flags|=4:null===e||e.memoizedState.isDehydrated&&0===(256&t.flags)||(t.flags|=1024,null!==ss&&(oc(ss),ss=null))),Do(e,t),Go(t),null;case 5:aa(t);var i=na(ta.current);if(n=t.type,null!==e&&null!=t.stateNode)Oo(e,t,n,r,i),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!r){if(null===t.stateNode)throw Error(s(166));return Go(t),null}if(e=na(Zs.current),hs(t)){r=t.stateNode,n=t.type;var a=t.memoizedProps;switch(r[di]=t,r[fi]=a,e=0!==(1&t.mode),n){case"dialog":Ur("cancel",r),Ur("close",r);break;case"iframe":case"object":case"embed":Ur("load",r);break;case"video":case"audio":for(i=0;i<Lr.length;i++)Ur(Lr[i],r);break;case"source":Ur("error",r);break;case"img":case"image":case"link":Ur("error",r),Ur("load",r);break;case"details":Ur("toggle",r);break;case"input":Y(r,a),Ur("invalid",r);break;case"select":r._wrapperState={wasMultiple:!!a.multiple},Ur("invalid",r);break;case"textarea":ie(r,a),Ur("invalid",r)}for(var l in ye(n,a),i=null,a)if(a.hasOwnProperty(l)){var c=a[l];"children"===l?"string"===typeof c?r.textContent!==c&&(!0!==a.suppressHydrationWarning&&Jr(r.textContent,c,e),i=["children",c]):"number"===typeof c&&r.textContent!==""+c&&(!0!==a.suppressHydrationWarning&&Jr(r.textContent,c,e),i=["children",""+c]):o.hasOwnProperty(l)&&null!=c&&"onScroll"===l&&Ur("scroll",r)}switch(n){case"input":K(r),Z(r,a,!0);break;case"textarea":K(r),ae(r);break;case"select":case"option":break;default:"function"===typeof a.onClick&&(r.onclick=Zr)}r=i,t.updateQueue=r,null!==r&&(t.flags|=4)}else{l=9===i.nodeType?i:i.ownerDocument,"http://www.w3.org/1999/xhtml"===e&&(e=oe(n)),"http://www.w3.org/1999/xhtml"===e?"script"===n?((e=l.createElement("div")).innerHTML="<script><\/script>",e=e.removeChild(e.firstChild)):"string"===typeof r.is?e=l.createElement(n,{is:r.is}):(e=l.createElement(n),"select"===n&&(l=e,r.multiple?l.multiple=!0:r.size&&(l.size=r.size))):e=l.createElementNS(e,n),e[di]=t,e[fi]=r,Ro(e,t,!1,!1),t.stateNode=e;e:{switch(l=we(n,r),n){case"dialog":Ur("cancel",e),Ur("close",e),i=r;break;case"iframe":case"object":case"embed":Ur("load",e),i=r;break;case"video":case"audio":for(i=0;i<Lr.length;i++)Ur(Lr[i],e);i=r;break;case"source":Ur("error",e),i=r;break;case"img":case"image":case"link":Ur("error",e),Ur("load",e),i=r;break;case"details":Ur("toggle",e),i=r;break;case"input":Y(e,r),i=$(e,r),Ur("invalid",e);break;case"option":default:i=r;break;case"select":e._wrapperState={wasMultiple:!!r.multiple},i=j({},r,{value:void 0}),Ur("invalid",e);break;case"textarea":ie(e,r),i=re(e,r),Ur("invalid",e)}for(a in ye(n,i),c=i)if(c.hasOwnProperty(a)){var u=c[a];"style"===a?ge(e,u):"dangerouslySetInnerHTML"===a?null!=(u=u?u.__html:void 0)&&he(e,u):"children"===a?"string"===typeof u?("textarea"!==n||""!==u)&&de(e,u):"number"===typeof u&&de(e,""+u):"suppressContentEditableWarning"!==a&&"suppressHydrationWarning"!==a&&"autoFocus"!==a&&(o.hasOwnProperty(a)?null!=u&&"onScroll"===a&&Ur("scroll",e):null!=u&&w(e,a,u,l))}switch(n){case"input":K(e),Z(e,r,!1);break;case"textarea":K(e),ae(e);break;case"option":null!=r.value&&e.setAttribute("value",""+H(r.value));break;case"select":e.multiple=!!r.multiple,null!=(a=r.value)?ne(e,!!r.multiple,a,!1):null!=r.defaultValue&&ne(e,!!r.multiple,r.defaultValue,!0);break;default:"function"===typeof i.onClick&&(e.onclick=Zr)}switch(n){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}}r&&(t.flags|=4)}null!==t.ref&&(t.flags|=512,t.flags|=2097152)}return Go(t),null;case 6:if(e&&null!=t.stateNode)Lo(e,t,e.memoizedProps,r);else{if("string"!==typeof r&&null===t.stateNode)throw Error(s(166));if(n=na(ta.current),na(Zs.current),hs(t)){if(r=t.stateNode,n=t.memoizedProps,r[di]=t,(a=r.nodeValue!==n)&&null!==(e=ns))switch(e.tag){case 3:Jr(r.nodeValue,n,0!==(1&e.mode));break;case 5:!0!==e.memoizedProps.suppressHydrationWarning&&Jr(r.nodeValue,n,0!==(1&e.mode))}a&&(t.flags|=4)}else(r=(9===n.nodeType?n:n.ownerDocument).createTextNode(r))[di]=t,t.stateNode=r}return Go(t),null;case 13:if(Ii(oa),r=t.memoizedState,null===e||null!==e.memoizedState&&null!==e.memoizedState.dehydrated){if(is&&null!==rs&&0!==(1&t.mode)&&0===(128&t.flags))ds(),fs(),t.flags|=98560,a=!1;else if(a=hs(t),null!==r&&null!==r.dehydrated){if(null===e){if(!a)throw Error(s(318));if(!(a=null!==(a=t.memoizedState)?a.dehydrated:null))throw Error(s(317));a[di]=t}else fs(),0===(128&t.flags)&&(t.memoizedState=null),t.flags|=4;Go(t),a=!1}else null!==ss&&(oc(ss),ss=null),a=!0;if(!a)return 65536&t.flags?t:null}return 0!==(128&t.flags)?(t.lanes=n,t):((r=null!==r)!==(null!==e&&null!==e.memoizedState)&&r&&(t.child.flags|=8192,0!==(1&t.mode)&&(null===e||0!==(1&oa.current)?0===Ll&&(Ll=3):gc())),null!==t.updateQueue&&(t.flags|=4),Go(t),null);case 4:return ia(),Do(e,t),null===e&&zr(t.stateNode.containerInfo),Go(t),null;case 10:return Es(t.type._context),Go(t),null;case 19:if(Ii(oa),null===(a=t.memoizedState))return Go(t),null;if(r=0!==(128&t.flags),null===(l=a.rendering))if(r)Ko(a,!1);else{if(0!==Ll||null!==e&&0!==(128&e.flags))for(e=t.child;null!==e;){if(null!==(l=la(e))){for(t.flags|=128,Ko(a,!1),null!==(r=l.updateQueue)&&(t.updateQueue=r,t.flags|=4),t.subtreeFlags=0,r=n,n=t.child;null!==n;)e=r,(a=n).flags&=14680066,null===(l=a.alternate)?(a.childLanes=0,a.lanes=e,a.child=null,a.subtreeFlags=0,a.memoizedProps=null,a.memoizedState=null,a.updateQueue=null,a.dependencies=null,a.stateNode=null):(a.childLanes=l.childLanes,a.lanes=l.lanes,a.child=l.child,a.subtreeFlags=0,a.deletions=null,a.memoizedProps=l.memoizedProps,a.memoizedState=l.memoizedState,a.updateQueue=l.updateQueue,a.type=l.type,e=l.dependencies,a.dependencies=null===e?null:{lanes:e.lanes,firstContext:e.firstContext}),n=n.sibling;return Ti(oa,1&oa.current|2),t.child}e=e.sibling}null!==a.tail&&Xe()>ql&&(t.flags|=128,r=!0,Ko(a,!1),t.lanes=4194304)}else{if(!r)if(null!==(e=la(l))){if(t.flags|=128,r=!0,null!==(n=e.updateQueue)&&(t.updateQueue=n,t.flags|=4),Ko(a,!0),null===a.tail&&"hidden"===a.tailMode&&!l.alternate&&!is)return Go(t),null}else 2*Xe()-a.renderingStartTime>ql&&1073741824!==n&&(t.flags|=128,r=!0,Ko(a,!1),t.lanes=4194304);a.isBackwards?(l.sibling=t.child,t.child=l):(null!==(n=a.last)?n.sibling=l:t.child=l,a.last=l)}return null!==a.tail?(t=a.tail,a.rendering=t,a.tail=t.sibling,a.renderingStartTime=Xe(),t.sibling=null,n=oa.current,Ti(oa,r?1&n|2:1&n),t):(Go(t),null);case 22:case 23:return dc(),r=null!==t.memoizedState,null!==e&&null!==e.memoizedState!==r&&(t.flags|=8192),r&&0!==(1&t.mode)?0!==(1073741824&Dl)&&(Go(t),6&t.subtreeFlags&&(t.flags|=8192)):Go(t),null;case 24:case 25:return null}throw Error(s(156,t.tag))}function $o(e,t){switch(ts(t),t.tag){case 1:return Ri(t.type)&&Di(),65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 3:return ia(),Ii(Ni),Ii(xi),ua(),0!==(65536&(e=t.flags))&&0===(128&e)?(t.flags=-65537&e|128,t):null;case 5:return aa(t),null;case 13:if(Ii(oa),null!==(e=t.memoizedState)&&null!==e.dehydrated){if(null===t.alternate)throw Error(s(340));fs()}return 65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 19:return Ii(oa),null;case 4:return ia(),null;case 10:return Es(t.type._context),null;case 22:case 23:return dc(),null;default:return null}}Ro=function(e,t){for(var n=t.child;null!==n;){if(5===n.tag||6===n.tag)e.appendChild(n.stateNode);else if(4!==n.tag&&null!==n.child){n.child.return=n,n=n.child;continue}if(n===t)break;for(;null===n.sibling;){if(null===n.return||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}},Do=function(){},Oo=function(e,t,n,r){var i=e.memoizedProps;if(i!==r){e=t.stateNode,na(Zs.current);var s,a=null;switch(n){case"input":i=$(e,i),r=$(e,r),a=[];break;case"select":i=j({},i,{value:void 0}),r=j({},r,{value:void 0}),a=[];break;case"textarea":i=re(e,i),r=re(e,r),a=[];break;default:"function"!==typeof i.onClick&&"function"===typeof r.onClick&&(e.onclick=Zr)}for(u in ye(n,r),n=null,i)if(!r.hasOwnProperty(u)&&i.hasOwnProperty(u)&&null!=i[u])if("style"===u){var l=i[u];for(s in l)l.hasOwnProperty(s)&&(n||(n={}),n[s]="")}else"dangerouslySetInnerHTML"!==u&&"children"!==u&&"suppressContentEditableWarning"!==u&&"suppressHydrationWarning"!==u&&"autoFocus"!==u&&(o.hasOwnProperty(u)?a||(a=[]):(a=a||[]).push(u,null));for(u in r){var c=r[u];if(l=null!=i?i[u]:void 0,r.hasOwnProperty(u)&&c!==l&&(null!=c||null!=l))if("style"===u)if(l){for(s in l)!l.hasOwnProperty(s)||c&&c.hasOwnProperty(s)||(n||(n={}),n[s]="");for(s in c)c.hasOwnProperty(s)&&l[s]!==c[s]&&(n||(n={}),n[s]=c[s])}else n||(a||(a=[]),a.push(u,n)),n=c;else"dangerouslySetInnerHTML"===u?(c=c?c.__html:void 0,l=l?l.__html:void 0,null!=c&&l!==c&&(a=a||[]).push(u,c)):"children"===u?"string"!==typeof c&&"number"!==typeof c||(a=a||[]).push(u,""+c):"suppressContentEditableWarning"!==u&&"suppressHydrationWarning"!==u&&(o.hasOwnProperty(u)?(null!=c&&"onScroll"===u&&Ur("scroll",e),a||l===c||(a=[])):(a=a||[]).push(u,c))}n&&(a=a||[]).push("style",n);var u=a;(t.updateQueue=u)&&(t.flags|=4)}},Lo=function(e,t,n,r){n!==r&&(t.flags|=4)};var Yo=!1,Xo=!1,Jo="function"===typeof WeakSet?WeakSet:Set,Zo=null;function el(e,t){var n=e.ref;if(null!==n)if("function"===typeof n)try{n(null)}catch(r){Ic(e,t,r)}else n.current=null}function tl(e,t,n){try{n()}catch(r){Ic(e,t,r)}}var nl=!1;function rl(e,t,n){var r=t.updateQueue;if(null!==(r=null!==r?r.lastEffect:null)){var i=r=r.next;do{if((i.tag&e)===e){var s=i.destroy;i.destroy=void 0,void 0!==s&&tl(t,n,s)}i=i.next}while(i!==r)}}function il(e,t){if(null!==(t=null!==(t=t.updateQueue)?t.lastEffect:null)){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function sl(e){var t=e.ref;if(null!==t){var n=e.stateNode;e.tag,e=n,"function"===typeof t?t(e):t.current=e}}function al(e){var t=e.alternate;null!==t&&(e.alternate=null,al(t)),e.child=null,e.deletions=null,e.sibling=null,5===e.tag&&(null!==(t=e.stateNode)&&(delete t[di],delete t[fi],delete t[mi],delete t[gi],delete t[vi])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function ol(e){return 5===e.tag||3===e.tag||4===e.tag}function ll(e){e:for(;;){for(;null===e.sibling;){if(null===e.return||ol(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;5!==e.tag&&6!==e.tag&&18!==e.tag;){if(2&e.flags)continue e;if(null===e.child||4===e.tag)continue e;e.child.return=e,e=e.child}if(!(2&e.flags))return e.stateNode}}function cl(e,t,n){var r=e.tag;if(5===r||6===r)e=e.stateNode,t?8===n.nodeType?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(8===n.nodeType?(t=n.parentNode).insertBefore(e,n):(t=n).appendChild(e),null!==(n=n._reactRootContainer)&&void 0!==n||null!==t.onclick||(t.onclick=Zr));else if(4!==r&&null!==(e=e.child))for(cl(e,t,n),e=e.sibling;null!==e;)cl(e,t,n),e=e.sibling}function ul(e,t,n){var r=e.tag;if(5===r||6===r)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(4!==r&&null!==(e=e.child))for(ul(e,t,n),e=e.sibling;null!==e;)ul(e,t,n),e=e.sibling}var hl=null,dl=!1;function fl(e,t,n){for(n=n.child;null!==n;)pl(e,t,n),n=n.sibling}function pl(e,t,n){if(st&&"function"===typeof st.onCommitFiberUnmount)try{st.onCommitFiberUnmount(it,n)}catch(o){}switch(n.tag){case 5:Xo||el(n,t);case 6:var r=hl,i=dl;hl=null,fl(e,t,n),dl=i,null!==(hl=r)&&(dl?(e=hl,n=n.stateNode,8===e.nodeType?e.parentNode.removeChild(n):e.removeChild(n)):hl.removeChild(n.stateNode));break;case 18:null!==hl&&(dl?(e=hl,n=n.stateNode,8===e.nodeType?li(e.parentNode,n):1===e.nodeType&&li(e,n),zt(e)):li(hl,n.stateNode));break;case 4:r=hl,i=dl,hl=n.stateNode.containerInfo,dl=!0,fl(e,t,n),hl=r,dl=i;break;case 0:case 11:case 14:case 15:if(!Xo&&(null!==(r=n.updateQueue)&&null!==(r=r.lastEffect))){i=r=r.next;do{var s=i,a=s.destroy;s=s.tag,void 0!==a&&(0!==(2&s)||0!==(4&s))&&tl(n,t,a),i=i.next}while(i!==r)}fl(e,t,n);break;case 1:if(!Xo&&(el(n,t),"function"===typeof(r=n.stateNode).componentWillUnmount))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){Ic(n,t,o)}fl(e,t,n);break;case 21:fl(e,t,n);break;case 22:1&n.mode?(Xo=(r=Xo)||null!==n.memoizedState,fl(e,t,n),Xo=r):fl(e,t,n);break;default:fl(e,t,n)}}function ml(e){var t=e.updateQueue;if(null!==t){e.updateQueue=null;var n=e.stateNode;null===n&&(n=e.stateNode=new Jo),t.forEach((function(t){var r=Nc.bind(null,e,t);n.has(t)||(n.add(t),t.then(r,r))}))}}function gl(e,t){var n=t.deletions;if(null!==n)for(var r=0;r<n.length;r++){var i=n[r];try{var a=e,o=t,l=o;e:for(;null!==l;){switch(l.tag){case 5:hl=l.stateNode,dl=!1;break e;case 3:case 4:hl=l.stateNode.containerInfo,dl=!0;break e}l=l.return}if(null===hl)throw Error(s(160));pl(a,o,i),hl=null,dl=!1;var c=i.alternate;null!==c&&(c.return=null),i.return=null}catch(u){Ic(i,t,u)}}if(12854&t.subtreeFlags)for(t=t.child;null!==t;)vl(t,e),t=t.sibling}function vl(e,t){var n=e.alternate,r=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(gl(t,e),yl(e),4&r){try{rl(3,e,e.return),il(3,e)}catch(g){Ic(e,e.return,g)}try{rl(5,e,e.return)}catch(g){Ic(e,e.return,g)}}break;case 1:gl(t,e),yl(e),512&r&&null!==n&&el(n,n.return);break;case 5:if(gl(t,e),yl(e),512&r&&null!==n&&el(n,n.return),32&e.flags){var i=e.stateNode;try{de(i,"")}catch(g){Ic(e,e.return,g)}}if(4&r&&null!=(i=e.stateNode)){var a=e.memoizedProps,o=null!==n?n.memoizedProps:a,l=e.type,c=e.updateQueue;if(e.updateQueue=null,null!==c)try{"input"===l&&"radio"===a.type&&null!=a.name&&X(i,a),we(l,o);var u=we(l,a);for(o=0;o<c.length;o+=2){var h=c[o],d=c[o+1];"style"===h?ge(i,d):"dangerouslySetInnerHTML"===h?he(i,d):"children"===h?de(i,d):w(i,h,d,u)}switch(l){case"input":J(i,a);break;case"textarea":se(i,a);break;case"select":var f=i._wrapperState.wasMultiple;i._wrapperState.wasMultiple=!!a.multiple;var p=a.value;null!=p?ne(i,!!a.multiple,p,!1):f!==!!a.multiple&&(null!=a.defaultValue?ne(i,!!a.multiple,a.defaultValue,!0):ne(i,!!a.multiple,a.multiple?[]:"",!1))}i[fi]=a}catch(g){Ic(e,e.return,g)}}break;case 6:if(gl(t,e),yl(e),4&r){if(null===e.stateNode)throw Error(s(162));i=e.stateNode,a=e.memoizedProps;try{i.nodeValue=a}catch(g){Ic(e,e.return,g)}}break;case 3:if(gl(t,e),yl(e),4&r&&null!==n&&n.memoizedState.isDehydrated)try{zt(t.containerInfo)}catch(g){Ic(e,e.return,g)}break;case 4:default:gl(t,e),yl(e);break;case 13:gl(t,e),yl(e),8192&(i=e.child).flags&&(a=null!==i.memoizedState,i.stateNode.isHidden=a,!a||null!==i.alternate&&null!==i.alternate.memoizedState||(zl=Xe())),4&r&&ml(e);break;case 22:if(h=null!==n&&null!==n.memoizedState,1&e.mode?(Xo=(u=Xo)||h,gl(t,e),Xo=u):gl(t,e),yl(e),8192&r){if(u=null!==e.memoizedState,(e.stateNode.isHidden=u)&&!h&&0!==(1&e.mode))for(Zo=e,h=e.child;null!==h;){for(d=Zo=h;null!==Zo;){switch(p=(f=Zo).child,f.tag){case 0:case 11:case 14:case 15:rl(4,f,f.return);break;case 1:el(f,f.return);var m=f.stateNode;if("function"===typeof m.componentWillUnmount){r=f,n=f.return;try{t=r,m.props=t.memoizedProps,m.state=t.memoizedState,m.componentWillUnmount()}catch(g){Ic(r,n,g)}}break;case 5:el(f,f.return);break;case 22:if(null!==f.memoizedState){El(d);continue}}null!==p?(p.return=f,Zo=p):El(d)}h=h.sibling}e:for(h=null,d=e;;){if(5===d.tag){if(null===h){h=d;try{i=d.stateNode,u?"function"===typeof(a=i.style).setProperty?a.setProperty("display","none","important"):a.display="none":(l=d.stateNode,o=void 0!==(c=d.memoizedProps.style)&&null!==c&&c.hasOwnProperty("display")?c.display:null,l.style.display=me("display",o))}catch(g){Ic(e,e.return,g)}}}else if(6===d.tag){if(null===h)try{d.stateNode.nodeValue=u?"":d.memoizedProps}catch(g){Ic(e,e.return,g)}}else if((22!==d.tag&&23!==d.tag||null===d.memoizedState||d===e)&&null!==d.child){d.child.return=d,d=d.child;continue}if(d===e)break e;for(;null===d.sibling;){if(null===d.return||d.return===e)break e;h===d&&(h=null),d=d.return}h===d&&(h=null),d.sibling.return=d.return,d=d.sibling}}break;case 19:gl(t,e),yl(e),4&r&&ml(e);case 21:}}function yl(e){var t=e.flags;if(2&t){try{e:{for(var n=e.return;null!==n;){if(ol(n)){var r=n;break e}n=n.return}throw Error(s(160))}switch(r.tag){case 5:var i=r.stateNode;32&r.flags&&(de(i,""),r.flags&=-33),ul(e,ll(e),i);break;case 3:case 4:var a=r.stateNode.containerInfo;cl(e,ll(e),a);break;default:throw Error(s(161))}}catch(o){Ic(e,e.return,o)}e.flags&=-3}4096&t&&(e.flags&=-4097)}function wl(e,t,n){Zo=e,bl(e,t,n)}function bl(e,t,n){for(var r=0!==(1&e.mode);null!==Zo;){var i=Zo,s=i.child;if(22===i.tag&&r){var a=null!==i.memoizedState||Yo;if(!a){var o=i.alternate,l=null!==o&&null!==o.memoizedState||Xo;o=Yo;var c=Xo;if(Yo=a,(Xo=l)&&!c)for(Zo=i;null!==Zo;)l=(a=Zo).child,22===a.tag&&null!==a.memoizedState?Sl(i):null!==l?(l.return=a,Zo=l):Sl(i);for(;null!==s;)Zo=s,bl(s,t,n),s=s.sibling;Zo=i,Yo=o,Xo=c}_l(e)}else 0!==(8772&i.subtreeFlags)&&null!==s?(s.return=i,Zo=s):_l(e)}}function _l(e){for(;null!==Zo;){var t=Zo;if(0!==(8772&t.flags)){var n=t.alternate;try{if(0!==(8772&t.flags))switch(t.tag){case 0:case 11:case 15:Xo||il(5,t);break;case 1:var r=t.stateNode;if(4&t.flags&&!Xo)if(null===n)r.componentDidMount();else{var i=t.elementType===t.type?n.memoizedProps:gs(t.type,n.memoizedProps);r.componentDidUpdate(i,n.memoizedState,r.__reactInternalSnapshotBeforeUpdate)}var a=t.updateQueue;null!==a&&Fs(t,a,r);break;case 3:var o=t.updateQueue;if(null!==o){if(n=null,null!==t.child)switch(t.child.tag){case 5:case 1:n=t.child.stateNode}Fs(t,o,n)}break;case 5:var l=t.stateNode;if(null===n&&4&t.flags){n=l;var c=t.memoizedProps;switch(t.type){case"button":case"input":case"select":case"textarea":c.autoFocus&&n.focus();break;case"img":c.src&&(n.src=c.src)}}break;case 6:case 4:case 12:case 19:case 17:case 21:case 22:case 23:case 25:break;case 13:if(null===t.memoizedState){var u=t.alternate;if(null!==u){var h=u.memoizedState;if(null!==h){var d=h.dehydrated;null!==d&&zt(d)}}}break;default:throw Error(s(163))}Xo||512&t.flags&&sl(t)}catch(f){Ic(t,t.return,f)}}if(t===e){Zo=null;break}if(null!==(n=t.sibling)){n.return=t.return,Zo=n;break}Zo=t.return}}function El(e){for(;null!==Zo;){var t=Zo;if(t===e){Zo=null;break}var n=t.sibling;if(null!==n){n.return=t.return,Zo=n;break}Zo=t.return}}function Sl(e){for(;null!==Zo;){var t=Zo;try{switch(t.tag){case 0:case 11:case 15:var n=t.return;try{il(4,t)}catch(l){Ic(t,n,l)}break;case 1:var r=t.stateNode;if("function"===typeof r.componentDidMount){var i=t.return;try{r.componentDidMount()}catch(l){Ic(t,i,l)}}var s=t.return;try{sl(t)}catch(l){Ic(t,s,l)}break;case 5:var a=t.return;try{sl(t)}catch(l){Ic(t,a,l)}}}catch(l){Ic(t,t.return,l)}if(t===e){Zo=null;break}var o=t.sibling;if(null!==o){o.return=t.return,Zo=o;break}Zo=t.return}}var kl,Il=Math.ceil,Tl=b.ReactCurrentDispatcher,Cl=b.ReactCurrentOwner,xl=b.ReactCurrentBatchConfig,Nl=0,Al=null,Pl=null,Rl=0,Dl=0,Ol=ki(0),Ll=0,Ml=null,jl=0,Fl=0,Ul=0,Vl=null,Bl=null,zl=0,ql=1/0,Hl=null,Wl=!1,Kl=null,Gl=null,Ql=!1,$l=null,Yl=0,Xl=0,Jl=null,Zl=-1,ec=0;function tc(){return 0!==(6&Nl)?Xe():-1!==Zl?Zl:Zl=Xe()}function nc(e){return 0===(1&e.mode)?1:0!==(2&Nl)&&0!==Rl?Rl&-Rl:null!==ms.transition?(0===ec&&(ec=mt()),ec):0!==(e=wt)?e:e=void 0===(e=window.event)?16:Yt(e.type)}function rc(e,t,n,r){if(50<Xl)throw Xl=0,Jl=null,Error(s(185));vt(e,n,r),0!==(2&Nl)&&e===Al||(e===Al&&(0===(2&Nl)&&(Fl|=n),4===Ll&&lc(e,Rl)),ic(e,r),1===n&&0===Nl&&0===(1&t.mode)&&(ql=Xe()+500,Ui&&zi()))}function ic(e,t){var n=e.callbackNode;!function(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,s=e.pendingLanes;0<s;){var a=31-at(s),o=1<<a,l=i[a];-1===l?0!==(o&n)&&0===(o&r)||(i[a]=ft(o,t)):l<=t&&(e.expiredLanes|=o),s&=~o}}(e,t);var r=dt(e,e===Al?Rl:0);if(0===r)null!==n&&Qe(n),e.callbackNode=null,e.callbackPriority=0;else if(t=r&-r,e.callbackPriority!==t){if(null!=n&&Qe(n),1===t)0===e.tag?function(e){Ui=!0,Bi(e)}(cc.bind(null,e)):Bi(cc.bind(null,e)),ai((function(){0===(6&Nl)&&zi()})),n=null;else{switch(bt(r)){case 1:n=Ze;break;case 4:n=et;break;case 16:default:n=tt;break;case 536870912:n=rt}n=Ac(n,sc.bind(null,e))}e.callbackPriority=t,e.callbackNode=n}}function sc(e,t){if(Zl=-1,ec=0,0!==(6&Nl))throw Error(s(327));var n=e.callbackNode;if(Sc()&&e.callbackNode!==n)return null;var r=dt(e,e===Al?Rl:0);if(0===r)return null;if(0!==(30&r)||0!==(r&e.expiredLanes)||t)t=vc(e,r);else{t=r;var i=Nl;Nl|=2;var a=mc();for(Al===e&&Rl===t||(Hl=null,ql=Xe()+500,fc(e,t));;)try{wc();break}catch(l){pc(e,l)}_s(),Tl.current=a,Nl=i,null!==Pl?t=0:(Al=null,Rl=0,t=Ll)}if(0!==t){if(2===t&&(0!==(i=pt(e))&&(r=i,t=ac(e,i))),1===t)throw n=Ml,fc(e,0),lc(e,r),ic(e,Xe()),n;if(6===t)lc(e,r);else{if(i=e.current.alternate,0===(30&r)&&!function(e){for(var t=e;;){if(16384&t.flags){var n=t.updateQueue;if(null!==n&&null!==(n=n.stores))for(var r=0;r<n.length;r++){var i=n[r],s=i.getSnapshot;i=i.value;try{if(!or(s(),i))return!1}catch(o){return!1}}}if(n=t.child,16384&t.subtreeFlags&&null!==n)n.return=t,t=n;else{if(t===e)break;for(;null===t.sibling;){if(null===t.return||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}(i)&&(2===(t=vc(e,r))&&(0!==(a=pt(e))&&(r=a,t=ac(e,a))),1===t))throw n=Ml,fc(e,0),lc(e,r),ic(e,Xe()),n;switch(e.finishedWork=i,e.finishedLanes=r,t){case 0:case 1:throw Error(s(345));case 2:case 5:Ec(e,Bl,Hl);break;case 3:if(lc(e,r),(130023424&r)===r&&10<(t=zl+500-Xe())){if(0!==dt(e,0))break;if(((i=e.suspendedLanes)&r)!==r){tc(),e.pingedLanes|=e.suspendedLanes&i;break}e.timeoutHandle=ri(Ec.bind(null,e,Bl,Hl),t);break}Ec(e,Bl,Hl);break;case 4:if(lc(e,r),(4194240&r)===r)break;for(t=e.eventTimes,i=-1;0<r;){var o=31-at(r);a=1<<o,(o=t[o])>i&&(i=o),r&=~a}if(r=i,10<(r=(120>(r=Xe()-r)?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Il(r/1960))-r)){e.timeoutHandle=ri(Ec.bind(null,e,Bl,Hl),r);break}Ec(e,Bl,Hl);break;default:throw Error(s(329))}}}return ic(e,Xe()),e.callbackNode===n?sc.bind(null,e):null}function ac(e,t){var n=Vl;return e.current.memoizedState.isDehydrated&&(fc(e,t).flags|=256),2!==(e=vc(e,t))&&(t=Bl,Bl=n,null!==t&&oc(t)),e}function oc(e){null===Bl?Bl=e:Bl.push.apply(Bl,e)}function lc(e,t){for(t&=~Ul,t&=~Fl,e.suspendedLanes|=t,e.pingedLanes&=~t,e=e.expirationTimes;0<t;){var n=31-at(t),r=1<<n;e[n]=-1,t&=~r}}function cc(e){if(0!==(6&Nl))throw Error(s(327));Sc();var t=dt(e,0);if(0===(1&t))return ic(e,Xe()),null;var n=vc(e,t);if(0!==e.tag&&2===n){var r=pt(e);0!==r&&(t=r,n=ac(e,r))}if(1===n)throw n=Ml,fc(e,0),lc(e,t),ic(e,Xe()),n;if(6===n)throw Error(s(345));return e.finishedWork=e.current.alternate,e.finishedLanes=t,Ec(e,Bl,Hl),ic(e,Xe()),null}function uc(e,t){var n=Nl;Nl|=1;try{return e(t)}finally{0===(Nl=n)&&(ql=Xe()+500,Ui&&zi())}}function hc(e){null!==$l&&0===$l.tag&&0===(6&Nl)&&Sc();var t=Nl;Nl|=1;var n=xl.transition,r=wt;try{if(xl.transition=null,wt=1,e)return e()}finally{wt=r,xl.transition=n,0===(6&(Nl=t))&&zi()}}function dc(){Dl=Ol.current,Ii(Ol)}function fc(e,t){e.finishedWork=null,e.finishedLanes=0;var n=e.timeoutHandle;if(-1!==n&&(e.timeoutHandle=-1,ii(n)),null!==Pl)for(n=Pl.return;null!==n;){var r=n;switch(ts(r),r.tag){case 1:null!==(r=r.type.childContextTypes)&&void 0!==r&&Di();break;case 3:ia(),Ii(Ni),Ii(xi),ua();break;case 5:aa(r);break;case 4:ia();break;case 13:case 19:Ii(oa);break;case 10:Es(r.type._context);break;case 22:case 23:dc()}n=n.return}if(Al=e,Pl=e=Oc(e.current,null),Rl=Dl=t,Ll=0,Ml=null,Ul=Fl=jl=0,Bl=Vl=null,null!==Ts){for(t=0;t<Ts.length;t++)if(null!==(r=(n=Ts[t]).interleaved)){n.interleaved=null;var i=r.next,s=n.pending;if(null!==s){var a=s.next;s.next=i,r.next=a}n.pending=r}Ts=null}return e}function pc(e,t){for(;;){var n=Pl;try{if(_s(),ha.current=so,va){for(var r=pa.memoizedState;null!==r;){var i=r.queue;null!==i&&(i.pending=null),r=r.next}va=!1}if(fa=0,ga=ma=pa=null,ya=!1,wa=0,Cl.current=null,null===n||null===n.return){Ll=1,Ml=t,Pl=null;break}e:{var a=e,o=n.return,l=n,c=t;if(t=Rl,l.flags|=32768,null!==c&&"object"===typeof c&&"function"===typeof c.then){var u=c,h=l,d=h.tag;if(0===(1&h.mode)&&(0===d||11===d||15===d)){var f=h.alternate;f?(h.updateQueue=f.updateQueue,h.memoizedState=f.memoizedState,h.lanes=f.lanes):(h.updateQueue=null,h.memoizedState=null)}var p=vo(o);if(null!==p){p.flags&=-257,yo(p,o,l,0,t),1&p.mode&&go(a,u,t),c=u;var m=(t=p).updateQueue;if(null===m){var g=new Set;g.add(c),t.updateQueue=g}else m.add(c);break e}if(0===(1&t)){go(a,u,t),gc();break e}c=Error(s(426))}else if(is&&1&l.mode){var v=vo(o);if(null!==v){0===(65536&v.flags)&&(v.flags|=256),yo(v,o,l,0,t),ps(co(c,l));break e}}a=c=co(c,l),4!==Ll&&(Ll=2),null===Vl?Vl=[a]:Vl.push(a),a=o;do{switch(a.tag){case 3:a.flags|=65536,t&=-t,a.lanes|=t,Ms(a,po(0,c,t));break e;case 1:l=c;var y=a.type,w=a.stateNode;if(0===(128&a.flags)&&("function"===typeof y.getDerivedStateFromError||null!==w&&"function"===typeof w.componentDidCatch&&(null===Gl||!Gl.has(w)))){a.flags|=65536,t&=-t,a.lanes|=t,Ms(a,mo(a,l,t));break e}}a=a.return}while(null!==a)}_c(n)}catch(b){t=b,Pl===n&&null!==n&&(Pl=n=n.return);continue}break}}function mc(){var e=Tl.current;return Tl.current=so,null===e?so:e}function gc(){0!==Ll&&3!==Ll&&2!==Ll||(Ll=4),null===Al||0===(268435455&jl)&&0===(268435455&Fl)||lc(Al,Rl)}function vc(e,t){var n=Nl;Nl|=2;var r=mc();for(Al===e&&Rl===t||(Hl=null,fc(e,t));;)try{yc();break}catch(i){pc(e,i)}if(_s(),Nl=n,Tl.current=r,null!==Pl)throw Error(s(261));return Al=null,Rl=0,Ll}function yc(){for(;null!==Pl;)bc(Pl)}function wc(){for(;null!==Pl&&!$e();)bc(Pl)}function bc(e){var t=kl(e.alternate,e,Dl);e.memoizedProps=e.pendingProps,null===t?_c(e):Pl=t,Cl.current=null}function _c(e){var t=e;do{var n=t.alternate;if(e=t.return,0===(32768&t.flags)){if(null!==(n=Qo(n,t,Dl)))return void(Pl=n)}else{if(null!==(n=$o(n,t)))return n.flags&=32767,void(Pl=n);if(null===e)return Ll=6,void(Pl=null);e.flags|=32768,e.subtreeFlags=0,e.deletions=null}if(null!==(t=t.sibling))return void(Pl=t);Pl=t=e}while(null!==t);0===Ll&&(Ll=5)}function Ec(e,t,n){var r=wt,i=xl.transition;try{xl.transition=null,wt=1,function(e,t,n,r){do{Sc()}while(null!==$l);if(0!==(6&Nl))throw Error(s(327));n=e.finishedWork;var i=e.finishedLanes;if(null===n)return null;if(e.finishedWork=null,e.finishedLanes=0,n===e.current)throw Error(s(177));e.callbackNode=null,e.callbackPriority=0;var a=n.lanes|n.childLanes;if(function(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0<n;){var i=31-at(n),s=1<<i;t[i]=0,r[i]=-1,e[i]=-1,n&=~s}}(e,a),e===Al&&(Pl=Al=null,Rl=0),0===(2064&n.subtreeFlags)&&0===(2064&n.flags)||Ql||(Ql=!0,Ac(tt,(function(){return Sc(),null}))),a=0!==(15990&n.flags),0!==(15990&n.subtreeFlags)||a){a=xl.transition,xl.transition=null;var o=wt;wt=1;var l=Nl;Nl|=4,Cl.current=null,function(e,t){if(ei=Ht,fr(e=dr())){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{var r=(n=(n=e.ownerDocument)&&n.defaultView||window).getSelection&&n.getSelection();if(r&&0!==r.rangeCount){n=r.anchorNode;var i=r.anchorOffset,a=r.focusNode;r=r.focusOffset;try{n.nodeType,a.nodeType}catch(_){n=null;break e}var o=0,l=-1,c=-1,u=0,h=0,d=e,f=null;t:for(;;){for(var p;d!==n||0!==i&&3!==d.nodeType||(l=o+i),d!==a||0!==r&&3!==d.nodeType||(c=o+r),3===d.nodeType&&(o+=d.nodeValue.length),null!==(p=d.firstChild);)f=d,d=p;for(;;){if(d===e)break t;if(f===n&&++u===i&&(l=o),f===a&&++h===r&&(c=o),null!==(p=d.nextSibling))break;f=(d=f).parentNode}d=p}n=-1===l||-1===c?null:{start:l,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(ti={focusedElem:e,selectionRange:n},Ht=!1,Zo=t;null!==Zo;)if(e=(t=Zo).child,0!==(1028&t.subtreeFlags)&&null!==e)e.return=t,Zo=e;else for(;null!==Zo;){t=Zo;try{var m=t.alternate;if(0!==(1024&t.flags))switch(t.tag){case 0:case 11:case 15:case 5:case 6:case 4:case 17:break;case 1:if(null!==m){var g=m.memoizedProps,v=m.memoizedState,y=t.stateNode,w=y.getSnapshotBeforeUpdate(t.elementType===t.type?g:gs(t.type,g),v);y.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var b=t.stateNode.containerInfo;1===b.nodeType?b.textContent="":9===b.nodeType&&b.documentElement&&b.removeChild(b.documentElement);break;default:throw Error(s(163))}}catch(_){Ic(t,t.return,_)}if(null!==(e=t.sibling)){e.return=t.return,Zo=e;break}Zo=t.return}m=nl,nl=!1}(e,n),vl(n,e),pr(ti),Ht=!!ei,ti=ei=null,e.current=n,wl(n,e,i),Ye(),Nl=l,wt=o,xl.transition=a}else e.current=n;if(Ql&&(Ql=!1,$l=e,Yl=i),a=e.pendingLanes,0===a&&(Gl=null),function(e){if(st&&"function"===typeof st.onCommitFiberRoot)try{st.onCommitFiberRoot(it,e,void 0,128===(128&e.current.flags))}catch(t){}}(n.stateNode),ic(e,Xe()),null!==t)for(r=e.onRecoverableError,n=0;n<t.length;n++)i=t[n],r(i.value,{componentStack:i.stack,digest:i.digest});if(Wl)throw Wl=!1,e=Kl,Kl=null,e;0!==(1&Yl)&&0!==e.tag&&Sc(),a=e.pendingLanes,0!==(1&a)?e===Jl?Xl++:(Xl=0,Jl=e):Xl=0,zi()}(e,t,n,r)}finally{xl.transition=i,wt=r}return null}function Sc(){if(null!==$l){var e=bt(Yl),t=xl.transition,n=wt;try{if(xl.transition=null,wt=16>e?16:e,null===$l)var r=!1;else{if(e=$l,$l=null,Yl=0,0!==(6&Nl))throw Error(s(331));var i=Nl;for(Nl|=4,Zo=e.current;null!==Zo;){var a=Zo,o=a.child;if(0!==(16&Zo.flags)){var l=a.deletions;if(null!==l){for(var c=0;c<l.length;c++){var u=l[c];for(Zo=u;null!==Zo;){var h=Zo;switch(h.tag){case 0:case 11:case 15:rl(8,h,a)}var d=h.child;if(null!==d)d.return=h,Zo=d;else for(;null!==Zo;){var f=(h=Zo).sibling,p=h.return;if(al(h),h===u){Zo=null;break}if(null!==f){f.return=p,Zo=f;break}Zo=p}}}var m=a.alternate;if(null!==m){var g=m.child;if(null!==g){m.child=null;do{var v=g.sibling;g.sibling=null,g=v}while(null!==g)}}Zo=a}}if(0!==(2064&a.subtreeFlags)&&null!==o)o.return=a,Zo=o;else e:for(;null!==Zo;){if(0!==(2048&(a=Zo).flags))switch(a.tag){case 0:case 11:case 15:rl(9,a,a.return)}var y=a.sibling;if(null!==y){y.return=a.return,Zo=y;break e}Zo=a.return}}var w=e.current;for(Zo=w;null!==Zo;){var b=(o=Zo).child;if(0!==(2064&o.subtreeFlags)&&null!==b)b.return=o,Zo=b;else e:for(o=w;null!==Zo;){if(0!==(2048&(l=Zo).flags))try{switch(l.tag){case 0:case 11:case 15:il(9,l)}}catch(E){Ic(l,l.return,E)}if(l===o){Zo=null;break e}var _=l.sibling;if(null!==_){_.return=l.return,Zo=_;break e}Zo=l.return}}if(Nl=i,zi(),st&&"function"===typeof st.onPostCommitFiberRoot)try{st.onPostCommitFiberRoot(it,e)}catch(E){}r=!0}return r}finally{wt=n,xl.transition=t}}return!1}function kc(e,t,n){e=Os(e,t=po(0,t=co(n,t),1),1),t=tc(),null!==e&&(vt(e,1,t),ic(e,t))}function Ic(e,t,n){if(3===e.tag)kc(e,e,n);else for(;null!==t;){if(3===t.tag){kc(t,e,n);break}if(1===t.tag){var r=t.stateNode;if("function"===typeof t.type.getDerivedStateFromError||"function"===typeof r.componentDidCatch&&(null===Gl||!Gl.has(r))){t=Os(t,e=mo(t,e=co(n,e),1),1),e=tc(),null!==t&&(vt(t,1,e),ic(t,e));break}}t=t.return}}function Tc(e,t,n){var r=e.pingCache;null!==r&&r.delete(t),t=tc(),e.pingedLanes|=e.suspendedLanes&n,Al===e&&(Rl&n)===n&&(4===Ll||3===Ll&&(130023424&Rl)===Rl&&500>Xe()-zl?fc(e,0):Ul|=n),ic(e,t)}function Cc(e,t){0===t&&(0===(1&e.mode)?t=1:(t=ut,0===(130023424&(ut<<=1))&&(ut=4194304)));var n=tc();null!==(e=Ns(e,t))&&(vt(e,t,n),ic(e,n))}function xc(e){var t=e.memoizedState,n=0;null!==t&&(n=t.retryLane),Cc(e,n)}function Nc(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,i=e.memoizedState;null!==i&&(n=i.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(s(314))}null!==r&&r.delete(t),Cc(e,n)}function Ac(e,t){return Ge(e,t)}function Pc(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Rc(e,t,n,r){return new Pc(e,t,n,r)}function Dc(e){return!(!(e=e.prototype)||!e.isReactComponent)}function Oc(e,t){var n=e.alternate;return null===n?((n=Rc(e.tag,t,e.key,e.mode)).elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=14680064&e.flags,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=null===t?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Lc(e,t,n,r,i,a){var o=2;if(r=e,"function"===typeof e)Dc(e)&&(o=1);else if("string"===typeof e)o=5;else e:switch(e){case S:return Mc(n.children,i,a,t);case k:o=8,i|=8;break;case I:return(e=Rc(12,n,t,2|i)).elementType=I,e.lanes=a,e;case N:return(e=Rc(13,n,t,i)).elementType=N,e.lanes=a,e;case A:return(e=Rc(19,n,t,i)).elementType=A,e.lanes=a,e;case D:return jc(n,i,a,t);default:if("object"===typeof e&&null!==e)switch(e.$$typeof){case T:o=10;break e;case C:o=9;break e;case x:o=11;break e;case P:o=14;break e;case R:o=16,r=null;break e}throw Error(s(130,null==e?e:typeof e,""))}return(t=Rc(o,n,t,i)).elementType=e,t.type=r,t.lanes=a,t}function Mc(e,t,n,r){return(e=Rc(7,e,r,t)).lanes=n,e}function jc(e,t,n,r){return(e=Rc(22,e,r,t)).elementType=D,e.lanes=n,e.stateNode={isHidden:!1},e}function Fc(e,t,n){return(e=Rc(6,e,null,t)).lanes=n,e}function Uc(e,t,n){return(t=Rc(4,null!==e.children?e.children:[],e.key,t)).lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Vc(e,t,n,r,i){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=gt(0),this.expirationTimes=gt(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=gt(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function Bc(e,t,n,r,i,s,a,o,l){return e=new Vc(e,t,n,o,l),1===t?(t=1,!0===s&&(t|=8)):t=0,s=Rc(3,null,null,t),e.current=s,s.stateNode=e,s.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ps(s),e}function zc(e){if(!e)return Ci;e:{if(ze(e=e._reactInternals)!==e||1!==e.tag)throw Error(s(170));var t=e;do{switch(t.tag){case 3:t=t.stateNode.context;break e;case 1:if(Ri(t.type)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break e}}t=t.return}while(null!==t);throw Error(s(171))}if(1===e.tag){var n=e.type;if(Ri(n))return Li(e,n,t)}return t}function qc(e,t,n,r,i,s,a,o,l){return(e=Bc(n,r,!0,e,0,s,0,o,l)).context=zc(null),n=e.current,(s=Ds(r=tc(),i=nc(n))).callback=void 0!==t&&null!==t?t:null,Os(n,s,i),e.current.lanes=i,vt(e,i,r),ic(e,r),e}function Hc(e,t,n,r){var i=t.current,s=tc(),a=nc(i);return n=zc(n),null===t.context?t.context=n:t.pendingContext=n,(t=Ds(s,a)).payload={element:e},null!==(r=void 0===r?null:r)&&(t.callback=r),null!==(e=Os(i,t,a))&&(rc(e,i,a,s),Ls(e,i,a)),a}function Wc(e){return(e=e.current).child?(e.child.tag,e.child.stateNode):null}function Kc(e,t){if(null!==(e=e.memoizedState)&&null!==e.dehydrated){var n=e.retryLane;e.retryLane=0!==n&&n<t?n:t}}function Gc(e,t){Kc(e,t),(e=e.alternate)&&Kc(e,t)}kl=function(e,t,n){if(null!==e)if(e.memoizedProps!==t.pendingProps||Ni.current)bo=!0;else{if(0===(e.lanes&n)&&0===(128&t.flags))return bo=!1,function(e,t,n){switch(t.tag){case 3:Ao(t),fs();break;case 5:sa(t);break;case 1:Ri(t.type)&&Mi(t);break;case 4:ra(t,t.stateNode.containerInfo);break;case 10:var r=t.type._context,i=t.memoizedProps.value;Ti(vs,r._currentValue),r._currentValue=i;break;case 13:if(null!==(r=t.memoizedState))return null!==r.dehydrated?(Ti(oa,1&oa.current),t.flags|=128,null):0!==(n&t.child.childLanes)?Fo(e,t,n):(Ti(oa,1&oa.current),null!==(e=Wo(e,t,n))?e.sibling:null);Ti(oa,1&oa.current);break;case 19:if(r=0!==(n&t.childLanes),0!==(128&e.flags)){if(r)return qo(e,t,n);t.flags|=128}if(null!==(i=t.memoizedState)&&(i.rendering=null,i.tail=null,i.lastEffect=null),Ti(oa,oa.current),r)break;return null;case 22:case 23:return t.lanes=0,Io(e,t,n)}return Wo(e,t,n)}(e,t,n);bo=0!==(131072&e.flags)}else bo=!1,is&&0!==(1048576&t.flags)&&Zi(t,Ki,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ho(e,t),e=t.pendingProps;var i=Pi(t,xi.current);ks(t,n),i=Sa(null,t,r,e,i,n);var a=ka();return t.flags|=1,"object"===typeof i&&null!==i&&"function"===typeof i.render&&void 0===i.$$typeof?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Ri(r)?(a=!0,Mi(t)):a=!1,t.memoizedState=null!==i.state&&void 0!==i.state?i.state:null,Ps(t),i.updater=Bs,t.stateNode=i,i._reactInternals=t,Ws(t,r,e,n),t=No(null,t,r,!0,a,n)):(t.tag=0,is&&a&&es(t),_o(null,t,i,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ho(e,t),e=t.pendingProps,r=(i=r._init)(r._payload),t.type=r,i=t.tag=function(e){if("function"===typeof e)return Dc(e)?1:0;if(void 0!==e&&null!==e){if((e=e.$$typeof)===x)return 11;if(e===P)return 14}return 2}(r),e=gs(r,e),i){case 0:t=Co(null,t,r,e,n);break e;case 1:t=xo(null,t,r,e,n);break e;case 11:t=Eo(null,t,r,e,n);break e;case 14:t=So(null,t,r,gs(r.type,e),n);break e}throw Error(s(306,r,""))}return t;case 0:return r=t.type,i=t.pendingProps,Co(e,t,r,i=t.elementType===r?i:gs(r,i),n);case 1:return r=t.type,i=t.pendingProps,xo(e,t,r,i=t.elementType===r?i:gs(r,i),n);case 3:e:{if(Ao(t),null===e)throw Error(s(387));r=t.pendingProps,i=(a=t.memoizedState).element,Rs(e,t),js(t,r,null,n);var o=t.memoizedState;if(r=o.element,a.isDehydrated){if(a={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=a,t.memoizedState=a,256&t.flags){t=Po(e,t,r,n,i=co(Error(s(423)),t));break e}if(r!==i){t=Po(e,t,r,n,i=co(Error(s(424)),t));break e}for(rs=ci(t.stateNode.containerInfo.firstChild),ns=t,is=!0,ss=null,n=Xs(t,null,r,n),t.child=n;n;)n.flags=-3&n.flags|4096,n=n.sibling}else{if(fs(),r===i){t=Wo(e,t,n);break e}_o(e,t,r,n)}t=t.child}return t;case 5:return sa(t),null===e&&cs(t),r=t.type,i=t.pendingProps,a=null!==e?e.memoizedProps:null,o=i.children,ni(r,i)?o=null:null!==a&&ni(r,a)&&(t.flags|=32),To(e,t),_o(e,t,o,n),t.child;case 6:return null===e&&cs(t),null;case 13:return Fo(e,t,n);case 4:return ra(t,t.stateNode.containerInfo),r=t.pendingProps,null===e?t.child=Ys(t,null,r,n):_o(e,t,r,n),t.child;case 11:return r=t.type,i=t.pendingProps,Eo(e,t,r,i=t.elementType===r?i:gs(r,i),n);case 7:return _o(e,t,t.pendingProps,n),t.child;case 8:case 12:return _o(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,i=t.pendingProps,a=t.memoizedProps,o=i.value,Ti(vs,r._currentValue),r._currentValue=o,null!==a)if(or(a.value,o)){if(a.children===i.children&&!Ni.current){t=Wo(e,t,n);break e}}else for(null!==(a=t.child)&&(a.return=t);null!==a;){var l=a.dependencies;if(null!==l){o=a.child;for(var c=l.firstContext;null!==c;){if(c.context===r){if(1===a.tag){(c=Ds(-1,n&-n)).tag=2;var u=a.updateQueue;if(null!==u){var h=(u=u.shared).pending;null===h?c.next=c:(c.next=h.next,h.next=c),u.pending=c}}a.lanes|=n,null!==(c=a.alternate)&&(c.lanes|=n),Ss(a.return,n,t),l.lanes|=n;break}c=c.next}}else if(10===a.tag)o=a.type===t.type?null:a.child;else if(18===a.tag){if(null===(o=a.return))throw Error(s(341));o.lanes|=n,null!==(l=o.alternate)&&(l.lanes|=n),Ss(o,n,t),o=a.sibling}else o=a.child;if(null!==o)o.return=a;else for(o=a;null!==o;){if(o===t){o=null;break}if(null!==(a=o.sibling)){a.return=o.return,o=a;break}o=o.return}a=o}_o(e,t,i.children,n),t=t.child}return t;case 9:return i=t.type,r=t.pendingProps.children,ks(t,n),r=r(i=Is(i)),t.flags|=1,_o(e,t,r,n),t.child;case 14:return i=gs(r=t.type,t.pendingProps),So(e,t,r,i=gs(r.type,i),n);case 15:return ko(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:gs(r,i),Ho(e,t),t.tag=1,Ri(r)?(e=!0,Mi(t)):e=!1,ks(t,n),qs(t,r,i),Ws(t,r,i,n),No(null,t,r,!0,e,n);case 19:return qo(e,t,n);case 22:return Io(e,t,n)}throw Error(s(156,t.tag))};var Qc="function"===typeof reportError?reportError:function(e){console.error(e)};function $c(e){this._internalRoot=e}function Yc(e){this._internalRoot=e}function Xc(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType)}function Jc(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType&&(8!==e.nodeType||" react-mount-point-unstable "!==e.nodeValue))}function Zc(){}function eu(e,t,n,r,i){var s=n._reactRootContainer;if(s){var a=s;if("function"===typeof i){var o=i;i=function(){var e=Wc(a);o.call(e)}}Hc(t,a,e,i)}else a=function(e,t,n,r,i){if(i){if("function"===typeof r){var s=r;r=function(){var e=Wc(a);s.call(e)}}var a=qc(t,r,e,0,null,!1,0,"",Zc);return e._reactRootContainer=a,e[pi]=a.current,zr(8===e.nodeType?e.parentNode:e),hc(),a}for(;i=e.lastChild;)e.removeChild(i);if("function"===typeof r){var o=r;r=function(){var e=Wc(l);o.call(e)}}var l=Bc(e,0,!1,null,0,!1,0,"",Zc);return e._reactRootContainer=l,e[pi]=l.current,zr(8===e.nodeType?e.parentNode:e),hc((function(){Hc(t,l,n,r)})),l}(n,t,e,i,r);return Wc(a)}Yc.prototype.render=$c.prototype.render=function(e){var t=this._internalRoot;if(null===t)throw Error(s(409));Hc(e,t,null,null)},Yc.prototype.unmount=$c.prototype.unmount=function(){var e=this._internalRoot;if(null!==e){this._internalRoot=null;var t=e.containerInfo;hc((function(){Hc(null,e,null,null)})),t[pi]=null}},Yc.prototype.unstable_scheduleHydration=function(e){if(e){var t=kt();e={blockedOn:null,target:e,priority:t};for(var n=0;n<Dt.length&&0!==t&&t<Dt[n].priority;n++);Dt.splice(n,0,e),0===n&&jt(e)}},_t=function(e){switch(e.tag){case 3:var t=e.stateNode;if(t.current.memoizedState.isDehydrated){var n=ht(t.pendingLanes);0!==n&&(yt(t,1|n),ic(t,Xe()),0===(6&Nl)&&(ql=Xe()+500,zi()))}break;case 13:hc((function(){var t=Ns(e,1);if(null!==t){var n=tc();rc(t,e,1,n)}})),Gc(e,1)}},Et=function(e){if(13===e.tag){var t=Ns(e,134217728);if(null!==t)rc(t,e,134217728,tc());Gc(e,134217728)}},St=function(e){if(13===e.tag){var t=nc(e),n=Ns(e,t);if(null!==n)rc(n,e,t,tc());Gc(e,t)}},kt=function(){return wt},It=function(e,t){var n=wt;try{return wt=e,t()}finally{wt=n}},Ee=function(e,t,n){switch(t){case"input":if(J(e,n),t=n.name,"radio"===n.type&&null!=t){for(n=e;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<n.length;t++){var r=n[t];if(r!==e&&r.form===e.form){var i=_i(r);if(!i)throw Error(s(90));G(r),J(r,i)}}}break;case"textarea":se(e,n);break;case"select":null!=(t=n.value)&&ne(e,!!n.multiple,t,!1)}},xe=uc,Ne=hc;var tu={usingClientEntryPoint:!1,Events:[wi,bi,_i,Te,Ce,uc]},nu={findFiberByHostInstance:yi,bundleType:0,version:"18.2.0",rendererPackageName:"react-dom"},ru={bundleType:nu.bundleType,version:nu.version,rendererPackageName:nu.rendererPackageName,rendererConfig:nu.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:b.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return null===(e=We(e))?null:e.stateNode},findFiberByHostInstance:nu.findFiberByHostInstance||function(){return null},findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.2.0-next-9e3b772b8-20220608"};if("undefined"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__){var iu=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!iu.isDisabled&&iu.supportsFiber)try{it=iu.inject(ru),st=iu}catch(ue){}}t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=tu,t.createPortal=function(e,t){var n=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!Xc(t))throw Error(s(200));return function(e,t,n){var r=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:E,key:null==r?null:""+r,children:e,containerInfo:t,implementation:n}}(e,t,null,n)},t.createRoot=function(e,t){if(!Xc(e))throw Error(s(299));var n=!1,r="",i=Qc;return null!==t&&void 0!==t&&(!0===t.unstable_strictMode&&(n=!0),void 0!==t.identifierPrefix&&(r=t.identifierPrefix),void 0!==t.onRecoverableError&&(i=t.onRecoverableError)),t=Bc(e,1,!1,null,0,n,0,r,i),e[pi]=t.current,zr(8===e.nodeType?e.parentNode:e),new $c(t)},t.findDOMNode=function(e){if(null==e)return null;if(1===e.nodeType)return e;var t=e._reactInternals;if(void 0===t){if("function"===typeof e.render)throw Error(s(188));throw e=Object.keys(e).join(","),Error(s(268,e))}return e=null===(e=We(t))?null:e.stateNode},t.flushSync=function(e){return hc(e)},t.hydrate=function(e,t,n){if(!Jc(t))throw Error(s(200));return eu(null,e,t,!0,n)},t.hydrateRoot=function(e,t,n){if(!Xc(e))throw Error(s(405));var r=null!=n&&n.hydratedSources||null,i=!1,a="",o=Qc;if(null!==n&&void 0!==n&&(!0===n.unstable_strictMode&&(i=!0),void 0!==n.identifierPrefix&&(a=n.identifierPrefix),void 0!==n.onRecoverableError&&(o=n.onRecoverableError)),t=qc(t,null,e,1,null!=n?n:null,i,0,a,o),e[pi]=t.current,zr(e),r)for(e=0;e<r.length;e++)i=(i=(n=r[e])._getVersion)(n._source),null==t.mutableSourceEagerHydrationData?t.mutableSourceEagerHydrationData=[n,i]:t.mutableSourceEagerHydrationData.push(n,i);return new Yc(t)},t.render=function(e,t,n){if(!Jc(t))throw Error(s(200));return eu(null,e,t,!1,n)},t.unmountComponentAtNode=function(e){if(!Jc(e))throw Error(s(40));return!!e._reactRootContainer&&(hc((function(){eu(null,null,e,!1,(function(){e._reactRootContainer=null,e[pi]=null}))})),!0)},t.unstable_batchedUpdates=uc,t.unstable_renderSubtreeIntoContainer=function(e,t,n,r){if(!Jc(n))throw Error(s(200));if(null==e||void 0===e._reactInternals)throw Error(s(38));return eu(e,t,n,!1,r)},t.version="18.2.0-next-9e3b772b8-20220608"},250:(e,t,n)=>{var r=n(164);t.createRoot=r.createRoot,t.hydrateRoot=r.hydrateRoot},164:(e,t,n)=>{!function e(){if("undefined"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}(),e.exports=n(463)},374:(e,t,n)=>{var r=n(791),i=Symbol.for("react.element"),s=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,o=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function c(e,t,n){var r,s={},c=null,u=null;for(r in void 0!==n&&(c=""+n),void 0!==t.key&&(c=""+t.key),void 0!==t.ref&&(u=t.ref),t)a.call(t,r)&&!l.hasOwnProperty(r)&&(s[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps)void 0===s[r]&&(s[r]=t[r]);return{$$typeof:i,type:e,key:c,ref:u,props:s,_owner:o.current}}t.jsx=c,t.jsxs=c},117:(e,t)=>{var n=Symbol.for("react.element"),r=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),o=Symbol.for("react.provider"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),h=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),f=Symbol.iterator;var p={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},m=Object.assign,g={};function v(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||p}function y(){}function w(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||p}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if("object"!==typeof e&&"function"!==typeof e&&null!=e)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},y.prototype=v.prototype;var b=w.prototype=new y;b.constructor=w,m(b,v.prototype),b.isPureReactComponent=!0;var _=Array.isArray,E=Object.prototype.hasOwnProperty,S={current:null},k={key:!0,ref:!0,__self:!0,__source:!0};function I(e,t,r){var i,s={},a=null,o=null;if(null!=t)for(i in void 0!==t.ref&&(o=t.ref),void 0!==t.key&&(a=""+t.key),t)E.call(t,i)&&!k.hasOwnProperty(i)&&(s[i]=t[i]);var l=arguments.length-2;if(1===l)s.children=r;else if(1<l){for(var c=Array(l),u=0;u<l;u++)c[u]=arguments[u+2];s.children=c}if(e&&e.defaultProps)for(i in l=e.defaultProps)void 0===s[i]&&(s[i]=l[i]);return{$$typeof:n,type:e,key:a,ref:o,props:s,_owner:S.current}}function T(e){return"object"===typeof e&&null!==e&&e.$$typeof===n}var C=/\/+/g;function x(e,t){return"object"===typeof e&&null!==e&&null!=e.key?function(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,(function(e){return t[e]}))}(""+e.key):t.toString(36)}function N(e,t,i,s,a){var o=typeof e;"undefined"!==o&&"boolean"!==o||(e=null);var l=!1;if(null===e)l=!0;else switch(o){case"string":case"number":l=!0;break;case"object":switch(e.$$typeof){case n:case r:l=!0}}if(l)return a=a(l=e),e=""===s?"."+x(l,0):s,_(a)?(i="",null!=e&&(i=e.replace(C,"$&/")+"/"),N(a,t,i,"",(function(e){return e}))):null!=a&&(T(a)&&(a=function(e,t){return{$$typeof:n,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}(a,i+(!a.key||l&&l.key===a.key?"":(""+a.key).replace(C,"$&/")+"/")+e)),t.push(a)),1;if(l=0,s=""===s?".":s+":",_(e))for(var c=0;c<e.length;c++){var u=s+x(o=e[c],c);l+=N(o,t,i,u,a)}else if(u=function(e){return null===e||"object"!==typeof e?null:"function"===typeof(e=f&&e[f]||e["@@iterator"])?e:null}(e),"function"===typeof u)for(e=u.call(e),c=0;!(o=e.next()).done;)l+=N(o=o.value,t,i,u=s+x(o,c++),a);else if("object"===o)throw t=String(e),Error("Objects are not valid as a React child (found: "+("[object Object]"===t?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return l}function A(e,t,n){if(null==e)return e;var r=[],i=0;return N(e,r,"","",(function(e){return t.call(n,e,i++)})),r}function P(e){if(-1===e._status){var t=e._result;(t=t()).then((function(t){0!==e._status&&-1!==e._status||(e._status=1,e._result=t)}),(function(t){0!==e._status&&-1!==e._status||(e._status=2,e._result=t)})),-1===e._status&&(e._status=0,e._result=t)}if(1===e._status)return e._result.default;throw e._result}var R={current:null},D={transition:null},O={ReactCurrentDispatcher:R,ReactCurrentBatchConfig:D,ReactCurrentOwner:S};t.Children={map:A,forEach:function(e,t,n){A(e,(function(){t.apply(this,arguments)}),n)},count:function(e){var t=0;return A(e,(function(){t++})),t},toArray:function(e){return A(e,(function(e){return e}))||[]},only:function(e){if(!T(e))throw Error("React.Children.only expected to receive a single React element child.");return e}},t.Component=v,t.Fragment=i,t.Profiler=a,t.PureComponent=w,t.StrictMode=s,t.Suspense=u,t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=O,t.cloneElement=function(e,t,r){if(null===e||void 0===e)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var i=m({},e.props),s=e.key,a=e.ref,o=e._owner;if(null!=t){if(void 0!==t.ref&&(a=t.ref,o=S.current),void 0!==t.key&&(s=""+t.key),e.type&&e.type.defaultProps)var l=e.type.defaultProps;for(c in t)E.call(t,c)&&!k.hasOwnProperty(c)&&(i[c]=void 0===t[c]&&void 0!==l?l[c]:t[c])}var c=arguments.length-2;if(1===c)i.children=r;else if(1<c){l=Array(c);for(var u=0;u<c;u++)l[u]=arguments[u+2];i.children=l}return{$$typeof:n,type:e.type,key:s,ref:a,props:i,_owner:o}},t.createContext=function(e){return(e={$$typeof:l,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null}).Provider={$$typeof:o,_context:e},e.Consumer=e},t.createElement=I,t.createFactory=function(e){var t=I.bind(null,e);return t.type=e,t},t.createRef=function(){return{current:null}},t.forwardRef=function(e){return{$$typeof:c,render:e}},t.isValidElement=T,t.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:P}},t.memo=function(e,t){return{$$typeof:h,type:e,compare:void 0===t?null:t}},t.startTransition=function(e){var t=D.transition;D.transition={};try{e()}finally{D.transition=t}},t.unstable_act=function(){throw Error("act(...) is not supported in production builds of React.")},t.useCallback=function(e,t){return R.current.useCallback(e,t)},t.useContext=function(e){return R.current.useContext(e)},t.useDebugValue=function(){},t.useDeferredValue=function(e){return R.current.useDeferredValue(e)},t.useEffect=function(e,t){return R.current.useEffect(e,t)},t.useId=function(){return R.current.useId()},t.useImperativeHandle=function(e,t,n){return R.current.useImperativeHandle(e,t,n)},t.useInsertionEffect=function(e,t){return R.current.useInsertionEffect(e,t)},t.useLayoutEffect=function(e,t){return R.current.useLayoutEffect(e,t)},t.useMemo=function(e,t){return R.current.useMemo(e,t)},t.useReducer=function(e,t,n){return R.current.useReducer(e,t,n)},t.useRef=function(e){return R.current.useRef(e)},t.useState=function(e){return R.current.useState(e)},t.useSyncExternalStore=function(e,t,n){return R.current.useSyncExternalStore(e,t,n)},t.useTransition=function(){return R.current.useTransition()},t.version="18.2.0"},791:(e,t,n)=>{e.exports=n(117)},184:(e,t,n)=>{e.exports=n(374)},813:(e,t)=>{function n(e,t){var n=e.length;e.push(t);e:for(;0<n;){var r=n-1>>>1,i=e[r];if(!(0<s(i,t)))break e;e[r]=t,e[n]=i,n=r}}function r(e){return 0===e.length?null:e[0]}function i(e){if(0===e.length)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;e:for(var r=0,i=e.length,a=i>>>1;r<a;){var o=2*(r+1)-1,l=e[o],c=o+1,u=e[c];if(0>s(l,n))c<i&&0>s(u,l)?(e[r]=u,e[c]=n,r=c):(e[r]=l,e[o]=n,r=o);else{if(!(c<i&&0>s(u,n)))break e;e[r]=u,e[c]=n,r=c}}}return t}function s(e,t){var n=e.sortIndex-t.sortIndex;return 0!==n?n:e.id-t.id}if("object"===typeof performance&&"function"===typeof performance.now){var a=performance;t.unstable_now=function(){return a.now()}}else{var o=Date,l=o.now();t.unstable_now=function(){return o.now()-l}}var c=[],u=[],h=1,d=null,f=3,p=!1,m=!1,g=!1,v="function"===typeof setTimeout?setTimeout:null,y="function"===typeof clearTimeout?clearTimeout:null,w="undefined"!==typeof setImmediate?setImmediate:null;function b(e){for(var t=r(u);null!==t;){if(null===t.callback)i(u);else{if(!(t.startTime<=e))break;i(u),t.sortIndex=t.expirationTime,n(c,t)}t=r(u)}}function _(e){if(g=!1,b(e),!m)if(null!==r(c))m=!0,D(E);else{var t=r(u);null!==t&&O(_,t.startTime-e)}}function E(e,n){m=!1,g&&(g=!1,y(T),T=-1),p=!0;var s=f;try{for(b(n),d=r(c);null!==d&&(!(d.expirationTime>n)||e&&!N());){var a=d.callback;if("function"===typeof a){d.callback=null,f=d.priorityLevel;var o=a(d.expirationTime<=n);n=t.unstable_now(),"function"===typeof o?d.callback=o:d===r(c)&&i(c),b(n)}else i(c);d=r(c)}if(null!==d)var l=!0;else{var h=r(u);null!==h&&O(_,h.startTime-n),l=!1}return l}finally{d=null,f=s,p=!1}}"undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var S,k=!1,I=null,T=-1,C=5,x=-1;function N(){return!(t.unstable_now()-x<C)}function A(){if(null!==I){var e=t.unstable_now();x=e;var n=!0;try{n=I(!0,e)}finally{n?S():(k=!1,I=null)}}else k=!1}if("function"===typeof w)S=function(){w(A)};else if("undefined"!==typeof MessageChannel){var P=new MessageChannel,R=P.port2;P.port1.onmessage=A,S=function(){R.postMessage(null)}}else S=function(){v(A,0)};function D(e){I=e,k||(k=!0,S())}function O(e,n){T=v((function(){e(t.unstable_now())}),n)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(e){e.callback=null},t.unstable_continueExecution=function(){m||p||(m=!0,D(E))},t.unstable_forceFrameRate=function(e){0>e||125<e?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):C=0<e?Math.floor(1e3/e):5},t.unstable_getCurrentPriorityLevel=function(){return f},t.unstable_getFirstCallbackNode=function(){return r(c)},t.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},t.unstable_pauseExecution=function(){},t.unstable_requestPaint=function(){},t.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},t.unstable_scheduleCallback=function(e,i,s){var a=t.unstable_now();switch("object"===typeof s&&null!==s?s="number"===typeof(s=s.delay)&&0<s?a+s:a:s=a,e){case 1:var o=-1;break;case 2:o=250;break;case 5:o=1073741823;break;case 4:o=1e4;break;default:o=5e3}return e={id:h++,callback:i,priorityLevel:e,startTime:s,expirationTime:o=s+o,sortIndex:-1},s>a?(e.sortIndex=s,n(u,e),null===r(c)&&e===r(u)&&(g?(y(T),T=-1):g=!0,O(_,s-a))):(e.sortIndex=o,n(c,e),m||p||(m=!0,D(E))),e},t.unstable_shouldYield=N,t.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}},296:(e,t,n)=>{e.exports=n(813)}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var s=t[r]={exports:{}};return e[r](s,s.exports,n),s.exports}n.m=e,(()=>{var e,t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;n.t=function(r,i){if(1&i&&(r=this(r)),8&i)return r;if("object"===typeof r&&r){if(4&i&&r.__esModule)return r;if(16&i&&"function"===typeof r.then)return r}var s=Object.create(null);n.r(s);var a={};e=e||[null,t({}),t([]),t(t)];for(var o=2&i&&r;"object"==typeof o&&!~e.indexOf(o);o=t(o))Object.getOwnPropertyNames(o).forEach((e=>a[e]=()=>r[e]));return a.default=()=>r,n.d(s,a),s}})(),n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.f={},n.e=e=>Promise.all(Object.keys(n.f).reduce(((t,r)=>(n.f[r](e,t),t)),[])),n.u=e=>"static/js/"+e+".7e4c938d.chunk.js",n.miniCssF=e=>{},n.g=function(){if("object"===typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"===typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{var e={},t="friendlybetting:";n.l=(r,i,s,a)=>{if(e[r])e[r].push(i);else{var o,l;if(void 0!==s)for(var c=document.getElementsByTagName("script"),u=0;u<c.length;u++){var h=c[u];if(h.getAttribute("src")==r||h.getAttribute("data-webpack")==t+s){o=h;break}}o||(l=!0,(o=document.createElement("script")).charset="utf-8",o.timeout=120,n.nc&&o.setAttribute("nonce",n.nc),o.setAttribute("data-webpack",t+s),o.src=r),e[r]=[i];var d=(t,n)=>{o.onerror=o.onload=null,clearTimeout(f);var i=e[r];if(delete e[r],o.parentNode&&o.parentNode.removeChild(o),i&&i.forEach((e=>e(n))),t)return t(n)},f=setTimeout(d.bind(null,void 0,{type:"timeout",target:o}),12e4);o.onerror=d.bind(null,o.onerror),o.onload=d.bind(null,o.onload),l&&document.head.appendChild(o)}}})(),n.r=e=>{"undefined"!==typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.p="/Friendly-Betting/",(()=>{var e={179:0};n.f.j=(t,r)=>{var i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{var s=new Promise(((n,r)=>i=e[t]=[n,r]));r.push(i[2]=s);var a=n.p+n.u(t),o=new Error;n.l(a,(r=>{if(n.o(e,t)&&(0!==(i=e[t])&&(e[t]=void 0),i)){var s=r&&("load"===r.type?"missing":r.type),a=r&&r.target&&r.target.src;o.message="Loading chunk "+t+" failed.\n("+s+": "+a+")",o.name="ChunkLoadError",o.type=s,o.request=a,i[1](o)}}),"chunk-"+t,t)}};var t=(t,r)=>{var i,s,a=r[0],o=r[1],l=r[2],c=0;if(a.some((t=>0!==e[t]))){for(i in o)n.o(o,i)&&(n.m[i]=o[i]);if(l)l(n)}for(t&&t(r);c<a.length;c++)s=a[c],n.o(e,s)&&e[s]&&e[s][0](),e[s]=0},r=self.webpackChunkfriendlybetting=self.webpackChunkfriendlybetting||[];r.forEach(t.bind(null,0)),r.push=t.bind(null,r.push.bind(r))})(),(()=>{var e=n(791),t=n.t(e,2),r=n(250);const i=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):55296===(64512&i)&&r+1<e.length&&56320===(64512&e.charCodeAt(r+1))?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++r)),t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128)}return t},s={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"===typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let i=0;i<e.length;i+=3){const t=e[i],s=i+1<e.length,a=s?e[i+1]:0,o=i+2<e.length,l=o?e[i+2]:0,c=t>>2,u=(3&t)<<4|a>>4;let h=(15&a)<<2|l>>6,d=63&l;o||(d=64,s||(h=64)),r.push(n[c],n[u],n[h],n[d])}return r.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(i(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){const i=e[n++];if(i<128)t[r++]=String.fromCharCode(i);else if(i>191&&i<224){const s=e[n++];t[r++]=String.fromCharCode((31&i)<<6|63&s)}else if(i>239&&i<365){const s=((7&i)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))}else{const s=e[n++],a=e[n++];t[r++]=String.fromCharCode((15&i)<<12|(63&s)<<6|63&a)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let i=0;i<e.length;){const t=n[e.charAt(i++)],s=i<e.length?n[e.charAt(i)]:0;++i;const o=i<e.length?n[e.charAt(i)]:64;++i;const l=i<e.length?n[e.charAt(i)]:64;if(++i,null==t||null==s||null==o||null==l)throw new a;const c=t<<2|s>>4;if(r.push(c),64!==o){const e=s<<4&240|o>>2;if(r.push(e),64!==l){const e=o<<6&192|l;r.push(e)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class a extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const o=function(e){return function(e){const t=i(e);return s.encodeByteArray(t,!0)}(e).replace(/\./g,"")},l=function(e){try{return s.decodeString(e,!0)}catch(t){console.error("base64Decode failed: ",t)}return null};const c=()=>function(){if("undefined"!==typeof self)return self;if("undefined"!==typeof window)return window;if("undefined"!==typeof n.g)return n.g;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,u=()=>{try{return c()||(()=>{if("undefined"===typeof process)return;const e={NODE_ENV:"production",PUBLIC_URL:"/Friendly-Betting",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0}.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if("undefined"===typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(n){return}const t=e&&l(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info("Unable to get __FIREBASE_DEFAULTS__ due to: ".concat(e))}},h=e=>{var t,n;return null===(n=null===(t=u())||void 0===t?void 0:t.emulatorHosts)||void 0===n?void 0:n[e]},d=()=>{var e;return null===(e=u())||void 0===e?void 0:e.config},f=e=>{var t;return null===(t=u())||void 0===t?void 0:t["_".concat(e)]};class p{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,n)=>{t?this.reject(t):this.resolve(n),"function"===typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,n))}}}function m(){return"undefined"!==typeof navigator&&"string"===typeof navigator.userAgent?navigator.userAgent:""}function g(){const e="object"===typeof chrome?chrome.runtime:"object"===typeof browser?browser.runtime:void 0;return"object"===typeof e&&void 0!==e.id}function v(){try{return"object"===typeof indexedDB}catch(e){return!1}}function y(){return new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{var e;t((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(n){t(n)}}))}class w extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,w.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,b.prototype.create)}}class b{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e){const t=(arguments.length<=1?void 0:arguments[1])||{},n="".concat(this.service,"/").concat(e),r=this.errors[e],i=r?function(e,t){return e.replace(_,((e,n)=>{const r=t[n];return null!=r?String(r):"<".concat(n,"?>")}))}(r,t):"Error",s="".concat(this.serviceName,": ").concat(i," (").concat(n,").");return new w(n,s,t)}}const _=/\{\$([^}]+)}/g;function E(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const i of n){if(!r.includes(i))return!1;const n=e[i],s=t[i];if(S(n)&&S(s)){if(!E(n,s))return!1}else if(n!==s)return!1}for(const i of r)if(!n.includes(i))return!1;return!0}function S(e){return null!==e&&"object"===typeof e}function k(e){const t=[];for(const[n,r]of Object.entries(e))Array.isArray(r)?r.forEach((e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))})):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""}function I(e){const t={};return e.replace(/^\?/,"").split("&").forEach((e=>{if(e){const[n,r]=e.split("=");t[decodeURIComponent(n)]=decodeURIComponent(r)}})),t}function T(e){const t=e.indexOf("?");if(!t)return"";const n=e.indexOf("#",t);return e.substring(t,n>0?n:void 0)}class C{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then((()=>{e(this)})).catch((e=>{this.error(e)}))}next(e){this.forEachObserver((t=>{t.next(e)}))}error(e){this.forEachObserver((t=>{t.error(e)})),this.close(e)}complete(){this.forEachObserver((e=>{e.complete()})),this.close()}subscribe(e,t,n){let r;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");r=function(e,t){if("object"!==typeof e||null===e)return!1;for(const n of t)if(n in e&&"function"===typeof e[n])return!0;return!1}(e,["next","error","complete"])?e:{next:e,error:t,complete:n},void 0===r.next&&(r.next=x),void 0===r.error&&(r.error=x),void 0===r.complete&&(r.complete=x);const i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then((()=>{try{this.finalError?r.error(this.finalError):r.complete()}catch(e){}})),this.observers.push(r),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t<this.observers.length;t++)this.sendOne(t,e)}sendOne(e,t){this.task.then((()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(n){"undefined"!==typeof console&&console.error&&console.error(n)}}))}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then((()=>{this.observers=void 0,this.onNoObservers=void 0})))}}function x(){}const N=1e3,A=2,P=144e5,R=.5;function D(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:A;const n=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:N)*Math.pow(t,e),r=Math.round(R*n*(Math.random()-.5)*2);return Math.min(P,n+r)}function O(e){return e&&e._delegate?e._delegate:e}class L{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const M="[DEFAULT]";class j{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){const t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const e=new p;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{const n=this.getOrInitializeService({instanceIdentifier:t});n&&e.resolve(n)}catch(n){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t;const n=this.normalizeInstanceIdentifier(null===e||void 0===e?void 0:e.identifier),r=null!==(t=null===e||void 0===e?void 0:e.optional)&&void 0!==t&&t;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(r)return null;throw Error("Service ".concat(this.name," is not available"))}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(i){if(r)return null;throw i}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error("Mismatching Component ".concat(e.name," for Provider ").concat(this.name,"."));if(this.component)throw Error("Component for ".concat(this.name," has already been provided"));if(this.component=e,this.shouldAutoInitialize()){if(function(e){return"EAGER"===e.instantiationMode}(e))try{this.getOrInitializeService({instanceIdentifier:M})}catch(t){}for(const[e,n]of this.instancesDeferred.entries()){const r=this.normalizeInstanceIdentifier(e);try{const e=this.getOrInitializeService({instanceIdentifier:r});n.resolve(e)}catch(t){}}}}clearInstance(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:M;this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter((e=>"INTERNAL"in e)).map((e=>e.INTERNAL.delete())),...e.filter((e=>"_delete"in e)).map((e=>e._delete()))])}isComponentSet(){return null!=this.component}isInitialized(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:M;return this.instances.has(e)}getOptions(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:M;return this.instancesOptions.get(e)||{}}initialize(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error("".concat(this.name,"(").concat(n,") has already been initialized"));if(!this.isComponentSet())throw Error("Component ".concat(this.name," has not been registered yet"));const r=this.getOrInitializeService({instanceIdentifier:n,options:t});for(const[i,s]of this.instancesDeferred.entries()){n===this.normalizeInstanceIdentifier(i)&&s.resolve(r)}return r}onInit(e,t){var n;const r=this.normalizeInstanceIdentifier(t),i=null!==(n=this.onInitCallbacks.get(r))&&void 0!==n?n:new Set;i.add(e),this.onInitCallbacks.set(r,i);const s=this.instances.get(r);return s&&e(s,r),()=>{i.delete(e)}}invokeOnInitCallbacks(e,t){const n=this.onInitCallbacks.get(t);if(n)for(const i of n)try{i(e,t)}catch(r){}}getOrInitializeService(e){let{instanceIdentifier:t,options:n={}}=e,r=this.instances.get(t);if(!r&&this.component&&(r=this.component.instanceFactory(this.container,{instanceIdentifier:(i=t,i===M?void 0:i),options:n}),this.instances.set(t,r),this.instancesOptions.set(t,n),this.invokeOnInitCallbacks(r,t),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,t,r)}catch(s){}var i;return r||null}normalizeInstanceIdentifier(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:M;return this.component?this.component.multipleInstances?e:M:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class F{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error("Component ".concat(e.name," has already been registered with ").concat(this.name));t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const t=new j(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const U=[];var V;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(V||(V={}));const B={debug:V.DEBUG,verbose:V.VERBOSE,info:V.INFO,warn:V.WARN,error:V.ERROR,silent:V.SILENT},z=V.INFO,q={[V.DEBUG]:"log",[V.VERBOSE]:"log",[V.INFO]:"info",[V.WARN]:"warn",[V.ERROR]:"error"},H=function(e,t){if(t<e.logLevel)return;const n=(new Date).toISOString(),r=q[t];if(!r)throw new Error("Attempted to log a message with an invalid logType (value: ".concat(t,")"));for(var i=arguments.length,s=new Array(i>2?i-2:0),a=2;a<i;a++)s[a-2]=arguments[a];console[r]("[".concat(n,"] ").concat(e.name,":"),...s)};class W{constructor(e){this.name=e,this._logLevel=z,this._logHandler=H,this._userLogHandler=null,U.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in V))throw new TypeError('Invalid value "'.concat(e,'" assigned to `logLevel`'));this._logLevel=e}setLogLevel(e){this._logLevel="string"===typeof e?B[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!==typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this._userLogHandler&&this._userLogHandler(this,V.DEBUG,...t),this._logHandler(this,V.DEBUG,...t)}log(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this._userLogHandler&&this._userLogHandler(this,V.VERBOSE,...t),this._logHandler(this,V.VERBOSE,...t)}info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this._userLogHandler&&this._userLogHandler(this,V.INFO,...t),this._logHandler(this,V.INFO,...t)}warn(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this._userLogHandler&&this._userLogHandler(this,V.WARN,...t),this._logHandler(this,V.WARN,...t)}error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this._userLogHandler&&this._userLogHandler(this,V.ERROR,...t),this._logHandler(this,V.ERROR,...t)}}const K=(e,t)=>t.some((t=>e instanceof t));let G,Q;const $=new WeakMap,Y=new WeakMap,X=new WeakMap,J=new WeakMap,Z=new WeakMap;let ee={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return Y.get(e);if("objectStoreNames"===t)return e.objectStoreNames||X.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return re(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function te(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(Q||(Q=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return e.apply(ie(this),n),re($.get(this))}:function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return re(e.apply(ie(this),n))}:function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];const s=e.call(ie(this),t,...r);return X.set(s,t.sort?t.sort():[t]),re(s)}}function ne(e){return"function"===typeof e?te(e):(e instanceof IDBTransaction&&function(e){if(Y.has(e))return;const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",s),e.removeEventListener("abort",s)},i=()=>{t(),r()},s=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",i),e.addEventListener("error",s),e.addEventListener("abort",s)}));Y.set(e,t)}(e),K(e,G||(G=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,ee):e)}function re(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{t(re(e.result)),r()},s=()=>{n(e.error),r()};e.addEventListener("success",i),e.addEventListener("error",s)}));return t.then((t=>{t instanceof IDBCursor&&$.set(t,e)})).catch((()=>{})),Z.set(t,e),t}(e);if(J.has(e))return J.get(e);const t=ne(e);return t!==e&&(J.set(e,t),Z.set(t,e)),t}const ie=e=>Z.get(e);const se=["get","getKey","getAll","getAllKeys","count"],ae=["put","add","delete","clear"],oe=new Map;function le(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!==typeof t)return;if(oe.get(t))return oe.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=ae.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!se.includes(n))return;const s=async function(e){const t=this.transaction(e,i?"readwrite":"readonly");let s=t.store;for(var a=arguments.length,o=new Array(a>1?a-1:0),l=1;l<a;l++)o[l-1]=arguments[l];return r&&(s=s.index(o.shift())),(await Promise.all([s[n](...o),i&&t.done]))[0]};return oe.set(t,s),s}ee=(e=>({...e,get:(t,n,r)=>le(t,n)||e.get(t,n,r),has:(t,n)=>!!le(t,n)||e.has(t,n)}))(ee);class ce{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map((e=>{if(function(e){const t=e.getComponent();return"VERSION"===(null===t||void 0===t?void 0:t.type)}(e)){const t=e.getImmediate();return"".concat(t.library,"/").concat(t.version)}return null})).filter((e=>e)).join(" ")}}const ue="@firebase/app",he="0.9.23",de=new W("@firebase/app"),fe="[DEFAULT]",pe={[ue]:"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","fire-js":"fire-js",firebase:"fire-js-all"},me=new Map,ge=new Map;function ve(e,t){try{e.container.addComponent(t)}catch(n){de.debug("Component ".concat(t.name," failed to register with FirebaseApp ").concat(e.name),n)}}function ye(e){const t=e.name;if(ge.has(t))return de.debug("There were multiple attempts to register component ".concat(t,".")),!1;ge.set(t,e);for(const n of me.values())ve(n,e);return!0}function we(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}const be=new b("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}."});class _e{constructor(e,t,n){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new L("app",(()=>this),"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw be.create("app-deleted",{appName:this._name})}}const Ee="10.6.0";function Se(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e;if("object"!==typeof t){t={name:t}}const r=Object.assign({name:fe,automaticDataCollectionEnabled:!1},t),i=r.name;if("string"!==typeof i||!i)throw be.create("bad-app-name",{appName:String(i)});if(n||(n=d()),!n)throw be.create("no-options");const s=me.get(i);if(s){if(E(n,s.options)&&E(r,s.config))return s;throw be.create("duplicate-app",{appName:i})}const a=new F(i);for(const l of ge.values())a.addComponent(l);const o=new _e(n,r,a);return me.set(i,o),o}function ke(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:fe;const t=me.get(e);if(!t&&e===fe&&d())return Se();if(!t)throw be.create("no-app",{appName:e});return t}function Ie(e,t,n){var r;let i=null!==(r=pe[e])&&void 0!==r?r:e;n&&(i+="-".concat(n));const s=i.match(/\s|\//),a=t.match(/\s|\//);if(s||a){const e=['Unable to register library "'.concat(i,'" with version "').concat(t,'":')];return s&&e.push('library name "'.concat(i,'" contains illegal characters (whitespace or "/")')),s&&a&&e.push("and"),a&&e.push('version name "'.concat(t,'" contains illegal characters (whitespace or "/")')),void de.warn(e.join(" "))}ye(new L("".concat(i,"-version"),(()=>({library:i,version:t})),"VERSION"))}const Te="firebase-heartbeat-database",Ce=1,xe="firebase-heartbeat-store";let Ne=null;function Ae(){return Ne||(Ne=function(e,t){let{blocked:n,upgrade:r,blocking:i,terminated:s}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const a=indexedDB.open(e,t),o=re(a);return r&&a.addEventListener("upgradeneeded",(e=>{r(re(a.result),e.oldVersion,e.newVersion,re(a.transaction),e)})),n&&a.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),o.then((e=>{s&&e.addEventListener("close",(()=>s())),i&&e.addEventListener("versionchange",(e=>i(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),o}(Te,Ce,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(xe)}}).catch((e=>{throw be.create("idb-open",{originalErrorMessage:e.message})}))),Ne}async function Pe(e,t){try{const n=(await Ae()).transaction(xe,"readwrite"),r=n.objectStore(xe);await r.put(t,Re(e)),await n.done}catch(n){if(n instanceof w)de.warn(n.message);else{const e=be.create("idb-set",{originalErrorMessage:null===n||void 0===n?void 0:n.message});de.warn(e.message)}}}function Re(e){return"".concat(e.name,"!").concat(e.options.appId)}class De{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new Le(t),this._heartbeatsCachePromise=this._storage.read().then((e=>(this._heartbeatsCache=e,e)))}async triggerHeartbeat(){var e;const t=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),n=Oe();if(null==(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)&&(this._heartbeatsCache=await this._heartbeatsCachePromise),this._heartbeatsCache.lastSentHeartbeatDate!==n&&!this._heartbeatsCache.heartbeats.some((e=>e.date===n)))return this._heartbeatsCache.heartbeats.push({date:n,agent:t}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter((e=>{const t=new Date(e.date).valueOf();return Date.now()-t<=2592e6})),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){var e;if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null==(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)||0===this._heartbeatsCache.heartbeats.length)return"";const t=Oe(),{heartbeatsToSend:n,unsentEntries:r}=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1024;const n=[];let r=e.slice();for(const i of e){const e=n.find((e=>e.agent===i.agent));if(e){if(e.dates.push(i.date),Me(n)>t){e.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),Me(n)>t){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}(this._heartbeatsCache.heartbeats),i=o(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=t,r.length>0?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i}}function Oe(){return(new Date).toISOString().substring(0,10)}class Le{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!v()&&y().then((()=>!0)).catch((()=>!1))}async read(){if(await this._canUseIndexedDBPromise){const e=await async function(e){try{const t=await Ae();return await t.transaction(xe).objectStore(xe).get(Re(e))}catch(t){if(t instanceof w)de.warn(t.message);else{const e=be.create("idb-get",{originalErrorMessage:null===t||void 0===t?void 0:t.message});de.warn(e.message)}}}(this.app);return e||{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return Pe(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return Pe(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function Me(e){return o(JSON.stringify({version:2,heartbeats:e})).length}var je;je="",ye(new L("platform-logger",(e=>new ce(e)),"PRIVATE")),ye(new L("heartbeat",(e=>new De(e)),"PRIVATE")),Ie(ue,he,je),Ie(ue,he,"esm2017"),Ie("fire-js","");Ie("firebase","10.6.0","app");const Fe=(e,t)=>t.some((t=>e instanceof t));let Ue,Ve;const Be=new WeakMap,ze=new WeakMap,qe=new WeakMap,He=new WeakMap,We=new WeakMap;let Ke={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return ze.get(e);if("objectStoreNames"===t)return e.objectStoreNames||qe.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return $e(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function Ge(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(Ve||(Ve=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return e.apply(Ye(this),n),$e(Be.get(this))}:function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return $e(e.apply(Ye(this),n))}:function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];const s=e.call(Ye(this),t,...r);return qe.set(s,t.sort?t.sort():[t]),$e(s)}}function Qe(e){return"function"===typeof e?Ge(e):(e instanceof IDBTransaction&&function(e){if(ze.has(e))return;const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",s),e.removeEventListener("abort",s)},i=()=>{t(),r()},s=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",i),e.addEventListener("error",s),e.addEventListener("abort",s)}));ze.set(e,t)}(e),Fe(e,Ue||(Ue=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,Ke):e)}function $e(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{t($e(e.result)),r()},s=()=>{n(e.error),r()};e.addEventListener("success",i),e.addEventListener("error",s)}));return t.then((t=>{t instanceof IDBCursor&&Be.set(t,e)})).catch((()=>{})),We.set(t,e),t}(e);if(He.has(e))return He.get(e);const t=Qe(e);return t!==e&&(He.set(e,t),We.set(t,e)),t}const Ye=e=>We.get(e);const Xe=["get","getKey","getAll","getAllKeys","count"],Je=["put","add","delete","clear"],Ze=new Map;function et(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!==typeof t)return;if(Ze.get(t))return Ze.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=Je.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!Xe.includes(n))return;const s=async function(e){const t=this.transaction(e,i?"readwrite":"readonly");let s=t.store;for(var a=arguments.length,o=new Array(a>1?a-1:0),l=1;l<a;l++)o[l-1]=arguments[l];return r&&(s=s.index(o.shift())),(await Promise.all([s[n](...o),i&&t.done]))[0]};return Ze.set(t,s),s}!function(e){Ke=e(Ke)}((e=>({...e,get:(t,n,r)=>et(t,n)||e.get(t,n,r),has:(t,n)=>!!et(t,n)||e.has(t,n)})));const tt="@firebase/installations",nt="0.6.4",rt=1e4,it="w:".concat(nt),st="FIS_v2",at="https://firebaseinstallations.googleapis.com/v1",ot=36e5,lt=new b("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function ct(e){return e instanceof w&&e.code.includes("request-failed")}function ut(e){let{projectId:t}=e;return"".concat(at,"/projects/").concat(t,"/installations")}function ht(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function dt(e,t){const n=(await t.json()).error;return lt.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function ft(e){let{apiKey:t}=e;return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":t})}function pt(e,t){let{refreshToken:n}=t;const r=ft(e);return r.append("Authorization",function(e){return"".concat(st," ").concat(e)}(n)),r}async function mt(e){const t=await e();return t.status>=500&&t.status<600?e():t}function gt(e){return new Promise((t=>{setTimeout(t,e)}))}const vt=/^[cdef][\w-]{21}$/,yt="";function wt(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function(e){const t=(n=e,btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_"));var n;return t.substr(0,22)}(e);return vt.test(t)?t:yt}catch(e){return yt}}function bt(e){return"".concat(e.appName,"!").concat(e.appId)}const _t=new Map;function Et(e,t){const n=bt(e);St(n,t),function(e,t){const n=It();n&&n.postMessage({key:e,fid:t});Tt()}(n,t)}function St(e,t){const n=_t.get(e);if(n)for(const r of n)r(t)}let kt=null;function It(){return!kt&&"BroadcastChannel"in self&&(kt=new BroadcastChannel("[Firebase] FID Change"),kt.onmessage=e=>{St(e.data.key,e.data.fid)}),kt}function Tt(){0===_t.size&&kt&&(kt.close(),kt=null)}const Ct="firebase-installations-database",xt=1,Nt="firebase-installations-store";let At=null;function Pt(){return At||(At=function(e,t){let{blocked:n,upgrade:r,blocking:i,terminated:s}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const a=indexedDB.open(e,t),o=$e(a);return r&&a.addEventListener("upgradeneeded",(e=>{r($e(a.result),e.oldVersion,e.newVersion,$e(a.transaction))})),n&&a.addEventListener("blocked",(()=>n())),o.then((e=>{s&&e.addEventListener("close",(()=>s())),i&&e.addEventListener("versionchange",(()=>i()))})).catch((()=>{})),o}(Ct,xt,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(Nt)}})),At}async function Rt(e,t){const n=bt(e),r=(await Pt()).transaction(Nt,"readwrite"),i=r.objectStore(Nt),s=await i.get(n);return await i.put(t,n),await r.done,s&&s.fid===t.fid||Et(e,t.fid),t}async function Dt(e){const t=bt(e),n=(await Pt()).transaction(Nt,"readwrite");await n.objectStore(Nt).delete(t),await n.done}async function Ot(e,t){const n=bt(e),r=(await Pt()).transaction(Nt,"readwrite"),i=r.objectStore(Nt),s=await i.get(n),a=t(s);return void 0===a?await i.delete(n):await i.put(a,n),await r.done,!a||s&&s.fid===a.fid||Et(e,a.fid),a}async function Lt(e){let t;const n=await Ot(e.appConfig,(n=>{const r=function(e){const t=e||{fid:wt(),registrationStatus:0};return Ft(t)}(n),i=function(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(lt.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function(e,t){try{const n=await async function(e,t){let{appConfig:n,heartbeatServiceProvider:r}=e,{fid:i}=t;const s=ut(n),a=ft(n),o=r.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const l={fid:i,authVersion:st,appId:n.appId,sdkVersion:it},c={method:"POST",headers:a,body:JSON.stringify(l)},u=await mt((()=>fetch(s,c)));if(u.ok){const e=await u.json();return{fid:e.fid||i,registrationStatus:2,refreshToken:e.refreshToken,authToken:ht(e.authToken)}}throw await dt("Create Installation",u)}(e,t);return Rt(e.appConfig,n)}catch(n){throw ct(n)&&409===n.customData.serverCode?await Dt(e.appConfig):await Rt(e.appConfig,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:Mt(e)}:{installationEntry:t}}(e,r);return t=i.registrationPromise,i.installationEntry}));return n.fid===yt?{installationEntry:await t}:{installationEntry:n,registrationPromise:t}}async function Mt(e){let t=await jt(e.appConfig);for(;1===t.registrationStatus;)await gt(100),t=await jt(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:n}=await Lt(e);return n||t}return t}function jt(e){return Ot(e,(e=>{if(!e)throw lt.create("installation-not-found");return Ft(e)}))}function Ft(e){return 1===(t=e).registrationStatus&&t.registrationTime+rt<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t}async function Ut(e,t){let{appConfig:n,heartbeatServiceProvider:r}=e;const i=function(e,t){let{fid:n}=t;return"".concat(ut(e),"/").concat(n,"/authTokens:generate")}(n,t),s=pt(n,t),a=r.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&s.append("x-firebase-client",e)}const o={installation:{sdkVersion:it,appId:n.appId}},l={method:"POST",headers:s,body:JSON.stringify(o)},c=await mt((()=>fetch(i,l)));if(c.ok){return ht(await c.json())}throw await dt("Generate Auth Token",c)}async function Vt(e){let t,n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const r=await Ot(e.appConfig,(r=>{if(!zt(r))throw lt.create("not-registered");const i=r.authToken;if(!n&&function(e){return 2===e.requestStatus&&!function(e){const t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+ot}(e)}(i))return r;if(1===i.requestStatus)return t=async function(e,t){let n=await Bt(e.appConfig);for(;1===n.authToken.requestStatus;)await gt(100),n=await Bt(e.appConfig);const r=n.authToken;return 0===r.requestStatus?Vt(e,t):r}(e,n),r;{if(!navigator.onLine)throw lt.create("app-offline");const n=function(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(r);return t=async function(e,t){try{const n=await Ut(e,t),r=Object.assign(Object.assign({},t),{authToken:n});return await Rt(e.appConfig,r),n}catch(n){if(!ct(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await Rt(e.appConfig,n)}else await Dt(e.appConfig);throw n}}(e,n),n}}));return t?await t:r.authToken}function Bt(e){return Ot(e,(e=>{if(!zt(e))throw lt.create("not-registered");const t=e.authToken;return 1===(n=t).requestStatus&&n.requestTime+rt<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e;var n}))}function zt(e){return void 0!==e&&2===e.registrationStatus}async function qt(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=e;await async function(e){const{registrationPromise:t}=await Lt(e);t&&await t}(n);return(await Vt(n,t)).token}function Ht(e){return lt.create("missing-app-config-values",{valueName:e})}const Wt="installations",Kt=e=>{const t=e.getProvider("app").getImmediate(),n=function(e){if(!e||!e.options)throw Ht("App Configuration");if(!e.name)throw Ht("App Name");const t=["projectId","apiKey","appId"];for(const n of t)if(!e.options[n])throw Ht(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,heartbeatServiceProvider:we(t,"heartbeat"),_delete:()=>Promise.resolve()}},Gt=e=>{const t=we(e.getProvider("app").getImmediate(),Wt).getImmediate();return{getId:()=>async function(e){const t=e,{installationEntry:n,registrationPromise:r}=await Lt(t);return r?r.catch(console.error):Vt(t).catch(console.error),n.fid}(t),getToken:e=>qt(t,e)}};ye(new L(Wt,Kt,"PUBLIC")),ye(new L("installations-internal",Gt,"PRIVATE")),Ie(tt,nt),Ie(tt,nt,"esm2017");const Qt="analytics",$t="firebase_id",Yt="origin",Xt=6e4,Jt="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",Zt="https://www.googletagmanager.com/gtag/js",en=new W("@firebase/analytics"),tn=new b("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-intialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.',"no-client-id":'The "client_id" field is empty.',"invalid-gtag-resource":"Trusted Types detected an invalid gtag resource: {$gtagURL}."});function nn(e){if(!e.startsWith(Zt)){const t=tn.create("invalid-gtag-resource",{gtagURL:e});return en.warn(t.message),""}return e}function rn(e){return Promise.all(e.map((e=>e.catch((e=>e)))))}function sn(e,t){const n=function(e,t){let n;return window.trustedTypes&&(n=window.trustedTypes.createPolicy(e,t)),n}("firebase-js-sdk-policy",{createScriptURL:nn}),r=document.createElement("script"),i="".concat(Zt,"?l=").concat(e,"&id=").concat(t);r.src=n?null===n||void 0===n?void 0:n.createScriptURL(i):i,r.async=!0,document.head.appendChild(r)}function an(e,t,n,r){return async function(i){try{for(var s=arguments.length,a=new Array(s>1?s-1:0),o=1;o<s;o++)a[o-1]=arguments[o];if("event"===i){const[r,i]=a;await async function(e,t,n,r,i){try{let s=[];if(i&&i.send_to){let e=i.send_to;Array.isArray(e)||(e=[e]);const r=await rn(n);for(const n of e){const e=r.find((e=>e.measurementId===n)),i=e&&t[e.appId];if(!i){s=[];break}s.push(i)}}0===s.length&&(s=Object.values(t)),await Promise.all(s),e("event",r,i||{})}catch(s){en.error(s)}}(e,t,n,r,i)}else if("config"===i){const[i,s]=a;await async function(e,t,n,r,i,s){const a=r[i];try{if(a)await t[a];else{const e=(await rn(n)).find((e=>e.measurementId===i));e&&await t[e.appId]}}catch(o){en.error(o)}e("config",i,s)}(e,t,n,r,i,s)}else if("consent"===i){const[t]=a;e("consent","update",t)}else if("get"===i){const[t,n,r]=a;e("get",t,n,r)}else if("set"===i){const[t]=a;e("set",t)}else e(i,...a)}catch(l){en.error(l)}}}const on=30;const ln=new class{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3;this.throttleMetadata=e,this.intervalMillis=t}getThrottleMetadata(e){return this.throttleMetadata[e]}setThrottleMetadata(e,t){this.throttleMetadata[e]=t}deleteThrottleMetadata(e){delete this.throttleMetadata[e]}};function cn(e){return new Headers({Accept:"application/json","x-goog-api-key":e})}async function un(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ln,n=arguments.length>2?arguments[2]:void 0;const{appId:r,apiKey:i,measurementId:s}=e.options;if(!r)throw tn.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:r};throw tn.create("no-api-key")}const a=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()},o=new dn;return setTimeout((async()=>{o.abort()}),void 0!==n?n:Xt),hn({appId:r,apiKey:i,measurementId:s},a,o,t)}async function hn(e,t,n){let{throttleEndTimeMillis:r,backoffCount:i}=t,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:ln;var a;const{appId:o,measurementId:l}=e;try{await function(e,t){return new Promise(((n,r)=>{const i=Math.max(t-Date.now(),0),s=setTimeout(n,i);e.addEventListener((()=>{clearTimeout(s),r(tn.create("fetch-throttle",{throttleEndTimeMillis:t}))}))}))}(n,r)}catch(c){if(l)return en.warn("Timed out fetching this Firebase app's measurement ID from the server."+" Falling back to the measurement ID ".concat(l)+' provided in the "measurementId" field in the local Firebase config. ['.concat(null===c||void 0===c?void 0:c.message,"]")),{appId:o,measurementId:l};throw c}try{const t=await async function(e){var t;const{appId:n,apiKey:r}=e,i={method:"GET",headers:cn(r)},s=Jt.replace("{app-id}",n),a=await fetch(s,i);if(200!==a.status&&304!==a.status){let e="";try{const n=await a.json();(null===(t=n.error)||void 0===t?void 0:t.message)&&(e=n.error.message)}catch(o){}throw tn.create("config-fetch-failed",{httpStatus:a.status,responseMessage:e})}return a.json()}(e);return s.deleteThrottleMetadata(o),t}catch(c){const t=c;if(!function(e){if(!(e instanceof w)||!e.customData)return!1;const t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}(t)){if(s.deleteThrottleMetadata(o),l)return en.warn("Failed to fetch this Firebase app's measurement ID from the server."+" Falling back to the measurement ID ".concat(l)+' provided in the "measurementId" field in the local Firebase config. ['.concat(null===t||void 0===t?void 0:t.message,"]")),{appId:o,measurementId:l};throw c}const r=503===Number(null===(a=null===t||void 0===t?void 0:t.customData)||void 0===a?void 0:a.httpStatus)?D(i,s.intervalMillis,on):D(i,s.intervalMillis),u={throttleEndTimeMillis:Date.now()+r,backoffCount:i+1};return s.setThrottleMetadata(o,u),en.debug("Calling attemptFetch again in ".concat(r," millis")),hn(e,u,n,s)}}class dn{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}let fn,pn;function mn(e){pn=e}function gn(e){fn=e}async function vn(e,t,n,r,i,s,a){var o;const l=un(e);l.then((t=>{n[t.measurementId]=t.appId,e.options.measurementId&&t.measurementId!==e.options.measurementId&&en.warn("The measurement ID in the local Firebase config (".concat(e.options.measurementId,")")+" does not match the measurement ID fetched from the server (".concat(t.measurementId,").")+" To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.")})).catch((e=>en.error(e))),t.push(l);const c=async function(){if(!v())return en.warn(tn.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await y()}catch(e){return en.warn(tn.create("indexeddb-unavailable",{errorInfo:null===e||void 0===e?void 0:e.toString()}).message),!1}return!0}().then((e=>e?r.getId():void 0)),[u,h]=await Promise.all([l,c]);(function(e){const t=window.document.getElementsByTagName("script");for(const n of Object.values(t))if(n.src&&n.src.includes(Zt)&&n.src.includes(e))return n;return null})(s)||sn(s,u.measurementId),pn&&(i("consent","default",pn),mn(void 0)),i("js",new Date);const d=null!==(o=null===a||void 0===a?void 0:a.config)&&void 0!==o?o:{};return d[Yt]="firebase",d.update=!0,null!=h&&(d[$t]=h),i("config",u.measurementId,d),fn&&(i("set",fn),gn(void 0)),u.measurementId}class yn{constructor(e){this.app=e}_delete(){return delete wn[this.app.options.appId],Promise.resolve()}}let wn={},bn=[];const _n={};let En,Sn,kn="dataLayer",In="gtag",Tn=!1;function Cn(){const e=[];if(g()&&e.push("This is a browser extension environment."),"undefined"!==typeof navigator&&navigator.cookieEnabled||e.push("Cookies are not available."),e.length>0){const t=e.map(((e,t)=>"(".concat(t+1,") ").concat(e))).join(" "),n=tn.create("invalid-analytics-context",{errorInfo:t});en.warn(n.message)}}function xn(e,t,n){Cn();const r=e.options.appId;if(!r)throw tn.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw tn.create("no-api-key");en.warn('The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest'+" measurement ID for this Firebase app. Falling back to the measurement ID ".concat(e.options.measurementId)+' provided in the "measurementId" field in the local Firebase config.')}if(null!=wn[r])throw tn.create("already-exists",{id:r});if(!Tn){!function(e){let t=[];Array.isArray(window[e])?t=window[e]:window[e]=t}(kn);const{wrappedGtag:e,gtagCore:t}=function(e,t,n,r,i){let s=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];window[r].push(arguments)};return window[i]&&"function"===typeof window[i]&&(s=window[i]),window[i]=an(s,e,t,n),{gtagCore:s,wrappedGtag:window[i]}}(wn,bn,_n,kn,In);Sn=e,En=t,Tn=!0}wn[r]=vn(e,bn,_n,t,En,kn,n);return new yn(e)}function Nn(e,t,n,r){e=O(e),async function(e,t,n,r,i){if(i&&i.global)e("event",n,r);else{const i=await t;e("event",n,Object.assign(Object.assign({},r),{send_to:i}))}}(Sn,wn[e.app.options.appId],t,n,r).catch((e=>en.error(e)))}const An="@firebase/analytics",Pn="0.10.0";ye(new L(Qt,((e,t)=>{let{options:n}=t;return xn(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),n)}),"PUBLIC")),ye(new L("analytics-internal",(function(e){try{const t=e.getProvider(Qt).getImmediate();return{logEvent:(e,n,r)=>Nn(t,e,n,r)}}catch(t){throw tn.create("interop-component-reg-failed",{reason:t})}}),"PRIVATE")),Ie(An,Pn),Ie(An,Pn,"esm2017");function Rn(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"===typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}Object.create;Object.create;"function"===typeof SuppressedError&&SuppressedError;function Dn(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}const On=Dn,Ln=new b("auth","Firebase",{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}),Mn=new W("@firebase/auth");function jn(e){if(Mn.logLevel<=V.ERROR){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];Mn.error("Auth (".concat(Ee,"): ").concat(e),...n)}}function Fn(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];throw Bn(e,...n)}function Un(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return Bn(e,...n)}function Vn(e,t,n){const r=Object.assign(Object.assign({},On()),{[t]:n});return new b("auth","Firebase",r).create(t,{appName:e.name})}function Bn(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];if("string"!==typeof e){const t=n[0],r=[...n.slice(1)];return r[0]&&(r[0].appName=e.name),e._errorFactory.create(t,...r)}return Ln.create(e,...n)}function zn(e,t){if(!e){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i<n;i++)r[i-2]=arguments[i];throw Bn(t,...r)}}function qn(e){const t="INTERNAL ASSERTION FAILED: "+e;throw jn(t),new Error(t)}function Hn(e,t){e||qn(t)}function Wn(){var e;return"undefined"!==typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function Kn(){return"http:"===Gn()||"https:"===Gn()}function Gn(){var e;return"undefined"!==typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}class Qn{constructor(e,t){this.shortDelay=e,this.longDelay=t,Hn(t>e,"Short delay should be less than long delay!"),this.isMobile="undefined"!==typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(m())||"object"===typeof navigator&&"ReactNative"===navigator.product}get(){return"undefined"!==typeof navigator&&navigator&&"onLine"in navigator&&"boolean"===typeof navigator.onLine&&(Kn()||g()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function $n(e,t){Hn(e.emulator,"Emulator should always be set here");const{url:n}=e.emulator;return t?"".concat(n).concat(t.startsWith("/")?t.slice(1):t):n}class Yn{static initialize(e,t,n){this.fetchImpl=e,t&&(this.headersImpl=t),n&&(this.responseImpl=n)}static fetch(){return this.fetchImpl?this.fetchImpl:"undefined"!==typeof self&&"fetch"in self?self.fetch:"undefined"!==typeof globalThis&&globalThis.fetch?globalThis.fetch:"undefined"!==typeof fetch?fetch:void qn("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){return this.headersImpl?this.headersImpl:"undefined"!==typeof self&&"Headers"in self?self.Headers:"undefined"!==typeof globalThis&&globalThis.Headers?globalThis.Headers:"undefined"!==typeof Headers?Headers:void qn("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){return this.responseImpl?this.responseImpl:"undefined"!==typeof self&&"Response"in self?self.Response:"undefined"!==typeof globalThis&&globalThis.Response?globalThis.Response:"undefined"!==typeof Response?Response:void qn("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const Xn={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"},Jn=new Qn(3e4,6e4);function Zn(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function er(e,t,n,r){return tr(e,arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},(async()=>{let i={},s={};r&&("GET"===t?s=r:i={body:JSON.stringify(r)});const a=k(Object.assign({key:e.config.apiKey},s)).slice(1),o=await e._getAdditionalHeaders();return o["Content-Type"]="application/json",e.languageCode&&(o["X-Firebase-Locale"]=e.languageCode),Yn.fetch()(rr(e,e.config.apiHost,n,a),Object.assign({method:t,headers:o,referrerPolicy:"no-referrer"},i))}))}async function tr(e,t,n){e._canInitEmulator=!1;const r=Object.assign(Object.assign({},Xn),t);try{const t=new sr(e),i=await Promise.race([n(),t.promise]);t.clearNetworkTimeout();const s=await i.json();if("needConfirmation"in s)throw ar(e,"account-exists-with-different-credential",s);if(i.ok&&!("errorMessage"in s))return s;{const t=i.ok?s.errorMessage:s.error.message,[n,a]=t.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===n)throw ar(e,"credential-already-in-use",s);if("EMAIL_EXISTS"===n)throw ar(e,"email-already-in-use",s);if("USER_DISABLED"===n)throw ar(e,"user-disabled",s);const o=r[n]||n.toLowerCase().replace(/[_\s]+/g,"-");if(a)throw Vn(e,o,a);Fn(e,o)}}catch(i){if(i instanceof w)throw i;Fn(e,"network-request-failed",{message:String(i)})}}async function nr(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};const s=await er(e,t,n,r,i);return"mfaPendingCredential"in s&&Fn(e,"multi-factor-auth-required",{_serverResponse:s}),s}function rr(e,t,n,r){const i="".concat(t).concat(n,"?").concat(r);return e.config.emulator?$n(e.config,i):"".concat(e.config.apiScheme,"://").concat(i)}function ir(e){switch(e){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}class sr{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise(((e,t)=>{this.timer=setTimeout((()=>t(Un(this.auth,"network-request-failed"))),Jn.get())}))}clearNetworkTimeout(){clearTimeout(this.timer)}}function ar(e,t,n){const r={appName:e.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);const i=Un(e,t,r);return i.customData._tokenResponse=n,i}function or(e){return void 0!==e&&void 0!==e.enterprise}class lr{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],void 0===e.recaptchaKey)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||0===this.recaptchaEnforcementState.length)return null;for(const t of this.recaptchaEnforcementState)if(t.provider&&t.provider===e)return ir(t.enforcementState);return null}isProviderEnabled(e){return"ENFORCE"===this.getProviderEnforcementState(e)||"AUDIT"===this.getProviderEnforcementState(e)}}async function cr(e,t){return er(e,"GET","/v2/recaptchaConfig",Zn(e,t))}function ur(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(t){}}function hr(e){return 1e3*Number(e)}function dr(e){const[t,n,r]=e.split(".");if(void 0===t||void 0===n||void 0===r)return jn("JWT malformed, contained fewer than 3 sections"),null;try{const e=l(n);return e?JSON.parse(e):(jn("Failed to decode base64 JWT payload"),null)}catch(i){return jn("Caught error parsing JWT payload as JSON",null===i||void 0===i?void 0:i.toString()),null}}async function fr(e,t){if(arguments.length>2&&void 0!==arguments[2]&&arguments[2])return t;try{return await t}catch(n){throw n instanceof w&&function(e){let{code:t}=e;return t==="auth/".concat("user-disabled")||t==="auth/".concat("user-token-expired")}(n)&&e.auth.currentUser===e&&await e.auth.signOut(),n}}class pr{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){var t;if(e){const e=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),e}{this.errorBackoff=3e4;const e=(null!==(t=this.user.stsTokenManager.expirationTime)&&void 0!==t?t:0)-Date.now()-3e5;return Math.max(0,e)}}schedule(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!this.isRunning)return;const t=this.getInterval(e);this.timerId=setTimeout((async()=>{await this.iteration()}),t)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){return void((null===e||void 0===e?void 0:e.code)==="auth/".concat("network-request-failed")&&this.schedule(!0))}this.schedule()}}class mr{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=ur(this.lastLoginAt),this.creationTime=ur(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function gr(e){var t;const n=e.auth,r=await e.getIdToken(),i=await fr(e,async function(e,t){return er(e,"POST","/v1/accounts:lookup",t)}(n,{idToken:r}));zn(null===i||void 0===i?void 0:i.users.length,n,"internal-error");const s=i.users[0];e._notifyReloadListener(s);const a=(null===(t=s.providerUserInfo)||void 0===t?void 0:t.length)?s.providerUserInfo.map((e=>{var{providerId:t}=e,n=Rn(e,["providerId"]);return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}})):[];const o=(l=e.providerData,c=a,[...l.filter((e=>!c.some((t=>t.providerId===e.providerId)))),...c]);var l,c;const u=e.isAnonymous,h=!(e.email&&s.passwordHash)&&!(null===o||void 0===o?void 0:o.length),d=!!u&&h,f={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:o,metadata:new mr(s.createdAt,s.lastLoginAt),isAnonymous:d};Object.assign(e,f)}class vr{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){zn(e.idToken,"internal-error"),zn("undefined"!==typeof e.idToken,"internal-error"),zn("undefined"!==typeof e.refreshToken,"internal-error");const t="expiresIn"in e&&"undefined"!==typeof e.expiresIn?Number(e.expiresIn):function(e){const t=dr(e);return zn(t,"internal-error"),zn("undefined"!==typeof t.exp,"internal-error"),zn("undefined"!==typeof t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}async getToken(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return zn(!this.accessToken||this.refreshToken,e,"user-token-expired"),t||!this.accessToken||this.isExpired?this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null:this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){const{accessToken:n,refreshToken:r,expiresIn:i}=await async function(e,t){const n=await tr(e,{},(async()=>{const n=k({grant_type:"refresh_token",refresh_token:t}).slice(1),{tokenApiHost:r,apiKey:i}=e.config,s=rr(e,r,"/v1/token","key=".concat(i)),a=await e._getAdditionalHeaders();return a["Content-Type"]="application/x-www-form-urlencoded",Yn.fetch()(s,{method:"POST",headers:a,body:n})}));return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}(e,t);this.updateTokensAndExpiration(n,r,Number(i))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(e,t){const{refreshToken:n,accessToken:r,expirationTime:i}=t,s=new vr;return n&&(zn("string"===typeof n,"internal-error",{appName:e}),s.refreshToken=n),r&&(zn("string"===typeof r,"internal-error",{appName:e}),s.accessToken=r),i&&(zn("number"===typeof i,"internal-error",{appName:e}),s.expirationTime=i),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new vr,this.toJSON())}_performRefresh(){return qn("not implemented")}}function yr(e,t){zn("string"===typeof e||"undefined"===typeof e,"internal-error",{appName:t})}class wr{constructor(e){var{uid:t,auth:n,stsTokenManager:r}=e,i=Rn(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new pr(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[...i.providerData]:[],this.metadata=new mr(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){const t=await fr(this,this.stsTokenManager.getToken(this.auth,e));return zn(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return async function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=O(e),r=await n.getIdToken(t),i=dr(r);zn(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");const s="object"===typeof i.firebase?i.firebase:void 0,a=null===s||void 0===s?void 0:s.sign_in_provider;return{claims:i,token:r,authTime:ur(hr(i.auth_time)),issuedAtTime:ur(hr(i.iat)),expirationTime:ur(hr(i.exp)),signInProvider:a||null,signInSecondFactor:(null===s||void 0===s?void 0:s.sign_in_second_factor)||null}}(this,e)}reload(){return async function(e){const t=O(e);await gr(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}(this)}_assign(e){this!==e&&(zn(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map((e=>Object.assign({},e))),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){const t=new wr(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}));return t.metadata._copy(this.metadata),t}_onReload(e){zn(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),n=!0),t&&await gr(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){const e=await this.getIdToken();return await fr(this,async function(e,t){return er(e,"POST","/v1/accounts:delete",t)}(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return Object.assign(Object.assign({uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map((e=>Object.assign({},e))),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId},this.metadata.toJSON()),{apiKey:this.auth.config.apiKey,appName:this.auth.name})}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){var n,r,i,s,a,o,l,c;const u=null!==(n=t.displayName)&&void 0!==n?n:void 0,h=null!==(r=t.email)&&void 0!==r?r:void 0,d=null!==(i=t.phoneNumber)&&void 0!==i?i:void 0,f=null!==(s=t.photoURL)&&void 0!==s?s:void 0,p=null!==(a=t.tenantId)&&void 0!==a?a:void 0,m=null!==(o=t._redirectEventId)&&void 0!==o?o:void 0,g=null!==(l=t.createdAt)&&void 0!==l?l:void 0,v=null!==(c=t.lastLoginAt)&&void 0!==c?c:void 0,{uid:y,emailVerified:w,isAnonymous:b,providerData:_,stsTokenManager:E}=t;zn(y&&E,e,"internal-error");const S=vr.fromJSON(this.name,E);zn("string"===typeof y,e,"internal-error"),yr(u,e.name),yr(h,e.name),zn("boolean"===typeof w,e,"internal-error"),zn("boolean"===typeof b,e,"internal-error"),yr(d,e.name),yr(f,e.name),yr(p,e.name),yr(m,e.name),yr(g,e.name),yr(v,e.name);const k=new wr({uid:y,auth:e,email:h,emailVerified:w,displayName:u,isAnonymous:b,photoURL:f,phoneNumber:d,tenantId:p,stsTokenManager:S,createdAt:g,lastLoginAt:v});return _&&Array.isArray(_)&&(k.providerData=_.map((e=>Object.assign({},e)))),m&&(k._redirectEventId=m),k}static async _fromIdTokenResponse(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const r=new vr;r.updateFromServerResponse(t);const i=new wr({uid:t.localId,auth:e,stsTokenManager:r,isAnonymous:n});return await gr(i),i}}const br=new Map;function _r(e){Hn(e instanceof Function,"Expected a class definition");let t=br.get(e);return t?(Hn(t instanceof e,"Instance stored in cache mismatched with class"),t):(t=new e,br.set(e,t),t)}class Er{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){const t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}Er.type="NONE";const Sr=Er;function kr(e,t,n){return"firebase".concat(":",e,":").concat(t,":").concat(n)}class Ir{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;const{config:r,name:i}=this.auth;this.fullUserKey=kr(this.userKey,r.apiKey,i),this.fullPersistenceKey=kr("persistence",r.apiKey,i),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){const e=await this.persistence._get(this.fullUserKey);return e?wr._fromJSON(this.auth,e):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;const t=await this.getCurrentUser();return await this.removeCurrentUser(),this.persistence=e,t?this.setCurrentUser(t):void 0}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"authUser";if(!t.length)return new Ir(_r(Sr),e,n);const r=(await Promise.all(t.map((async e=>{if(await e._isAvailable())return e})))).filter((e=>e));let i=r[0]||_r(Sr);const s=kr(n,e.config.apiKey,e.name);let a=null;for(const c of t)try{const t=await c._get(s);if(t){const n=wr._fromJSON(e,t);c!==i&&(a=n),i=c;break}}catch(l){}const o=r.filter((e=>e._shouldAllowMigration));return i._shouldAllowMigration&&o.length?(i=o[0],a&&await i._set(s,a.toJSON()),await Promise.all(t.map((async e=>{if(e!==i)try{await e._remove(s)}catch(l){}}))),new Ir(i,e,n)):new Ir(i,e,n)}}function Tr(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(Ar(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(Cr(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(Rr(t))return"Blackberry";if(Dr(t))return"Webos";if(xr(t))return"Safari";if((t.includes("chrome/")||Nr(t))&&!t.includes("edge/"))return"Chrome";if(Pr(t))return"Android";{const t=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,n=e.match(t);if(2===(null===n||void 0===n?void 0:n.length))return n[1]}return"Other"}function Cr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m();return/firefox\//i.test(e)}function xr(){const e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:m()).toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function Nr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m();return/crios\//i.test(e)}function Ar(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m();return/iemobile/i.test(e)}function Pr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m();return/android/i.test(e)}function Rr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m();return/blackberry/i.test(e)}function Dr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m();return/webos/i.test(e)}function Or(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m();return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function Lr(){return function(){const e=m();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0}()&&10===document.documentMode}function Mr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m();return Or(e)||Pr(e)||Dr(e)||Rr(e)||/windows phone/i.test(e)||Ar(e)}function jr(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];switch(e){case"Browser":t=Tr(m());break;case"Worker":t="".concat(Tr(m()),"-").concat(e);break;default:t=e}const r=n.length?n.join(","):"FirebaseCore-web";return"".concat(t,"/","JsCore","/").concat(Ee,"/").concat(r)}class Fr{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){const n=t=>new Promise(((n,r)=>{try{n(e(t))}catch(i){r(i)}}));n.onAbort=t,this.queue.push(n);const r=this.queue.length-1;return()=>{this.queue[r]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;const t=[];try{for(const n of this.queue)await n(e),n.onAbort&&t.push(n.onAbort)}catch(n){t.reverse();for(const e of t)try{e()}catch(r){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:null===n||void 0===n?void 0:n.message})}}}class Ur{constructor(e){var t,n,r,i;const s=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=null!==(t=s.minPasswordLength)&&void 0!==t?t:6,s.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=s.maxPasswordLength),void 0!==s.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=s.containsLowercaseCharacter),void 0!==s.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=s.containsUppercaseCharacter),void 0!==s.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=s.containsNumericCharacter),void 0!==s.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=s.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=null!==(r=null===(n=e.allowedNonAlphanumericCharacters)||void 0===n?void 0:n.join(""))&&void 0!==r?r:"",this.forceUpgradeOnSignin=null!==(i=e.forceUpgradeOnSignin)&&void 0!==i&&i,this.schemaVersion=e.schemaVersion}validatePassword(e){var t,n,r,i,s,a;const o={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,o),this.validatePasswordCharacterOptions(e,o),o.isValid&&(o.isValid=null===(t=o.meetsMinPasswordLength)||void 0===t||t),o.isValid&&(o.isValid=null===(n=o.meetsMaxPasswordLength)||void 0===n||n),o.isValid&&(o.isValid=null===(r=o.containsLowercaseLetter)||void 0===r||r),o.isValid&&(o.isValid=null===(i=o.containsUppercaseLetter)||void 0===i||i),o.isValid&&(o.isValid=null===(s=o.containsNumericCharacter)||void 0===s||s),o.isValid&&(o.isValid=null===(a=o.containsNonAlphanumericCharacter)||void 0===a||a),o}validatePasswordLengthOptions(e,t){const n=this.customStrengthOptions.minPasswordLength,r=this.customStrengthOptions.maxPasswordLength;n&&(t.meetsMinPasswordLength=e.length>=n),r&&(t.meetsMaxPasswordLength=e.length<=r)}validatePasswordCharacterOptions(e,t){let n;this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);for(let r=0;r<e.length;r++)n=e.charAt(r),this.updatePasswordCharacterOptionsStatuses(t,n>="a"&&n<="z",n>="A"&&n<="Z",n>="0"&&n<="9",this.allowedNonAlphanumericCharacters.includes(n))}updatePasswordCharacterOptionsStatuses(e,t,n,r,i){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=n)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=r)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=i))}}class Vr{constructor(e,t,n,r){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=n,this.config=r,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new zr(this),this.idTokenSubscription=new zr(this),this.beforeStateQueue=new Fr(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=Ln,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=r.sdkClientVersion}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=_r(t)),this._initializationPromise=this.queue((async()=>{var n,r;if(!this._deleted&&(this.persistenceManager=await Ir.create(this,e),!this._deleted)){if(null===(n=this._popupRedirectResolver)||void 0===n?void 0:n._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(i){}await this.initializeCurrentUser(t),this.lastNotifiedUid=(null===(r=this.currentUser)||void 0===r?void 0:r.uid)||null,this._deleted||(this._isInitialized=!0)}})),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();return this.currentUser||e?this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(e,!0):void 0}async initializeCurrentUser(e){var t;const n=await this.assertedPersistence.getCurrentUser();let r=n,i=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const n=null===(t=this.redirectUser)||void 0===t?void 0:t._redirectEventId,s=null===r||void 0===r?void 0:r._redirectEventId,a=await this.tryRedirectSignIn(e);n&&n!==s||!(null===a||void 0===a?void 0:a.user)||(r=a.user,i=!0)}if(!r)return this.directlySetCurrentUser(null);if(!r._redirectEventId){if(i)try{await this.beforeStateQueue.runMiddleware(r)}catch(s){r=n,this._popupRedirectResolver._overrideRedirectResult(this,(()=>Promise.reject(s)))}return r?this.reloadAndSetCurrentUserOrClear(r):this.directlySetCurrentUser(null)}return zn(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===r._redirectEventId?this.directlySetCurrentUser(r):this.reloadAndSetCurrentUserOrClear(r)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(n){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await gr(e)}catch(t){if((null===t||void 0===t?void 0:t.code)!=="auth/".concat("network-request-failed"))return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function(){if("undefined"===typeof navigator)return null;const e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(e){const t=e?O(e):null;return t&&zn(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!this._deleted)return e&&zn(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),t||await this.beforeStateQueue.runMiddleware(e),this.queue((async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()}))}async signOut(){return await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0)}setPersistence(e){return this.queue((async()=>{await this.assertedPersistence.setPersistence(_r(e))}))}_getRecaptchaConfig(){return null==this.tenantId?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();const t=this._getPasswordPolicyInternal();return t.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):t.validatePassword(e)}_getPasswordPolicyInternal(){return null===this.tenantId?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){const e=await async function(e){return er(e,"GET","/v2/passwordPolicy",Zn(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}))}(this),t=new Ur(e);null===this.tenantId?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new b("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}authStateReady(){return new Promise(((e,t)=>{if(this.currentUser)e();else{const n=this.onAuthStateChanged((()=>{n(),e()}),t)}}))}async revokeAccessToken(e){if(this.currentUser){const t={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:await this.currentUser.getIdToken()};null!=this.tenantId&&(t.tenantId=this.tenantId),await async function(e,t){return er(e,"POST","/v2/accounts:revokeToken",Zn(e,t))}(this,t)}}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?void 0:e.toJSON()}}async _setRedirectUser(e,t){const n=await this.getOrInitRedirectPersistenceManager(t);return null===e?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&_r(e)||this._popupRedirectResolver;zn(t,this,"argument-error"),this.redirectPersistenceManager=await Ir.create(this,[_r(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){var t,n;return this._isInitialized&&await this.queue((async()=>{})),(null===(t=this._currentUser)||void 0===t?void 0:t._redirectEventId)===e?this._currentUser:(null===(n=this.redirectUser)||void 0===n?void 0:n._redirectEventId)===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue((async()=>this.directlySetCurrentUser(e)))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return"".concat(this.config.authDomain,":").concat(this.config.apiKey,":").concat(this.name)}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){var e,t;if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const n=null!==(t=null===(e=this.currentUser)||void 0===e?void 0:e.uid)&&void 0!==t?t:null;this.lastNotifiedUid!==n&&(this.lastNotifiedUid=n,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,n,r){if(this._deleted)return()=>{};const i="function"===typeof t?t:t.next.bind(t);let s=!1;const a=this._isInitialized?Promise.resolve():this._initializationPromise;if(zn(a,this,"internal-error"),a.then((()=>{s||i(this.currentUser)})),"function"===typeof t){const i=e.addObserver(t,n,r);return()=>{s=!0,i()}}{const n=e.addObserver(t);return()=>{s=!0,n()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return zn(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=jr(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var e;const t={"X-Client-Version":this.clientVersion};this.app.options.appId&&(t["X-Firebase-gmpid"]=this.app.options.appId);const n=await(null===(e=this.heartbeatServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getHeartbeatsHeader());n&&(t["X-Firebase-Client"]=n);const r=await this._getAppCheckToken();return r&&(t["X-Firebase-AppCheck"]=r),t}async _getAppCheckToken(){var e;const t=await(null===(e=this.appCheckServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getToken());return(null===t||void 0===t?void 0:t.error)&&function(e){if(Mn.logLevel<=V.WARN){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];Mn.warn("Auth (".concat(Ee,"): ").concat(e),...n)}}("Error while retrieving App Check token: ".concat(t.error)),null===t||void 0===t?void 0:t.token}}function Br(e){return O(e)}class zr{constructor(e){this.auth=e,this.observer=null,this.addObserver=function(e,t){const n=new C(e,t);return n.subscribe.bind(n)}((e=>this.observer=e))}get next(){return zn(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}function qr(e){return new Promise(((t,n)=>{const r=document.createElement("script");r.setAttribute("src",e),r.onload=t,r.onerror=e=>{const t=Un("internal-error");t.customData=e,n(t)},r.type="text/javascript",r.charset="UTF-8",function(){var e,t;return null!==(t=null===(e=document.getElementsByTagName("head"))||void 0===e?void 0:e[0])&&void 0!==t?t:document}().appendChild(r)}))}function Hr(e){return"__".concat(e).concat(Math.floor(1e6*Math.random()))}class Wr{constructor(e){this.type="recaptcha-enterprise",this.auth=Br(e)}async verify(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"verify",t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];function n(t,n,r){const i=window.grecaptcha;or(i)?i.enterprise.ready((()=>{i.enterprise.execute(t,{action:e}).then((e=>{n(e)})).catch((()=>{n("NO_RECAPTCHA")}))})):r(Error("No reCAPTCHA enterprise script loaded."))}return new Promise(((e,r)=>{(async function(e){if(!t){if(null==e.tenantId&&null!=e._agentRecaptchaConfig)return e._agentRecaptchaConfig.siteKey;if(null!=e.tenantId&&void 0!==e._tenantRecaptchaConfigs[e.tenantId])return e._tenantRecaptchaConfigs[e.tenantId].siteKey}return new Promise((async(t,n)=>{cr(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then((r=>{if(void 0!==r.recaptchaKey){const n=new lr(r);return null==e.tenantId?e._agentRecaptchaConfig=n:e._tenantRecaptchaConfigs[e.tenantId]=n,t(n.siteKey)}n(new Error("recaptcha Enterprise site key undefined"))})).catch((e=>{n(e)}))}))})(this.auth).then((i=>{if(!t&&or(window.grecaptcha))n(i,e,r);else{if("undefined"===typeof window)return void r(new Error("RecaptchaVerifier is only supported in browser"));qr("https://www.google.com/recaptcha/enterprise.js?render="+i).then((()=>{n(i,e,r)})).catch((e=>{r(e)}))}})).catch((e=>{r(e)}))}))}}async function Kr(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const i=new Wr(e);let s;try{s=await i.verify(n)}catch(o){s=await i.verify(n,!0)}const a=Object.assign({},t);return r?Object.assign(a,{captchaResp:s}):Object.assign(a,{captchaResponse:s}),Object.assign(a,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(a,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),a}async function Gr(e,t,n,r){var i;if(null===(i=e._getRecaptchaConfig())||void 0===i?void 0:i.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){const i=await Kr(e,t,n,"getOobCode"===n);return r(e,i)}return r(e,t).catch((async i=>{if(i.code==="auth/".concat("missing-recaptcha-token")){console.log("".concat(n," is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow."));const i=await Kr(e,t,n,"getOobCode"===n);return r(e,i)}return Promise.reject(i)}))}function Qr(e,t,n){const r=Br(e);zn(r._canInitEmulator,r,"emulator-config-failed"),zn(/^https?:\/\//.test(t),r,"invalid-emulator-scheme");const i=!!(null===n||void 0===n?void 0:n.disableWarnings),s=$r(t),{host:a,port:o}=function(e){const t=$r(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:"",port:null};const r=n[2].split("@").pop()||"",i=/^(\[[^\]]+\])(:|$)/.exec(r);if(i){const e=i[1];return{host:e,port:Yr(r.substr(e.length+1))}}{const[e,t]=r.split(":");return{host:e,port:Yr(t)}}}(t),l=null===o?"":":".concat(o);r.config.emulator={url:"".concat(s,"//").concat(a).concat(l,"/")},r.settings.appVerificationDisabledForTesting=!0,r.emulatorConfig=Object.freeze({host:a,port:o,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})}),i||function(){function e(){const e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}"undefined"!==typeof console&&"function"===typeof console.info&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials.");"undefined"!==typeof window&&"undefined"!==typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",e):e())}()}function $r(e){const t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function Yr(e){if(!e)return null;const t=Number(e);return isNaN(t)?null:t}class Xr{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return qn("not implemented")}_getIdTokenResponse(e){return qn("not implemented")}_linkToIdToken(e,t){return qn("not implemented")}_getReauthenticationResolver(e){return qn("not implemented")}}async function Jr(e,t){return er(e,"POST","/v1/accounts:signUp",t)}async function Zr(e,t){return nr(e,"POST","/v1/accounts:signInWithPassword",Zn(e,t))}class ei extends Xr{constructor(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;super("password",n),this._email=e,this._password=t,this._tenantId=r}static _fromEmailAndPassword(e,t){return new ei(e,t,"password")}static _fromEmailAndCode(e,t){return new ei(e,t,"emailLink",arguments.length>2&&void 0!==arguments[2]?arguments[2]:null)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){const t="string"===typeof e?JSON.parse(e):e;if((null===t||void 0===t?void 0:t.email)&&(null===t||void 0===t?void 0:t.password)){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return Gr(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",Zr);case"emailLink":return async function(e,t){return nr(e,"POST","/v1/accounts:signInWithEmailLink",Zn(e,t))}(e,{email:this._email,oobCode:this._password});default:Fn(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return Gr(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",Jr);case"emailLink":return async function(e,t){return nr(e,"POST","/v1/accounts:signInWithEmailLink",Zn(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:Fn(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function ti(e,t){return nr(e,"POST","/v1/accounts:signInWithIdp",Zn(e,t))}class ni extends Xr{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new ni(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):Fn("argument-error"),t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){const t="string"===typeof e?JSON.parse(e):e,{providerId:n,signInMethod:r}=t,i=Rn(t,["providerId","signInMethod"]);if(!n||!r)return null;const s=new ni(n,r);return s.idToken=i.idToken||void 0,s.accessToken=i.accessToken||void 0,s.secret=i.secret,s.nonce=i.nonce,s.pendingToken=i.pendingToken||null,s}_getIdTokenResponse(e){return ti(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,ti(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,ti(e,t)}buildRequest(){const e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=k(t)}return e}}const ri={USER_NOT_FOUND:"user-not-found"};class ii extends Xr{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new ii({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new ii({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function(e,t){return nr(e,"POST","/v1/accounts:signInWithPhoneNumber",Zn(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){const n=await nr(e,"POST","/v1/accounts:signInWithPhoneNumber",Zn(e,t));if(n.temporaryProof)throw ar(e,"account-exists-with-different-credential",n);return n}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function(e,t){return nr(e,"POST","/v1/accounts:signInWithPhoneNumber",Zn(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),ri)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:r}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:r}}toJSON(){const e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){"string"===typeof e&&(e=JSON.parse(e));const{verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}=e;return n||t||r||i?new ii({verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}):null}}class si{constructor(e){var t,n,r,i,s,a;const o=I(T(e)),l=null!==(t=o.apiKey)&&void 0!==t?t:null,c=null!==(n=o.oobCode)&&void 0!==n?n:null,u=function(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(null!==(r=o.mode)&&void 0!==r?r:null);zn(l&&c&&u,"argument-error"),this.apiKey=l,this.operation=u,this.code=c,this.continueUrl=null!==(i=o.continueUrl)&&void 0!==i?i:null,this.languageCode=null!==(s=o.languageCode)&&void 0!==s?s:null,this.tenantId=null!==(a=o.tenantId)&&void 0!==a?a:null}static parseLink(e){const t=function(e){const t=I(T(e)).link,n=t?I(T(t)).deep_link_id:null,r=I(T(e)).deep_link_id;return(r?I(T(r)).link:null)||r||n||t||e}(e);try{return new si(t)}catch(n){return null}}}class ai{constructor(){this.providerId=ai.PROVIDER_ID}static credential(e,t){return ei._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const n=si.parseLink(t);return zn(n,"argument-error"),ei._fromEmailAndCode(e,n.code,n.tenantId)}}ai.PROVIDER_ID="password",ai.EMAIL_PASSWORD_SIGN_IN_METHOD="password",ai.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class oi{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}}class li extends oi{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class ci extends li{constructor(){super("facebook.com")}static credential(e){return ni._fromParams({providerId:ci.PROVIDER_ID,signInMethod:ci.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return ci.credentialFromTaggedObject(e)}static credentialFromError(e){return ci.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject(e){let{_tokenResponse:t}=e;if(!t||!("oauthAccessToken"in t))return null;if(!t.oauthAccessToken)return null;try{return ci.credential(t.oauthAccessToken)}catch(n){return null}}}ci.FACEBOOK_SIGN_IN_METHOD="facebook.com",ci.PROVIDER_ID="facebook.com";class ui extends li{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return ni._fromParams({providerId:ui.PROVIDER_ID,signInMethod:ui.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return ui.credentialFromTaggedObject(e)}static credentialFromError(e){return ui.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject(e){let{_tokenResponse:t}=e;if(!t)return null;const{oauthIdToken:n,oauthAccessToken:r}=t;if(!n&&!r)return null;try{return ui.credential(n,r)}catch(i){return null}}}ui.GOOGLE_SIGN_IN_METHOD="google.com",ui.PROVIDER_ID="google.com";class hi extends li{constructor(){super("github.com")}static credential(e){return ni._fromParams({providerId:hi.PROVIDER_ID,signInMethod:hi.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return hi.credentialFromTaggedObject(e)}static credentialFromError(e){return hi.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject(e){let{_tokenResponse:t}=e;if(!t||!("oauthAccessToken"in t))return null;if(!t.oauthAccessToken)return null;try{return hi.credential(t.oauthAccessToken)}catch(n){return null}}}hi.GITHUB_SIGN_IN_METHOD="github.com",hi.PROVIDER_ID="github.com";class di extends li{constructor(){super("twitter.com")}static credential(e,t){return ni._fromParams({providerId:di.PROVIDER_ID,signInMethod:di.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return di.credentialFromTaggedObject(e)}static credentialFromError(e){return di.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject(e){let{_tokenResponse:t}=e;if(!t)return null;const{oauthAccessToken:n,oauthTokenSecret:r}=t;if(!n||!r)return null;try{return di.credential(n,r)}catch(i){return null}}}async function fi(e,t){return nr(e,"POST","/v1/accounts:signUp",Zn(e,t))}di.TWITTER_SIGN_IN_METHOD="twitter.com",di.PROVIDER_ID="twitter.com";class pi{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const i=await wr._fromIdTokenResponse(e,n,r),s=mi(n);return new pi({user:i,providerId:s,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);const r=mi(n);return new pi({user:e,providerId:r,_tokenResponse:n,operationType:t})}}function mi(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}class gi extends w{constructor(e,t,n,r){var i;super(t.code,t.message),this.operationType=n,this.user=r,Object.setPrototypeOf(this,gi.prototype),this.customData={appName:e.name,tenantId:null!==(i=e.tenantId)&&void 0!==i?i:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,r){return new gi(e,t,n,r)}}function vi(e,t,n,r){return("reauthenticate"===t?n._getReauthenticationResolver(e):n._getIdTokenResponse(e)).catch((n=>{if(n.code==="auth/".concat("multi-factor-auth-required"))throw gi._fromErrorAndOperation(e,n,t,r);throw n}))}async function yi(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const r=await fr(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return pi._forOperation(e,"link",r)}async function wi(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const{auth:r}=e,i="reauthenticate";try{const s=await fr(e,vi(r,i,t,e),n);zn(s.idToken,r,"internal-error");const a=dr(s.idToken);zn(a,r,"internal-error");const{sub:o}=a;return zn(e.uid===o,r,"user-mismatch"),pi._forOperation(e,i,s)}catch(s){throw(null===s||void 0===s?void 0:s.code)==="auth/".concat("user-not-found")&&Fn(r,"user-mismatch"),s}}async function bi(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const r="signIn",i=await vi(e,r,t),s=await pi._fromIdTokenResponse(e,r,i);return n||await e._updateCurrentUser(s.user),s}async function _i(e){const t=Br(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}new WeakMap;const Ei="__sak";class Si{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(Ei,"1"),this.storage.removeItem(Ei),Promise.resolve(!0)):Promise.resolve(!1)}catch(e){return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){const t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}class ki extends Si{constructor(){super((()=>window.localStorage),"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=function(){const e=m();return xr(e)||Or(e)}()&&function(){try{return!(!window||window===window.top)}catch(e){return!1}}(),this.fallbackToPolling=Mr(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const n=this.storage.getItem(t),r=this.localCache[t];n!==r&&e(t,r,n)}}onStorageEvent(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!e.key)return void this.forAllChangedKeys(((e,t,n)=>{this.notifyListeners(e,n)}));const n=e.key;if(t?this.detachListener():this.stopPolling(),this.safariLocalStorageNotSynced){const r=this.storage.getItem(n);if(e.newValue!==r)null!==e.newValue?this.storage.setItem(n,e.newValue):this.storage.removeItem(n);else if(this.localCache[n]===e.newValue&&!t)return}const r=()=>{const e=this.storage.getItem(n);(t||this.localCache[n]!==e)&&this.notifyListeners(n,e)},i=this.storage.getItem(n);Lr()&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(r,10):r()}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n)for(const r of Array.from(n))r(t?JSON.parse(t):t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((()=>{this.forAllChangedKeys(((e,t,n)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:n}),!0)}))}),1e3)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){const t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}ki.type="LOCAL";const Ii=ki;class Ti extends Si{constructor(){super((()=>window.sessionStorage),"SESSION")}_addListener(e,t){}_removeListener(e,t){}}Ti.type="SESSION";const Ci=Ti;class xi{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const t=this.receivers.find((t=>t.isListeningto(e)));if(t)return t;const n=new xi(e);return this.receivers.push(n),n}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:n,eventType:r,data:i}=t.data,s=this.handlersMap[r];if(!(null===s||void 0===s?void 0:s.size))return;t.ports[0].postMessage({status:"ack",eventId:n,eventType:r});const a=Array.from(s).map((async e=>e(t.origin,i))),o=await function(e){return Promise.all(e.map((async e=>{try{return{fulfilled:!0,value:await e}}catch(t){return{fulfilled:!1,reason:t}}})))}(a);t.ports[0].postMessage({status:"done",eventId:n,eventType:r,response:o})}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function Ni(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10,n="";for(let r=0;r<t;r++)n+=Math.floor(10*Math.random());return e+n}xi.receivers=[];class Ai{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:50;const r="undefined"!==typeof MessageChannel?new MessageChannel:null;if(!r)throw new Error("connection_unavailable");let i,s;return new Promise(((a,o)=>{const l=Ni("",20);r.port1.start();const c=setTimeout((()=>{o(new Error("unsupported_event"))}),n);s={messageChannel:r,onMessage(e){const t=e;if(t.data.eventId===l)switch(t.data.status){case"ack":clearTimeout(c),i=setTimeout((()=>{o(new Error("timeout"))}),3e3);break;case"done":clearTimeout(i),a(t.data.response);break;default:clearTimeout(c),clearTimeout(i),o(new Error("invalid_response"))}}},this.handlers.add(s),r.port1.addEventListener("message",s.onMessage),this.target.postMessage({eventType:e,eventId:l,data:t},[r.port2])})).finally((()=>{s&&this.removeMessageHandler(s)}))}}function Pi(){return window}function Ri(){return"undefined"!==typeof Pi().WorkerGlobalScope&&"function"===typeof Pi().importScripts}const Di="firebaseLocalStorageDb",Oi="firebaseLocalStorage",Li="fbase_key";class Mi{constructor(e){this.request=e}toPromise(){return new Promise(((e,t)=>{this.request.addEventListener("success",(()=>{e(this.request.result)})),this.request.addEventListener("error",(()=>{t(this.request.error)}))}))}}function ji(e,t){return e.transaction([Oi],t?"readwrite":"readonly").objectStore(Oi)}function Fi(){const e=indexedDB.open(Di,1);return new Promise(((t,n)=>{e.addEventListener("error",(()=>{n(e.error)})),e.addEventListener("upgradeneeded",(()=>{const t=e.result;try{t.createObjectStore(Oi,{keyPath:Li})}catch(r){n(r)}})),e.addEventListener("success",(async()=>{const n=e.result;n.objectStoreNames.contains(Oi)?t(n):(n.close(),await function(){const e=indexedDB.deleteDatabase(Di);return new Mi(e).toPromise()}(),t(await Fi()))}))}))}async function Ui(e,t,n){const r=ji(e,!0).put({[Li]:t,value:n});return new Mi(r).toPromise()}function Vi(e,t){const n=ji(e,!0).delete(t);return new Mi(n).toPromise()}class Bi{constructor(){this.type="LOCAL",this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then((()=>{}),(()=>{}))}async _openDb(){return this.db||(this.db=await Fi()),this.db}async _withRetries(e){let t=0;for(;;)try{const t=await this._openDb();return await e(t)}catch(n){if(t++>3)throw n;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return Ri()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=xi._getInstance(Ri()?self:null),this.receiver._subscribe("keyChanged",(async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)}))),this.receiver._subscribe("ping",(async(e,t)=>["keyChanged"]))}async initializeSender(){var e,t;if(this.activeServiceWorker=await async function(){if(!(null===navigator||void 0===navigator?void 0:navigator.serviceWorker))return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}}(),!this.activeServiceWorker)return;this.sender=new Ai(this.activeServiceWorker);const n=await this.sender._send("ping",{},800);n&&(null===(e=n[0])||void 0===e?void 0:e.fulfilled)&&(null===(t=n[0])||void 0===t?void 0:t.value.includes("keyChanged"))&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(this.sender&&this.activeServiceWorker&&function(){var e;return(null===(e=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===e?void 0:e.controller)||null}()===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(t){}}async _isAvailable(){try{if(!indexedDB)return!1;const e=await Fi();return await Ui(e,Ei,"1"),await Vi(e,Ei),!0}catch(e){}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite((async()=>(await this._withRetries((n=>Ui(n,e,t))),this.localCache[e]=t,this.notifyServiceWorker(e))))}async _get(e){const t=await this._withRetries((t=>async function(e,t){const n=ji(e,!1).get(t),r=await new Mi(n).toPromise();return void 0===r?null:r.value}(t,e)));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite((async()=>(await this._withRetries((t=>Vi(t,e))),delete this.localCache[e],this.notifyServiceWorker(e))))}async _poll(){const e=await this._withRetries((e=>{const t=ji(e,!1).getAll();return new Mi(t).toPromise()}));if(!e)return[];if(0!==this.pendingWrites)return[];const t=[],n=new Set;for(const{fbase_key:r,value:i}of e)n.add(r),JSON.stringify(this.localCache[r])!==JSON.stringify(i)&&(this.notifyListeners(r,i),t.push(r));for(const r of Object.keys(this.localCache))this.localCache[r]&&!n.has(r)&&(this.notifyListeners(r,null),t.push(r));return t}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n)for(const r of Array.from(n))r(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((async()=>this._poll()),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&this.stopPolling()}}Bi.type="LOCAL";const zi=Bi;Hr("rcb"),new Qn(3e4,6e4);const qi="recaptcha";async function Hi(e,t,n){var r;const i=await n.verify();try{let s;if(zn("string"===typeof i,e,"argument-error"),zn(n.type===qi,e,"argument-error"),s="string"===typeof t?{phoneNumber:t}:t,"session"in s){const t=s.session;if("phoneNumber"in s){zn("enroll"===t.type,e,"internal-error");const n=await function(e,t){return er(e,"POST","/v2/accounts/mfaEnrollment:start",Zn(e,t))}(e,{idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:s.phoneNumber,recaptchaToken:i}});return n.phoneSessionInfo.sessionInfo}{zn("signin"===t.type,e,"internal-error");const n=(null===(r=s.multiFactorHint)||void 0===r?void 0:r.uid)||s.multiFactorUid;zn(n,e,"missing-multi-factor-info");const a=await function(e,t){return er(e,"POST","/v2/accounts/mfaSignIn:start",Zn(e,t))}(e,{mfaPendingCredential:t.credential,mfaEnrollmentId:n,phoneSignInInfo:{recaptchaToken:i}});return a.phoneResponseInfo.sessionInfo}}{const{sessionInfo:t}=await async function(e,t){return er(e,"POST","/v1/accounts:sendVerificationCode",Zn(e,t))}(e,{phoneNumber:s.phoneNumber,recaptchaToken:i});return t}}finally{n._reset()}}class Wi{constructor(e){this.providerId=Wi.PROVIDER_ID,this.auth=Br(e)}verifyPhoneNumber(e,t){return Hi(this.auth,e,O(t))}static credential(e,t){return ii._fromVerification(e,t)}static credentialFromResult(e){const t=e;return Wi.credentialFromTaggedObject(t)}static credentialFromError(e){return Wi.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject(e){let{_tokenResponse:t}=e;if(!t)return null;const{phoneNumber:n,temporaryProof:r}=t;return n&&r?ii._fromTokenResponse(n,r):null}}function Ki(e,t){return t?_r(t):(zn(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}Wi.PROVIDER_ID="phone",Wi.PHONE_SIGN_IN_METHOD="phone";class Gi extends Xr{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return ti(e,this._buildIdpRequest())}_linkToIdToken(e,t){return ti(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return ti(e,this._buildIdpRequest())}_buildIdpRequest(e){const t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function Qi(e){return bi(e.auth,new Gi(e),e.bypassAuthState)}function $i(e){const{auth:t,user:n}=e;return zn(n,t,"internal-error"),wi(n,new Gi(e),e.bypassAuthState)}async function Yi(e){const{auth:t,user:n}=e;return zn(n,t,"internal-error"),yi(n,new Gi(e),e.bypassAuthState)}class Xi{constructor(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]&&arguments[4];this.auth=e,this.resolver=n,this.user=r,this.bypassAuthState=i,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise((async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(n){this.reject(n)}}))}async onAuthEvent(e){const{urlResponse:t,sessionId:n,postBody:r,tenantId:i,error:s,type:a}=e;if(s)return void this.reject(s);const o={auth:this.auth,requestUri:t,sessionId:n,tenantId:i||void 0,postBody:r||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(a)(o))}catch(l){this.reject(l)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return Qi;case"linkViaPopup":case"linkViaRedirect":return Yi;case"reauthViaPopup":case"reauthViaRedirect":return $i;default:Fn(this.auth,"internal-error")}}resolve(e){Hn(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){Hn(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}const Ji=new Qn(2e3,1e4);class Zi extends Xi{constructor(e,t,n,r,i){super(e,t,r,i),this.provider=n,this.authWindow=null,this.pollId=null,Zi.currentPopupAction&&Zi.currentPopupAction.cancel(),Zi.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return zn(e,this.auth,"internal-error"),e}async onExecution(){Hn(1===this.filter.length,"Popup operations only handle one event");const e=Ni();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch((e=>{this.reject(e)})),this.resolver._isIframeWebStorageSupported(this.auth,(e=>{e||this.reject(Un(this.auth,"web-storage-unsupported"))})),this.pollUserCancellation()}get eventId(){var e;return(null===(e=this.authWindow)||void 0===e?void 0:e.associatedEvent)||null}cancel(){this.reject(Un(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,Zi.currentPopupAction=null}pollUserCancellation(){const e=()=>{var t,n;(null===(n=null===(t=this.authWindow)||void 0===t?void 0:t.window)||void 0===n?void 0:n.closed)?this.pollId=window.setTimeout((()=>{this.pollId=null,this.reject(Un(this.auth,"popup-closed-by-user"))}),8e3):this.pollId=window.setTimeout(e,Ji.get())};e()}}Zi.currentPopupAction=null;const es="pendingRedirect",ts=new Map;class ns extends Xi{constructor(e,t){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,arguments.length>2&&void 0!==arguments[2]&&arguments[2]),this.eventId=null}async execute(){let e=ts.get(this.auth._key());if(!e){try{const t=await async function(e,t){const n=ss(t),r=is(e);if(!await r._isAvailable())return!1;const i="true"===await r._get(n);return await r._remove(n),i}(this.resolver,this.auth),n=t?await super.execute():null;e=()=>Promise.resolve(n)}catch(t){e=()=>Promise.reject(t)}ts.set(this.auth._key(),e)}return this.bypassAuthState||ts.set(this.auth._key(),(()=>Promise.resolve(null))),e()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"!==e.type){if(e.eventId){const t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}else this.resolve(null)}async onExecution(){}cleanUp(){}}function rs(e,t){ts.set(e._key(),t)}function is(e){return _r(e._redirectPersistence)}function ss(e){return kr(es,e.config.apiKey,e.name)}async function as(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const r=Br(e),i=Ki(r,t),s=new ns(r,i,n),a=await s.execute();return a&&!n&&(delete a.user._redirectEventId,await r._persistUserIfCurrent(a.user),await r._setRedirectUser(null,t)),a}class os{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(e){if(this.hasEventBeenHandled(e))return!1;let t=!1;return this.consumers.forEach((n=>{this.isEventForConsumer(e,n)&&(t=!0,this.sendToConsumer(e,n),this.saveEventToCache(e))})),this.hasHandledPotentialRedirect||!function(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return cs(e);default:return!1}}(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){var n;if(e.error&&!cs(e)){const r=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error";t.onError(Un(this.auth,r))}else t.onAuthEvent(e)}isEventForConsumer(e,t){const n=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=6e5&&this.cachedEventUids.clear(),this.cachedEventUids.has(ls(e))}saveEventToCache(e){this.cachedEventUids.add(ls(e)),this.lastProcessedEventTime=Date.now()}}function ls(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter((e=>e)).join("-")}function cs(e){let{type:t,error:n}=e;return"unknown"===t&&(null===n||void 0===n?void 0:n.code)==="auth/".concat("no-auth-event")}const us=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,hs=/^https?/;async function ds(e){if(e.config.emulator)return;const{authorizedDomains:t}=await async function(e){return er(e,"GET","/v1/projects",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}(e);for(const r of t)try{if(fs(r))return}catch(n){}Fn(e,"unauthorized-domain")}function fs(e){const t=Wn(),{protocol:n,hostname:r}=new URL(t);if(e.startsWith("chrome-extension://")){const i=new URL(e);return""===i.hostname&&""===r?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&i.hostname===r}if(!hs.test(n))return!1;if(us.test(e))return r===e;const i=e.replace(/\./g,"\\.");return new RegExp("^(.+\\."+i+"|"+i+")$","i").test(r)}const ps=new Qn(3e4,6e4);function ms(){const e=Pi().___jsl;if(null===e||void 0===e?void 0:e.H)for(const t of Object.keys(e.H))if(e.H[t].r=e.H[t].r||[],e.H[t].L=e.H[t].L||[],e.H[t].r=[...e.H[t].L],e.CP)for(let n=0;n<e.CP.length;n++)e.CP[n]=null}let gs=null;function vs(e){return gs=gs||function(e){return new Promise(((t,n)=>{var r,i,s;function a(){ms(),gapi.load("gapi.iframes",{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{ms(),n(Un(e,"network-request-failed"))},timeout:ps.get()})}if(null===(i=null===(r=Pi().gapi)||void 0===r?void 0:r.iframes)||void 0===i?void 0:i.Iframe)t(gapi.iframes.getContext());else{if(!(null===(s=Pi().gapi)||void 0===s?void 0:s.load)){const t=Hr("iframefcb");return Pi()[t]=()=>{gapi.load?a():n(Un(e,"network-request-failed"))},qr("https://apis.google.com/js/api.js?onload=".concat(t)).catch((e=>n(e)))}a()}})).catch((e=>{throw gs=null,e}))}(e),gs}const ys=new Qn(5e3,15e3),ws="__/auth/iframe",bs="emulator/auth/iframe",_s={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},Es=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function Ss(e){const t=e.config;zn(t.authDomain,e,"auth-domain-config-required");const n=t.emulator?$n(t,bs):"https://".concat(e.config.authDomain,"/").concat(ws),r={apiKey:t.apiKey,appName:e.name,v:Ee},i=Es.get(e.config.apiHost);i&&(r.eid=i);const s=e._getFrameworks();return s.length&&(r.fw=s.join(",")),"".concat(n,"?").concat(k(r).slice(1))}const ks={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class Is{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function Ts(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:500,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:600;const s=Math.max((window.screen.availHeight-i)/2,0).toString(),a=Math.max((window.screen.availWidth-r)/2,0).toString();let o="";const l=Object.assign(Object.assign({},ks),{width:r.toString(),height:i.toString(),top:s,left:a}),c=m().toLowerCase();n&&(o=Nr(c)?"_blank":n),Cr(c)&&(t=t||"http://localhost",l.scrollbars="yes");const u=Object.entries(l).reduce(((e,t)=>{let[n,r]=t;return"".concat(e).concat(n,"=").concat(r,",")}),"");if(function(){var e;return Or(arguments.length>0&&void 0!==arguments[0]?arguments[0]:m())&&!!(null===(e=window.navigator)||void 0===e?void 0:e.standalone)}(c)&&"_self"!==o)return function(e,t){const n=document.createElement("a");n.href=e,n.target=t;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(r)}(t||"",o),new Is(null);const h=window.open(t||"",o,u);zn(h,e,"popup-blocked");try{h.focus()}catch(d){}return new Is(h)}const Cs="__/auth/handler",xs="emulator/auth/handler",Ns=encodeURIComponent("fac");async function As(e,t,n,r,i,s){zn(e.config.authDomain,e,"auth-domain-config-required"),zn(e.config.apiKey,e,"invalid-api-key");const a={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:r,v:Ee,eventId:i};if(t instanceof oi){t.setDefaultLanguage(e.languageCode),a.providerId=t.providerId||"",function(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}(t.getCustomParameters())||(a.customParameters=JSON.stringify(t.getCustomParameters()));for(const[e,t]of Object.entries(s||{}))a[e]=t}if(t instanceof li){const e=t.getScopes().filter((e=>""!==e));e.length>0&&(a.scopes=e.join(","))}e.tenantId&&(a.tid=e.tenantId);const o=a;for(const u of Object.keys(o))void 0===o[u]&&delete o[u];const l=await e._getAppCheckToken(),c=l?"#".concat(Ns,"=").concat(encodeURIComponent(l)):"";return"".concat(function(e){let{config:t}=e;if(!t.emulator)return"https://".concat(t.authDomain,"/").concat(Cs);return $n(t,xs)}(e),"?").concat(k(o).slice(1)).concat(c)}const Ps="webStorageSupport";const Rs=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=Ci,this._completeRedirectFn=as,this._overrideRedirectResult=rs}async _openPopup(e,t,n,r){var i;Hn(null===(i=this.eventManagers[e._key()])||void 0===i?void 0:i.manager,"_initialize() not called before _openPopup()");return Ts(e,await As(e,t,n,Wn(),r),Ni())}async _openRedirect(e,t,n,r){await this._originValidation(e);return function(e){Pi().location.href=e}(await As(e,t,n,Wn(),r)),new Promise((()=>{}))}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:e,promise:n}=this.eventManagers[t];return e?Promise.resolve(e):(Hn(n,"If manager is not set, promise should be"),n)}const n=this.initAndGetManager(e);return this.eventManagers[t]={promise:n},n.catch((()=>{delete this.eventManagers[t]})),n}async initAndGetManager(e){const t=await async function(e){const t=await vs(e),n=Pi().gapi;return zn(n,e,"internal-error"),t.open({where:document.body,url:Ss(e),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:_s,dontclear:!0},(t=>new Promise((async(n,r)=>{await t.restyle({setHideOnLeave:!1});const i=Un(e,"network-request-failed"),s=Pi().setTimeout((()=>{r(i)}),ys.get());function a(){Pi().clearTimeout(s),n(t)}t.ping(a).then(a,(()=>{r(i)}))}))))}(e),n=new os(e);return t.register("authEvent",(t=>{zn(null===t||void 0===t?void 0:t.authEvent,e,"invalid-auth-event");return{status:n.onEvent(t.authEvent)?"ACK":"ERROR"}}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:n},this.iframes[e._key()]=t,n}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(Ps,{type:Ps},(n=>{var r;const i=null===(r=null===n||void 0===n?void 0:n[0])||void 0===r?void 0:r[Ps];void 0!==i&&t(!!i),Fn(e,"internal-error")}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=ds(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return Mr()||xr()||Or()}};var Ds="@firebase/auth",Os="1.4.0";class Ls{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),(null===(e=this.auth.currentUser)||void 0===e?void 0:e.uid)||null}async getToken(e){if(this.assertAuthConfigured(),await this.auth._initializationPromise,!this.auth.currentUser)return null;return{accessToken:await this.auth.currentUser.getIdToken(e)}}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const t=this.auth.onIdTokenChanged((t=>{e((null===t||void 0===t?void 0:t.stsTokenManager.accessToken)||null)}));this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){zn(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}const Ms=f("authIdTokenMaxAge")||300;let js=null;var Fs;Fs="Browser",ye(new L("auth",((e,t)=>{let{options:n}=t;const r=e.getProvider("app").getImmediate(),i=e.getProvider("heartbeat"),s=e.getProvider("app-check-internal"),{apiKey:a,authDomain:o}=r.options;zn(a&&!a.includes(":"),"invalid-api-key",{appName:r.name});const l={apiKey:a,authDomain:o,clientPlatform:Fs,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:jr(Fs)},c=new Vr(r,i,s,l);return function(e,t){const n=(null===t||void 0===t?void 0:t.persistence)||[],r=(Array.isArray(n)?n:[n]).map(_r);(null===t||void 0===t?void 0:t.errorMap)&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,null===t||void 0===t?void 0:t.popupRedirectResolver)}(c,n),c}),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,n)=>{e.getProvider("auth-internal").initialize()}))),ye(new L("auth-internal",(e=>(e=>new Ls(e))(Br(e.getProvider("auth").getImmediate()))),"PRIVATE").setInstantiationMode("EXPLICIT")),Ie(Ds,Os,function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";default:return}}(Fs)),Ie(Ds,Os,"esm2017");var Us,Vs="undefined"!==typeof globalThis?globalThis:"undefined"!==typeof window?window:"undefined"!==typeof global?global:"undefined"!==typeof self?self:{},Bs={},zs=zs||{},qs=Vs||self;function Hs(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function Ws(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var Ks="closure_uid_"+(1e9*Math.random()>>>0),Gs=0;function Qs(e,t,n){return e.call.apply(e.bind,arguments)}function $s(e,t,n){if(!e)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var n=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(n,r),e.apply(t,n)}}return function(){return e.apply(t,arguments)}}function Ys(e,t,n){return(Ys=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?Qs:$s).apply(null,arguments)}function Xs(e,t){var n=Array.prototype.slice.call(arguments,1);return function(){var t=n.slice();return t.push.apply(t,arguments),e.apply(this,t)}}function Js(e,t){function n(){}n.prototype=t.prototype,e.$=t.prototype,e.prototype=new n,e.prototype.constructor=e,e.ac=function(e,n,r){for(var i=Array(arguments.length-2),s=2;s<arguments.length;s++)i[s-2]=arguments[s];return t.prototype[n].apply(e,i)}}function Zs(){this.s=this.s,this.o=this.o}Zs.prototype.s=!1,Zs.prototype.sa=function(){var e;!this.s&&(this.s=!0,this.N(),0)&&(e=this,Object.prototype.hasOwnProperty.call(e,Ks)&&e[Ks]||(e[Ks]=++Gs))},Zs.prototype.N=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const ea=Array.prototype.indexOf?function(e,t){return Array.prototype.indexOf.call(e,t,void 0)}:function(e,t){if("string"===typeof e)return"string"!==typeof t||1!=t.length?-1:e.indexOf(t,0);for(let n=0;n<e.length;n++)if(n in e&&e[n]===t)return n;return-1};function ta(e){const t=e.length;if(0<t){const n=Array(t);for(let r=0;r<t;r++)n[r]=e[r];return n}return[]}function na(e,t){for(let n=1;n<arguments.length;n++){const t=arguments[n];if(Hs(t)){const n=e.length||0,r=t.length||0;e.length=n+r;for(let i=0;i<r;i++)e[n+i]=t[i]}else e.push(t)}}function ra(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}ra.prototype.h=function(){this.defaultPrevented=!0};var ia=function(){if(!qs.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{qs.addEventListener("test",(()=>{}),t),qs.removeEventListener("test",(()=>{}),t)}catch(n){}return e}();function sa(e){return/^[\s\xa0]*$/.test(e)}function aa(){var e=qs.navigator;return e&&(e=e.userAgent)?e:""}function oa(e){return-1!=aa().indexOf(e)}function la(e){return la[" "](e),e}la[" "]=function(){};var ca,ua,ha=oa("Opera"),da=oa("Trident")||oa("MSIE"),fa=oa("Edge"),pa=fa||da,ma=oa("Gecko")&&!(-1!=aa().toLowerCase().indexOf("webkit")&&!oa("Edge"))&&!(oa("Trident")||oa("MSIE"))&&!oa("Edge"),ga=-1!=aa().toLowerCase().indexOf("webkit")&&!oa("Edge");function va(){var e=qs.document;return e?e.documentMode:void 0}e:{var ya="",wa=function(){var e=aa();return ma?/rv:([^\);]+)(\)|;)/.exec(e):fa?/Edge\/([\d\.]+)/.exec(e):da?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(e):ga?/WebKit\/(\S+)/.exec(e):ha?/(?:Version)[ \/]?(\S+)/.exec(e):void 0}();if(wa&&(ya=wa?wa[1]:""),da){var ba=va();if(null!=ba&&ba>parseFloat(ya)){ca=String(ba);break e}}ca=ya}if(qs.document&&da){var _a=va();ua=_a||(parseInt(ca,10)||void 0)}else ua=void 0;var Ea=ua;function Sa(e,t){if(ra.call(this,e?e.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,e){var n=this.type=e.type,r=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(ma){e:{try{la(t.nodeName);var i=!0;break e}catch(s){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType="string"===typeof e.pointerType?e.pointerType:ka[e.pointerType]||"",this.state=e.state,this.i=e,e.defaultPrevented&&Sa.$.h.call(this)}}Js(Sa,ra);var ka={2:"touch",3:"pen",4:"mouse"};Sa.prototype.h=function(){Sa.$.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var Ia="closure_listenable_"+(1e6*Math.random()|0),Ta=0;function Ca(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.la=i,this.key=++Ta,this.fa=this.ia=!1}function xa(e){e.fa=!0,e.listener=null,e.proxy=null,e.src=null,e.la=null}function Na(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function Aa(e){const t={};for(const n in e)t[n]=e[n];return t}const Pa="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function Ra(e,t){let n,r;for(let i=1;i<arguments.length;i++){for(n in r=arguments[i],r)e[n]=r[n];for(let t=0;t<Pa.length;t++)n=Pa[t],Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}}function Da(e){this.src=e,this.g={},this.h=0}function Oa(e,t){var n=t.type;if(n in e.g){var r,i=e.g[n],s=ea(i,t);(r=0<=s)&&Array.prototype.splice.call(i,s,1),r&&(xa(t),0==e.g[n].length&&(delete e.g[n],e.h--))}}function La(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.fa&&s.listener==t&&s.capture==!!n&&s.la==r)return i}return-1}Da.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var a=La(e,t,r,i);return-1<a?(t=e[a],n||(t.ia=!1)):((t=new Ca(t,this.src,s,!!r,i)).ia=n,e.push(t)),t};var Ma="closure_lm_"+(1e6*Math.random()|0),ja={};function Fa(e,t,n,r,i){if(r&&r.once)return Va(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)Fa(e,t[s],n,r,i);return null}return n=Ga(n),e&&e[Ia]?e.O(t,n,Ws(r)?!!r.capture:!!r,i):Ua(e,t,n,!1,r,i)}function Ua(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var a=Ws(i)?!!i.capture:!!i,o=Wa(e);if(o||(e[Ma]=o=new Da(e)),(n=o.add(t,n,r,a,s)).proxy)return n;if(r=function(){function e(n){return t.call(e.src,e.listener,n)}const t=Ha;return e}(),n.proxy=r,r.src=e,r.listener=n,e.addEventListener)ia||(i=a),void 0===i&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(qa(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function Va(e,t,n,r,i){if(Array.isArray(t)){for(var s=0;s<t.length;s++)Va(e,t[s],n,r,i);return null}return n=Ga(n),e&&e[Ia]?e.P(t,n,Ws(r)?!!r.capture:!!r,i):Ua(e,t,n,!0,r,i)}function Ba(e,t,n,r,i){if(Array.isArray(t))for(var s=0;s<t.length;s++)Ba(e,t[s],n,r,i);else r=Ws(r)?!!r.capture:!!r,n=Ga(n),e&&e[Ia]?(e=e.i,(t=String(t).toString())in e.g&&(-1<(n=La(s=e.g[t],n,r,i))&&(xa(s[n]),Array.prototype.splice.call(s,n,1),0==s.length&&(delete e.g[t],e.h--)))):e&&(e=Wa(e))&&(t=e.g[t.toString()],e=-1,t&&(e=La(t,n,r,i)),(n=-1<e?t[e]:null)&&za(n))}function za(e){if("number"!==typeof e&&e&&!e.fa){var t=e.src;if(t&&t[Ia])Oa(t.i,e);else{var n=e.type,r=e.proxy;t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(qa(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=Wa(t))?(Oa(n,e),0==n.h&&(n.src=null,t[Ma]=null)):xa(e)}}}function qa(e){return e in ja?ja[e]:ja[e]="on"+e}function Ha(e,t){if(e.fa)e=!0;else{t=new Sa(t,this);var n=e.listener,r=e.la||e.src;e.ia&&za(e),e=n.call(r,t)}return e}function Wa(e){return(e=e[Ma])instanceof Da?e:null}var Ka="__closure_events_fn_"+(1e9*Math.random()>>>0);function Ga(e){return"function"===typeof e?e:(e[Ka]||(e[Ka]=function(t){return e.handleEvent(t)}),e[Ka])}function Qa(){Zs.call(this),this.i=new Da(this),this.S=this,this.J=null}function $a(e,t){var n,r=e.J;if(r)for(n=[];r;r=r.J)n.push(r);if(e=e.S,r=t.type||t,"string"===typeof t)t=new ra(t,e);else if(t instanceof ra)t.target=t.target||e;else{var i=t;Ra(t=new ra(r,e),i)}if(i=!0,n)for(var s=n.length-1;0<=s;s--){var a=t.g=n[s];i=Ya(a,r,!0,t)&&i}if(i=Ya(a=t.g=e,r,!0,t)&&i,i=Ya(a,r,!1,t)&&i,n)for(s=0;s<n.length;s++)i=Ya(a=t.g=n[s],r,!1,t)&&i}function Ya(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var i=!0,s=0;s<t.length;++s){var a=t[s];if(a&&!a.fa&&a.capture==n){var o=a.listener,l=a.la||a.src;a.ia&&Oa(e.i,a),i=!1!==o.call(l,r)&&i}}return i&&!r.defaultPrevented}Js(Qa,Zs),Qa.prototype[Ia]=!0,Qa.prototype.removeEventListener=function(e,t,n,r){Ba(this,e,t,n,r)},Qa.prototype.N=function(){if(Qa.$.N.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)xa(n[r]);delete t.g[e],t.h--}}this.J=null},Qa.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},Qa.prototype.P=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var Xa=qs.JSON.stringify;function Ja(){var e=so;let t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t}var Za=new class{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}((()=>new eo),(e=>e.reset()));class eo{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}function to(e){var t=1;e=e.split(":");const n=[];for(;0<t&&e.length;)n.push(e.shift()),t--;return e.length&&n.push(e.join(":")),n}function no(e){qs.setTimeout((()=>{throw e}),0)}let ro,io=!1,so=new class{constructor(){this.h=this.g=null}add(e,t){const n=Za.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}},ao=()=>{const e=qs.Promise.resolve(void 0);ro=()=>{e.then(oo)}};var oo=()=>{for(var e;e=Ja();){try{e.h.call(e.g)}catch(n){no(n)}var t=Za;t.j(e),100>t.h&&(t.h++,e.next=t.g,t.g=e)}io=!1};function lo(e,t){Qa.call(this),this.h=e||1,this.g=t||qs,this.j=Ys(this.qb,this),this.l=Date.now()}function co(e){e.ga=!1,e.T&&(e.g.clearTimeout(e.T),e.T=null)}function uo(e,t,n){if("function"===typeof e)n&&(e=Ys(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=Ys(e.handleEvent,e)}return 2147483647<Number(t)?-1:qs.setTimeout(e,t||0)}function ho(e){e.g=uo((()=>{e.g=null,e.i&&(e.i=!1,ho(e))}),e.j);const t=e.h;e.h=null,e.m.apply(null,t)}Js(lo,Qa),(Us=lo.prototype).ga=!1,Us.T=null,Us.qb=function(){if(this.ga){var e=Date.now()-this.l;0<e&&e<.8*this.h?this.T=this.g.setTimeout(this.j,this.h-e):(this.T&&(this.g.clearTimeout(this.T),this.T=null),$a(this,"tick"),this.ga&&(co(this),this.start()))}},Us.start=function(){this.ga=!0,this.T||(this.T=this.g.setTimeout(this.j,this.h),this.l=Date.now())},Us.N=function(){lo.$.N.call(this),co(this),delete this.g};class fo extends Zs{constructor(e,t){super(),this.m=e,this.j=t,this.h=null,this.i=!1,this.g=null}l(e){this.h=arguments,this.g?this.i=!0:ho(this)}N(){super.N(),this.g&&(qs.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function po(e){Zs.call(this),this.h=e,this.g={}}Js(po,Zs);var mo=[];function go(e,t,n,r){Array.isArray(n)||(n&&(mo[0]=n.toString()),n=mo);for(var i=0;i<n.length;i++){var s=Fa(t,n[i],r||e.handleEvent,!1,e.h||e);if(!s)break;e.g[s.key]=s}}function vo(e){Na(e.g,(function(e,t){this.g.hasOwnProperty(t)&&za(e)}),e),e.g={}}function yo(){this.g=!0}function wo(e,t,n,r){e.info((function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{var n=JSON.parse(t);if(n)for(e=0;e<n.length;e++)if(Array.isArray(n[e])){var r=n[e];if(!(2>r.length)){var i=r[1];if(Array.isArray(i)&&!(1>i.length)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var a=1;a<i.length;a++)i[a]=""}}}return Xa(n)}catch(o){return t}}(e,n)+(r?" "+r:"")}))}po.prototype.N=function(){po.$.N.call(this),vo(this)},po.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},yo.prototype.Ea=function(){this.g=!1},yo.prototype.info=function(){};var bo={},_o=null;function Eo(){return _o=_o||new Qa}function So(e){ra.call(this,bo.Ta,e)}function ko(e){const t=Eo();$a(t,new So(t))}function Io(e,t){ra.call(this,bo.STAT_EVENT,e),this.stat=t}function To(e){const t=Eo();$a(t,new Io(t,e))}function Co(e,t){ra.call(this,bo.Ua,e),this.size=t}function xo(e,t){if("function"!==typeof e)throw Error("Fn must not be null and must be a function");return qs.setTimeout((function(){e()}),t)}bo.Ta="serverreachability",Js(So,ra),bo.STAT_EVENT="statevent",Js(Io,ra),bo.Ua="timingevent",Js(Co,ra);var No={NO_ERROR:0,rb:1,Eb:2,Db:3,yb:4,Cb:5,Fb:6,Qa:7,TIMEOUT:8,Ib:9},Ao={wb:"complete",Sb:"success",Ra:"error",Qa:"abort",Kb:"ready",Lb:"readystatechange",TIMEOUT:"timeout",Gb:"incrementaldata",Jb:"progress",zb:"downloadprogress",$b:"uploadprogress"};function Po(){}function Ro(e){return e.h||(e.h=e.i())}function Do(){}Po.prototype.h=null;var Oo,Lo={OPEN:"a",vb:"b",Ra:"c",Hb:"d"};function Mo(){ra.call(this,"d")}function jo(){ra.call(this,"c")}function Fo(){}function Uo(e,t,n,r){this.l=e,this.j=t,this.m=n,this.W=r||1,this.U=new po(this),this.P=Bo,e=pa?125:void 0,this.V=new lo(e),this.I=null,this.i=!1,this.s=this.A=this.v=this.L=this.G=this.Y=this.B=null,this.F=[],this.g=null,this.C=0,this.o=this.u=null,this.ca=-1,this.J=!1,this.O=0,this.M=null,this.ba=this.K=this.aa=this.S=!1,this.h=new Vo}function Vo(){this.i=null,this.g="",this.h=!1}Js(Mo,ra),Js(jo,ra),Js(Fo,Po),Fo.prototype.g=function(){return new XMLHttpRequest},Fo.prototype.i=function(){return{}},Oo=new Fo;var Bo=45e3,zo={},qo={};function Ho(e,t,n){e.L=1,e.v=cl(il(t)),e.s=n,e.S=!0,Wo(e,null)}function Wo(e,t){e.G=Date.now(),$o(e),e.A=il(e.v);var n=e.A,r=e.W;Array.isArray(r)||(r=[String(r)]),El(n.i,"t",r),e.C=0,n=e.l.J,e.h=new Vo,e.g=Sc(e.l,n?t:null,!e.s),0<e.O&&(e.M=new fo(Ys(e.Pa,e,e.g),e.O)),go(e.U,e.g,"readystatechange",e.nb),t=e.I?Aa(e.I):{},e.s?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ha(e.A,e.u,e.s,t)):(e.u="GET",e.g.ha(e.A,e.u,null,t)),ko(),function(e,t,n,r,i,s){e.info((function(){if(e.g)if(s)for(var a="",o=s.split("&"),l=0;l<o.length;l++){var c=o[l].split("=");if(1<c.length){var u=c[0];c=c[1];var h=u.split("_");a=2<=h.length&&"type"==h[1]?a+(u+"=")+c+"&":a+(u+"=redacted&")}}else a=null;else a=s;return"XMLHTTP REQ ("+r+") [attempt "+i+"]: "+t+"\n"+n+"\n"+a}))}(e.j,e.u,e.A,e.m,e.W,e.s)}function Ko(e){return!!e.g&&("GET"==e.u&&2!=e.L&&e.l.Ha)}function Go(e,t,n){let r,i=!0;for(;!e.J&&e.C<n.length;){if(r=Qo(e,n),r==qo){4==t&&(e.o=4,To(14),i=!1),wo(e.j,e.m,null,"[Incomplete Response]");break}if(r==zo){e.o=4,To(15),wo(e.j,e.m,n,"[Invalid Chunk]"),i=!1;break}wo(e.j,e.m,r,null),el(e,r)}Ko(e)&&r!=qo&&r!=zo&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,To(16),i=!1),e.i=e.i&&i,i?0<n.length&&!e.ba&&(e.ba=!0,(t=e.l).g==e&&t.ca&&!t.M&&(t.l.info("Great, no buffering proxy detected. Bytes received: "+n.length),mc(t),t.M=!0,To(11))):(wo(e.j,e.m,n,"[Invalid Chunked Response]"),Zo(e),Jo(e))}function Qo(e,t){var n=e.C,r=t.indexOf("\n",n);return-1==r?qo:(n=Number(t.substring(n,r)),isNaN(n)?zo:(r+=1)+n>t.length?qo:(t=t.slice(r,r+n),e.C=r+n,t))}function $o(e){e.Y=Date.now()+e.P,Yo(e,e.P)}function Yo(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=xo(Ys(e.lb,e),t)}function Xo(e){e.B&&(qs.clearTimeout(e.B),e.B=null)}function Jo(e){0==e.l.H||e.J||yc(e.l,e)}function Zo(e){Xo(e);var t=e.M;t&&"function"==typeof t.sa&&t.sa(),e.M=null,co(e.V),vo(e.U),e.g&&(t=e.g,e.g=null,t.abort(),t.sa())}function el(e,t){try{var n=e.l;if(0!=n.H&&(n.g==e||Nl(n.i,e)))if(!e.K&&Nl(n.i,e)&&3==n.H){try{var r=n.Ja.g.parse(t)}catch(c){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.G+3e3<e.G))break e;vc(n),oc(n)}pc(n),To(18)}}else n.Fa=i[1],0<n.Fa-n.V&&37500>i[2]&&n.G&&0==n.A&&!n.v&&(n.v=xo(Ys(n.ib,n),6e3));if(1>=xl(n.i)&&n.oa){try{n.oa()}catch(c){}n.oa=void 0}}else bc(n,11)}else if((e.K||n.g==e)&&vc(n),!sa(t))for(i=n.Ja.g.parse(t),t=0;t<i.length;t++){let c=i[t];if(n.V=c[0],c=c[1],2==n.H)if("c"==c[0]){n.K=c[1],n.pa=c[2];const t=c[3];null!=t&&(n.ra=t,n.l.info("VER="+n.ra));const i=c[4];null!=i&&(n.Ga=i,n.l.info("SVER="+n.Ga));const u=c[5];null!=u&&"number"===typeof u&&0<u&&(r=1.5*u,n.L=r,n.l.info("backChannelRequestTimeoutMs_="+r)),r=n;const h=e.g;if(h){const e=h.g?h.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(e){var s=r.i;s.g||-1==e.indexOf("spdy")&&-1==e.indexOf("quic")&&-1==e.indexOf("h2")||(s.j=s.l,s.g=new Set,s.h&&(Al(s,s.h),s.h=null))}if(r.F){const e=h.g?h.g.getResponseHeader("X-HTTP-Session-Id"):null;e&&(r.Da=e,ll(r.I,r.F,e))}}n.H=3,n.h&&n.h.Ba(),n.ca&&(n.S=Date.now()-e.G,n.l.info("Handshake RTT: "+n.S+"ms"));var a=e;if((r=n).wa=Ec(r,r.J?r.pa:null,r.Y),a.K){Pl(r.i,a);var o=a,l=r.L;l&&o.setTimeout(l),o.B&&(Xo(o),$o(o)),r.g=a}else fc(r);0<n.j.length&&cc(n)}else"stop"!=c[0]&&"close"!=c[0]||bc(n,7);else 3==n.H&&("stop"==c[0]||"close"==c[0]?"stop"==c[0]?bc(n,7):ac(n):"noop"!=c[0]&&n.h&&n.h.Aa(c),n.A=0)}ko()}catch(c){}}function tl(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(Hs(e)||"string"===typeof e)Array.prototype.forEach.call(e,t,void 0);else for(var n=function(e){if(e.ta&&"function"==typeof e.ta)return e.ta();if(!e.Z||"function"!=typeof e.Z){if("undefined"!==typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!==typeof Set&&e instanceof Set)){if(Hs(e)||"string"===typeof e){var t=[];e=e.length;for(var n=0;n<e;n++)t.push(n);return t}t=[],n=0;for(const r in e)t[n++]=r;return t}}}(e),r=function(e){if(e.Z&&"function"==typeof e.Z)return e.Z();if("undefined"!==typeof Map&&e instanceof Map||"undefined"!==typeof Set&&e instanceof Set)return Array.from(e.values());if("string"===typeof e)return e.split("");if(Hs(e)){for(var t=[],n=e.length,r=0;r<n;r++)t.push(e[r]);return t}for(r in t=[],n=0,e)t[n++]=e[r];return t}(e),i=r.length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}(Us=Uo.prototype).setTimeout=function(e){this.P=e},Us.nb=function(e){e=e.target;const t=this.M;t&&3==ec(e)?t.l():this.Pa(e)},Us.Pa=function(e){try{if(e==this.g)e:{const u=ec(this.g);var t=this.g.Ia();this.g.da();if(!(3>u)&&(3!=u||pa||this.g&&(this.h.h||this.g.ja()||tc(this.g)))){this.J||4!=u||7==t||ko(),Xo(this);var n=this.g.da();this.ca=n;t:if(Ko(this)){var r=tc(this.g);e="";var i=r.length,s=4==ec(this.g);if(!this.h.i){if("undefined"===typeof TextDecoder){Zo(this),Jo(this);var a="";break t}this.h.i=new qs.TextDecoder}for(t=0;t<i;t++)this.h.h=!0,e+=this.h.i.decode(r[t],{stream:s&&t==i-1});r.splice(0,i),this.h.g+=e,this.C=0,a=this.h.g}else a=this.g.ja();if(this.i=200==n,function(e,t,n,r,i,s,a){e.info((function(){return"XMLHTTP RESP ("+r+") [ attempt "+i+"]: "+t+"\n"+n+"\n"+s+" "+a}))}(this.j,this.u,this.A,this.m,this.W,u,n),this.i){if(this.aa&&!this.K){t:{if(this.g){var o,l=this.g;if((o=l.g?l.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!sa(o)){var c=o;break t}}c=null}if(!(n=c)){this.i=!1,this.o=3,To(12),Zo(this),Jo(this);break e}wo(this.j,this.m,n,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,el(this,n)}this.S?(Go(this,u,a),pa&&this.i&&3==u&&(go(this.U,this.V,"tick",this.mb),this.V.start())):(wo(this.j,this.m,a,null),el(this,a)),4==u&&Zo(this),this.i&&!this.J&&(4==u?yc(this.l,this):(this.i=!1,$o(this)))}else(function(e){const t={};e=(e.g&&2<=ec(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let r=0;r<e.length;r++){if(sa(e[r]))continue;var n=to(e[r]);const i=n[0];if("string"!==typeof(n=n[1]))continue;n=n.trim();const s=t[i]||[];t[i]=s,s.push(n)}!function(e,t){for(const n in e)t.call(void 0,e[n],n,e)}(t,(function(e){return e.join(", ")}))})(this.g),400==n&&0<a.indexOf("Unknown SID")?(this.o=3,To(12)):(this.o=0,To(13)),Zo(this),Jo(this)}}}catch(u){}},Us.mb=function(){if(this.g){var e=ec(this.g),t=this.g.ja();this.C<t.length&&(Xo(this),Go(this,e,t),this.i&&4!=e&&$o(this))}},Us.cancel=function(){this.J=!0,Zo(this)},Us.lb=function(){this.B=null;const e=Date.now();0<=e-this.Y?(function(e,t){e.info((function(){return"TIMEOUT: "+t}))}(this.j,this.A),2!=this.L&&(ko(),To(17)),Zo(this),this.o=2,Jo(this)):Yo(this,this.Y-e)};var nl=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function rl(e){if(this.g=this.s=this.j="",this.m=null,this.o=this.l="",this.h=!1,e instanceof rl){this.h=e.h,sl(this,e.j),this.s=e.s,this.g=e.g,al(this,e.m),this.l=e.l;var t=e.i,n=new yl;n.i=t.i,t.g&&(n.g=new Map(t.g),n.h=t.h),ol(this,n),this.o=e.o}else e&&(t=String(e).match(nl))?(this.h=!1,sl(this,t[1]||"",!0),this.s=ul(t[2]||""),this.g=ul(t[3]||"",!0),al(this,t[4]),this.l=ul(t[5]||"",!0),ol(this,t[6]||"",!0),this.o=ul(t[7]||"")):(this.h=!1,this.i=new yl(null,this.h))}function il(e){return new rl(e)}function sl(e,t,n){e.j=n?ul(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function al(e,t){if(t){if(t=Number(t),isNaN(t)||0>t)throw Error("Bad port number "+t);e.m=t}else e.m=null}function ol(e,t,n){t instanceof yl?(e.i=t,function(e,t){t&&!e.j&&(wl(e),e.i=null,e.g.forEach((function(e,t){var n=t.toLowerCase();t!=n&&(bl(this,t),El(this,n,e))}),e)),e.j=t}(e.i,e.h)):(n||(t=hl(t,gl)),e.i=new yl(t,e.h))}function ll(e,t,n){e.i.set(t,n)}function cl(e){return ll(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function ul(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function hl(e,t,n){return"string"===typeof e?(e=encodeURI(e).replace(t,dl),n&&(e=e.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),e):null}function dl(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}rl.prototype.toString=function(){var e=[],t=this.j;t&&e.push(hl(t,fl,!0),":");var n=this.g;return(n||"file"==t)&&(e.push("//"),(t=this.s)&&e.push(hl(t,fl,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&e.push(":",String(n))),(n=this.l)&&(this.g&&"/"!=n.charAt(0)&&e.push("/"),e.push(hl(n,"/"==n.charAt(0)?ml:pl,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.o)&&e.push("#",hl(n,vl)),e.join("")};var fl=/[#\/\?@]/g,pl=/[#\?:]/g,ml=/[#\?]/g,gl=/[#\?@]/g,vl=/#/g;function yl(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function wl(e){e.g||(e.g=new Map,e.h=0,e.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r=e[n].indexOf("="),i=null;if(0<=r){var s=e[n].substring(0,r);i=e[n].substring(r+1)}else s=e[n];t(s,i?decodeURIComponent(i.replace(/\+/g," ")):"")}}}(e.i,(function(t,n){e.add(decodeURIComponent(t.replace(/\+/g," ")),n)})))}function bl(e,t){wl(e),t=Sl(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function _l(e,t){return wl(e),t=Sl(e,t),e.g.has(t)}function El(e,t,n){bl(e,t),0<n.length&&(e.i=null,e.g.set(Sl(e,t),ta(n)),e.h+=n.length)}function Sl(e,t){return t=String(t),e.j&&(t=t.toLowerCase()),t}(Us=yl.prototype).add=function(e,t){wl(this),this.i=null,e=Sl(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},Us.forEach=function(e,t){wl(this),this.g.forEach((function(n,r){n.forEach((function(n){e.call(t,n,r,this)}),this)}),this)},Us.ta=function(){wl(this);const e=Array.from(this.g.values()),t=Array.from(this.g.keys()),n=[];for(let r=0;r<t.length;r++){const i=e[r];for(let e=0;e<i.length;e++)n.push(t[r])}return n},Us.Z=function(e){wl(this);let t=[];if("string"===typeof e)_l(this,e)&&(t=t.concat(this.g.get(Sl(this,e))));else{e=Array.from(this.g.values());for(let n=0;n<e.length;n++)t=t.concat(e[n])}return t},Us.set=function(e,t){return wl(this),this.i=null,_l(this,e=Sl(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},Us.get=function(e,t){return e&&0<(e=this.Z(e)).length?String(e[0]):t},Us.toString=function(){if(this.i)return this.i;if(!this.g)return"";const e=[],t=Array.from(this.g.keys());for(var n=0;n<t.length;n++){var r=t[n];const s=encodeURIComponent(String(r)),a=this.Z(r);for(r=0;r<a.length;r++){var i=s;""!==a[r]&&(i+="="+encodeURIComponent(String(a[r]))),e.push(i)}}return this.i=e.join("&")};var kl=class{constructor(e,t){this.g=e,this.map=t}};function Il(e){this.l=e||Tl,qs.PerformanceNavigationTiming?e=0<(e=qs.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):e=!!(qs.g&&qs.g.Ka&&qs.g.Ka()&&qs.g.Ka().dc),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}var Tl=10;function Cl(e){return!!e.h||!!e.g&&e.g.size>=e.j}function xl(e){return e.h?1:e.g?e.g.size:0}function Nl(e,t){return e.h?e.h==t:!!e.g&&e.g.has(t)}function Al(e,t){e.g?e.g.add(t):e.h=t}function Pl(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function Rl(e){if(null!=e.h)return e.i.concat(e.h.F);if(null!=e.g&&0!==e.g.size){let t=e.i;for(const n of e.g.values())t=t.concat(n.F);return t}return ta(e.i)}Il.prototype.cancel=function(){if(this.i=Rl(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}};var Dl,Ol=class{stringify(e){return qs.JSON.stringify(e,void 0)}parse(e){return qs.JSON.parse(e,void 0)}};function Ll(){this.g=new Ol}function Ml(e,t,n){const r=n||"";try{tl(e,(function(e,n){let i=e;Ws(e)&&(i=Xa(e)),t.push(r+n+"="+encodeURIComponent(i))}))}catch(i){throw t.push(r+"type="+encodeURIComponent("_badmap")),i}}function jl(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(s){}}function Fl(e){this.l=e.ec||null,this.j=e.ob||!1}function Ul(e,t){Qa.call(this),this.F=e,this.u=t,this.m=void 0,this.readyState=Vl,this.status=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.v=new Headers,this.h=null,this.C="GET",this.B="",this.g=!1,this.A=this.j=this.l=null}Js(Fl,Po),Fl.prototype.g=function(){return new Ul(this.l,this.j)},Fl.prototype.i=(Dl={},function(){return Dl}),Js(Ul,Qa);var Vl=0;function Bl(e){e.j.read().then(e.Xa.bind(e)).catch(e.ka.bind(e))}function zl(e){e.readyState=4,e.l=null,e.j=null,e.A=null,ql(e)}function ql(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(Us=Ul.prototype).open=function(e,t){if(this.readyState!=Vl)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,ql(this)},Us.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.F||qs).fetch(new Request(this.B,t)).then(this.$a.bind(this),this.ka.bind(this))},Us.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch((()=>{})),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,zl(this)),this.readyState=Vl},Us.$a=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,ql(this)),this.g&&(this.readyState=3,ql(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ya.bind(this),this.ka.bind(this));else if("undefined"!==typeof qs.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.u){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.A=new TextDecoder;Bl(this)}else e.text().then(this.Za.bind(this),this.ka.bind(this))},Us.Xa=function(e){if(this.g){if(this.u&&e.value)this.response.push(e.value);else if(!this.u){var t=e.value?e.value:new Uint8Array(0);(t=this.A.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)}e.done?zl(this):ql(this),3==this.readyState&&Bl(this)}},Us.Za=function(e){this.g&&(this.response=this.responseText=e,zl(this))},Us.Ya=function(e){this.g&&(this.response=e,zl(this))},Us.ka=function(){this.g&&zl(this)},Us.setRequestHeader=function(e,t){this.v.append(e,t)},Us.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},Us.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(Ul.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var Hl=qs.JSON.parse;function Wl(e){Qa.call(this),this.headers=new Map,this.u=e||null,this.h=!1,this.C=this.g=null,this.I="",this.m=0,this.j="",this.l=this.G=this.v=this.F=!1,this.B=0,this.A=null,this.K=Kl,this.L=this.M=!1}Js(Wl,Qa);var Kl="",Gl=/^https?$/i,Ql=["POST","PUT"];function $l(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,Yl(e),Jl(e)}function Yl(e){e.F||(e.F=!0,$a(e,"complete"),$a(e,"error"))}function Xl(e){if(e.h&&"undefined"!=typeof zs&&(!e.C[1]||4!=ec(e)||2!=e.da()))if(e.v&&4==ec(e))uo(e.La,0,e);else if($a(e,"readystatechange"),4==ec(e)){e.h=!1;try{const o=e.da();e:switch(o){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var t=!0;break e;default:t=!1}var n;if(!(n=t)){var r;if(r=0===o){var i=String(e.I).match(nl)[1]||null;!i&&qs.self&&qs.self.location&&(i=qs.self.location.protocol.slice(0,-1)),r=!Gl.test(i?i.toLowerCase():"")}n=r}if(n)$a(e,"complete"),$a(e,"success");else{e.m=6;try{var s=2<ec(e)?e.g.statusText:""}catch(a){s=""}e.j=s+" ["+e.da()+"]",Yl(e)}}finally{Jl(e)}}}function Jl(e,t){if(e.g){Zl(e);const r=e.g,i=e.C[0]?()=>{}:null;e.g=null,e.C=null,t||$a(e,"ready");try{r.onreadystatechange=i}catch(n){}}}function Zl(e){e.g&&e.L&&(e.g.ontimeout=null),e.A&&(qs.clearTimeout(e.A),e.A=null)}function ec(e){return e.g?e.g.readyState:0}function tc(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.K){case Kl:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(lu){return null}}function nc(e){let t="";return Na(e,(function(e,n){t+=n,t+=":",t+=e,t+="\r\n"})),t}function rc(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=nc(n),"string"===typeof e?null!=n&&encodeURIComponent(String(n)):ll(e,t,n))}function ic(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function sc(e){this.Ga=0,this.j=[],this.l=new yo,this.pa=this.wa=this.I=this.Y=this.g=this.Da=this.F=this.na=this.o=this.U=this.s=null,this.fb=this.W=0,this.cb=ic("failFast",!1,e),this.G=this.v=this.u=this.m=this.h=null,this.aa=!0,this.Fa=this.V=-1,this.ba=this.A=this.C=0,this.ab=ic("baseRetryDelayMs",5e3,e),this.hb=ic("retryDelaySeedMs",1e4,e),this.eb=ic("forwardChannelMaxRetries",2,e),this.xa=ic("forwardChannelRequestTimeoutMs",2e4,e),this.va=e&&e.xmlHttpFactory||void 0,this.Ha=e&&e.useFetchStreams||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.i=new Il(e&&e.concurrentRequestLimit),this.Ja=new Ll,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.bb=e&&e.bc||!1,e&&e.Ea&&this.l.Ea(),e&&e.forceLongPolling&&(this.aa=!1),this.ca=!this.P&&this.aa&&e&&e.detectBufferingProxy||!1,this.qa=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.qa=e.longPollingTimeout),this.oa=void 0,this.S=0,this.M=!1,this.ma=this.B=null}function ac(e){if(lc(e),3==e.H){var t=e.W++,n=il(e.I);if(ll(n,"SID",e.K),ll(n,"RID",t),ll(n,"TYPE","terminate"),hc(e,n),(t=new Uo(e,e.l,t)).L=2,t.v=cl(il(n)),n=!1,qs.navigator&&qs.navigator.sendBeacon)try{n=qs.navigator.sendBeacon(t.v.toString(),"")}catch(r){}!n&&qs.Image&&((new Image).src=t.v,n=!0),n||(t.g=Sc(t.l,null),t.g.ha(t.v)),t.G=Date.now(),$o(t)}_c(e)}function oc(e){e.g&&(mc(e),e.g.cancel(),e.g=null)}function lc(e){oc(e),e.u&&(qs.clearTimeout(e.u),e.u=null),vc(e),e.i.cancel(),e.m&&("number"===typeof e.m&&qs.clearTimeout(e.m),e.m=null)}function cc(e){if(!Cl(e.i)&&!e.m){e.m=!0;var t=e.Na;ro||ao(),io||(ro(),io=!0),so.add(t,e),e.C=0}}function uc(e,t){var n;n=t?t.m:e.W++;const r=il(e.I);ll(r,"SID",e.K),ll(r,"RID",n),ll(r,"AID",e.V),hc(e,r),e.o&&e.s&&rc(r,e.o,e.s),n=new Uo(e,e.l,n,e.C+1),null===e.o&&(n.I=e.s),t&&(e.j=t.F.concat(e.j)),t=dc(e,n,1e3),n.setTimeout(Math.round(.5*e.xa)+Math.round(.5*e.xa*Math.random())),Al(e.i,n),Ho(n,r,t)}function hc(e,t){e.na&&Na(e.na,(function(e,n){ll(t,n,e)})),e.h&&tl({},(function(e,n){ll(t,n,e)}))}function dc(e,t,n){n=Math.min(e.j.length,n);var r=e.h?Ys(e.h.Va,e.h,e):null;e:{var i=e.j;let t=-1;for(;;){const e=["count="+n];-1==t?0<n?(t=i[0].g,e.push("ofs="+t)):t=0:e.push("ofs="+t);let a=!0;for(let o=0;o<n;o++){let n=i[o].g;const l=i[o].map;if(n-=t,0>n)t=Math.max(0,i[o].g-100),a=!1;else try{Ml(l,e,"req"+n+"_")}catch(s){r&&r(l)}}if(a){r=e.join("&");break e}}}return e=e.j.splice(0,n),t.F=e,r}function fc(e){if(!e.g&&!e.u){e.ba=1;var t=e.Ma;ro||ao(),io||(ro(),io=!0),so.add(t,e),e.A=0}}function pc(e){return!(e.g||e.u||3<=e.A)&&(e.ba++,e.u=xo(Ys(e.Ma,e),wc(e,e.A)),e.A++,!0)}function mc(e){null!=e.B&&(qs.clearTimeout(e.B),e.B=null)}function gc(e){e.g=new Uo(e,e.l,"rpc",e.ba),null===e.o&&(e.g.I=e.s),e.g.O=0;var t=il(e.wa);ll(t,"RID","rpc"),ll(t,"SID",e.K),ll(t,"AID",e.V),ll(t,"CI",e.G?"0":"1"),!e.G&&e.qa&&ll(t,"TO",e.qa),ll(t,"TYPE","xmlhttp"),hc(e,t),e.o&&e.s&&rc(t,e.o,e.s),e.L&&e.g.setTimeout(e.L);var n=e.g;e=e.pa,n.L=1,n.v=cl(il(t)),n.s=null,n.S=!0,Wo(n,e)}function vc(e){null!=e.v&&(qs.clearTimeout(e.v),e.v=null)}function yc(e,t){var n=null;if(e.g==t){vc(e),mc(e),e.g=null;var r=2}else{if(!Nl(e.i,t))return;n=t.F,Pl(e.i,t),r=1}if(0!=e.H)if(t.i)if(1==r){n=t.s?t.s.length:0,t=Date.now()-t.G;var i=e.C;$a(r=Eo(),new Co(r,n)),cc(e)}else fc(e);else if(3==(i=t.o)||0==i&&0<t.ca||!(1==r&&function(e,t){return!(xl(e.i)>=e.i.j-(e.m?1:0))&&(e.m?(e.j=t.F.concat(e.j),!0):!(1==e.H||2==e.H||e.C>=(e.cb?0:e.eb))&&(e.m=xo(Ys(e.Na,e,t),wc(e,e.C)),e.C++,!0))}(e,t)||2==r&&pc(e)))switch(n&&0<n.length&&(t=e.i,t.i=t.i.concat(n)),i){case 1:bc(e,5);break;case 4:bc(e,10);break;case 3:bc(e,6);break;default:bc(e,2)}}function wc(e,t){let n=e.ab+Math.floor(Math.random()*e.hb);return e.isActive()||(n*=2),n*t}function bc(e,t){if(e.l.info("Error code "+t),2==t){var n=null;e.h&&(n=null);var r=Ys(e.pb,e);n||(n=new rl("//www.google.com/images/cleardot.gif"),qs.location&&"http"==qs.location.protocol||sl(n,"https"),cl(n)),function(e,t){const n=new yo;if(qs.Image){const r=new Image;r.onload=Xs(jl,n,r,"TestLoadImage: loaded",!0,t),r.onerror=Xs(jl,n,r,"TestLoadImage: error",!1,t),r.onabort=Xs(jl,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=Xs(jl,n,r,"TestLoadImage: timeout",!1,t),qs.setTimeout((function(){r.ontimeout&&r.ontimeout()}),1e4),r.src=e}else t(!1)}(n.toString(),r)}else To(2);e.H=0,e.h&&e.h.za(t),_c(e),lc(e)}function _c(e){if(e.H=0,e.ma=[],e.h){const t=Rl(e.i);0==t.length&&0==e.j.length||(na(e.ma,t),na(e.ma,e.j),e.i.i.length=0,ta(e.j),e.j.length=0),e.h.ya()}}function Ec(e,t,n){var r=n instanceof rl?il(n):new rl(n);if(""!=r.g)t&&(r.g=t+"."+r.g),al(r,r.m);else{var i=qs.location;r=i.protocol,t=t?t+"."+i.hostname:i.hostname,i=+i.port;var s=new rl(null);r&&sl(s,r),t&&(s.g=t),i&&al(s,i),n&&(s.l=n),r=s}return n=e.F,t=e.Da,n&&t&&ll(r,n,t),ll(r,"VER",e.ra),hc(e,r),r}function Sc(e,t,n){if(t&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(t=n&&e.Ha&&!e.va?new Wl(new Fl({ob:!0})):new Wl(e.va)).Oa(e.J),t}function kc(){}function Ic(){if(da&&!(10<=Number(Ea)))throw Error("Environmental error: no available transport.")}function Tc(e,t){Qa.call(this),this.g=new sc(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.s=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.Ca&&(e?e["X-WebChannel-Client-Profile"]=t.Ca:e={"X-WebChannel-Client-Profile":t.Ca}),this.g.U=e,(e=t&&t.cc)&&!sa(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!sa(t)&&(this.g.F=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new Nc(this)}function Cc(e){Mo.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);var t=e.__sm__;if(t){e:{for(const n in t){e=n;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function xc(){jo.call(this),this.status=1}function Nc(e){this.g=e}function Ac(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.m=Array(this.blockSize),this.i=this.h=0,this.reset()}function Pc(e,t,n){n||(n=0);var r=Array(16);if("string"===typeof t)for(var i=0;16>i;++i)r[i]=t.charCodeAt(n++)|t.charCodeAt(n++)<<8|t.charCodeAt(n++)<<16|t.charCodeAt(n++)<<24;else for(i=0;16>i;++i)r[i]=t[n++]|t[n++]<<8|t[n++]<<16|t[n++]<<24;t=e.g[0],n=e.g[1],i=e.g[2];var s=e.g[3],a=t+(s^n&(i^s))+r[0]+3614090360&4294967295;a=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=n+(a<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[1]+3905402710&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[2]+606105819&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[3]+3250441966&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[4]+4118548399&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[5]+1200080426&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[6]+2821735955&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[7]+4249261313&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[8]+1770035416&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[9]+2336552879&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[10]+4294925233&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[11]+2304563134&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[12]+1804603682&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[13]+4254626195&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[14]+2792965006&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[15]+1236535329&4294967295)<<22&4294967295|a>>>10))+((a=t+(i^s&(n^i))+r[1]+4129170786&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[6]+3225465664&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[11]+643717713&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[0]+3921069994&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[5]+3593408605&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[10]+38016083&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[15]+3634488961&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[4]+3889429448&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[9]+568446438&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[14]+3275163606&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[3]+4107603335&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[8]+1163531501&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[13]+2850285829&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[2]+4243563512&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[7]+1735328473&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[12]+2368359562&4294967295)<<20&4294967295|a>>>12))+((a=t+(n^i^s)+r[5]+4294588738&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[8]+2272392833&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[11]+1839030562&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[14]+4259657740&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[1]+2763975236&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[4]+1272893353&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[7]+4139469664&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[10]+3200236656&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[13]+681279174&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[0]+3936430074&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[3]+3572445317&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[6]+76029189&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[9]+3654602809&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[12]+3873151461&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[15]+530742520&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[2]+3299628645&4294967295)<<23&4294967295|a>>>9))+((a=t+(i^(n|~s))+r[0]+4096336452&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[7]+1126891415&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[14]+2878612391&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[5]+4237533241&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[12]+1700485571&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[3]+2399980690&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[10]+4293915773&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[1]+2240044497&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[8]+1873313359&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[15]+4264355552&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[6]+2734768916&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[13]+1309151649&4294967295)<<21&4294967295|a>>>11))+((s=(t=n+((a=t+(i^(n|~s))+r[4]+4149444226&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[11]+3174756917&4294967295)<<10&4294967295|a>>>22))^((i=s+((a=i+(t^(s|~n))+r[2]+718787259&4294967295)<<15&4294967295|a>>>17))|~t))+r[9]+3951481745&4294967295,e.g[0]=e.g[0]+t&4294967295,e.g[1]=e.g[1]+(i+(a<<21&4294967295|a>>>11))&4294967295,e.g[2]=e.g[2]+i&4294967295,e.g[3]=e.g[3]+s&4294967295}function Rc(e,t){this.h=t;for(var n=[],r=!0,i=e.length-1;0<=i;i--){var s=0|e[i];r&&s==t||(n[i]=s,r=!1)}this.g=n}(Us=Wl.prototype).Oa=function(e){this.M=e},Us.ha=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.I+"; newUri="+e);t=t?t.toUpperCase():"GET",this.I=e,this.j="",this.m=0,this.F=!1,this.h=!0,this.g=this.u?this.u.g():Oo.g(),this.C=this.u?Ro(this.u):Ro(Oo),this.g.onreadystatechange=Ys(this.La,this);try{this.G=!0,this.g.open(t,String(e),!0),this.G=!1}catch(s){return void $l(this,s)}if(e=n||"",n=new Map(this.headers),r)if(Object.getPrototypeOf(r)===Object.prototype)for(var i in r)n.set(i,r[i]);else{if("function"!==typeof r.keys||"function"!==typeof r.get)throw Error("Unknown input type for opt_headers: "+String(r));for(const e of r.keys())n.set(e,r.get(e))}r=Array.from(n.keys()).find((e=>"content-type"==e.toLowerCase())),i=qs.FormData&&e instanceof qs.FormData,!(0<=ea(Ql,t))||r||i||n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(const[a,o]of n)this.g.setRequestHeader(a,o);this.K&&(this.g.responseType=this.K),"withCredentials"in this.g&&this.g.withCredentials!==this.M&&(this.g.withCredentials=this.M);try{Zl(this),0<this.B&&((this.L=function(e){return da&&"number"===typeof e.timeout&&void 0!==e.ontimeout}(this.g))?(this.g.timeout=this.B,this.g.ontimeout=Ys(this.ua,this)):this.A=uo(this.ua,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(s){$l(this,s)}},Us.ua=function(){"undefined"!=typeof zs&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,$a(this,"timeout"),this.abort(8))},Us.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,$a(this,"complete"),$a(this,"abort"),Jl(this))},Us.N=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),Jl(this,!0)),Wl.$.N.call(this)},Us.La=function(){this.s||(this.G||this.v||this.l?Xl(this):this.kb())},Us.kb=function(){Xl(this)},Us.isActive=function(){return!!this.g},Us.da=function(){try{return 2<ec(this)?this.g.status:-1}catch(Dl){return-1}},Us.ja=function(){try{return this.g?this.g.responseText:""}catch(Dl){return""}},Us.Wa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),Hl(t)}},Us.Ia=function(){return this.m},Us.Sa=function(){return"string"===typeof this.j?this.j:String(this.j)},(Us=sc.prototype).ra=8,Us.H=1,Us.Na=function(e){if(this.m)if(this.m=null,1==this.H){if(!e){this.W=Math.floor(1e5*Math.random()),e=this.W++;const i=new Uo(this,this.l,e);let s=this.s;if(this.U&&(s?(s=Aa(s),Ra(s,this.U)):s=this.U),null!==this.o||this.O||(i.I=s,s=null),this.P)e:{for(var t=0,n=0;n<this.j.length;n++){var r=this.j[n];if(void 0===(r="__data__"in r.map&&"string"===typeof(r=r.map.__data__)?r.length:void 0))break;if(4096<(t+=r)){t=n;break e}if(4096===t||n===this.j.length-1){t=n+1;break e}}t=1e3}else t=1e3;t=dc(this,i,t),ll(n=il(this.I),"RID",e),ll(n,"CVER",22),this.F&&ll(n,"X-HTTP-Session-Id",this.F),hc(this,n),s&&(this.O?t="headers="+encodeURIComponent(String(nc(s)))+"&"+t:this.o&&rc(n,this.o,s)),Al(this.i,i),this.bb&&ll(n,"TYPE","init"),this.P?(ll(n,"$req",t),ll(n,"SID","null"),i.aa=!0,Ho(i,n,null)):Ho(i,n,t),this.H=2}}else 3==this.H&&(e?uc(this,e):0==this.j.length||Cl(this.i)||uc(this))},Us.Ma=function(){if(this.u=null,gc(this),this.ca&&!(this.M||null==this.g||0>=this.S)){var e=2*this.S;this.l.info("BP detection timer enabled: "+e),this.B=xo(Ys(this.jb,this),e)}},Us.jb=function(){this.B&&(this.B=null,this.l.info("BP detection timeout reached."),this.l.info("Buffering proxy detected and switch to long-polling!"),this.G=!1,this.M=!0,To(10),oc(this),gc(this))},Us.ib=function(){null!=this.v&&(this.v=null,oc(this),pc(this),To(19))},Us.pb=function(e){e?(this.l.info("Successfully pinged google.com"),To(2)):(this.l.info("Failed to ping google.com"),To(1))},Us.isActive=function(){return!!this.h&&this.h.isActive(this)},(Us=kc.prototype).Ba=function(){},Us.Aa=function(){},Us.za=function(){},Us.ya=function(){},Us.isActive=function(){return!0},Us.Va=function(){},Ic.prototype.g=function(e,t){return new Tc(e,t)},Js(Tc,Qa),Tc.prototype.m=function(){this.g.h=this.j,this.A&&(this.g.J=!0);var e=this.g,t=this.l,n=this.h||void 0;To(0),e.Y=t,e.na=n||{},e.G=e.aa,e.I=Ec(e,null,e.Y),cc(e)},Tc.prototype.close=function(){ac(this.g)},Tc.prototype.u=function(e){var t=this.g;if("string"===typeof e){var n={};n.__data__=e,e=n}else this.v&&((n={}).__data__=Xa(e),e=n);t.j.push(new kl(t.fb++,e)),3==t.H&&cc(t)},Tc.prototype.N=function(){this.g.h=null,delete this.j,ac(this.g),delete this.g,Tc.$.N.call(this)},Js(Cc,Mo),Js(xc,jo),Js(Nc,kc),Nc.prototype.Ba=function(){$a(this.g,"a")},Nc.prototype.Aa=function(e){$a(this.g,new Cc(e))},Nc.prototype.za=function(e){$a(this.g,new xc)},Nc.prototype.ya=function(){$a(this.g,"b")},Js(Ac,(function(){this.blockSize=-1})),Ac.prototype.reset=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.i=this.h=0},Ac.prototype.j=function(e,t){void 0===t&&(t=e.length);for(var n=t-this.blockSize,r=this.m,i=this.h,s=0;s<t;){if(0==i)for(;s<=n;)Pc(this,e,s),s+=this.blockSize;if("string"===typeof e){for(;s<t;)if(r[i++]=e.charCodeAt(s++),i==this.blockSize){Pc(this,r),i=0;break}}else for(;s<t;)if(r[i++]=e[s++],i==this.blockSize){Pc(this,r),i=0;break}}this.h=i,this.i+=t},Ac.prototype.l=function(){var e=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var t=1;t<e.length-8;++t)e[t]=0;var n=8*this.i;for(t=e.length-8;t<e.length;++t)e[t]=255&n,n/=256;for(this.j(e),e=Array(16),t=n=0;4>t;++t)for(var r=0;32>r;r+=8)e[n++]=this.g[t]>>>r&255;return e};var Dc={};function Oc(e){return-128<=e&&128>e?function(e,t){var n=Dc;return Object.prototype.hasOwnProperty.call(n,e)?n[e]:n[e]=t(e)}(e,(function(e){return new Rc([0|e],0>e?-1:0)})):new Rc([0|e],0>e?-1:0)}function Lc(e){if(isNaN(e)||!isFinite(e))return jc;if(0>e)return zc(Lc(-e));for(var t=[],n=1,r=0;e>=n;r++)t[r]=e/n|0,n*=Mc;return new Rc(t,0)}var Mc=4294967296,jc=Oc(0),Fc=Oc(1),Uc=Oc(16777216);function Vc(e){if(0!=e.h)return!1;for(var t=0;t<e.g.length;t++)if(0!=e.g[t])return!1;return!0}function Bc(e){return-1==e.h}function zc(e){for(var t=e.g.length,n=[],r=0;r<t;r++)n[r]=~e.g[r];return new Rc(n,~e.h).add(Fc)}function qc(e,t){return e.add(zc(t))}function Hc(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function Wc(e,t){this.g=e,this.h=t}function Kc(e,t){if(Vc(t))throw Error("division by zero");if(Vc(e))return new Wc(jc,jc);if(Bc(e))return t=Kc(zc(e),t),new Wc(zc(t.g),zc(t.h));if(Bc(t))return t=Kc(e,zc(t)),new Wc(zc(t.g),t.h);if(30<e.g.length){if(Bc(e)||Bc(t))throw Error("slowDivide_ only works with positive integers.");for(var n=Fc,r=t;0>=r.X(e);)n=Gc(n),r=Gc(r);var i=Qc(n,1),s=Qc(r,1);for(r=Qc(r,2),n=Qc(n,2);!Vc(r);){var a=s.add(r);0>=a.X(e)&&(i=i.add(n),s=a),r=Qc(r,1),n=Qc(n,1)}return t=qc(e,i.R(t)),new Wc(i,t)}for(i=jc;0<=e.X(t);){for(n=Math.max(1,Math.floor(e.ea()/t.ea())),r=48>=(r=Math.ceil(Math.log(n)/Math.LN2))?1:Math.pow(2,r-48),a=(s=Lc(n)).R(t);Bc(a)||0<a.X(e);)a=(s=Lc(n-=r)).R(t);Vc(s)&&(s=Fc),i=i.add(s),e=qc(e,a)}return new Wc(i,e)}function Gc(e){for(var t=e.g.length+1,n=[],r=0;r<t;r++)n[r]=e.D(r)<<1|e.D(r-1)>>>31;return new Rc(n,e.h)}function Qc(e,t){var n=t>>5;t%=32;for(var r=e.g.length-n,i=[],s=0;s<r;s++)i[s]=0<t?e.D(s+n)>>>t|e.D(s+n+1)<<32-t:e.D(s+n);return new Rc(i,e.h)}(Us=Rc.prototype).ea=function(){if(Bc(this))return-zc(this).ea();for(var e=0,t=1,n=0;n<this.g.length;n++){var r=this.D(n);e+=(0<=r?r:Mc+r)*t,t*=Mc}return e},Us.toString=function(e){if(2>(e=e||10)||36<e)throw Error("radix out of range: "+e);if(Vc(this))return"0";if(Bc(this))return"-"+zc(this).toString(e);for(var t=Lc(Math.pow(e,6)),n=this,r="";;){var i=Kc(n,t).g,s=((0<(n=qc(n,i.R(t))).g.length?n.g[0]:n.h)>>>0).toString(e);if(Vc(n=i))return s+r;for(;6>s.length;)s="0"+s;r=s+r}},Us.D=function(e){return 0>e?0:e<this.g.length?this.g[e]:this.h},Us.X=function(e){return Bc(e=qc(this,e))?-1:Vc(e)?0:1},Us.abs=function(){return Bc(this)?zc(this):this},Us.add=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0,i=0;i<=t;i++){var s=r+(65535&this.D(i))+(65535&e.D(i)),a=(s>>>16)+(this.D(i)>>>16)+(e.D(i)>>>16);r=a>>>16,s&=65535,a&=65535,n[i]=a<<16|s}return new Rc(n,-2147483648&n[n.length-1]?-1:0)},Us.R=function(e){if(Vc(this)||Vc(e))return jc;if(Bc(this))return Bc(e)?zc(this).R(zc(e)):zc(zc(this).R(e));if(Bc(e))return zc(this.R(zc(e)));if(0>this.X(Uc)&&0>e.X(Uc))return Lc(this.ea()*e.ea());for(var t=this.g.length+e.g.length,n=[],r=0;r<2*t;r++)n[r]=0;for(r=0;r<this.g.length;r++)for(var i=0;i<e.g.length;i++){var s=this.D(r)>>>16,a=65535&this.D(r),o=e.D(i)>>>16,l=65535&e.D(i);n[2*r+2*i]+=a*l,Hc(n,2*r+2*i),n[2*r+2*i+1]+=s*l,Hc(n,2*r+2*i+1),n[2*r+2*i+1]+=a*o,Hc(n,2*r+2*i+1),n[2*r+2*i+2]+=s*o,Hc(n,2*r+2*i+2)}for(r=0;r<t;r++)n[r]=n[2*r+1]<<16|n[2*r];for(r=t;r<2*t;r++)n[r]=0;return new Rc(n,0)},Us.gb=function(e){return Kc(this,e).h},Us.and=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)&e.D(r);return new Rc(n,this.h&e.h)},Us.or=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)|e.D(r);return new Rc(n,this.h|e.h)},Us.xor=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)^e.D(r);return new Rc(n,this.h^e.h)},Ic.prototype.createWebChannel=Ic.prototype.g,Tc.prototype.send=Tc.prototype.u,Tc.prototype.open=Tc.prototype.m,Tc.prototype.close=Tc.prototype.close,No.NO_ERROR=0,No.TIMEOUT=8,No.HTTP_ERROR=6,Ao.COMPLETE="complete",Do.EventType=Lo,Lo.OPEN="a",Lo.CLOSE="b",Lo.ERROR="c",Lo.MESSAGE="d",Qa.prototype.listen=Qa.prototype.O,Wl.prototype.listenOnce=Wl.prototype.P,Wl.prototype.getLastError=Wl.prototype.Sa,Wl.prototype.getLastErrorCode=Wl.prototype.Ia,Wl.prototype.getStatus=Wl.prototype.da,Wl.prototype.getResponseJson=Wl.prototype.Wa,Wl.prototype.getResponseText=Wl.prototype.ja,Wl.prototype.send=Wl.prototype.ha,Wl.prototype.setWithCredentials=Wl.prototype.Oa,Ac.prototype.digest=Ac.prototype.l,Ac.prototype.reset=Ac.prototype.reset,Ac.prototype.update=Ac.prototype.j,Rc.prototype.add=Rc.prototype.add,Rc.prototype.multiply=Rc.prototype.R,Rc.prototype.modulo=Rc.prototype.gb,Rc.prototype.compare=Rc.prototype.X,Rc.prototype.toNumber=Rc.prototype.ea,Rc.prototype.toString=Rc.prototype.toString,Rc.prototype.getBits=Rc.prototype.D,Rc.fromNumber=Lc,Rc.fromString=function e(t,n){if(0==t.length)throw Error("number format error: empty string");if(2>(n=n||10)||36<n)throw Error("radix out of range: "+n);if("-"==t.charAt(0))return zc(e(t.substring(1),n));if(0<=t.indexOf("-"))throw Error('number format error: interior "-" character');for(var r=Lc(Math.pow(n,8)),i=jc,s=0;s<t.length;s+=8){var a=Math.min(8,t.length-s),o=parseInt(t.substring(s,s+a),n);8>a?(a=Lc(Math.pow(n,a)),i=i.R(a).add(Lc(o))):i=(i=i.R(r)).add(Lc(o))}return i};var $c=Bs.createWebChannelTransport=function(){return new Ic},Yc=Bs.getStatEventTarget=function(){return Eo()},Xc=Bs.ErrorCode=No,Jc=Bs.EventType=Ao,Zc=Bs.Event=bo,eu=Bs.Stat={xb:0,Ab:1,Bb:2,Ub:3,Zb:4,Wb:5,Xb:6,Vb:7,Tb:8,Yb:9,PROXY:10,NOPROXY:11,Rb:12,Nb:13,Ob:14,Mb:15,Pb:16,Qb:17,tb:18,sb:19,ub:20},tu=Bs.FetchXmlHttpFactory=Fl,nu=Bs.WebChannel=Do,ru=Bs.XhrIo=Wl,iu=Bs.Md5=Ac,su=Bs.Integer=Rc;const au="@firebase/firestore";class ou{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}ou.UNAUTHENTICATED=new ou(null),ou.GOOGLE_CREDENTIALS=new ou("google-credentials-uid"),ou.FIRST_PARTY=new ou("first-party-uid"),ou.MOCK_USER=new ou("mock-user");let lu="10.5.2";const cu=new W("@firebase/firestore");function uu(){return cu.logLevel}function hu(e){if(cu.logLevel<=V.DEBUG){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];const i=n.map(pu);cu.debug("Firestore (".concat(lu,"): ").concat(e),...i)}}function du(e){if(cu.logLevel<=V.ERROR){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];const i=n.map(pu);cu.error("Firestore (".concat(lu,"): ").concat(e),...i)}}function fu(e){if(cu.logLevel<=V.WARN){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];const i=n.map(pu);cu.warn("Firestore (".concat(lu,"): ").concat(e),...i)}}function pu(e){if("string"==typeof e)return e;try{return function(e){return JSON.stringify(e)}(e)}catch(t){return e}}function mu(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unexpected state";const t="FIRESTORE (".concat(lu,") INTERNAL ASSERTION FAILED: ")+e;throw du(t),new Error(t)}function gu(e,t){e||mu()}function vu(e,t){return e}const yu={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class wu extends w{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>"".concat(this.name,": [code=").concat(this.code,"]: ").concat(this.message)}}class bu{constructor(){this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}class _u{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization","Bearer ".concat(e))}}class Eu{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable((()=>t(ou.UNAUTHENTICATED)))}shutdown(){}}class Su{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable((()=>t(this.token.user)))}shutdown(){this.changeListener=null}}class ku{constructor(e){this.t=e,this.currentUser=ou.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){let n=this.i;const r=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve();let i=new bu;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new bu,e.enqueueRetryable((()=>r(this.currentUser)))};const s=()=>{const t=i;e.enqueueRetryable((async()=>{await t.promise,await r(this.currentUser)}))},a=e=>{hu("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),s()};this.t.onInit((e=>a(e))),setTimeout((()=>{if(!this.auth){const e=this.t.getImmediate({optional:!0});e?a(e):(hu("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new bu)}}),0),s()}getToken(){const e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then((t=>this.i!==e?(hu("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(gu("string"==typeof t.accessToken),new _u(t.accessToken,this.currentUser)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){const e=this.auth&&this.auth.getUid();return gu(null===e||"string"==typeof e),new ou(e)}}class Iu{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=ou.FIRST_PARTY,this.I=new Map}T(){return this.P?this.P():null}get headers(){this.I.set("X-Goog-AuthUser",this.l);const e=this.T();return e&&this.I.set("Authorization",e),this.h&&this.I.set("X-Goog-Iam-Authorization-Token",this.h),this.I}}class Tu{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new Iu(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable((()=>t(ou.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class Cu{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class xu{constructor(e){this.A=e,this.forceRefresh=!1,this.appCheck=null,this.R=null}start(e,t){const n=e=>{null!=e.error&&hu("FirebaseAppCheckTokenProvider","Error getting App Check token; using placeholder token instead. Error: ".concat(e.error.message));const n=e.token!==this.R;return this.R=e.token,hu("FirebaseAppCheckTokenProvider","Received ".concat(n?"new":"existing"," token.")),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable((()=>n(t)))};const r=e=>{hu("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.A.onInit((e=>r(e))),setTimeout((()=>{if(!this.appCheck){const e=this.A.getImmediate({optional:!0});e?r(e):hu("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}}),0)}getToken(){const e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then((e=>e?(gu("string"==typeof e.token),this.R=e.token,new Cu(e.token)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}function Nu(e){const t="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(e);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(n);else for(let r=0;r<e;r++)n[r]=Math.floor(256*Math.random());return n}class Au{static newId(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=62*Math.floor(256/62);let n="";for(;n.length<20;){const r=Nu(40);for(let i=0;i<r.length;++i)n.length<20&&r[i]<t&&(n+=e.charAt(r[i]%62))}return n}}function Pu(e,t){return e<t?-1:e>t?1:0}function Ru(e,t,n){return e.length===t.length&&e.every(((e,r)=>n(e,t[r])))}class Du{constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new wu(yu.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new wu(yu.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new wu(yu.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new wu(yu.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return Du.fromMillis(Date.now())}static fromDate(e){return Du.fromMillis(e.getTime())}static fromMillis(e){const t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new Du(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Pu(this.nanoseconds,e.nanoseconds):Pu(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class Ou{constructor(e){this.timestamp=e}static fromTimestamp(e){return new Ou(e)}static min(){return new Ou(new Du(0,0))}static max(){return new Ou(new Du(253402300799,999999999))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}class Lu{constructor(e,t,n){void 0===t?t=0:t>e.length&&mu(),void 0===n?n=e.length-t:n>e.length-t&&mu(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===Lu.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof Lu?e.forEach((e=>{t.push(e)})):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return e=void 0===e?1:e,this.construct(this.segments,this.offset+e,this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),i=t.get(r);if(n<i)return-1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class Mu extends Lu{construct(e,t,n){return new Mu(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(){const e=[];for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];for(const i of n){if(i.indexOf("//")>=0)throw new wu(yu.INVALID_ARGUMENT,"Invalid segment (".concat(i,"). Paths must not contain // in them."));e.push(...i.split("/").filter((e=>e.length>0)))}return new Mu(e)}static emptyPath(){return new Mu([])}}const ju=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class Fu extends Lu{construct(e,t,n){return new Fu(e,t,n)}static isValidIdentifier(e){return ju.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),Fu.isValidIdentifier(e)||(e="`"+e+"`"),e))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new Fu(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;const i=()=>{if(0===n.length)throw new wu(yu.INVALID_ARGUMENT,"Invalid field path (".concat(e,"). Paths must not be empty, begin with '.', end with '.', or contain '..'"));t.push(n),n=""};let s=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new wu(yu.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new wu(yu.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?(s=!s,r++):"."!==t||s?(n+=t,r++):(i(),r++)}if(i(),s)throw new wu(yu.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new Fu(t)}static emptyPath(){return new Fu([])}}class Uu{constructor(e){this.path=e}static fromPath(e){return new Uu(Mu.fromString(e))}static fromName(e){return new Uu(Mu.fromString(e).popFirst(5))}static empty(){return new Uu(Mu.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return this.path.length>=2&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===Mu.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return Mu.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new Uu(new Mu(e.slice()))}}class Vu{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}Vu.UNKNOWN_ID=-1;function Bu(e,t){const n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,i=Ou.fromTimestamp(1e9===r?new Du(n+1,0):new Du(n,r));return new qu(i,Uu.empty(),t)}function zu(e){return new qu(e.readTime,e.key,-1)}class qu{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new qu(Ou.min(),Uu.empty(),-1)}static max(){return new qu(Ou.max(),Uu.empty(),-1)}}function Hu(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=Uu.comparator(e.documentKey,t.documentKey),0!==n?n:Pu(e.largestBatchId,t.largestBatchId))}const Wu="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class Ku{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach((e=>e()))}}async function Gu(e){if(e.code!==yu.FAILED_PRECONDITION||e.message!==Wu)throw e;hu("LocalStore","Unexpectedly lost primary lease")}class Qu{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e((e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)}),(e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)}))}catch(e){return this.next(void 0,e)}next(e,t){return this.callbackAttached&&mu(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new Qu(((n,r)=>{this.nextCallback=t=>{this.wrapSuccess(e,t).next(n,r)},this.catchCallback=e=>{this.wrapFailure(t,e).next(n,r)}}))}toPromise(){return new Promise(((e,t)=>{this.next(e,t)}))}wrapUserFunction(e){try{const t=e();return t instanceof Qu?t:Qu.resolve(t)}catch(e){return Qu.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction((()=>e(t))):Qu.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction((()=>e(t))):Qu.reject(t)}static resolve(e){return new Qu(((t,n)=>{t(e)}))}static reject(e){return new Qu(((t,n)=>{n(e)}))}static waitFor(e){return new Qu(((t,n)=>{let r=0,i=0,s=!1;e.forEach((e=>{++r,e.next((()=>{++i,s&&i===r&&t()}),(e=>n(e)))})),s=!0,i===r&&t()}))}static or(e){let t=Qu.resolve(!1);for(const n of e)t=t.next((e=>e?Qu.resolve(e):n()));return t}static forEach(e,t){const n=[];return e.forEach(((e,r)=>{n.push(t.call(this,e,r))})),this.waitFor(n)}static mapArray(e,t){return new Qu(((n,r)=>{const i=e.length,s=new Array(i);let a=0;for(let o=0;o<i;o++){const l=o;t(e[l]).next((e=>{s[l]=e,++a,a===i&&n(s)}),(e=>r(e)))}}))}static doWhile(e,t){return new Qu(((n,r)=>{const i=()=>{!0===e()?t().next((()=>{i()}),r):n()};i()}))}}function $u(e){return"IndexedDbTransactionError"===e.name}class Yu{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.se(e),this.oe=e=>t.writeSequenceNumber(e))}se(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){const e=++this.previousValue;return this.oe&&this.oe(e),e}}function Xu(e){return null==e}function Ju(e){return 0===e&&1/e==-1/0}function Zu(e){return"number"==typeof e&&Number.isInteger(e)&&!Ju(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}Yu._e=-1;const eh=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],th=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],nh=th;function rh(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function ih(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function sh(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class ah{constructor(e,t){this.comparator=e,this.root=t||lh.EMPTY}insert(e,t){return new ah(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,lh.BLACK,null,null))}remove(e){return new ah(this.comparator,this.root.remove(e,this.comparator).copy(null,null,lh.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){const n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:n>0&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){const r=this.comparator(e,n.key);if(0===r)return t+n.left.size;r<0?n=n.left:(t+=n.left.size+1,n=n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal(((t,n)=>(e(t,n),!1)))}toString(){const e=[];return this.inorderTraversal(((t,n)=>(e.push("".concat(t,":").concat(n)),!1))),"{".concat(e.join(", "),"}")}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new oh(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new oh(this.root,e,this.comparator,!1)}getReverseIterator(){return new oh(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new oh(this.root,e,this.comparator,!0)}}class oh{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();const t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;const e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class lh{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:lh.RED,this.left=null!=r?r:lh.EMPTY,this.right=null!=i?i:lh.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new lh(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;const i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return lh.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return lh.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){const e=this.copy(null,null,lh.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,lh.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){const e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw mu();if(this.right.isRed())throw mu();const e=this.left.check();if(e!==this.right.check())throw mu();return e+(this.isRed()?0:1)}}lh.EMPTY=null,lh.RED=!0,lh.BLACK=!1,lh.EMPTY=new class{constructor(){this.size=0}get key(){throw mu()}get value(){throw mu()}get color(){throw mu()}get left(){throw mu()}get right(){throw mu()}copy(e,t,n,r,i){return this}insert(e,t,n){return new lh(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class ch{constructor(e){this.comparator=e,this.data=new ah(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(e){this.data.inorderTraversal(((t,n)=>(e(t),!1)))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){const r=n.getNext();if(this.comparator(r.key,e[1])>=0)return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new uh(this.data.getIterator())}getIteratorFrom(e){return new uh(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach((e=>{t=t.add(e)})),t}isEqual(e){if(!(e instanceof ch))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const e=[];return this.forEach((t=>{e.push(t)})),e}toString(){const e=[];return this.forEach((t=>e.push(t))),"SortedSet("+e.toString()+")"}copy(e){const t=new ch(this.comparator);return t.data=e,t}}class uh{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}class hh{constructor(e){this.fields=e,e.sort(Fu.comparator)}static empty(){return new hh([])}unionWith(e){let t=new ch(Fu.comparator);for(const n of this.fields)t=t.add(n);for(const n of e)t=t.add(n);return new hh(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Ru(this.fields,e.fields,((e,t)=>e.isEqual(t)))}}class dh extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class fh{constructor(e){this.binaryString=e}static fromBase64String(e){const t=function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new dh("Invalid base64 string: "+e):e}}(e);return new fh(t)}static fromUint8Array(e){const t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new fh(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return Pu(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}fh.EMPTY_BYTE_STRING=new fh("");const ph=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function mh(e){if(gu(!!e),"string"==typeof e){let t=0;const n=ph.exec(e);if(gu(!!n),n[1]){let e=n[1];e=(e+"000000000").substr(0,9),t=Number(e)}const r=new Date(e);return{seconds:Math.floor(r.getTime()/1e3),nanos:t}}return{seconds:gh(e.seconds),nanos:gh(e.nanos)}}function gh(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function vh(e){return"string"==typeof e?fh.fromBase64String(e):fh.fromUint8Array(e)}function yh(e){var t,n;return"server_timestamp"===(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===n?void 0:n.stringValue)}function wh(e){const t=e.mapValue.fields.__previous_value__;return yh(t)?wh(t):t}function bh(e){const t=mh(e.mapValue.fields.__local_write_time__.timestampValue);return new Du(t.seconds,t.nanos)}class _h{constructor(e,t,n,r,i,s,a,o,l){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=l}}class Eh{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new Eh("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Eh&&e.projectId===this.projectId&&e.database===this.database}}const Sh={mapValue:{fields:{__type__:{stringValue:"__max__"}}}};function kh(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?yh(e)?4:Fh(e)?9007199254740991:10:mu()}function Ih(e,t){if(e===t)return!0;const n=kh(e);if(n!==kh(t))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return bh(e).isEqual(bh(t));case 3:return function(e,t){if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;const n=mh(e.timestampValue),r=mh(t.timestampValue);return n.seconds===r.seconds&&n.nanos===r.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return function(e,t){return vh(e.bytesValue).isEqual(vh(t.bytesValue))}(e,t);case 7:return e.referenceValue===t.referenceValue;case 8:return function(e,t){return gh(e.geoPointValue.latitude)===gh(t.geoPointValue.latitude)&&gh(e.geoPointValue.longitude)===gh(t.geoPointValue.longitude)}(e,t);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return gh(e.integerValue)===gh(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){const n=gh(e.doubleValue),r=gh(t.doubleValue);return n===r?Ju(n)===Ju(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return Ru(e.arrayValue.values||[],t.arrayValue.values||[],Ih);case 10:return function(e,t){const n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(rh(n)!==rh(r))return!1;for(const i in n)if(n.hasOwnProperty(i)&&(void 0===r[i]||!Ih(n[i],r[i])))return!1;return!0}(e,t);default:return mu()}}function Th(e,t){return void 0!==(e.values||[]).find((e=>Ih(e,t)))}function Ch(e,t){if(e===t)return 0;const n=kh(e),r=kh(t);if(n!==r)return Pu(n,r);switch(n){case 0:case 9007199254740991:return 0;case 1:return Pu(e.booleanValue,t.booleanValue);case 2:return function(e,t){const n=gh(e.integerValue||e.doubleValue),r=gh(t.integerValue||t.doubleValue);return n<r?-1:n>r?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1}(e,t);case 3:return xh(e.timestampValue,t.timestampValue);case 4:return xh(bh(e),bh(t));case 5:return Pu(e.stringValue,t.stringValue);case 6:return function(e,t){const n=vh(e),r=vh(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){const n=e.split("/"),r=t.split("/");for(let i=0;i<n.length&&i<r.length;i++){const e=Pu(n[i],r[i]);if(0!==e)return e}return Pu(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){const n=Pu(gh(e.latitude),gh(t.latitude));return 0!==n?n:Pu(gh(e.longitude),gh(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return function(e,t){const n=e.values||[],r=t.values||[];for(let i=0;i<n.length&&i<r.length;++i){const e=Ch(n[i],r[i]);if(e)return e}return Pu(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===Sh.mapValue&&t===Sh.mapValue)return 0;if(e===Sh.mapValue)return 1;if(t===Sh.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let a=0;a<r.length&&a<s.length;++a){const e=Pu(r[a],s[a]);if(0!==e)return e;const t=Ch(n[r[a]],i[s[a]]);if(0!==t)return t}return Pu(r.length,s.length)}(e.mapValue,t.mapValue);default:throw mu()}}function xh(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return Pu(e,t);const n=mh(e),r=mh(t),i=Pu(n.seconds,r.seconds);return 0!==i?i:Pu(n.nanos,r.nanos)}function Nh(e){return Ah(e)}function Ah(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=mh(e);return"time(".concat(t.seconds,",").concat(t.nanos,")")}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?function(e){return vh(e).toBase64()}(e.bytesValue):"referenceValue"in e?function(e){return Uu.fromName(e).toString()}(e.referenceValue):"geoPointValue"in e?function(e){return"geo(".concat(e.latitude,",").concat(e.longitude,")")}(e.geoPointValue):"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=Ah(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const i of t)r?r=!1:n+=",",n+="".concat(i,":").concat(Ah(e.fields[i]));return n+"}"}(e.mapValue):mu()}function Ph(e,t){return{referenceValue:"projects/".concat(e.projectId,"/databases/").concat(e.database,"/documents/").concat(t.path.canonicalString())}}function Rh(e){return!!e&&"integerValue"in e}function Dh(e){return!!e&&"arrayValue"in e}function Oh(e){return!!e&&"nullValue"in e}function Lh(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Mh(e){return!!e&&"mapValue"in e}function jh(e){if(e.geoPointValue)return{geoPointValue:Object.assign({},e.geoPointValue)};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:Object.assign({},e.timestampValue)};if(e.mapValue){const t={mapValue:{fields:{}}};return ih(e.mapValue.fields,((e,n)=>t.mapValue.fields[e]=jh(n))),t}if(e.arrayValue){const t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=jh(e.arrayValue.values[n]);return t}return Object.assign({},e)}function Fh(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}class Uh{constructor(e){this.value=e}static empty(){return new Uh({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(t=(t.mapValue.fields||{})[e.get(n)],!Mh(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=jh(t)}setAll(e){let t=Fu.emptyPath(),n={},r=[];e.forEach(((e,i)=>{if(!t.isImmediateParentOf(i)){const e=this.getFieldsMap(t);this.applyChanges(e,n,r),n={},r=[],t=i.popLast()}e?n[i.lastSegment()]=jh(e):r.push(i.lastSegment())}));const i=this.getFieldsMap(t);this.applyChanges(i,n,r)}delete(e){const t=this.field(e.popLast());Mh(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Ih(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let n=0;n<e.length;++n){let r=t.mapValue.fields[e.get(n)];Mh(r)&&r.mapValue.fields||(r={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=r),t=r}return t.mapValue.fields}applyChanges(e,t,n){ih(t,((t,n)=>e[t]=n));for(const r of n)delete e[r]}clone(){return new Uh(jh(this.value))}}function Vh(e){const t=[];return ih(e.fields,((e,n)=>{const r=new Fu([e]);if(Mh(n)){const e=Vh(n.mapValue).fields;if(0===e.length)t.push(r);else for(const n of e)t.push(r.child(n))}else t.push(r)})),new hh(t)}class Bh{constructor(e,t,n,r,i,s,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new Bh(e,0,Ou.min(),Ou.min(),Ou.min(),Uh.empty(),0)}static newFoundDocument(e,t,n,r){return new Bh(e,1,t,Ou.min(),n,r,0)}static newNoDocument(e,t){return new Bh(e,2,t,Ou.min(),Ou.min(),Uh.empty(),0)}static newUnknownDocument(e,t){return new Bh(e,3,t,Ou.min(),Ou.min(),Uh.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(Ou.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Uh.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Uh.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=Ou.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof Bh&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new Bh(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return"Document(".concat(this.key,", ").concat(this.version,", ").concat(JSON.stringify(this.data.value),", {createTime: ").concat(this.createTime,"}), {documentType: ").concat(this.documentType,"}), {documentState: ").concat(this.documentState,"})")}}class zh{constructor(e,t){this.position=e,this.inclusive=t}}function qh(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){const s=t[i],a=e.position[i];if(r=s.field.isKeyField()?Uu.comparator(Uu.fromName(a.referenceValue),n.key):Ch(a,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function Hh(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!Ih(e.position[n],t.position[n]))return!1;return!0}class Wh{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"asc";this.field=e,this.dir=t}}function Kh(e,t){return e.dir===t.dir&&e.field.isEqual(t.field)}class Gh{}class Qh extends Gh{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,n):new nd(e,t,n):"array-contains"===t?new ad(e,n):"in"===t?new od(e,n):"not-in"===t?new ld(e,n):"array-contains-any"===t?new cd(e,n):new Qh(e,t,n)}static createKeyFieldInFilter(e,t,n){return"in"===t?new rd(e,n):new id(e,n)}matches(e){const t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(Ch(t,this.value)):null!==t&&kh(this.value)===kh(t)&&this.matchesComparison(Ch(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return e>0;case">=":return e>=0;default:return mu()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class $h extends Gh{constructor(e,t){super(),this.filters=e,this.op=t,this.ue=null}static create(e,t){return new $h(e,t)}matches(e){return Yh(this)?void 0===this.filters.find((t=>!t.matches(e))):void 0!==this.filters.find((t=>t.matches(e)))}getFlattenedFilters(){return null!==this.ue||(this.ue=this.filters.reduce(((e,t)=>e.concat(t.getFlattenedFilters())),[])),this.ue}getFilters(){return Object.assign([],this.filters)}}function Yh(e){return"and"===e.op}function Xh(e){return Jh(e)&&Yh(e)}function Jh(e){for(const t of e.filters)if(t instanceof $h)return!1;return!0}function Zh(e){if(e instanceof Qh)return e.field.canonicalString()+e.op.toString()+Nh(e.value);if(Xh(e))return e.filters.map((e=>Zh(e))).join(",");{const t=e.filters.map((e=>Zh(e))).join(",");return"".concat(e.op,"(").concat(t,")")}}function ed(e,t){return e instanceof Qh?function(e,t){return t instanceof Qh&&e.op===t.op&&e.field.isEqual(t.field)&&Ih(e.value,t.value)}(e,t):e instanceof $h?function(e,t){return t instanceof $h&&e.op===t.op&&e.filters.length===t.filters.length&&e.filters.reduce(((e,n,r)=>e&&ed(n,t.filters[r])),!0)}(e,t):void mu()}function td(e){return e instanceof Qh?function(e){return"".concat(e.field.canonicalString()," ").concat(e.op," ").concat(Nh(e.value))}(e):e instanceof $h?function(e){return e.op.toString()+" {"+e.getFilters().map(td).join(" ,")+"}"}(e):"Filter"}class nd extends Qh{constructor(e,t,n){super(e,t,n),this.key=Uu.fromName(n.referenceValue)}matches(e){const t=Uu.comparator(e.key,this.key);return this.matchesComparison(t)}}class rd extends Qh{constructor(e,t){super(e,"in",t),this.keys=sd("in",t)}matches(e){return this.keys.some((t=>t.isEqual(e.key)))}}class id extends Qh{constructor(e,t){super(e,"not-in",t),this.keys=sd("not-in",t)}matches(e){return!this.keys.some((t=>t.isEqual(e.key)))}}function sd(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map((e=>Uu.fromName(e.referenceValue)))}class ad extends Qh{constructor(e,t){super(e,"array-contains",t)}matches(e){const t=e.data.field(this.field);return Dh(t)&&Th(t.arrayValue,this.value)}}class od extends Qh{constructor(e,t){super(e,"in",t)}matches(e){const t=e.data.field(this.field);return null!==t&&Th(this.value.arrayValue,t)}}class ld extends Qh{constructor(e,t){super(e,"not-in",t)}matches(e){if(Th(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return null!==t&&!Th(this.value.arrayValue,t)}}class cd extends Qh{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!Dh(t)||!t.arrayValue.values)&&t.arrayValue.values.some((e=>Th(this.value.arrayValue,e)))}}class ud{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null;this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=a,this.ce=null}}function hd(e){return new ud(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,arguments.length>6&&void 0!==arguments[6]?arguments[6]:null)}function dd(e){const t=vu(e);if(null===t.ce){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map((e=>Zh(e))).join(","),e+="|ob:",e+=t.orderBy.map((e=>function(e){return e.field.canonicalString()+e.dir}(e))).join(","),Xu(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map((e=>Nh(e))).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map((e=>Nh(e))).join(",")),t.ce=e}return t.ce}function fd(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let n=0;n<e.orderBy.length;n++)if(!Kh(e.orderBy[n],t.orderBy[n]))return!1;if(e.filters.length!==t.filters.length)return!1;for(let n=0;n<e.filters.length;n++)if(!ed(e.filters[n],t.filters[n]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!Hh(e.startAt,t.startAt)&&Hh(e.endAt,t.endAt)}function pd(e){return Uu.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}class md{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:"F",a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,o=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null;this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this.le=null,this.he=null,this.Pe=null,this.startAt,this.endAt}}function gd(e,t,n,r,i,s,a,o){return new md(e,t,n,r,i,s,a,o)}function vd(e){return new md(e)}function yd(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function wd(e){return null!==e.collectionGroup}function bd(e){const t=vu(e);if(null===t.le){t.le=[];const e=new Set;for(const i of t.explicitOrderBy)t.le.push(i),e.add(i.field.canonicalString());const n=t.explicitOrderBy.length>0?t.explicitOrderBy[t.explicitOrderBy.length-1].dir:"asc",r=function(e){let t=new ch(Fu.comparator);return e.filters.forEach((e=>{e.getFlattenedFilters().forEach((e=>{e.isInequality()&&(t=t.add(e.field))}))})),t}(t);r.forEach((r=>{e.has(r.canonicalString())||r.isKeyField()||t.le.push(new Wh(r,n))})),e.has(Fu.keyField().canonicalString())||t.le.push(new Wh(Fu.keyField(),n))}return t.le}function _d(e){const t=vu(e);return t.he||(t.he=Ed(t,bd(e))),t.he}function Ed(e,t){if("F"===e.limitType)return hd(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map((e=>{const t="desc"===e.dir?"asc":"desc";return new Wh(e.field,t)}));const n=e.endAt?new zh(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new zh(e.startAt.position,e.startAt.inclusive):null;return hd(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}function Sd(e,t){const n=e.filters.concat([t]);return new md(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function kd(e,t,n){return new md(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function Id(e,t){return fd(_d(e),_d(t))&&e.limitType===t.limitType}function Td(e){return"".concat(dd(_d(e)),"|lt:").concat(e.limitType)}function Cd(e){return"Query(target=".concat(function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),e.filters.length>0&&(t+=", filters: [".concat(e.filters.map((e=>td(e))).join(", "),"]")),Xu(e.limit)||(t+=", limit: "+e.limit),e.orderBy.length>0&&(t+=", orderBy: [".concat(e.orderBy.map((e=>function(e){return"".concat(e.field.canonicalString()," (").concat(e.dir,")")}(e))).join(", "),"]")),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map((e=>Nh(e))).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map((e=>Nh(e))).join(",")),"Target(".concat(t,")")}(_d(e)),"; limitType=").concat(e.limitType,")")}function xd(e,t){return t.isFoundDocument()&&function(e,t){const n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):Uu.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(const n of bd(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return!1;return!0}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return!1;return!0}(e,t)&&function(e,t){return!(e.startAt&&!function(e,t,n){const r=qh(e,t,n);return e.inclusive?r<=0:r<0}(e.startAt,bd(e),t))&&!(e.endAt&&!function(e,t,n){const r=qh(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,bd(e),t))}(e,t)}function Nd(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function Ad(e){return(t,n)=>{let r=!1;for(const i of bd(e)){const e=Pd(i,t,n);if(0!==e)return e;r=r||i.field.isKeyField()}return 0}}function Pd(e,t,n){const r=e.field.isKeyField()?Uu.comparator(t.key,n.key):function(e,t,n){const r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?Ch(r,i):mu()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return mu()}}class Rd{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[r,i]of n)if(this.equalsFn(r,e))return i}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let i=0;i<r.length;i++)if(this.equalsFn(r[i][0],e))return void(r[i]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(e){ih(this.inner,((t,n)=>{for(const[r,i]of n)e(r,i)}))}isEmpty(){return sh(this.inner)}size(){return this.innerSize}}const Dd=new ah(Uu.comparator);function Od(){return Dd}const Ld=new ah(Uu.comparator);function Md(){let e=Ld;for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];for(const i of n)e=e.insert(i.key,i);return e}function jd(e){let t=Ld;return e.forEach(((e,n)=>t=t.insert(e,n.overlayedDocument))),t}function Fd(){return Vd()}function Ud(){return Vd()}function Vd(){return new Rd((e=>e.toString()),((e,t)=>e.isEqual(t)))}const Bd=new ah(Uu.comparator),zd=new ch(Uu.comparator);function qd(){let e=zd;for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];for(const i of n)e=e.add(i);return e}const Hd=new ch(Pu);function Wd(){return Hd}function Kd(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Ju(t)?"-0":t}}function Gd(e){return{integerValue:""+e}}function Qd(e,t){return Zu(t)?Gd(t):Kd(e,t)}class $d{constructor(){this._=void 0}}function Yd(e,t,n){return e instanceof Zd?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&yh(t)&&(t=wh(t)),t&&(n.fields.__previous_value__=t),{mapValue:n}}(n,t):e instanceof ef?tf(e,t):e instanceof nf?rf(e,t):function(e,t){const n=Jd(e,t),r=af(n)+af(e.Ie);return Rh(n)&&Rh(e.Ie)?Gd(r):Kd(e.serializer,r)}(e,t)}function Xd(e,t,n){return e instanceof ef?tf(e,t):e instanceof nf?rf(e,t):n}function Jd(e,t){return e instanceof sf?function(e){return Rh(e)||function(e){return!!e&&"doubleValue"in e}(e)}(t)?t:{integerValue:0}:null}class Zd extends $d{}class ef extends $d{constructor(e){super(),this.elements=e}}function tf(e,t){const n=of(t);for(const r of e.elements)n.some((e=>Ih(e,r)))||n.push(r);return{arrayValue:{values:n}}}class nf extends $d{constructor(e){super(),this.elements=e}}function rf(e,t){let n=of(t);for(const r of e.elements)n=n.filter((e=>!Ih(e,r)));return{arrayValue:{values:n}}}class sf extends $d{constructor(e,t){super(),this.serializer=e,this.Ie=t}}function af(e){return gh(e.integerValue||e.doubleValue)}function of(e){return Dh(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class lf{constructor(e,t){this.version=e,this.transformResults=t}}class cf{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new cf}static exists(e){return new cf(void 0,e)}static updateTime(e){return new cf(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function uf(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class hf{}function df(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new Ef(e.key,cf.none()):new vf(e.key,e.data,cf.none());{const n=e.data,r=Uh.empty();let i=new ch(Fu.comparator);for(let e of t.fields)if(!i.has(e)){let t=n.field(e);null===t&&e.length>1&&(e=e.popLast(),t=n.field(e)),null===t?r.delete(e):r.set(e,t),i=i.add(e)}return new yf(e.key,r,new hh(i.toArray()),cf.none())}}function ff(e,t,n){e instanceof vf?function(e,t,n){const r=e.value.clone(),i=bf(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof yf?function(e,t,n){if(!uf(e.precondition,t))return void t.convertToUnknownDocument(n.version);const r=bf(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(wf(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):function(e,t,n){t.convertToNoDocument(n.version).setHasCommittedMutations()}(0,t,n)}function pf(e,t,n,r){return e instanceof vf?function(e,t,n,r){if(!uf(e.precondition,t))return n;const i=e.value.clone(),s=_f(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof yf?function(e,t,n,r){if(!uf(e.precondition,t))return n;const i=_f(e.fieldTransforms,r,t),s=t.data;return s.setAll(wf(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map((e=>e.field)))}(e,t,n,r):function(e,t,n){return uf(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}(e,t,n)}function mf(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=Jd(r.transform,e||null);null!=i&&(null===n&&(n=Uh.empty()),n.set(r.field,i))}return n||null}function gf(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&!!function(e,t){return void 0===e&&void 0===t||!(!e||!t)&&Ru(e,t,((e,t)=>function(e,t){return e.field.isEqual(t.field)&&function(e,t){return e instanceof ef&&t instanceof ef||e instanceof nf&&t instanceof nf?Ru(e.elements,t.elements,Ih):e instanceof sf&&t instanceof sf?Ih(e.Ie,t.Ie):e instanceof Zd&&t instanceof Zd}(e.transform,t.transform)}(e,t)))}(e.fieldTransforms,t.fieldTransforms)&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class vf extends hf{constructor(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class yf extends hf{constructor(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[];super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function wf(e){const t=new Map;return e.fieldMask.fields.forEach((n=>{if(!n.isEmpty()){const r=e.data.field(n);t.set(n,r)}})),t}function bf(e,t,n){const r=new Map;gu(e.length===n.length);for(let i=0;i<n.length;i++){const s=e[i],a=s.transform,o=t.data.field(s.field);r.set(s.field,Xd(a,o,n[i]))}return r}function _f(e,t,n){const r=new Map;for(const i of e){const e=i.transform,s=n.data.field(i.field);r.set(i.field,Yd(e,s,t))}return r}class Ef extends hf{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Sf extends hf{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class kf{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){const n=t.mutationResults;for(let r=0;r<this.mutations.length;r++){const t=this.mutations[r];t.key.isEqual(e.key)&&ff(t,e,n[r])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=pf(n,e,t,this.localWriteTime));for(const n of this.mutations)n.key.isEqual(e.key)&&(t=pf(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){const n=Ud();return this.mutations.forEach((r=>{const i=e.get(r.key),s=i.overlayedDocument;let a=this.applyToLocalView(s,i.mutatedFields);a=t.has(r.key)?null:a;const o=df(s,a);null!==o&&n.set(r.key,o),s.isValidDocument()||s.convertToNoDocument(Ou.min())})),n}keys(){return this.mutations.reduce(((e,t)=>e.add(t.key)),qd())}isEqual(e){return this.batchId===e.batchId&&Ru(this.mutations,e.mutations,((e,t)=>gf(e,t)))&&Ru(this.baseMutations,e.baseMutations,((e,t)=>gf(e,t)))}}class If{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){gu(e.mutations.length===n.length);let r=Bd;const i=e.mutations;for(let s=0;s<i.length;s++)r=r.insert(i[s].key,n[s].version);return new If(e,t,n,r)}}class Tf{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return"Overlay{\n largestBatchId: ".concat(this.largestBatchId,",\n mutation: ").concat(this.mutation.toString(),"\n }")}}class Cf{constructor(e,t){this.count=e,this.unchangedNames=t}}var xf,Nf;function Af(e){switch(e){default:return mu();case yu.CANCELLED:case yu.UNKNOWN:case yu.DEADLINE_EXCEEDED:case yu.RESOURCE_EXHAUSTED:case yu.INTERNAL:case yu.UNAVAILABLE:case yu.UNAUTHENTICATED:return!1;case yu.INVALID_ARGUMENT:case yu.NOT_FOUND:case yu.ALREADY_EXISTS:case yu.PERMISSION_DENIED:case yu.FAILED_PRECONDITION:case yu.ABORTED:case yu.OUT_OF_RANGE:case yu.UNIMPLEMENTED:case yu.DATA_LOSS:return!0}}function Pf(e){if(void 0===e)return du("GRPC error has no .code"),yu.UNKNOWN;switch(e){case xf.OK:return yu.OK;case xf.CANCELLED:return yu.CANCELLED;case xf.UNKNOWN:return yu.UNKNOWN;case xf.DEADLINE_EXCEEDED:return yu.DEADLINE_EXCEEDED;case xf.RESOURCE_EXHAUSTED:return yu.RESOURCE_EXHAUSTED;case xf.INTERNAL:return yu.INTERNAL;case xf.UNAVAILABLE:return yu.UNAVAILABLE;case xf.UNAUTHENTICATED:return yu.UNAUTHENTICATED;case xf.INVALID_ARGUMENT:return yu.INVALID_ARGUMENT;case xf.NOT_FOUND:return yu.NOT_FOUND;case xf.ALREADY_EXISTS:return yu.ALREADY_EXISTS;case xf.PERMISSION_DENIED:return yu.PERMISSION_DENIED;case xf.FAILED_PRECONDITION:return yu.FAILED_PRECONDITION;case xf.ABORTED:return yu.ABORTED;case xf.OUT_OF_RANGE:return yu.OUT_OF_RANGE;case xf.UNIMPLEMENTED:return yu.UNIMPLEMENTED;case xf.DATA_LOSS:return yu.DATA_LOSS;default:return mu()}}(Nf=xf||(xf={}))[Nf.OK=0]="OK",Nf[Nf.CANCELLED=1]="CANCELLED",Nf[Nf.UNKNOWN=2]="UNKNOWN",Nf[Nf.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",Nf[Nf.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",Nf[Nf.NOT_FOUND=5]="NOT_FOUND",Nf[Nf.ALREADY_EXISTS=6]="ALREADY_EXISTS",Nf[Nf.PERMISSION_DENIED=7]="PERMISSION_DENIED",Nf[Nf.UNAUTHENTICATED=16]="UNAUTHENTICATED",Nf[Nf.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",Nf[Nf.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",Nf[Nf.ABORTED=10]="ABORTED",Nf[Nf.OUT_OF_RANGE=11]="OUT_OF_RANGE",Nf[Nf.UNIMPLEMENTED=12]="UNIMPLEMENTED",Nf[Nf.INTERNAL=13]="INTERNAL",Nf[Nf.UNAVAILABLE=14]="UNAVAILABLE",Nf[Nf.DATA_LOSS=15]="DATA_LOSS";let Rf=null;function Df(){return new TextEncoder}const Of=new su([4294967295,4294967295],0);function Lf(e){const t=Df().encode(e),n=new iu;return n.update(t),new Uint8Array(n.digest())}function Mf(e){const t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new su([n,r],0),new su([i,s],0)]}class jf{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new Ff("Invalid padding: ".concat(t));if(n<0)throw new Ff("Invalid hash count: ".concat(n));if(e.length>0&&0===this.hashCount)throw new Ff("Invalid hash count: ".concat(n));if(0===e.length&&0!==t)throw new Ff("Invalid padding when bitmap length is 0: ".concat(t));this.Te=8*e.length-t,this.Ee=su.fromNumber(this.Te)}de(e,t,n){let r=e.add(t.multiply(su.fromNumber(n)));return 1===r.compare(Of)&&(r=new su([r.getBits(0),r.getBits(1)],0)),r.modulo(this.Ee).toNumber()}Ae(e){return 0!=(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.Te)return!1;const t=Lf(e),[n,r]=Mf(t);for(let i=0;i<this.hashCount;i++){const e=this.de(n,r,i);if(!this.Ae(e))return!1}return!0}static create(e,t,n){const r=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),s=new jf(i,r,t);return n.forEach((e=>s.insert(e))),s}insert(e){if(0===this.Te)return;const t=Lf(e),[n,r]=Mf(t);for(let i=0;i<this.hashCount;i++){const e=this.de(n,r,i);this.Re(e)}}Re(e){const t=Math.floor(e/8),n=e%8;this.bitmap[t]|=1<<n}}class Ff extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class Uf{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,Vf.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new Uf(Ou.min(),r,new ah(Pu),Od(),qd())}}class Vf{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new Vf(n,t,qd(),qd(),qd())}}class Bf{constructor(e,t,n,r){this.Ve=e,this.removedTargetIds=t,this.key=n,this.me=r}}class zf{constructor(e,t){this.targetId=e,this.fe=t}}class qf{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:fh.EMPTY_BYTE_STRING,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class Hf{constructor(){this.ge=0,this.pe=Gf(),this.ye=fh.EMPTY_BYTE_STRING,this.we=!1,this.Se=!0}get current(){return this.we}get resumeToken(){return this.ye}get be(){return 0!==this.ge}get De(){return this.Se}Ce(e){e.approximateByteSize()>0&&(this.Se=!0,this.ye=e)}ve(){let e=qd(),t=qd(),n=qd();return this.pe.forEach(((r,i)=>{switch(i){case 0:e=e.add(r);break;case 2:t=t.add(r);break;case 1:n=n.add(r);break;default:mu()}})),new Vf(this.ye,this.we,e,t,n)}Fe(){this.Se=!1,this.pe=Gf()}Me(e,t){this.Se=!0,this.pe=this.pe.insert(e,t)}xe(e){this.Se=!0,this.pe=this.pe.remove(e)}Oe(){this.ge+=1}Ne(){this.ge-=1}Be(){this.Se=!0,this.we=!0}}class Wf{constructor(e){this.Le=e,this.ke=new Map,this.qe=Od(),this.Qe=Kf(),this.Ke=new ah(Pu)}$e(e){for(const t of e.Ve)e.me&&e.me.isFoundDocument()?this.Ue(t,e.me):this.We(t,e.key,e.me);for(const t of e.removedTargetIds)this.We(t,e.key,e.me)}Ge(e){this.forEachTarget(e,(t=>{const n=this.ze(t);switch(e.state){case 0:this.je(t)&&n.Ce(e.resumeToken);break;case 1:n.Ne(),n.be||n.Fe(),n.Ce(e.resumeToken);break;case 2:n.Ne(),n.be||this.removeTarget(t);break;case 3:this.je(t)&&(n.Be(),n.Ce(e.resumeToken));break;case 4:this.je(t)&&(this.He(t),n.Ce(e.resumeToken));break;default:mu()}}))}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.ke.forEach(((e,n)=>{this.je(n)&&t(n)}))}Je(e){const t=e.targetId,n=e.fe.count,r=this.Ye(t);if(r){const i=r.target;if(pd(i))if(0===n){const e=new Uu(i.path);this.We(t,e,Bh.newNoDocument(e,Ou.min()))}else gu(1===n);else{const r=this.Ze(t);if(r!==n){const n=this.Xe(e),i=n?this.et(n,e,r):1;if(0!==i){this.He(t);const e=2===i?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ke=this.Ke.insert(t,e)}null==Rf||Rf.tt(function(e,t,n,r,i){var s,a,o,l,c,u;const h={localCacheCount:e,existenceFilterCount:t.count,databaseId:n.database,projectId:n.projectId},d=t.unchangedNames;return d&&(h.bloomFilter={applied:0===i,hashCount:null!==(s=null==d?void 0:d.hashCount)&&void 0!==s?s:0,bitmapLength:null!==(l=null===(o=null===(a=null==d?void 0:d.bits)||void 0===a?void 0:a.bitmap)||void 0===o?void 0:o.length)&&void 0!==l?l:0,padding:null!==(u=null===(c=null==d?void 0:d.bits)||void 0===c?void 0:c.padding)&&void 0!==u?u:0,mightContain:e=>{var t;return null!==(t=null==r?void 0:r.mightContain(e))&&void 0!==t&&t}}),h}(r,e.fe,this.Le.nt(),n,i))}}}}Xe(e){const t=e.fe.unchangedNames;if(!t||!t.bits)return null;const{bits:{bitmap:n="",padding:r=0},hashCount:i=0}=t;let s,a;try{s=vh(n).toUint8Array()}catch(e){if(e instanceof dh)return fu("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw e}try{a=new jf(s,r,i)}catch(e){return fu(e instanceof Ff?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===a.Te?null:a}et(e,t,n){return t.fe.count===n-this.rt(e,t.targetId)?0:2}rt(e,t){const n=this.Le.getRemoteKeysForTarget(t);let r=0;return n.forEach((n=>{const i=this.Le.nt(),s="projects/".concat(i.projectId,"/databases/").concat(i.database,"/documents/").concat(n.path.canonicalString());e.mightContain(s)||(this.We(t,n,null),r++)})),r}it(e){const t=new Map;this.ke.forEach(((n,r)=>{const i=this.Ye(r);if(i){if(n.current&&pd(i.target)){const t=new Uu(i.target.path);null!==this.qe.get(t)||this.st(r,t)||this.We(r,t,Bh.newNoDocument(t,e))}n.De&&(t.set(r,n.ve()),n.Fe())}}));let n=qd();this.Qe.forEach(((e,t)=>{let r=!0;t.forEachWhile((e=>{const t=this.Ye(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(r=!1,!1)})),r&&(n=n.add(e))})),this.qe.forEach(((t,n)=>n.setReadTime(e)));const r=new Uf(e,t,this.Ke,this.qe,n);return this.qe=Od(),this.Qe=Kf(),this.Ke=new ah(Pu),r}Ue(e,t){if(!this.je(e))return;const n=this.st(e,t.key)?2:0;this.ze(e).Me(t.key,n),this.qe=this.qe.insert(t.key,t),this.Qe=this.Qe.insert(t.key,this.ot(t.key).add(e))}We(e,t,n){if(!this.je(e))return;const r=this.ze(e);this.st(e,t)?r.Me(t,1):r.xe(t),this.Qe=this.Qe.insert(t,this.ot(t).delete(e)),n&&(this.qe=this.qe.insert(t,n))}removeTarget(e){this.ke.delete(e)}Ze(e){const t=this.ze(e).ve();return this.Le.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Oe(e){this.ze(e).Oe()}ze(e){let t=this.ke.get(e);return t||(t=new Hf,this.ke.set(e,t)),t}ot(e){let t=this.Qe.get(e);return t||(t=new ch(Pu),this.Qe=this.Qe.insert(e,t)),t}je(e){const t=null!==this.Ye(e);return t||hu("WatchChangeAggregator","Detected inactive target",e),t}Ye(e){const t=this.ke.get(e);return t&&t.be?null:this.Le._t(e)}He(e){this.ke.set(e,new Hf),this.Le.getRemoteKeysForTarget(e).forEach((t=>{this.We(e,t,null)}))}st(e,t){return this.Le.getRemoteKeysForTarget(e).has(t)}}function Kf(){return new ah(Uu.comparator)}function Gf(){return new ah(Uu.comparator)}const Qf={asc:"ASCENDING",desc:"DESCENDING"},$f={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"},Yf={and:"AND",or:"OR"};class Xf{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function Jf(e,t){return e.useProto3Json||Xu(t)?t:{value:t}}function Zf(e,t){return e.useProto3Json?"".concat(new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z",""),".").concat(("000000000"+t.nanoseconds).slice(-9),"Z"):{seconds:""+t.seconds,nanos:t.nanoseconds}}function ep(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function tp(e,t){return Zf(e,t.toTimestamp())}function np(e){return gu(!!e),Ou.fromTimestamp(function(e){const t=mh(e);return new Du(t.seconds,t.nanos)}(e))}function rp(e,t){return function(e){return new Mu(["projects",e.projectId,"databases",e.database])}(e).child("documents").child(t).canonicalString()}function ip(e){const t=Mu.fromString(e);return gu(kp(t)),t}function sp(e,t){return rp(e.databaseId,t.path)}function ap(e,t){const n=ip(t);if(n.get(1)!==e.databaseId.projectId)throw new wu(yu.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new wu(yu.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new Uu(up(n))}function op(e,t){return rp(e.databaseId,t)}function lp(e){const t=ip(e);return 4===t.length?Mu.emptyPath():up(t)}function cp(e){return new Mu(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function up(e){return gu(e.length>4&&"documents"===e.get(4)),e.popFirst(5)}function hp(e,t,n){return{name:sp(e,t),fields:n.value.mapValue.fields}}function dp(e,t){let n;if(t instanceof vf)n={update:hp(e,t.key,t.value)};else if(t instanceof Ef)n={delete:sp(e,t.key)};else if(t instanceof yf)n={update:hp(e,t.key,t.data),updateMask:Sp(t.fieldMask)};else{if(!(t instanceof Sf))return mu();n={verify:sp(e,t.key)}}return t.fieldTransforms.length>0&&(n.updateTransforms=t.fieldTransforms.map((e=>function(e,t){const n=t.transform;if(n instanceof Zd)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof ef)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof nf)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof sf)return{fieldPath:t.field.canonicalString(),increment:n.Ie};throw mu()}(0,e)))),t.precondition.isNone||(n.currentDocument=function(e,t){return void 0!==t.updateTime?{updateTime:tp(e,t.updateTime)}:void 0!==t.exists?{exists:t.exists}:mu()}(e,t.precondition)),n}function fp(e,t){return{documents:[op(e,t.path)]}}function pp(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=op(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=op(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);const i=function(e){if(0!==e.length)return Ep($h.create(e,"and"))}(t.filters);i&&(n.structuredQuery.where=i);const s=function(e){if(0!==e.length)return e.map((e=>function(e){return{field:bp(e.field),direction:vp(e.dir)}}(e)))}(t.orderBy);s&&(n.structuredQuery.orderBy=s);const a=Jf(e,t.limit);return null!==a&&(n.structuredQuery.limit=a),t.startAt&&(n.structuredQuery.startAt=function(e){return{before:e.inclusive,values:e.position}}(t.startAt)),t.endAt&&(n.structuredQuery.endAt=function(e){return{before:!e.inclusive,values:e.position}}(t.endAt)),n}function mp(e){let t=lp(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let i=null;if(r>0){gu(1===r);const e=n.from[0];e.allDescendants?i=e.collectionId:t=t.child(e.collectionId)}let s=[];n.where&&(s=function(e){const t=gp(e);return t instanceof $h&&Xh(t)?t.getFilters():[t]}(n.where));let a=[];n.orderBy&&(a=function(e){return e.map((e=>function(e){return new Wh(_p(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)))}(n.orderBy));let o=null;n.limit&&(o=function(e){let t;return t="object"==typeof e?e.value:e,Xu(t)?null:t}(n.limit));let l=null;n.startAt&&(l=function(e){const t=!!e.before,n=e.values||[];return new zh(n,t)}(n.startAt));let c=null;return n.endAt&&(c=function(e){const t=!e.before,n=e.values||[];return new zh(n,t)}(n.endAt)),gd(t,i,a,s,o,"F",l,c)}function gp(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=_p(e.unaryFilter.field);return Qh.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=_p(e.unaryFilter.field);return Qh.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=_p(e.unaryFilter.field);return Qh.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const i=_p(e.unaryFilter.field);return Qh.create(i,"!=",{nullValue:"NULL_VALUE"});default:return mu()}}(e):void 0!==e.fieldFilter?function(e){return Qh.create(_p(e.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return mu()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return $h.create(e.compositeFilter.filters.map((e=>gp(e))),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return mu()}}(e.compositeFilter.op))}(e):mu()}function vp(e){return Qf[e]}function yp(e){return $f[e]}function wp(e){return Yf[e]}function bp(e){return{fieldPath:e.canonicalString()}}function _p(e){return Fu.fromServerFormat(e.fieldPath)}function Ep(e){return e instanceof Qh?function(e){if("=="===e.op){if(Lh(e.value))return{unaryFilter:{field:bp(e.field),op:"IS_NAN"}};if(Oh(e.value))return{unaryFilter:{field:bp(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Lh(e.value))return{unaryFilter:{field:bp(e.field),op:"IS_NOT_NAN"}};if(Oh(e.value))return{unaryFilter:{field:bp(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:bp(e.field),op:yp(e.op),value:e.value}}}(e):e instanceof $h?function(e){const t=e.getFilters().map((e=>Ep(e)));return 1===t.length?t[0]:{compositeFilter:{op:wp(e.op),filters:t}}}(e):mu()}function Sp(e){const t=[];return e.fields.forEach((e=>t.push(e.canonicalString()))),{fieldPaths:t}}function kp(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class Ip{constructor(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:Ou.min(),s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:Ou.min(),a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:fh.EMPTY_BYTE_STRING,o=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null;this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new Ip(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new Ip(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new Ip(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new Ip(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class Tp{constructor(e){this.ut=e}}function Cp(e){const t=mp({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?kd(t,t.limit,"L"):t}class xp{constructor(){}ht(e,t){this.Pt(e,t),t.It()}Pt(e,t){if("nullValue"in e)this.Tt(t,5);else if("booleanValue"in e)this.Tt(t,10),t.Et(e.booleanValue?1:0);else if("integerValue"in e)this.Tt(t,15),t.Et(gh(e.integerValue));else if("doubleValue"in e){const n=gh(e.doubleValue);isNaN(n)?this.Tt(t,13):(this.Tt(t,15),Ju(n)?t.Et(0):t.Et(n))}else if("timestampValue"in e){const n=e.timestampValue;this.Tt(t,20),"string"==typeof n?t.dt(n):(t.dt("".concat(n.seconds||"")),t.Et(n.nanos||0))}else if("stringValue"in e)this.At(e.stringValue,t),this.Rt(t);else if("bytesValue"in e)this.Tt(t,30),t.Vt(vh(e.bytesValue)),this.Rt(t);else if("referenceValue"in e)this.ft(e.referenceValue,t);else if("geoPointValue"in e){const n=e.geoPointValue;this.Tt(t,45),t.Et(n.latitude||0),t.Et(n.longitude||0)}else"mapValue"in e?Fh(e)?this.Tt(t,Number.MAX_SAFE_INTEGER):(this.gt(e.mapValue,t),this.Rt(t)):"arrayValue"in e?(this.yt(e.arrayValue,t),this.Rt(t)):mu()}At(e,t){this.Tt(t,25),this.wt(e,t)}wt(e,t){t.dt(e)}gt(e,t){const n=e.fields||{};this.Tt(t,55);for(const r of Object.keys(n))this.At(r,t),this.Pt(n[r],t)}yt(e,t){const n=e.values||[];this.Tt(t,50);for(const r of n)this.Pt(r,t)}ft(e,t){this.Tt(t,37),Uu.fromName(e).path.forEach((e=>{this.Tt(t,60),this.wt(e,t)}))}Tt(e,t){e.Et(t)}Rt(e){e.Et(2)}}xp.St=new xp;class Np{constructor(){this.on=new Ap}addToCollectionParentIndex(e,t){return this.on.add(t),Qu.resolve()}getCollectionParents(e,t){return Qu.resolve(this.on.getEntries(t))}addFieldIndex(e,t){return Qu.resolve()}deleteFieldIndex(e,t){return Qu.resolve()}deleteAllFieldIndexes(e){return Qu.resolve()}createTargetIndexes(e,t){return Qu.resolve()}getDocumentsMatchingTarget(e,t){return Qu.resolve(null)}getIndexType(e,t){return Qu.resolve(0)}getFieldIndexes(e,t){return Qu.resolve([])}getNextCollectionGroupToUpdate(e){return Qu.resolve(null)}getMinOffset(e,t){return Qu.resolve(qu.min())}getMinOffsetFromCollectionGroup(e,t){return Qu.resolve(qu.min())}updateCollectionGroup(e,t,n){return Qu.resolve()}updateIndexEntries(e,t){return Qu.resolve()}}class Ap{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new ch(Mu.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new ch(Mu.comparator)).toArray()}}new Uint8Array(0);class Pp{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new Pp(e,Pp.DEFAULT_COLLECTION_PERCENTILE,Pp.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}Pp.DEFAULT_COLLECTION_PERCENTILE=10,Pp.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Pp.DEFAULT=new Pp(41943040,Pp.DEFAULT_COLLECTION_PERCENTILE,Pp.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Pp.DISABLED=new Pp(-1,0,0);class Rp{constructor(e){this.xn=e}next(){return this.xn+=2,this.xn}static On(){return new Rp(0)}static Nn(){return new Rp(-1)}}class Dp{constructor(){this.changes=new Rd((e=>e.toString()),((e,t)=>e.isEqual(t))),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,Bh.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();const n=this.changes.get(t);return void 0!==n?Qu.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class Op{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class Lp{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(e,t){let n=null;return this.documentOverlayCache.getOverlay(e,t).next((r=>(n=r,this.remoteDocumentCache.getEntry(e,t)))).next((e=>(null!==n&&pf(n.mutation,e,hh.empty(),Du.now()),e)))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next((t=>this.getLocalViewOfDocuments(e,t,qd()).next((()=>t))))}getLocalViewOfDocuments(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:qd();const r=Fd();return this.populateOverlays(e,r,t).next((()=>this.computeViews(e,t,r,n).next((e=>{let t=Md();return e.forEach(((e,n)=>{t=t.insert(e,n.overlayedDocument)})),t}))))}getOverlayedDocuments(e,t){const n=Fd();return this.populateOverlays(e,n,t).next((()=>this.computeViews(e,t,n,qd())))}populateOverlays(e,t,n){const r=[];return n.forEach((e=>{t.has(e)||r.push(e)})),this.documentOverlayCache.getOverlays(e,r).next((e=>{e.forEach(((e,n)=>{t.set(e,n)}))}))}computeViews(e,t,n,r){let i=Od();const s=Vd(),a=Vd();return t.forEach(((e,t)=>{const a=n.get(t.key);r.has(t.key)&&(void 0===a||a.mutation instanceof yf)?i=i.insert(t.key,t):void 0!==a?(s.set(t.key,a.mutation.getFieldMask()),pf(a.mutation,t,a.mutation.getFieldMask(),Du.now())):s.set(t.key,hh.empty())})),this.recalculateAndSaveOverlays(e,i).next((e=>(e.forEach(((e,t)=>s.set(e,t))),t.forEach(((e,t)=>{var n;return a.set(e,new Op(t,null!==(n=s.get(e))&&void 0!==n?n:null))})),a)))}recalculateAndSaveOverlays(e,t){const n=Vd();let r=new ah(((e,t)=>e-t)),i=qd();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next((e=>{for(const i of e)i.keys().forEach((e=>{const s=t.get(e);if(null===s)return;let a=n.get(e)||hh.empty();a=i.applyToLocalView(s,a),n.set(e,a);const o=(r.get(i.batchId)||qd()).add(e);r=r.insert(i.batchId,o)}))})).next((()=>{const s=[],a=r.getReverseIterator();for(;a.hasNext();){const r=a.getNext(),o=r.key,l=r.value,c=Ud();l.forEach((e=>{if(!i.has(e)){const r=df(t.get(e),n.get(e));null!==r&&c.set(e,r),i=i.add(e)}})),s.push(this.documentOverlayCache.saveOverlays(e,o,c))}return Qu.waitFor(s)})).next((()=>n))}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next((t=>this.recalculateAndSaveOverlays(e,t)))}getDocumentsMatchingQuery(e,t,n,r){return function(e){return Uu.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):wd(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,r):this.getDocumentsMatchingCollectionQuery(e,t,n,r)}getNextDocuments(e,t,n,r){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,r).next((i=>{const s=r-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,r-i.size):Qu.resolve(Fd());let a=-1,o=i;return s.next((t=>Qu.forEach(t,((t,n)=>(a<n.largestBatchId&&(a=n.largestBatchId),i.get(t)?Qu.resolve():this.remoteDocumentCache.getEntry(e,t).next((e=>{o=o.insert(t,e)}))))).next((()=>this.populateOverlays(e,t,i))).next((()=>this.computeViews(e,o,t,qd()))).next((e=>({batchId:a,changes:jd(e)})))))}))}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new Uu(t)).next((e=>{let t=Md();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t}))}getDocumentsMatchingCollectionGroupQuery(e,t,n,r){const i=t.collectionGroup;let s=Md();return this.indexManager.getCollectionParents(e,i).next((a=>Qu.forEach(a,(a=>{const o=function(e,t){return new md(t,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(t,a.child(i));return this.getDocumentsMatchingCollectionQuery(e,o,n,r).next((e=>{e.forEach(((e,t)=>{s=s.insert(e,t)}))}))})).next((()=>s))))}getDocumentsMatchingCollectionQuery(e,t,n,r){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next((s=>(i=s,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,i,r)))).next((e=>{i.forEach(((t,n)=>{const r=n.getKey();null===e.get(r)&&(e=e.insert(r,Bh.newInvalidDocument(r)))}));let n=Md();return e.forEach(((e,r)=>{const s=i.get(e);void 0!==s&&pf(s.mutation,r,hh.empty(),Du.now()),xd(t,r)&&(n=n.insert(e,r))})),n}))}}class Mp{constructor(e){this.serializer=e,this.ur=new Map,this.cr=new Map}getBundleMetadata(e,t){return Qu.resolve(this.ur.get(t))}saveBundleMetadata(e,t){return this.ur.set(t.id,function(e){return{id:e.id,version:e.version,createTime:np(e.createTime)}}(t)),Qu.resolve()}getNamedQuery(e,t){return Qu.resolve(this.cr.get(t))}saveNamedQuery(e,t){return this.cr.set(t.name,function(e){return{name:e.name,query:Cp(e.bundledQuery),readTime:np(e.readTime)}}(t)),Qu.resolve()}}class jp{constructor(){this.overlays=new ah(Uu.comparator),this.lr=new Map}getOverlay(e,t){return Qu.resolve(this.overlays.get(t))}getOverlays(e,t){const n=Fd();return Qu.forEach(t,(t=>this.getOverlay(e,t).next((e=>{null!==e&&n.set(t,e)})))).next((()=>n))}saveOverlays(e,t,n){return n.forEach(((n,r)=>{this.lt(e,t,r)})),Qu.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.lr.get(n);return void 0!==r&&(r.forEach((e=>this.overlays=this.overlays.remove(e))),this.lr.delete(n)),Qu.resolve()}getOverlaysForCollection(e,t,n){const r=Fd(),i=t.length+1,s=new Uu(t.child("")),a=this.overlays.getIteratorFrom(s);for(;a.hasNext();){const e=a.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return Qu.resolve(r)}getOverlaysForCollectionGroup(e,t,n,r){let i=new ah(((e,t)=>e-t));const s=this.overlays.getIterator();for(;s.hasNext();){const e=s.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>n){let t=i.get(e.largestBatchId);null===t&&(t=Fd(),i=i.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}const a=Fd(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach(((e,t)=>a.set(e,t))),!(a.size()>=r)););return Qu.resolve(a)}lt(e,t,n){const r=this.overlays.get(n.key);if(null!==r){const e=this.lr.get(r.largestBatchId).delete(n.key);this.lr.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new Tf(t,n));let i=this.lr.get(t);void 0===i&&(i=qd(),this.lr.set(t,i)),this.lr.set(t,i.add(n.key))}}class Fp{constructor(){this.hr=new ch(Up.Pr),this.Ir=new ch(Up.Tr)}isEmpty(){return this.hr.isEmpty()}addReference(e,t){const n=new Up(e,t);this.hr=this.hr.add(n),this.Ir=this.Ir.add(n)}Er(e,t){e.forEach((e=>this.addReference(e,t)))}removeReference(e,t){this.dr(new Up(e,t))}Ar(e,t){e.forEach((e=>this.removeReference(e,t)))}Rr(e){const t=new Uu(new Mu([])),n=new Up(t,e),r=new Up(t,e+1),i=[];return this.Ir.forEachInRange([n,r],(e=>{this.dr(e),i.push(e.key)})),i}Vr(){this.hr.forEach((e=>this.dr(e)))}dr(e){this.hr=this.hr.delete(e),this.Ir=this.Ir.delete(e)}mr(e){const t=new Uu(new Mu([])),n=new Up(t,e),r=new Up(t,e+1);let i=qd();return this.Ir.forEachInRange([n,r],(e=>{i=i.add(e.key)})),i}containsKey(e){const t=new Up(e,0),n=this.hr.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class Up{constructor(e,t){this.key=e,this.gr=t}static Pr(e,t){return Uu.comparator(e.key,t.key)||Pu(e.gr,t.gr)}static Tr(e,t){return Pu(e.gr,t.gr)||Uu.comparator(e.key,t.key)}}class Vp{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.pr=1,this.yr=new ch(Up.Pr)}checkEmpty(e){return Qu.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){const i=this.pr;this.pr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];const s=new kf(i,t,n,r);this.mutationQueue.push(s);for(const a of r)this.yr=this.yr.add(new Up(a.key,i)),this.indexManager.addToCollectionParentIndex(e,a.key.path.popLast());return Qu.resolve(s)}lookupMutationBatch(e,t){return Qu.resolve(this.wr(t))}getNextMutationBatchAfterBatchId(e,t){const n=t+1,r=this.Sr(n),i=r<0?0:r;return Qu.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)}getHighestUnacknowledgedBatchId(){return Qu.resolve(0===this.mutationQueue.length?-1:this.pr-1)}getAllMutationBatches(e){return Qu.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new Up(t,0),r=new Up(t,Number.POSITIVE_INFINITY),i=[];return this.yr.forEachInRange([n,r],(e=>{const t=this.wr(e.gr);i.push(t)})),Qu.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new ch(Pu);return t.forEach((e=>{const t=new Up(e,0),r=new Up(e,Number.POSITIVE_INFINITY);this.yr.forEachInRange([t,r],(e=>{n=n.add(e.gr)}))})),Qu.resolve(this.br(n))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;Uu.isDocumentKey(i)||(i=i.child(""));const s=new Up(new Uu(i),0);let a=new ch(Pu);return this.yr.forEachWhile((e=>{const t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.gr)),!0)}),s),Qu.resolve(this.br(a))}br(e){const t=[];return e.forEach((e=>{const n=this.wr(e);null!==n&&t.push(n)})),t}removeMutationBatch(e,t){gu(0===this.Dr(t.batchId,"removed")),this.mutationQueue.shift();let n=this.yr;return Qu.forEach(t.mutations,(r=>{const i=new Up(r.key,t.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,r.key)})).next((()=>{this.yr=n}))}Fn(e){}containsKey(e,t){const n=new Up(t,0),r=this.yr.firstAfterOrEqual(n);return Qu.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,Qu.resolve()}Dr(e,t){return this.Sr(e)}Sr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}wr(e){const t=this.Sr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class Bp{constructor(e){this.Cr=e,this.docs=new ah(Uu.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.Cr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){const t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return Qu.resolve(n?n.document.mutableCopy():Bh.newInvalidDocument(t))}getEntries(e,t){let n=Od();return t.forEach((e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Bh.newInvalidDocument(e))})),Qu.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=Od();const s=t.path,a=new Uu(s.child("")),o=this.docs.getIteratorFrom(a);for(;o.hasNext();){const{key:e,value:{document:a}}=o.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||Hu(zu(a),n)<=0||(r.has(a.key)||xd(t,a))&&(i=i.insert(a.key,a.mutableCopy()))}return Qu.resolve(i)}getAllFromCollectionGroup(e,t,n,r){mu()}vr(e,t){return Qu.forEach(this.docs,(e=>t(e)))}newChangeBuffer(e){return new zp(this)}getSize(e){return Qu.resolve(this.size)}}class zp extends Dp{constructor(e){super(),this._r=e}applyChanges(e){const t=[];return this.changes.forEach(((n,r)=>{r.isValidDocument()?t.push(this._r.addEntry(e,r)):this._r.removeEntry(n)})),Qu.waitFor(t)}getFromCache(e,t){return this._r.getEntry(e,t)}getAllFromCache(e,t){return this._r.getEntries(e,t)}}class qp{constructor(e){this.persistence=e,this.Fr=new Rd((e=>dd(e)),fd),this.lastRemoteSnapshotVersion=Ou.min(),this.highestTargetId=0,this.Mr=0,this.Or=new Fp,this.targetCount=0,this.Nr=Rp.On()}forEachTarget(e,t){return this.Fr.forEach(((e,n)=>t(n))),Qu.resolve()}getLastRemoteSnapshotVersion(e){return Qu.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return Qu.resolve(this.Mr)}allocateTargetId(e){return this.highestTargetId=this.Nr.next(),Qu.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Mr&&(this.Mr=t),Qu.resolve()}kn(e){this.Fr.set(e.target,e);const t=e.targetId;t>this.highestTargetId&&(this.Nr=new Rp(t),this.highestTargetId=t),e.sequenceNumber>this.Mr&&(this.Mr=e.sequenceNumber)}addTargetData(e,t){return this.kn(t),this.targetCount+=1,Qu.resolve()}updateTargetData(e,t){return this.kn(t),Qu.resolve()}removeTargetData(e,t){return this.Fr.delete(t.target),this.Or.Rr(t.targetId),this.targetCount-=1,Qu.resolve()}removeTargets(e,t,n){let r=0;const i=[];return this.Fr.forEach(((s,a)=>{a.sequenceNumber<=t&&null===n.get(a.targetId)&&(this.Fr.delete(s),i.push(this.removeMatchingKeysForTargetId(e,a.targetId)),r++)})),Qu.waitFor(i).next((()=>r))}getTargetCount(e){return Qu.resolve(this.targetCount)}getTargetData(e,t){const n=this.Fr.get(t)||null;return Qu.resolve(n)}addMatchingKeys(e,t,n){return this.Or.Er(t,n),Qu.resolve()}removeMatchingKeys(e,t,n){this.Or.Ar(t,n);const r=this.persistence.referenceDelegate,i=[];return r&&t.forEach((t=>{i.push(r.markPotentiallyOrphaned(e,t))})),Qu.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Or.Rr(t),Qu.resolve()}getMatchingKeysForTargetId(e,t){const n=this.Or.mr(t);return Qu.resolve(n)}containsKey(e,t){return Qu.resolve(this.Or.containsKey(t))}}class Hp{constructor(e,t){this.Br={},this.overlays={},this.Lr=new Yu(0),this.kr=!1,this.kr=!0,this.referenceDelegate=e(this),this.qr=new qp(this),this.indexManager=new Np,this.remoteDocumentCache=function(e){return new Bp(e)}((e=>this.referenceDelegate.Qr(e))),this.serializer=new Tp(t),this.Kr=new Mp(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.kr=!1,Promise.resolve()}get started(){return this.kr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new jp,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Br[e.toKey()];return n||(n=new Vp(t,this.referenceDelegate),this.Br[e.toKey()]=n),n}getTargetCache(){return this.qr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Kr}runTransaction(e,t,n){hu("MemoryPersistence","Starting transaction:",e);const r=new Wp(this.Lr.next());return this.referenceDelegate.$r(),n(r).next((e=>this.referenceDelegate.Ur(r).next((()=>e)))).toPromise().then((e=>(r.raiseOnCommittedEvent(),e)))}Wr(e,t){return Qu.or(Object.values(this.Br).map((n=>()=>n.containsKey(e,t))))}}class Wp extends Ku{constructor(e){super(),this.currentSequenceNumber=e}}class Kp{constructor(e){this.persistence=e,this.Gr=new Fp,this.zr=null}static jr(e){return new Kp(e)}get Hr(){if(this.zr)return this.zr;throw mu()}addReference(e,t,n){return this.Gr.addReference(n,t),this.Hr.delete(n.toString()),Qu.resolve()}removeReference(e,t,n){return this.Gr.removeReference(n,t),this.Hr.add(n.toString()),Qu.resolve()}markPotentiallyOrphaned(e,t){return this.Hr.add(t.toString()),Qu.resolve()}removeTarget(e,t){this.Gr.Rr(t.targetId).forEach((e=>this.Hr.add(e.toString())));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next((e=>{e.forEach((e=>this.Hr.add(e.toString())))})).next((()=>n.removeTargetData(e,t)))}$r(){this.zr=new Set}Ur(e){const t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return Qu.forEach(this.Hr,(n=>{const r=Uu.fromPath(n);return this.Jr(e,r).next((e=>{e||t.removeEntry(r,Ou.min())}))})).next((()=>(this.zr=null,t.apply(e))))}updateLimboDocument(e,t){return this.Jr(e,t).next((e=>{e?this.Hr.delete(t.toString()):this.Hr.add(t.toString())}))}Qr(e){return 0}Jr(e,t){return Qu.or([()=>Qu.resolve(this.Gr.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Wr(e,t)])}}class Gp{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.ki=n,this.qi=r}static Qi(e,t){let n=qd(),r=qd();for(const i of t.docChanges)switch(i.type){case 0:n=n.add(i.doc.key);break;case 1:r=r.add(i.doc.key)}return new Gp(e,t.fromCache,n,r)}}class Qp{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class $p{constructor(){this.Ki=!1,this.$i=!1,this.Ui=100,this.Wi=8}initialize(e,t){this.Gi=e,this.indexManager=t,this.Ki=!0}getDocumentsMatchingQuery(e,t,n,r){const i={result:null};return this.zi(e,t).next((e=>{i.result=e})).next((()=>{if(!i.result)return this.ji(e,t,r,n).next((e=>{i.result=e}))})).next((()=>{if(i.result)return;const n=new Qp;return this.Hi(e,t,n).next((r=>{if(i.result=r,this.$i)return this.Ji(e,t,n,r.size)}))})).next((()=>i.result))}Ji(e,t,n,r){return n.documentReadCount<this.Ui?(uu()<=V.DEBUG&&hu("QueryEngine","SDK will not create cache indexes for query:",Cd(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Ui,"documents"),Qu.resolve()):(uu()<=V.DEBUG&&hu("QueryEngine","Query:",Cd(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.Wi*r?(uu()<=V.DEBUG&&hu("QueryEngine","The SDK decides to create cache indexes for query:",Cd(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,_d(t))):Qu.resolve())}zi(e,t){if(yd(t))return Qu.resolve(null);let n=_d(t);return this.indexManager.getIndexType(e,n).next((r=>0===r?null:(null!==t.limit&&1===r&&(t=kd(t,null,"F"),n=_d(t)),this.indexManager.getDocumentsMatchingTarget(e,n).next((r=>{const i=qd(...r);return this.Gi.getDocuments(e,i).next((r=>this.indexManager.getMinOffset(e,n).next((n=>{const s=this.Yi(t,r);return this.Zi(t,s,i,n.readTime)?this.zi(e,kd(t,null,"F")):this.Xi(e,s,t,n)}))))})))))}ji(e,t,n,r){return yd(t)||r.isEqual(Ou.min())?Qu.resolve(null):this.Gi.getDocuments(e,n).next((i=>{const s=this.Yi(t,i);return this.Zi(t,s,n,r)?Qu.resolve(null):(uu()<=V.DEBUG&&hu("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),Cd(t)),this.Xi(e,s,t,Bu(r,-1)).next((e=>e)))}))}Yi(e,t){let n=new ch(Ad(e));return t.forEach(((t,r)=>{xd(e,r)&&(n=n.add(r))})),n}Zi(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(r)>0)}Hi(e,t,n){return uu()<=V.DEBUG&&hu("QueryEngine","Using full collection scan to execute query:",Cd(t)),this.Gi.getDocumentsMatchingQuery(e,t,qu.min(),n)}Xi(e,t,n,r){return this.Gi.getDocumentsMatchingQuery(e,n,r).next((e=>(t.forEach((t=>{e=e.insert(t.key,t)})),e)))}}class Yp{constructor(e,t,n,r){this.persistence=e,this.es=t,this.serializer=r,this.ts=new ah(Pu),this.ns=new Rd((e=>dd(e)),fd),this.rs=new Map,this.ss=e.getRemoteDocumentCache(),this.qr=e.getTargetCache(),this.Kr=e.getBundleCache(),this.os(n)}os(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new Lp(this.ss,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.ss.setIndexManager(this.indexManager),this.es.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",(t=>e.collect(t,this.ts)))}}function Xp(e,t,n,r){return new Yp(e,t,n,r)}async function Jp(e,t){const n=vu(e);return await n.persistence.runTransaction("Handle user change","readonly",(e=>{let r;return n.mutationQueue.getAllMutationBatches(e).next((i=>(r=i,n.os(t),n.mutationQueue.getAllMutationBatches(e)))).next((t=>{const i=[],s=[];let a=qd();for(const e of r){i.push(e.batchId);for(const t of e.mutations)a=a.add(t.key)}for(const e of t){s.push(e.batchId);for(const t of e.mutations)a=a.add(t.key)}return n.localDocuments.getDocuments(e,a).next((e=>({_s:e,removedBatchIds:i,addedBatchIds:s})))}))}))}function Zp(e){const t=vu(e);return t.persistence.runTransaction("Get last remote snapshot version","readonly",(e=>t.qr.getLastRemoteSnapshotVersion(e)))}function em(e,t,n){let r=qd(),i=qd();return n.forEach((e=>r=r.add(e))),t.getEntries(e,r).next((e=>{let r=Od();return n.forEach(((n,s)=>{const a=e.get(n);s.isFoundDocument()!==a.isFoundDocument()&&(i=i.add(n)),s.isNoDocument()&&s.version.isEqual(Ou.min())?(t.removeEntry(n,s.readTime),r=r.insert(n,s)):!a.isValidDocument()||s.version.compareTo(a.version)>0||0===s.version.compareTo(a.version)&&a.hasPendingWrites?(t.addEntry(s),r=r.insert(n,s)):hu("LocalStore","Ignoring outdated watch update for ",n,". Current version:",a.version," Watch version:",s.version)})),{us:r,cs:i}}))}function tm(e,t){const n=vu(e);return n.persistence.runTransaction("Get next mutation batch","readonly",(e=>(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t))))}function nm(e,t){const n=vu(e);return n.persistence.runTransaction("Allocate target","readwrite",(e=>{let r;return n.qr.getTargetData(e,t).next((i=>i?(r=i,Qu.resolve(r)):n.qr.allocateTargetId(e).next((i=>(r=new Ip(t,i,"TargetPurposeListen",e.currentSequenceNumber),n.qr.addTargetData(e,r).next((()=>r)))))))})).then((e=>{const r=n.ts.get(e.targetId);return(null===r||e.snapshotVersion.compareTo(r.snapshotVersion)>0)&&(n.ts=n.ts.insert(e.targetId,e),n.ns.set(t,e.targetId)),e}))}async function rm(e,t,n){const r=vu(e),i=r.ts.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,(e=>r.persistence.referenceDelegate.removeTarget(e,i)))}catch(e){if(!$u(e))throw e;hu("LocalStore","Failed to update sequence numbers for target ".concat(t,": ").concat(e))}r.ts=r.ts.remove(t),r.ns.delete(i.target)}function im(e,t,n){const r=vu(e);let i=Ou.min(),s=qd();return r.persistence.runTransaction("Execute query","readwrite",(e=>function(e,t,n){const r=vu(e),i=r.ns.get(n);return void 0!==i?Qu.resolve(r.ts.get(i)):r.qr.getTargetData(t,n)}(r,e,_d(t)).next((t=>{if(t)return i=t.lastLimboFreeSnapshotVersion,r.qr.getMatchingKeysForTargetId(e,t.targetId).next((e=>{s=e}))})).next((()=>r.es.getDocumentsMatchingQuery(e,t,n?i:Ou.min(),n?s:qd()))).next((e=>(sm(r,Nd(t),e),{documents:e,ls:s})))))}function sm(e,t,n){let r=e.rs.get(t)||Ou.min();n.forEach(((e,t)=>{t.readTime.compareTo(r)>0&&(r=t.readTime)})),e.rs.set(t,r)}class am{constructor(){this.activeTargetIds=Wd()}ds(e){this.activeTargetIds=this.activeTargetIds.add(e)}As(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Es(){const e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class om{constructor(){this.eo=new am,this.no={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.eo.ds(e),this.no[e]||"not-current"}updateQueryState(e,t,n){this.no[e]=t}removeLocalQueryTarget(e){this.eo.As(e)}isLocalQueryTarget(e){return this.eo.activeTargetIds.has(e)}clearQueryState(e){delete this.no[e]}getAllActiveQueryTargets(){return this.eo.activeTargetIds}isActiveQueryTarget(e){return this.eo.activeTargetIds.has(e)}start(){return this.eo=new am,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class lm{ro(e){}shutdown(){}}class cm{constructor(){this.io=()=>this.so(),this.oo=()=>this._o(),this.ao=[],this.uo()}ro(e){this.ao.push(e)}shutdown(){window.removeEventListener("online",this.io),window.removeEventListener("offline",this.oo)}uo(){window.addEventListener("online",this.io),window.addEventListener("offline",this.oo)}so(){hu("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.ao)e(0)}_o(){hu("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.ao)e(1)}static D(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let um=null;function hm(){return null===um?um=268435456+Math.round(2147483648*Math.random()):um++,"0x"+um.toString(16)}const dm={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class fm{constructor(e){this.co=e.co,this.lo=e.lo}ho(e){this.Po=e}Io(e){this.To=e}onMessage(e){this.Eo=e}close(){this.lo()}send(e){this.co(e)}Ao(){this.Po()}Ro(e){this.To(e)}Vo(e){this.Eo(e)}}const pm="WebChannelConnection";class mm extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),r=encodeURIComponent(this.databaseId.database);this.mo=t+"://"+e.host,this.fo="projects/".concat(n,"/databases/").concat(r),this.po="(default)"===this.databaseId.database?"project_id=".concat(n):"project_id=".concat(n,"&database_id=").concat(r)}get yo(){return!1}wo(e,t,n,r,i){const s=hm(),a=this.So(e,t);hu("RestConnection","Sending RPC '".concat(e,"' ").concat(s,":"),a,n);const o={"google-cloud-resource-prefix":this.fo,"x-goog-request-params":this.po};return this.bo(o,r,i),this.Do(e,a,o,n).then((t=>(hu("RestConnection","Received RPC '".concat(e,"' ").concat(s,": "),t),t)),(t=>{throw fu("RestConnection","RPC '".concat(e,"' ").concat(s," failed with error: "),t,"url: ",a,"request:",n),t}))}Co(e,t,n,r,i,s){return this.wo(e,t,n,r,i)}bo(e,t,n){e["X-Goog-Api-Client"]="gl-js/ fire/"+lu,e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach(((t,n)=>e[n]=t)),n&&n.headers.forEach(((t,n)=>e[n]=t))}So(e,t){const n=dm[e];return"".concat(this.mo,"/v1/").concat(t,":").concat(n)}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}Do(e,t,n,r){const i=hm();return new Promise(((s,a)=>{const o=new ru;o.setWithCredentials(!0),o.listenOnce(Jc.COMPLETE,(()=>{try{switch(o.getLastErrorCode()){case Xc.NO_ERROR:const t=o.getResponseJson();hu(pm,"XHR for RPC '".concat(e,"' ").concat(i," received:"),JSON.stringify(t)),s(t);break;case Xc.TIMEOUT:hu(pm,"RPC '".concat(e,"' ").concat(i," timed out")),a(new wu(yu.DEADLINE_EXCEEDED,"Request time out"));break;case Xc.HTTP_ERROR:const n=o.getStatus();if(hu(pm,"RPC '".concat(e,"' ").concat(i," failed with status:"),n,"response text:",o.getResponseText()),n>0){let e=o.getResponseJson();Array.isArray(e)&&(e=e[0]);const t=null==e?void 0:e.error;if(t&&t.status&&t.message){const e=function(e){const t=e.toLowerCase().replace(/_/g,"-");return Object.values(yu).indexOf(t)>=0?t:yu.UNKNOWN}(t.status);a(new wu(e,t.message))}else a(new wu(yu.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new wu(yu.UNAVAILABLE,"Connection failed."));break;default:mu()}}finally{hu(pm,"RPC '".concat(e,"' ").concat(i," completed."))}}));const l=JSON.stringify(r);hu(pm,"RPC '".concat(e,"' ").concat(i," sending request:"),r),o.send(t,"POST",l,n,15)}))}vo(e,t,n){const r=hm(),i=[this.mo,"/","google.firestore.v1.Firestore","/",e,"/channel"],s=$c(),a=Yc(),o={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:"projects/".concat(this.databaseId.projectId,"/databases/").concat(this.databaseId.database)},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},l=this.longPollingOptions.timeoutSeconds;void 0!==l&&(o.longPollingTimeout=Math.round(1e3*l)),this.useFetchStreams&&(o.xmlHttpFactory=new tu({})),this.bo(o.initMessageHeaders,t,n),o.encodeInitMessageHeaders=!0;const c=i.join("");hu(pm,"Creating RPC '".concat(e,"' stream ").concat(r,": ").concat(c),o);const u=s.createWebChannel(c,o);let h=!1,d=!1;const f=new fm({co:t=>{d?hu(pm,"Not sending because RPC '".concat(e,"' stream ").concat(r," is closed:"),t):(h||(hu(pm,"Opening RPC '".concat(e,"' stream ").concat(r," transport.")),u.open(),h=!0),hu(pm,"RPC '".concat(e,"' stream ").concat(r," sending:"),t),u.send(t))},lo:()=>u.close()}),p=(e,t,n)=>{e.listen(t,(e=>{try{n(e)}catch(e){setTimeout((()=>{throw e}),0)}}))};return p(u,nu.EventType.OPEN,(()=>{d||hu(pm,"RPC '".concat(e,"' stream ").concat(r," transport opened."))})),p(u,nu.EventType.CLOSE,(()=>{d||(d=!0,hu(pm,"RPC '".concat(e,"' stream ").concat(r," transport closed")),f.Ro())})),p(u,nu.EventType.ERROR,(t=>{d||(d=!0,fu(pm,"RPC '".concat(e,"' stream ").concat(r," transport errored:"),t),f.Ro(new wu(yu.UNAVAILABLE,"The operation could not be completed")))})),p(u,nu.EventType.MESSAGE,(t=>{var n;if(!d){const i=t.data[0];gu(!!i);const s=i,a=s.error||(null===(n=s[0])||void 0===n?void 0:n.error);if(a){hu(pm,"RPC '".concat(e,"' stream ").concat(r," received error:"),a);const t=a.status;let n=function(e){const t=xf[e];if(void 0!==t)return Pf(t)}(t),i=a.message;void 0===n&&(n=yu.INTERNAL,i="Unknown error status: "+t+" with message "+a.message),d=!0,f.Ro(new wu(n,i)),u.close()}else hu(pm,"RPC '".concat(e,"' stream ").concat(r," received:"),i),f.Vo(i)}})),p(a,Zc.STAT_EVENT,(t=>{t.stat===eu.PROXY?hu(pm,"RPC '".concat(e,"' stream ").concat(r," detected buffering proxy")):t.stat===eu.NOPROXY&&hu(pm,"RPC '".concat(e,"' stream ").concat(r," detected no buffering proxy"))})),setTimeout((()=>{f.Ao()}),0),f}}function gm(){return"undefined"!=typeof document?document:null}function vm(e){return new Xf(e,!0)}class ym{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1e3,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1.5,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:6e4;this.si=e,this.timerId=t,this.Fo=n,this.Mo=r,this.xo=i,this.Oo=0,this.No=null,this.Bo=Date.now(),this.reset()}reset(){this.Oo=0}Lo(){this.Oo=this.xo}ko(e){this.cancel();const t=Math.floor(this.Oo+this.qo()),n=Math.max(0,Date.now()-this.Bo),r=Math.max(0,t-n);r>0&&hu("ExponentialBackoff","Backing off for ".concat(r," ms (base delay: ").concat(this.Oo," ms, delay with jitter: ").concat(t," ms, last attempt: ").concat(n," ms ago)")),this.No=this.si.enqueueAfterDelay(this.timerId,r,(()=>(this.Bo=Date.now(),e()))),this.Oo*=this.Mo,this.Oo<this.Fo&&(this.Oo=this.Fo),this.Oo>this.xo&&(this.Oo=this.xo)}Qo(){null!==this.No&&(this.No.skipDelay(),this.No=null)}cancel(){null!==this.No&&(this.No.cancel(),this.No=null)}qo(){return(Math.random()-.5)*this.Oo}}class wm{constructor(e,t,n,r,i,s,a,o){this.si=e,this.Ko=n,this.$o=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.Uo=0,this.Wo=null,this.Go=null,this.stream=null,this.zo=new ym(e,t)}jo(){return 1===this.state||5===this.state||this.Ho()}Ho(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.Jo()}async stop(){this.jo()&&await this.close(0)}Yo(){this.state=0,this.zo.reset()}Zo(){this.Ho()&&null===this.Wo&&(this.Wo=this.si.enqueueAfterDelay(this.Ko,6e4,(()=>this.Xo())))}e_(e){this.t_(),this.stream.send(e)}async Xo(){if(this.Ho())return this.close(0)}t_(){this.Wo&&(this.Wo.cancel(),this.Wo=null)}n_(){this.Go&&(this.Go.cancel(),this.Go=null)}async close(e,t){this.t_(),this.n_(),this.zo.cancel(),this.Uo++,4!==e?this.zo.reset():t&&t.code===yu.RESOURCE_EXHAUSTED?(du(t.toString()),du("Using maximum backoff delay to prevent overloading the backend."),this.zo.Lo()):t&&t.code===yu.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.r_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Io(t)}r_(){}auth(){this.state=1;const e=this.i_(this.Uo),t=this.Uo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((e=>{let[n,r]=e;this.Uo===t&&this.s_(n,r)}),(t=>{e((()=>{const e=new wu(yu.UNKNOWN,"Fetching auth token failed: "+t.message);return this.o_(e)}))}))}s_(e,t){const n=this.i_(this.Uo);this.stream=this.__(e,t),this.stream.ho((()=>{n((()=>(this.state=2,this.Go=this.si.enqueueAfterDelay(this.$o,1e4,(()=>(this.Ho()&&(this.state=3),Promise.resolve()))),this.listener.ho())))})),this.stream.Io((e=>{n((()=>this.o_(e)))})),this.stream.onMessage((e=>{n((()=>this.onMessage(e)))}))}Jo(){this.state=5,this.zo.ko((async()=>{this.state=0,this.start()}))}o_(e){return hu("PersistentStream","close with error: ".concat(e)),this.stream=null,this.close(4,e)}i_(e){return t=>{this.si.enqueueAndForget((()=>this.Uo===e?t():(hu("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}}class bm extends wm{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}__(e,t){return this.connection.vo("Listen",e,t)}onMessage(e){this.zo.reset();const t=function(e,t){let n;if("targetChange"in t){t.targetChange;const r=function(e){return"NO_CHANGE"===e?0:"ADD"===e?1:"REMOVE"===e?2:"CURRENT"===e?3:"RESET"===e?4:mu()}(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],s=function(e,t){return e.useProto3Json?(gu(void 0===t||"string"==typeof t),fh.fromBase64String(t||"")):(gu(void 0===t||t instanceof Uint8Array),fh.fromUint8Array(t||new Uint8Array))}(e,t.targetChange.resumeToken),a=t.targetChange.cause,o=a&&function(e){const t=void 0===e.code?yu.UNKNOWN:Pf(e.code);return new wu(t,e.message||"")}(a);n=new qf(r,i,s,o||null)}else if("documentChange"in t){t.documentChange;const r=t.documentChange;r.document,r.document.name,r.document.updateTime;const i=ap(e,r.document.name),s=np(r.document.updateTime),a=r.document.createTime?np(r.document.createTime):Ou.min(),o=new Uh({mapValue:{fields:r.document.fields}}),l=Bh.newFoundDocument(i,s,a,o),c=r.targetIds||[],u=r.removedTargetIds||[];n=new Bf(c,u,l.key,l)}else if("documentDelete"in t){t.documentDelete;const r=t.documentDelete;r.document;const i=ap(e,r.document),s=r.readTime?np(r.readTime):Ou.min(),a=Bh.newNoDocument(i,s),o=r.removedTargetIds||[];n=new Bf([],o,a.key,a)}else if("documentRemove"in t){t.documentRemove;const r=t.documentRemove;r.document;const i=ap(e,r.document),s=r.removedTargetIds||[];n=new Bf([],s,i,null)}else{if(!("filter"in t))return mu();{t.filter;const e=t.filter;e.targetId;const{count:r=0,unchangedNames:i}=e,s=new Cf(r,i),a=e.targetId;n=new zf(a,s)}}return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return Ou.min();const t=e.targetChange;return t.targetIds&&t.targetIds.length?Ou.min():t.readTime?np(t.readTime):Ou.min()}(e);return this.listener.a_(t,n)}u_(e){const t={};t.database=cp(this.serializer),t.addTarget=function(e,t){let n;const r=t.target;if(n=pd(r)?{documents:fp(e,r)}:{query:pp(e,r)},n.targetId=t.targetId,t.resumeToken.approximateByteSize()>0){n.resumeToken=ep(e,t.resumeToken);const r=Jf(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(t.snapshotVersion.compareTo(Ou.min())>0){n.readTime=Zf(e,t.snapshotVersion.toTimestamp());const r=Jf(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);const n=function(e,t){const n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return mu()}}(t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.serializer,e);n&&(t.labels=n),this.e_(t)}c_(e){const t={};t.database=cp(this.serializer),t.removeTarget=e,this.e_(t)}}class _m extends wm{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i,this.l_=!1}get h_(){return this.l_}start(){this.l_=!1,this.lastStreamToken=void 0,super.start()}r_(){this.l_&&this.P_([])}__(e,t){return this.connection.vo("Write",e,t)}onMessage(e){if(gu(!!e.streamToken),this.lastStreamToken=e.streamToken,this.l_){this.zo.reset();const t=function(e,t){return e&&e.length>0?(gu(void 0!==t),e.map((e=>function(e,t){let n=e.updateTime?np(e.updateTime):np(t);return n.isEqual(Ou.min())&&(n=np(t)),new lf(n,e.transformResults||[])}(e,t)))):[]}(e.writeResults,e.commitTime),n=np(e.commitTime);return this.listener.I_(n,t)}return gu(!e.writeResults||0===e.writeResults.length),this.l_=!0,this.listener.T_()}E_(){const e={};e.database=cp(this.serializer),this.e_(e)}P_(e){const t={streamToken:this.lastStreamToken,writes:e.map((e=>dp(this.serializer,e)))};this.e_(t)}}class Em extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.d_=!1}A_(){if(this.d_)throw new wu(yu.FAILED_PRECONDITION,"The client has already been terminated.")}wo(e,t,n){return this.A_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((r=>{let[i,s]=r;return this.connection.wo(e,t,n,i,s)})).catch((e=>{throw"FirebaseError"===e.name?(e.code===yu.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new wu(yu.UNKNOWN,e.toString())}))}Co(e,t,n,r){return this.A_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((i=>{let[s,a]=i;return this.connection.Co(e,t,n,s,a,r)})).catch((e=>{throw"FirebaseError"===e.name?(e.code===yu.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new wu(yu.UNKNOWN,e.toString())}))}terminate(){this.d_=!0}}class Sm{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.V_=0,this.m_=null,this.f_=!0}g_(){0===this.V_&&(this.p_("Unknown"),this.m_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,(()=>(this.m_=null,this.y_("Backend didn't respond within 10 seconds."),this.p_("Offline"),Promise.resolve()))))}w_(e){"Online"===this.state?this.p_("Unknown"):(this.V_++,this.V_>=1&&(this.S_(),this.y_("Connection failed 1 times. Most recent error: ".concat(e.toString())),this.p_("Offline")))}set(e){this.S_(),this.V_=0,"Online"===e&&(this.f_=!1),this.p_(e)}p_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}y_(e){const t="Could not reach Cloud Firestore backend. ".concat(e,"\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.");this.f_?(du(t),this.f_=!1):hu("OnlineStateTracker",t)}S_(){null!==this.m_&&(this.m_.cancel(),this.m_=null)}}class km{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.b_=[],this.D_=new Map,this.C_=new Set,this.v_=[],this.F_=i,this.F_.ro((e=>{n.enqueueAndForget((async()=>{Dm(this)&&(hu("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=vu(e);t.C_.add(4),await Tm(t),t.M_.set("Unknown"),t.C_.delete(4),await Im(t)}(this))}))})),this.M_=new Sm(n,r)}}async function Im(e){if(Dm(e))for(const t of e.v_)await t(!0)}async function Tm(e){for(const t of e.v_)await t(!1)}function Cm(e,t){const n=vu(e);n.D_.has(t.targetId)||(n.D_.set(t.targetId,t),Rm(n)?Pm(n):Xm(n).Ho()&&Nm(n,t))}function xm(e,t){const n=vu(e),r=Xm(n);n.D_.delete(t),r.Ho()&&Am(n,t),0===n.D_.size&&(r.Ho()?r.Zo():Dm(n)&&n.M_.set("Unknown"))}function Nm(e,t){if(e.x_.Oe(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(Ou.min())>0){const n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(n)}Xm(e).u_(t)}function Am(e,t){e.x_.Oe(t),Xm(e).c_(t)}function Pm(e){e.x_=new Wf({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),_t:t=>e.D_.get(t)||null,nt:()=>e.datastore.serializer.databaseId}),Xm(e).start(),e.M_.g_()}function Rm(e){return Dm(e)&&!Xm(e).jo()&&e.D_.size>0}function Dm(e){return 0===vu(e).C_.size}function Om(e){e.x_=void 0}async function Lm(e){e.D_.forEach(((t,n)=>{Nm(e,t)}))}async function Mm(e,t){Om(e),Rm(e)?(e.M_.w_(t),Pm(e)):e.M_.set("Unknown")}async function jm(e,t,n){if(e.M_.set("Online"),t instanceof qf&&2===t.state&&t.cause)try{await async function(e,t){const n=t.cause;for(const r of t.targetIds)e.D_.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.D_.delete(r),e.x_.removeTarget(r))}(e,t)}catch(n){hu("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await Fm(e,n)}else if(t instanceof Bf?e.x_.$e(t):t instanceof zf?e.x_.Je(t):e.x_.Ge(t),!n.isEqual(Ou.min()))try{const t=await Zp(e.localStore);n.compareTo(t)>=0&&await function(e,t){const n=e.x_.it(t);return n.targetChanges.forEach(((n,r)=>{if(n.resumeToken.approximateByteSize()>0){const i=e.D_.get(r);i&&e.D_.set(r,i.withResumeToken(n.resumeToken,t))}})),n.targetMismatches.forEach(((t,n)=>{const r=e.D_.get(t);if(!r)return;e.D_.set(t,r.withResumeToken(fh.EMPTY_BYTE_STRING,r.snapshotVersion)),Am(e,t);const i=new Ip(r.target,t,n,r.sequenceNumber);Nm(e,i)})),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){hu("RemoteStore","Failed to raise snapshot:",t),await Fm(e,t)}}async function Fm(e,t,n){if(!$u(t))throw t;e.C_.add(1),await Tm(e),e.M_.set("Offline"),n||(n=()=>Zp(e.localStore)),e.asyncQueue.enqueueRetryable((async()=>{hu("RemoteStore","Retrying IndexedDB access"),await n(),e.C_.delete(1),await Im(e)}))}function Um(e,t){return t().catch((n=>Fm(e,n,t)))}async function Vm(e){const t=vu(e),n=Jm(t);let r=t.b_.length>0?t.b_[t.b_.length-1].batchId:-1;for(;Bm(t);)try{const e=await tm(t.localStore,r);if(null===e){0===t.b_.length&&n.Zo();break}r=e.batchId,zm(t,e)}catch(e){await Fm(t,e)}qm(t)&&Hm(t)}function Bm(e){return Dm(e)&&e.b_.length<10}function zm(e,t){e.b_.push(t);const n=Jm(e);n.Ho()&&n.h_&&n.P_(t.mutations)}function qm(e){return Dm(e)&&!Jm(e).jo()&&e.b_.length>0}function Hm(e){Jm(e).start()}async function Wm(e){Jm(e).E_()}async function Km(e){const t=Jm(e);for(const n of e.b_)t.P_(n.mutations)}async function Gm(e,t,n){const r=e.b_.shift(),i=If.from(r,t,n);await Um(e,(()=>e.remoteSyncer.applySuccessfulWrite(i))),await Vm(e)}async function Qm(e,t){t&&Jm(e).h_&&await async function(e,t){if(function(e){return Af(e)&&e!==yu.ABORTED}(t.code)){const n=e.b_.shift();Jm(e).Yo(),await Um(e,(()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t))),await Vm(e)}}(e,t),qm(e)&&Hm(e)}async function $m(e,t){const n=vu(e);n.asyncQueue.verifyOperationInProgress(),hu("RemoteStore","RemoteStore received new credentials");const r=Dm(n);n.C_.add(3),await Tm(n),r&&n.M_.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.C_.delete(3),await Im(n)}async function Ym(e,t){const n=vu(e);t?(n.C_.delete(2),await Im(n)):t||(n.C_.add(2),await Tm(n),n.M_.set("Unknown"))}function Xm(e){return e.O_||(e.O_=function(e,t,n){const r=vu(e);return r.A_(),new bm(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(e.datastore,e.asyncQueue,{ho:Lm.bind(null,e),Io:Mm.bind(null,e),a_:jm.bind(null,e)}),e.v_.push((async t=>{t?(e.O_.Yo(),Rm(e)?Pm(e):e.M_.set("Unknown")):(await e.O_.stop(),Om(e))}))),e.O_}function Jm(e){return e.N_||(e.N_=function(e,t,n){const r=vu(e);return r.A_(),new _m(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(e.datastore,e.asyncQueue,{ho:Wm.bind(null,e),Io:Qm.bind(null,e),T_:Km.bind(null,e),I_:Gm.bind(null,e)}),e.v_.push((async t=>{t?(e.N_.Yo(),await Vm(e)):(await e.N_.stop(),e.b_.length>0&&(hu("RemoteStore","Stopping write stream with ".concat(e.b_.length," pending writes")),e.b_=[]))}))),e.N_}class Zm{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new bu,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((e=>{}))}get promise(){return this.deferred.promise}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,a=new Zm(e,t,s,r,i);return a.start(n),a}start(e){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new wu(yu.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget((()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then((e=>this.deferred.resolve(e)))):Promise.resolve()))}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function eg(e,t){if(du("AsyncQueue","".concat(t,": ").concat(e)),$u(e))return new wu(yu.UNAVAILABLE,"".concat(t,": ").concat(e));throw e}class tg{constructor(e){this.comparator=e?(t,n)=>e(t,n)||Uu.comparator(t.key,n.key):(e,t)=>Uu.comparator(e.key,t.key),this.keyedMap=Md(),this.sortedSet=new ah(this.comparator)}static emptySet(e){return new tg(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){const t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal(((t,n)=>(e(t),!1)))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){const t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof tg))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const e=[];return this.forEach((t=>{e.push(t.toString())})),0===e.length?"DocumentSet ()":"DocumentSet (\n "+e.join(" \n")+"\n)"}copy(e,t){const n=new tg;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class ng{constructor(){this.B_=new ah(Uu.comparator)}track(e){const t=e.doc.key,n=this.B_.get(t);n?0!==e.type&&3===n.type?this.B_=this.B_.insert(t,e):3===e.type&&1!==n.type?this.B_=this.B_.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.B_=this.B_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.B_=this.B_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.B_=this.B_.remove(t):1===e.type&&2===n.type?this.B_=this.B_.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.B_=this.B_.insert(t,{type:2,doc:e.doc}):mu():this.B_=this.B_.insert(t,e)}L_(){const e=[];return this.B_.inorderTraversal(((t,n)=>{e.push(n)})),e}}class rg{constructor(e,t,n,r,i,s,a,o,l){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=l}static fromInitialDocuments(e,t,n,r,i){const s=[];return t.forEach((e=>{s.push({type:0,doc:e})})),new rg(e,t,tg.emptySet(t),s,n,r,!0,!1,i)}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)&&Id(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r].type!==n[r].type||!t[r].doc.isEqual(n[r].doc))return!1;return!0}}class ig{constructor(){this.k_=void 0,this.listeners=[]}}class sg{constructor(){this.queries=new Rd((e=>Td(e)),Id),this.onlineState="Unknown",this.q_=new Set}}async function ag(e,t){const n=vu(e),r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new ig),i)try{s.k_=await n.onListen(r)}catch(e){const n=eg(e,"Initialization of query '".concat(Cd(t.query),"' failed"));return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.Q_(n.onlineState),s.k_&&t.K_(s.k_)&&ug(n)}async function og(e,t){const n=vu(e),r=t.query;let i=!1;const s=n.queries.get(r);if(s){const e=s.listeners.indexOf(t);e>=0&&(s.listeners.splice(e,1),i=0===s.listeners.length)}if(i)return n.queries.delete(r),n.onUnlisten(r)}function lg(e,t){const n=vu(e);let r=!1;for(const i of t){const e=i.query,t=n.queries.get(e);if(t){for(const e of t.listeners)e.K_(i)&&(r=!0);t.k_=i}}r&&ug(n)}function cg(e,t,n){const r=vu(e),i=r.queries.get(t);if(i)for(const s of i.listeners)s.onError(n);r.queries.delete(t)}function ug(e){e.q_.forEach((e=>{e.next()}))}class hg{constructor(e,t,n){this.query=e,this.U_=t,this.W_=!1,this.G_=null,this.onlineState="Unknown",this.options=n||{}}K_(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new rg(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.W_?this.z_(e)&&(this.U_.next(e),t=!0):this.j_(e,this.onlineState)&&(this.H_(e),t=!0),this.G_=e,t}onError(e){this.U_.error(e)}Q_(e){this.onlineState=e;let t=!1;return this.G_&&!this.W_&&this.j_(this.G_,e)&&(this.H_(this.G_),t=!0),t}j_(e,t){if(!e.fromCache)return!0;const n="Offline"!==t;return(!this.options.J_||!n)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}z_(e){if(e.docChanges.length>0)return!0;const t=this.G_&&this.G_.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}H_(e){e=rg.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.W_=!0,this.U_.next(e)}}class dg{constructor(e){this.key=e}}class fg{constructor(e){this.key=e}}class pg{constructor(e,t){this.query=e,this.ia=t,this.sa=null,this.hasCachedResults=!1,this.current=!1,this.oa=qd(),this.mutatedKeys=qd(),this._a=Ad(e),this.aa=new tg(this._a)}get ua(){return this.ia}ca(e,t){const n=t?t.la:new ng,r=t?t.aa:this.aa;let i=t?t.mutatedKeys:this.mutatedKeys,s=r,a=!1;const o="F"===this.query.limitType&&r.size===this.query.limit?r.last():null,l="L"===this.query.limitType&&r.size===this.query.limit?r.first():null;if(e.inorderTraversal(((e,t)=>{const c=r.get(e),u=xd(this.query,t)?t:null,h=!!c&&this.mutatedKeys.has(c.key),d=!!u&&(u.hasLocalMutations||this.mutatedKeys.has(u.key)&&u.hasCommittedMutations);let f=!1;c&&u?c.data.isEqual(u.data)?h!==d&&(n.track({type:3,doc:u}),f=!0):this.ha(c,u)||(n.track({type:2,doc:u}),f=!0,(o&&this._a(u,o)>0||l&&this._a(u,l)<0)&&(a=!0)):!c&&u?(n.track({type:0,doc:u}),f=!0):c&&!u&&(n.track({type:1,doc:c}),f=!0,(o||l)&&(a=!0)),f&&(u?(s=s.add(u),i=d?i.add(e):i.delete(e)):(s=s.delete(e),i=i.delete(e)))})),null!==this.query.limit)for(;s.size>this.query.limit;){const e="F"===this.query.limitType?s.last():s.first();s=s.delete(e.key),i=i.delete(e.key),n.track({type:1,doc:e})}return{aa:s,la:n,Zi:a,mutatedKeys:i}}ha(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){const r=this.aa;this.aa=e.aa,this.mutatedKeys=e.mutatedKeys;const i=e.la.L_();i.sort(((e,t)=>function(e,t){const n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return mu()}};return n(e)-n(t)}(e.type,t.type)||this._a(e.doc,t.doc))),this.Pa(n);const s=t?this.Ia():[],a=0===this.oa.size&&this.current?1:0,o=a!==this.sa;return this.sa=a,0!==i.length||o?{snapshot:new rg(this.query,e.aa,r,i,e.mutatedKeys,0===a,o,!1,!!n&&n.resumeToken.approximateByteSize()>0),Ta:s}:{Ta:s}}Q_(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({aa:this.aa,la:new ng,mutatedKeys:this.mutatedKeys,Zi:!1},!1)):{Ta:[]}}Ea(e){return!this.ia.has(e)&&!!this.aa.has(e)&&!this.aa.get(e).hasLocalMutations}Pa(e){e&&(e.addedDocuments.forEach((e=>this.ia=this.ia.add(e))),e.modifiedDocuments.forEach((e=>{})),e.removedDocuments.forEach((e=>this.ia=this.ia.delete(e))),this.current=e.current)}Ia(){if(!this.current)return[];const e=this.oa;this.oa=qd(),this.aa.forEach((e=>{this.Ea(e.key)&&(this.oa=this.oa.add(e.key))}));const t=[];return e.forEach((e=>{this.oa.has(e)||t.push(new fg(e))})),this.oa.forEach((n=>{e.has(n)||t.push(new dg(n))})),t}da(e){this.ia=e.ls,this.oa=qd();const t=this.ca(e.documents);return this.applyChanges(t,!0)}Aa(){return rg.fromInitialDocuments(this.query,this.aa,this.mutatedKeys,0===this.sa,this.hasCachedResults)}}class mg{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class gg{constructor(e){this.key=e,this.Ra=!1}}class vg{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.Va={},this.ma=new Rd((e=>Td(e)),Id),this.fa=new Map,this.ga=new Set,this.pa=new ah(Uu.comparator),this.ya=new Map,this.wa=new Fp,this.Sa={},this.ba=new Map,this.Da=Rp.Nn(),this.onlineState="Unknown",this.Ca=void 0}get isPrimaryClient(){return!0===this.Ca}}async function yg(e,t){const n=Mg(e);let r,i;const s=n.ma.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.Aa();else{const e=await nm(n.localStore,_d(t)),s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await wg(n,t,r,"current"===s,e.resumeToken),n.isPrimaryClient&&Cm(n.remoteStore,e)}return i}async function wg(e,t,n,r,i){e.va=(t,n,r)=>async function(e,t,n,r){let i=t.view.ca(n);i.Zi&&(i=await im(e.localStore,t.query,!1).then((e=>{let{documents:n}=e;return t.view.ca(n,i)})));const s=r&&r.targetChanges.get(t.targetId),a=t.view.applyChanges(i,e.isPrimaryClient,s);return Ag(e,t.targetId,a.Ta),a.snapshot}(e,t,n,r);const s=await im(e.localStore,t,!0),a=new pg(t,s.ls),o=a.ca(s.documents),l=Vf.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,i),c=a.applyChanges(o,e.isPrimaryClient,l);Ag(e,n,c.Ta);const u=new mg(t,n,a);return e.ma.set(t,u),e.fa.has(n)?e.fa.get(n).push(t):e.fa.set(n,[t]),c.snapshot}async function bg(e,t){const n=vu(e),r=n.ma.get(t),i=n.fa.get(r.targetId);if(i.length>1)return n.fa.set(r.targetId,i.filter((e=>!Id(e,t)))),void n.ma.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await rm(n.localStore,r.targetId,!1).then((()=>{n.sharedClientState.clearQueryState(r.targetId),xm(n.remoteStore,r.targetId),xg(n,r.targetId)})).catch(Gu)):(xg(n,r.targetId),await rm(n.localStore,r.targetId,!0))}async function _g(e,t){const n=vu(e);try{const e=await function(e,t){const n=vu(e),r=t.snapshotVersion;let i=n.ts;return n.persistence.runTransaction("Apply remote event","readwrite-primary",(e=>{const s=n.ss.newChangeBuffer({trackRemovals:!0});i=n.ts;const a=[];t.targetChanges.forEach(((s,o)=>{const l=i.get(o);if(!l)return;a.push(n.qr.removeMatchingKeys(e,s.removedDocuments,o).next((()=>n.qr.addMatchingKeys(e,s.addedDocuments,o))));let c=l.withSequenceNumber(e.currentSequenceNumber);null!==t.targetMismatches.get(o)?c=c.withResumeToken(fh.EMPTY_BYTE_STRING,Ou.min()).withLastLimboFreeSnapshotVersion(Ou.min()):s.resumeToken.approximateByteSize()>0&&(c=c.withResumeToken(s.resumeToken,r)),i=i.insert(o,c),function(e,t,n){return 0===e.resumeToken.approximateByteSize()||t.snapshotVersion.toMicroseconds()-e.snapshotVersion.toMicroseconds()>=3e8||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0}(l,c,s)&&a.push(n.qr.updateTargetData(e,c))}));let o=Od(),l=qd();if(t.documentUpdates.forEach((r=>{t.resolvedLimboDocuments.has(r)&&a.push(n.persistence.referenceDelegate.updateLimboDocument(e,r))})),a.push(em(e,s,t.documentUpdates).next((e=>{o=e.us,l=e.cs}))),!r.isEqual(Ou.min())){const t=n.qr.getLastRemoteSnapshotVersion(e).next((t=>n.qr.setTargetsMetadata(e,e.currentSequenceNumber,r)));a.push(t)}return Qu.waitFor(a).next((()=>s.apply(e))).next((()=>n.localDocuments.getLocalViewOfDocuments(e,o,l))).next((()=>o))})).then((e=>(n.ts=i,e)))}(n.localStore,t);t.targetChanges.forEach(((e,t)=>{const r=n.ya.get(t);r&&(gu(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),e.addedDocuments.size>0?r.Ra=!0:e.modifiedDocuments.size>0?gu(r.Ra):e.removedDocuments.size>0&&(gu(r.Ra),r.Ra=!1))})),await Dg(n,e,t)}catch(e){await Gu(e)}}function Eg(e,t,n){const r=vu(e);if(r.isPrimaryClient&&0===n||!r.isPrimaryClient&&1===n){const e=[];r.ma.forEach(((n,r)=>{const i=r.view.Q_(t);i.snapshot&&e.push(i.snapshot)})),function(e,t){const n=vu(e);n.onlineState=t;let r=!1;n.queries.forEach(((e,n)=>{for(const i of n.listeners)i.Q_(t)&&(r=!0)})),r&&ug(n)}(r.eventManager,t),e.length&&r.Va.a_(e),r.onlineState=t,r.isPrimaryClient&&r.sharedClientState.setOnlineState(t)}}async function Sg(e,t,n){const r=vu(e);r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.ya.get(t),s=i&&i.key;if(s){let e=new ah(Uu.comparator);e=e.insert(s,Bh.newNoDocument(s,Ou.min()));const n=qd().add(s),i=new Uf(Ou.min(),new Map,new ah(Pu),e,n);await _g(r,i),r.pa=r.pa.remove(s),r.ya.delete(t),Rg(r)}else await rm(r.localStore,t,!1).then((()=>xg(r,t,n))).catch(Gu)}async function kg(e,t){const n=vu(e),r=t.batch.batchId;try{const e=await function(e,t){const n=vu(e);return n.persistence.runTransaction("Acknowledge batch","readwrite-primary",(e=>{const r=t.batch.keys(),i=n.ss.newChangeBuffer({trackRemovals:!0});return function(e,t,n,r){const i=n.batch,s=i.keys();let a=Qu.resolve();return s.forEach((e=>{a=a.next((()=>r.getEntry(t,e))).next((t=>{const s=n.docVersions.get(e);gu(null!==s),t.version.compareTo(s)<0&&(i.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),r.addEntry(t)))}))})),a.next((()=>e.mutationQueue.removeMutationBatch(t,i)))}(n,e,t,i).next((()=>i.apply(e))).next((()=>n.mutationQueue.performConsistencyCheck(e))).next((()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t.batch.batchId))).next((()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=qd();for(let n=0;n<e.mutationResults.length;++n)e.mutationResults[n].transformResults.length>0&&(t=t.add(e.batch.mutations[n].key));return t}(t)))).next((()=>n.localDocuments.getDocuments(e,r)))}))}(n.localStore,t);Cg(n,r,null),Tg(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await Dg(n,e)}catch(e){await Gu(e)}}async function Ig(e,t,n){const r=vu(e);try{const e=await function(e,t){const n=vu(e);return n.persistence.runTransaction("Reject batch","readwrite-primary",(e=>{let r;return n.mutationQueue.lookupMutationBatch(e,t).next((t=>(gu(null!==t),r=t.keys(),n.mutationQueue.removeMutationBatch(e,t)))).next((()=>n.mutationQueue.performConsistencyCheck(e))).next((()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t))).next((()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,r))).next((()=>n.localDocuments.getDocuments(e,r)))}))}(r.localStore,t);Cg(r,t,n),Tg(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await Dg(r,e)}catch(n){await Gu(n)}}function Tg(e,t){(e.ba.get(t)||[]).forEach((e=>{e.resolve()})),e.ba.delete(t)}function Cg(e,t,n){const r=vu(e);let i=r.Sa[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.Sa[r.currentUser.toKey()]=i}}function xg(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;e.sharedClientState.removeLocalQueryTarget(t);for(const r of e.fa.get(t))e.ma.delete(r),n&&e.Va.Fa(r,n);e.fa.delete(t),e.isPrimaryClient&&e.wa.Rr(t).forEach((t=>{e.wa.containsKey(t)||Ng(e,t)}))}function Ng(e,t){e.ga.delete(t.path.canonicalString());const n=e.pa.get(t);null!==n&&(xm(e.remoteStore,n),e.pa=e.pa.remove(t),e.ya.delete(n),Rg(e))}function Ag(e,t,n){for(const r of n)r instanceof dg?(e.wa.addReference(r.key,t),Pg(e,r)):r instanceof fg?(hu("SyncEngine","Document no longer in limbo: "+r.key),e.wa.removeReference(r.key,t),e.wa.containsKey(r.key)||Ng(e,r.key)):mu()}function Pg(e,t){const n=t.key,r=n.path.canonicalString();e.pa.get(n)||e.ga.has(r)||(hu("SyncEngine","New document in limbo: "+n),e.ga.add(r),Rg(e))}function Rg(e){for(;e.ga.size>0&&e.pa.size<e.maxConcurrentLimboResolutions;){const t=e.ga.values().next().value;e.ga.delete(t);const n=new Uu(Mu.fromString(t)),r=e.Da.next();e.ya.set(r,new gg(n)),e.pa=e.pa.insert(n,r),Cm(e.remoteStore,new Ip(_d(vd(n.path)),r,"TargetPurposeLimboResolution",Yu._e))}}async function Dg(e,t,n){const r=vu(e),i=[],s=[],a=[];r.ma.isEmpty()||(r.ma.forEach(((e,o)=>{a.push(r.va(o,t,n).then((e=>{if((e||n)&&r.isPrimaryClient&&r.sharedClientState.updateQueryState(o.targetId,(null==e?void 0:e.fromCache)?"not-current":"current"),e){i.push(e);const t=Gp.Qi(o.targetId,e);s.push(t)}})))})),await Promise.all(a),r.Va.a_(i),await async function(e,t){const n=vu(e);try{await n.persistence.runTransaction("notifyLocalViewChanges","readwrite",(e=>Qu.forEach(t,(t=>Qu.forEach(t.ki,(r=>n.persistence.referenceDelegate.addReference(e,t.targetId,r))).next((()=>Qu.forEach(t.qi,(r=>n.persistence.referenceDelegate.removeReference(e,t.targetId,r)))))))))}catch(e){if(!$u(e))throw e;hu("LocalStore","Failed to update sequence numbers: "+e)}for(const r of t){const e=r.targetId;if(!r.fromCache){const t=n.ts.get(e),r=t.snapshotVersion,i=t.withLastLimboFreeSnapshotVersion(r);n.ts=n.ts.insert(e,i)}}}(r.localStore,s))}async function Og(e,t){const n=vu(e);if(!n.currentUser.isEqual(t)){hu("SyncEngine","User change. New user:",t.toKey());const e=await Jp(n.localStore,t);n.currentUser=t,function(e,t){e.ba.forEach((e=>{e.forEach((e=>{e.reject(new wu(yu.CANCELLED,t))}))})),e.ba.clear()}(n,"'waitForPendingWrites' promise is rejected due to a user change."),n.sharedClientState.handleUserChange(t,e.removedBatchIds,e.addedBatchIds),await Dg(n,e._s)}}function Lg(e,t){const n=vu(e),r=n.ya.get(t);if(r&&r.Ra)return qd().add(r.key);{let e=qd();const r=n.fa.get(t);if(!r)return e;for(const t of r){const r=n.ma.get(t);e=e.unionWith(r.view.ua)}return e}}function Mg(e){const t=vu(e);return t.remoteStore.remoteSyncer.applyRemoteEvent=_g.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=Lg.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=Sg.bind(null,t),t.Va.a_=lg.bind(null,t.eventManager),t.Va.Fa=cg.bind(null,t.eventManager),t}function jg(e){const t=vu(e);return t.remoteStore.remoteSyncer.applySuccessfulWrite=kg.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=Ig.bind(null,t),t}class Fg{constructor(){this.synchronizeTabs=!1}async initialize(e){this.serializer=vm(e.databaseInfo.databaseId),this.sharedClientState=this.createSharedClientState(e),this.persistence=this.createPersistence(e),await this.persistence.start(),this.localStore=this.createLocalStore(e),this.gcScheduler=this.createGarbageCollectionScheduler(e,this.localStore),this.indexBackfillerScheduler=this.createIndexBackfillerScheduler(e,this.localStore)}createGarbageCollectionScheduler(e,t){return null}createIndexBackfillerScheduler(e,t){return null}createLocalStore(e){return Xp(this.persistence,new $p,e.initialUser,this.serializer)}createPersistence(e){return new Hp(Kp.jr,this.serializer)}createSharedClientState(e){return new om}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class Ug{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>Eg(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=Og.bind(null,this.syncEngine),await Ym(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new sg}createDatastore(e){const t=vm(e.databaseInfo.databaseId),n=function(e){return new mm(e)}(e.databaseInfo);return function(e,t,n,r){return new Em(e,t,n,r)}(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return function(e,t,n,r,i){return new km(e,t,n,r,i)}(this.localStore,this.datastore,e.asyncQueue,(e=>Eg(this.syncEngine,e,0)),cm.D()?new cm:new lm)}createSyncEngine(e,t){return function(e,t,n,r,i,s,a){const o=new vg(e,t,n,r,i,s);return a&&(o.Ca=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=vu(e);hu("RemoteStore","RemoteStore shutting down."),t.C_.add(5),await Tm(t),t.F_.shutdown(),t.M_.set("Unknown")}(this.remoteStore)}}class Vg{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Oa(this.observer.next,e)}error(e){this.observer.error?this.Oa(this.observer.error,e):du("Uncaught Error in snapshot listener:",e.toString())}Na(){this.muted=!0}Oa(e,t){this.muted||setTimeout((()=>{this.muted||e(t)}),0)}}class Bg{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=ou.UNAUTHENTICATED,this.clientId=Au.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,(async e=>{hu("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e})),this.appCheckCredentials.start(n,(e=>(hu("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user))))}async getConfiguration(){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}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new wu(yu.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const e=new bu;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(t){const n=eg(t,"Failed to shutdown persistence");e.reject(n)}})),e.promise}}async function zg(e,t){e.asyncQueue.verifyOperationInProgress(),hu("FirestoreClient","Initializing OfflineComponentProvider");const n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener((async e=>{r.isEqual(e)||(await Jp(t.localStore,e),r=e)})),t.persistence.setDatabaseDeletedListener((()=>e.terminate())),e._offlineComponents=t}async function qg(e,t){e.asyncQueue.verifyOperationInProgress();const n=await Wg(e);hu("FirestoreClient","Initializing OnlineComponentProvider");const r=await e.getConfiguration();await t.initialize(n,r),e.setCredentialChangeListener((e=>$m(t.remoteStore,e))),e.setAppCheckTokenChangeListener(((e,n)=>$m(t.remoteStore,n))),e._onlineComponents=t}function Hg(e){return"FirebaseError"===e.name?e.code===yu.FAILED_PRECONDITION||e.code===yu.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}async function Wg(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){hu("FirestoreClient","Using user provided OfflineComponentProvider");try{await zg(e,e._uninitializedComponentsProvider._offline)}catch(t){const n=t;if(!Hg(n))throw n;fu("Error using user provided cache. Falling back to memory cache: "+n),await zg(e,new Fg)}}else hu("FirestoreClient","Using default OfflineComponentProvider"),await zg(e,new Fg);return e._offlineComponents}async function Kg(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(hu("FirestoreClient","Using user provided OnlineComponentProvider"),await qg(e,e._uninitializedComponentsProvider._online)):(hu("FirestoreClient","Using default OnlineComponentProvider"),await qg(e,new Ug))),e._onlineComponents}function Gg(e){return Kg(e).then((e=>e.syncEngine))}async function Qg(e){const t=await Kg(e),n=t.eventManager;return n.onListen=yg.bind(null,t.syncEngine),n.onUnlisten=bg.bind(null,t.syncEngine),n}function $g(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const r=new bu;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,i){const s=new Vg({next:n=>{t.enqueueAndForget((()=>og(e,a))),n.fromCache&&"server"===r.source?i.reject(new wu(yu.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.)')):i.resolve(n)},error:e=>i.reject(e)}),a=new hg(n,s,{includeMetadataChanges:!0,J_:!0});return ag(e,a)}(await Qg(e),e.asyncQueue,t,n,r))),r.promise}function Yg(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const Xg=new Map;function Jg(e,t,n){if(!n)throw new wu(yu.INVALID_ARGUMENT,"Function ".concat(e,"() cannot be called with an empty ").concat(t,"."))}function Zg(e){if(!Uu.isDocumentKey(e))throw new wu(yu.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but ".concat(e," has ").concat(e.length,"."))}function ev(e){if(Uu.isDocumentKey(e))throw new wu(yu.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but ".concat(e," has ").concat(e.length,"."))}function tv(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e="".concat(e.substring(0,20),"...")),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{const t=function(e){return e.constructor?e.constructor.name:null}(e);return t?"a custom ".concat(t," object"):"an object"}}return"function"==typeof e?"a function":mu()}function nv(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new wu(yu.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const n=tv(e);throw new wu(yu.INVALID_ARGUMENT,"Expected type '".concat(t.name,"', but it was: ").concat(n))}}return e}class rv{constructor(e){var t,n;if(void 0===e.host){if(void 0!==e.ssl)throw new wu(yu.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new wu(yu.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}(function(e,t,n,r){if(!0===t&&!0===r)throw new wu(yu.INVALID_ARGUMENT,"".concat(e," and ").concat(n," cannot be used together."))})("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=Yg(null!==(n=e.experimentalLongPollingOptions)&&void 0!==n?n:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new wu(yu.INVALID_ARGUMENT,"invalid long polling timeout: ".concat(e.timeoutSeconds," (must not be NaN)"));if(e.timeoutSeconds<5)throw new wu(yu.INVALID_ARGUMENT,"invalid long polling timeout: ".concat(e.timeoutSeconds," (minimum allowed value is 5)"));if(e.timeoutSeconds>30)throw new wu(yu.INVALID_ARGUMENT,"invalid long polling timeout: ".concat(e.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(e,t){return e.timeoutSeconds===t.timeoutSeconds}(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class iv{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new rv({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new wu(yu.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 void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new wu(yu.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 rv(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new Eu;switch(e.type){case"firstParty":return new Tu(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new wu(yu.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=Xg.get(e);t&&(hu("ComponentProvider","Removing Datastore"),Xg.delete(e),t.terminate())}(this),Promise.resolve()}}function sv(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};var i;const s=(e=nv(e,iv))._getSettings(),a="".concat(t,":").concat(n);if("firestore.googleapis.com"!==s.host&&s.host!==a&&fu("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),e._setSettings(Object.assign(Object.assign({},s),{host:a,ssl:!1})),r.mockUserToken){let t,n;if("string"==typeof r.mockUserToken)t=r.mockUserToken,n=ou.MOCK_USER;else{t=function(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const s=Object.assign({iss:"https://securetoken.google.com/".concat(n),aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e);return[o(JSON.stringify({alg:"none",type:"JWT"})),o(JSON.stringify(s)),""].join(".")}(r.mockUserToken,null===(i=e._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new wu(yu.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");n=new ou(s)}e._authCredentials=new Su(new _u(t,n))}}class av{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new av(this.firestore,e,this._query)}}class ov{constructor(e,t,n){this.converter=t,this._key=n,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 lv(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new ov(this.firestore,e,this._key)}}class lv extends av{constructor(e,t,n){super(e,t,vd(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new ov(this.firestore,null,new Uu(e))}withConverter(e){return new lv(this.firestore,e,this._path)}}function cv(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i<n;i++)r[i-2]=arguments[i];if(e=O(e),Jg("collection","path",t),e instanceof iv){const n=Mu.fromString(t,...r);return ev(n),new lv(e,null,n)}{if(!(e instanceof ov||e instanceof lv))throw new wu(yu.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const n=e._path.child(Mu.fromString(t,...r));return ev(n),new lv(e.firestore,null,n)}}function uv(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i<n;i++)r[i-2]=arguments[i];if(e=O(e),1===arguments.length&&(t=Au.newId()),Jg("doc","path",t),e instanceof iv){const n=Mu.fromString(t,...r);return Zg(n),new ov(e,null,new Uu(n))}{if(!(e instanceof ov||e instanceof lv))throw new wu(yu.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const n=e._path.child(Mu.fromString(t,...r));return Zg(n),new ov(e.firestore,e instanceof lv?e.converter:null,new Uu(n))}}class hv{constructor(){this.Ja=Promise.resolve(),this.Ya=[],this.Za=!1,this.Xa=[],this.eu=null,this.tu=!1,this.nu=!1,this.ru=[],this.zo=new ym(this,"async_queue_retry"),this.iu=()=>{const e=gm();e&&hu("AsyncQueue","Visibility state changed to "+e.visibilityState),this.zo.Qo()};const e=gm();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.iu)}get isShuttingDown(){return this.Za}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.su(),this.ou(e)}enterRestrictedMode(e){if(!this.Za){this.Za=!0,this.nu=e||!1;const t=gm();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.iu)}}enqueue(e){if(this.su(),this.Za)return new Promise((()=>{}));const t=new bu;return this.ou((()=>this.Za&&this.nu?Promise.resolve():(e().then(t.resolve,t.reject),t.promise))).then((()=>t.promise))}enqueueRetryable(e){this.enqueueAndForget((()=>(this.Ya.push(e),this._u())))}async _u(){if(0!==this.Ya.length){try{await this.Ya[0](),this.Ya.shift(),this.zo.reset()}catch(e){if(!$u(e))throw e;hu("AsyncQueue","Operation failed with retryable error: "+e)}this.Ya.length>0&&this.zo.ko((()=>this._u()))}}ou(e){const t=this.Ja.then((()=>(this.tu=!0,e().catch((e=>{this.eu=e,this.tu=!1;const t=function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e);throw du("INTERNAL UNHANDLED ERROR: ",t),e})).then((e=>(this.tu=!1,e))))));return this.Ja=t,t}enqueueAfterDelay(e,t,n){this.su(),this.ru.indexOf(e)>-1&&(t=0);const r=Zm.createAndSchedule(this,e,t,n,(e=>this.au(e)));return this.Xa.push(r),r}su(){this.eu&&mu()}verifyOperationInProgress(){}async uu(){let e;do{e=this.Ja,await e}while(e!==this.Ja)}cu(e){for(const t of this.Xa)if(t.timerId===e)return!0;return!1}lu(e){return this.uu().then((()=>{this.Xa.sort(((e,t)=>e.targetTimeMs-t.targetTimeMs));for(const t of this.Xa)if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.uu()}))}hu(e){this.ru.push(e)}au(e){const t=this.Xa.indexOf(e);this.Xa.splice(t,1)}}class dv extends iv{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new hv,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||pv(this),this._firestoreClient.terminate()}}function fv(e){return e._firestoreClient||pv(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function pv(e){var t,n,r;const i=e._freezeSettings(),s=function(e,t,n,r){return new _h(e,t,n,r.host,r.ssl,r.experimentalForceLongPolling,r.experimentalAutoDetectLongPolling,Yg(r.experimentalLongPollingOptions),r.useFetchStreams)}(e._databaseId,(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",e._persistenceKey,i);e._firestoreClient=new Bg(e._authCredentials,e._appCheckCredentials,e._queue,s),(null===(n=i.localCache)||void 0===n?void 0:n._offlineComponentProvider)&&(null===(r=i.localCache)||void 0===r?void 0:r._onlineComponentProvider)&&(e._firestoreClient._uninitializedComponentsProvider={_offlineKind:i.localCache.kind,_offline:i.localCache._offlineComponentProvider,_online:i.localCache._onlineComponentProvider})}class mv{constructor(e){this._byteString=e}static fromBase64String(e){try{return new mv(fh.fromBase64String(e))}catch(e){throw new wu(yu.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new mv(fh.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)}}class gv{constructor(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(let r=0;r<t.length;++r)if(0===t[r].length)throw new wu(yu.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Fu(t)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class vv{constructor(e){this._methodName=e}}class yv{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new wu(yu.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new wu(yu.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return Pu(this._lat,e._lat)||Pu(this._long,e._long)}}const wv=/^__.*__$/;class bv{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new yf(e,this.data,this.fieldMask,t,this.fieldTransforms):new vf(e,this.data,t,this.fieldTransforms)}}function _v(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw mu()}}class Ev{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===i&&this.Pu(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Iu(){return this.settings.Iu}Tu(e){return new Ev(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Eu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Tu({path:n,du:!1});return r.Au(e),r}Ru(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Tu({path:n,du:!1});return r.Pu(),r}Vu(e){return this.Tu({path:void 0,du:!0})}mu(e){return Ov(e,this.settings.methodName,this.settings.fu||!1,this.path,this.settings.gu)}contains(e){return void 0!==this.fieldMask.find((t=>e.isPrefixOf(t)))||void 0!==this.fieldTransforms.find((t=>e.isPrefixOf(t.field)))}Pu(){if(this.path)for(let e=0;e<this.path.length;e++)this.Au(this.path.get(e))}Au(e){if(0===e.length)throw this.mu("Document fields must not be empty");if(_v(this.Iu)&&wv.test(e))throw this.mu('Document fields cannot begin and end with "__"')}}class Sv{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||vm(e)}pu(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return new Ev({Iu:e,methodName:t,gu:n,path:Fu.emptyPath(),du:!1,fu:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function kv(e){const t=e._freezeSettings(),n=vm(e._databaseId);return new Sv(e._databaseId,!!t.ignoreUndefinedProperties,n)}function Iv(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};const a=e.pu(s.merge||s.mergeFields?2:0,t,n,i);Av("Data must be an object, but it was:",a,r);const o=xv(r,a);let l,c;if(s.merge)l=new hh(a.fieldMask),c=a.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=Pv(t,r,n);if(!a.contains(i))throw new wu(yu.INVALID_ARGUMENT,"Field '".concat(i,"' is specified in your field mask but missing from your input data."));Lv(e,i)||e.push(i)}l=new hh(e),c=a.fieldTransforms.filter((e=>l.covers(e.field)))}else l=null,c=a.fieldTransforms;return new bv(new Uh(o),l,c)}function Tv(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return Cv(n,e.pu(r?4:3,t))}function Cv(e,t){if(Nv(e=O(e)))return Av("Unsupported field value:",t,e),xv(e,t);if(e instanceof vv)return function(e,t){if(!_v(t.Iu))throw t.mu("".concat(e._methodName,"() can only be used with update() and set()"));if(!t.path)throw t.mu("".concat(e._methodName,"() is not currently supported inside arrays"));const n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.du&&4!==t.Iu)throw t.mu("Nested arrays are not supported");return function(e,t){const n=[];let r=0;for(const i of e){let e=Cv(i,t.Vu(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=O(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return Qd(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){const n=Du.fromDate(e);return{timestampValue:Zf(t.serializer,n)}}if(e instanceof Du){const n=new Du(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:Zf(t.serializer,n)}}if(e instanceof yv)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof mv)return{bytesValue:ep(t.serializer,e._byteString)};if(e instanceof ov){const n=t.databaseId,r=e.firestore._databaseId;if(!r.isEqual(n))throw t.mu("Document reference is for database ".concat(r.projectId,"/").concat(r.database," but should be for database ").concat(n.projectId,"/").concat(n.database));return{referenceValue:rp(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.mu("Unsupported field value: ".concat(tv(e)))}(e,t)}function xv(e,t){const n={};return sh(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):ih(e,((e,r)=>{const i=Cv(r,t.Eu(e));null!=i&&(n[e]=i)})),{mapValue:{fields:n}}}function Nv(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof Du||e instanceof yv||e instanceof mv||e instanceof ov||e instanceof vv)}function Av(e,t,n){if(!Nv(n)||!function(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(n)){const r=tv(n);throw"an object"===r?t.mu(e+" a custom object"):t.mu(e+" "+r)}}function Pv(e,t,n){if((t=O(t))instanceof gv)return t._internalPath;if("string"==typeof t)return Dv(e,t);throw Ov("Field path arguments must be of type string or ",e,!1,void 0,n)}const Rv=new RegExp("[~\\*/\\[\\]]");function Dv(e,t,n){if(t.search(Rv)>=0)throw Ov("Invalid field path (".concat(t,"). Paths must not contain '~', '*', '/', '[', or ']'"),e,!1,void 0,n);try{return new gv(...t.split("."))._internalPath}catch(Js){throw Ov("Invalid field path (".concat(t,"). Paths must not be empty, begin with '.', end with '.', or contain '..'"),e,!1,void 0,n)}}function Ov(e,t,n,r,i){const s=r&&!r.isEmpty(),a=void 0!==i;let o="Function ".concat(t,"() called with invalid data");n&&(o+=" (via `toFirestore()`)"),o+=". ";let l="";return(s||a)&&(l+=" (found",s&&(l+=" in field ".concat(r)),a&&(l+=" in document ".concat(i)),l+=")"),new wu(yu.INVALID_ARGUMENT,o+e+l)}function Lv(e,t){return e.some((e=>e.isEqual(t)))}class Mv{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new ov(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new jv(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){const t=this._document.data.field(Fv("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class jv extends Mv{data(){return super.data()}}function Fv(e,t){return"string"==typeof t?Dv(e,t):t instanceof gv?t._internalPath:t._delegate._internalPath}function Uv(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new wu(yu.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class Vv{}class Bv extends Vv{}function zv(e,t){let n=[];for(var r=arguments.length,i=new Array(r>2?r-2:0),s=2;s<r;s++)i[s-2]=arguments[s];t instanceof Vv&&n.push(t),n=n.concat(i),function(e){const t=e.filter((e=>e instanceof Wv)).length,n=e.filter((e=>e instanceof qv)).length;if(t>1||t>0&&n>0)throw new wu(yu.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(...)))`.")}(n);for(const a of n)e=a._apply(e);return e}class qv extends Bv{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new qv(e,t,n)}_apply(e){const t=this._parse(e);return Qv(e._query,t),new av(e.firestore,e.converter,Sd(e._query,t))}_parse(e){const t=kv(e.firestore),n=function(e,t,n,r,i,s,a){let o;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new wu(yu.INVALID_ARGUMENT,"Invalid Query. You can't perform '".concat(s,"' queries on documentId()."));if("in"===s||"not-in"===s){Gv(a,s);const t=[];for(const n of a)t.push(Kv(r,e,n));o={arrayValue:{values:t}}}else o=Kv(r,e,a)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||Gv(a,s),o=Tv(n,t,a,"in"===s||"not-in"===s);return Qh.create(i,s,o)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value);return n}}function Hv(e,t,n){const r=t,i=Fv("where",e);return qv._create(i,r,n)}class Wv extends Vv{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new Wv(e,t)}_parse(e){const t=this._queryConstraints.map((t=>t._parse(e))).filter((e=>e.getFilters().length>0));return 1===t.length?t[0]:$h.create(t,this._getOperator())}_apply(e){const t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;const r=t.getFlattenedFilters();for(const i of r)Qv(n,i),n=Sd(n,i)}(e._query,t),new av(e.firestore,e.converter,Sd(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}function Kv(e,t,n){if("string"==typeof(n=O(n))){if(""===n)throw new wu(yu.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!wd(t)&&-1!==n.indexOf("/"))throw new wu(yu.INVALID_ARGUMENT,"Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '".concat(n,"' contains a '/' character."));const r=t.path.child(Mu.fromString(n));if(!Uu.isDocumentKey(r))throw new wu(yu.INVALID_ARGUMENT,"Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '".concat(r,"' is not because it has an odd number of segments (").concat(r.length,")."));return Ph(e,new Uu(r))}if(n instanceof ov)return Ph(e,n._key);throw new wu(yu.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ".concat(tv(n),"."))}function Gv(e,t){if(!Array.isArray(e)||0===e.length)throw new wu(yu.INVALID_ARGUMENT,"Invalid Query. A non-empty array is required for '".concat(t.toString(),"' filters."))}function Qv(e,t){const n=function(e,t){for(const n of e)for(const e of n.getFlattenedFilters())if(t.indexOf(e.op)>=0)return e.op;return null}(e.filters,function(e){switch(e){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[]}}(t.op));if(null!==n)throw n===t.op?new wu(yu.INVALID_ARGUMENT,"Invalid query. You cannot use more than one '".concat(t.op.toString(),"' filter.")):new wu(yu.INVALID_ARGUMENT,"Invalid query. You cannot use '".concat(t.op.toString(),"' filters with '").concat(n.toString(),"' filters."))}class $v{convertValue(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"none";switch(kh(e)){case 0:return null;case 1:return e.booleanValue;case 2:return gh(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(vh(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 10:return this.convertObject(e.mapValue,t);default:throw mu()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"none";const n={};return ih(e,((e,r)=>{n[e]=this.convertValue(r,t)})),n}convertGeoPoint(e){return new yv(gh(e.latitude),gh(e.longitude))}convertArray(e,t){return(e.values||[]).map((e=>this.convertValue(e,t)))}convertServerTimestamp(e,t){switch(t){case"previous":const n=wh(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(bh(e));default:return null}}convertTimestamp(e){const t=mh(e);return new Du(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=Mu.fromString(e);gu(kp(n));const r=new Eh(n.get(1),n.get(3)),i=new Uu(n.popFirst(5));return r.isEqual(t)||du("Document ".concat(i," contains a document reference within a different database (").concat(r.projectId,"/").concat(r.database,") which is not supported. It will be treated as a reference in the current database (").concat(t.projectId,"/").concat(t.database,") instead.")),i}}function Yv(e,t,n){let r;return r=e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t,r}class Xv{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class Jv extends Mv{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this._document){if(this._converter){const t=new Zv(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this._document){const n=this._document.data.field(Fv("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class Zv extends Jv{data(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return super.data(e)}}class ey{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new Xv(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const e=[];return this.forEach((t=>e.push(t))),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,t){this._snapshot.docs.forEach((n=>{e.call(t,new Zv(this._firestore,this._userDataWriter,n.key,n,new Xv(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))}))}docChanges(){const e=!!(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).includeMetadataChanges;if(e&&this._snapshot.excludesMetadataChanges)throw new wu(yu.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===e||(this._cachedChanges=function(e,t){if(e._snapshot.oldDocs.isEmpty()){let t=0;return e._snapshot.docChanges.map((n=>{const r=new Zv(e._firestore,e._userDataWriter,n.doc.key,n.doc,new Xv(e._snapshot.mutatedKeys.has(n.doc.key),e._snapshot.fromCache),e.query.converter);return n.doc,{type:"added",doc:r,oldIndex:-1,newIndex:t++}}))}{let n=e._snapshot.oldDocs;return e._snapshot.docChanges.filter((e=>t||3!==e.type)).map((t=>{const r=new Zv(e._firestore,e._userDataWriter,t.doc.key,t.doc,new Xv(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter);let i=-1,s=-1;return 0!==t.type&&(i=n.indexOf(t.doc.key),n=n.delete(t.doc.key)),1!==t.type&&(n=n.add(t.doc),s=n.indexOf(t.doc.key)),{type:ty(t.type),doc:r,oldIndex:i,newIndex:s}}))}}(this,e),this._cachedChangesIncludeMetadataChanges=e),this._cachedChanges}}function ty(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return mu()}}class ny extends $v{constructor(e){super(),this.firestore=e}convertBytes(e){return new mv(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new ov(this.firestore,null,t)}}function ry(e){e=nv(e,av);const t=nv(e.firestore,dv),n=fv(t),r=new ny(t);return Uv(e._query),$g(n,e._query).then((n=>new ey(t,r,e,n)))}function iy(e){return ay(nv(e.firestore,dv),[new Ef(e._key,cf.none())])}function sy(e,t){const n=nv(e.firestore,dv),r=uv(e),i=Yv(e.converter,t);return ay(n,[Iv(kv(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,cf.exists(!1))]).then((()=>r))}function ay(e,t){return function(e,t){const n=new bu;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){const r=jg(e);try{const e=await function(e,t){const n=vu(e),r=Du.now(),i=t.reduce(((e,t)=>e.add(t.key)),qd());let s,a;return n.persistence.runTransaction("Locally write mutations","readwrite",(e=>{let o=Od(),l=qd();return n.ss.getEntries(e,i).next((e=>{o=e,o.forEach(((e,t)=>{t.isValidDocument()||(l=l.add(e))}))})).next((()=>n.localDocuments.getOverlayedDocuments(e,o))).next((i=>{s=i;const a=[];for(const e of t){const t=mf(e,s.get(e.key).overlayedDocument);null!=t&&a.push(new yf(e.key,t,Vh(t.value.mapValue),cf.exists(!0)))}return n.mutationQueue.addMutationBatch(e,r,a,t)})).next((t=>{a=t;const r=t.applyToLocalDocumentSet(s,l);return n.documentOverlayCache.saveOverlays(e,t.batchId,r)}))})).then((()=>({batchId:a.batchId,changes:jd(s)})))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.Sa[e.currentUser.toKey()];r||(r=new ah(Pu)),r=r.insert(t,n),e.Sa[e.currentUser.toKey()]=r}(r,e.batchId,n),await Dg(r,e.changes),await Vm(r.remoteStore)}catch(e){const t=eg(e,"Failed to persist write");n.reject(t)}}(await Gg(e),t,n))),n.promise}(fv(e),t)}new WeakMap;!function(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];!function(e){lu=e}(Ee),ye(new L("firestore",((e,n)=>{let{instanceIdentifier:r,options:i}=n;const s=e.getProvider("app").getImmediate(),a=new dv(new ku(e.getProvider("auth-internal")),new xu(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new wu(yu.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Eh(e.options.projectId,t)}(s,r),s);return i=Object.assign({useFetchStreams:t},i),a._setSettings(i),a}),"PUBLIC").setMultipleInstances(!0)),Ie(au,"4.3.2",e),Ie(au,"4.3.2","esm2017")}();const oy=Se({apiKey:"AIzaSyDZjgosQcTQgNfvwAaFC_W6R5Sv0JjjxkM",authDomain:"friendly-betting-fb47e.firebaseapp.com",projectId:"friendly-betting-fb47e",storageBucket:"friendly-betting-fb47e.appspot.com",messagingSenderId:"897713635691",appId:"1:897713635691:web:70b530052a319f77e14c2e",measurementId:"G-74305KF5X4"}),ly=(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ke();e=O(e);const t=we(e,Qt);t.isInitialized()?t.getImmediate():function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=we(e,Qt);if(n.isInitialized()){const e=n.getImmediate();if(E(t,n.getOptions()))return e;throw tn.create("already-initialized")}const r=n.initialize({options:t})}(e)}(oy),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ke();const t=we(e,"auth");if(t.isInitialized())return t.getImmediate();const n=function(e,t){const n=we(e,"auth");if(n.isInitialized()){const e=n.getImmediate();if(E(n.getOptions(),null!==t&&void 0!==t?t:{}))return e;Fn(e,"already-initialized")}return n.initialize({options:t})}(e,{popupRedirectResolver:Rs,persistence:[zi,Ii,Ci]}),r=f("authTokenSyncURL");if(r){const e=(i=r,async e=>{const t=e&&await e.getIdTokenResult(),n=t&&((new Date).getTime()-Date.parse(t.issuedAtTime))/1e3;if(n&&n>Ms)return;const r=null===t||void 0===t?void 0:t.token;js!==r&&(js=r,await fetch(i,{method:r?"POST":"DELETE",headers:r?{Authorization:"Bearer ".concat(r)}:{}}))});!function(e,t,n){O(e).beforeAuthStateChanged(t,n)}(n,e,(()=>e(n.currentUser))),function(e,t,n,r){O(e).onIdTokenChanged(t,n,r)}(n,(t=>e(t)))}var i;const s=h("auth");return s&&Qr(n,"http://".concat(s)),n}(oy)),cy=function(e,t){const n="string"==typeof e?e:t||"(default)",r=we("object"==typeof e?e:ke(),"firestore").getImmediate({identifier:n});if(!r._initialized){const e=(e=>{const t=h(e);if(!t)return;const n=t.lastIndexOf(":");if(n<=0||n+1===t.length)throw new Error("Invalid host ".concat(t," with no separate hostname and port!"));const r=parseInt(t.substring(n+1),10);return"["===t[0]?[t.substring(1,n-1),r]:[t.substring(0,n),r]})("firestore");e&&sv(r,...e)}return r}(oy);function uy(){return uy=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},uy.apply(this,arguments)}var hy;!function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"}(hy||(hy={}));const dy="popstate";function fy(e,t){if(!1===e||null===e||"undefined"===typeof e)throw new Error(t)}function py(e,t){if(!e){"undefined"!==typeof console&&console.warn(t);try{throw new Error(t)}catch(n){}}}function my(e,t){return{usr:e.state,key:e.key,idx:t}}function gy(e,t,n,r){return void 0===n&&(n=null),uy({pathname:"string"===typeof e?e:e.pathname,search:"",hash:""},"string"===typeof t?yy(t):t,{state:n,key:t&&t.key||r||Math.random().toString(36).substr(2,8)})}function vy(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&"?"!==n&&(t+="?"===n.charAt(0)?n:"?"+n),r&&"#"!==r&&(t+="#"===r.charAt(0)?r:"#"+r),t}function yy(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function wy(e,t,n,r){void 0===r&&(r={});let{window:i=document.defaultView,v5Compat:s=!1}=r,a=i.history,o=hy.Pop,l=null,c=u();function u(){return(a.state||{idx:null}).idx}function h(){o=hy.Pop;let e=u(),t=null==e?null:e-c;c=e,l&&l({action:o,location:f.location,delta:t})}function d(e){let t="null"!==i.location.origin?i.location.origin:i.location.href,n="string"===typeof e?e:vy(e);return fy(t,"No window.location.(origin|href) available to create URL for href: "+n),new URL(n,t)}null==c&&(c=0,a.replaceState(uy({},a.state,{idx:c}),""));let f={get action(){return o},get location(){return e(i,a)},listen(e){if(l)throw new Error("A history only accepts one active listener");return i.addEventListener(dy,h),l=e,()=>{i.removeEventListener(dy,h),l=null}},createHref:e=>t(i,e),createURL:d,encodeLocation(e){let t=d(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:function(e,t){o=hy.Push;let r=gy(f.location,e,t);n&&n(r,e),c=u()+1;let h=my(r,c),d=f.createHref(r);try{a.pushState(h,"",d)}catch(p){if(p instanceof DOMException&&"DataCloneError"===p.name)throw p;i.location.assign(d)}s&&l&&l({action:o,location:f.location,delta:1})},replace:function(e,t){o=hy.Replace;let r=gy(f.location,e,t);n&&n(r,e),c=u();let i=my(r,c),h=f.createHref(r);a.replaceState(i,"",h),s&&l&&l({action:o,location:f.location,delta:0})},go:e=>a.go(e)};return f}var by;!function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"}(by||(by={}));new Set(["lazy","caseSensitive","path","id","index","children"]);function _y(e,t,n){void 0===n&&(n="/");let r=Ly(("string"===typeof t?yy(t):t).pathname||"/",n);if(null==r)return null;let i=Ey(e);!function(e){e.sort(((e,t)=>e.score!==t.score?t.score-e.score:function(e,t){let n=e.length===t.length&&e.slice(0,-1).every(((e,n)=>e===t[n]));return n?e[e.length-1]-t[t.length-1]:0}(e.routesMeta.map((e=>e.childrenIndex)),t.routesMeta.map((e=>e.childrenIndex)))))}(i);let s=null;for(let a=0;null==s&&a<i.length;++a)s=Ry(i[a],Oy(r));return s}function Ey(e,t,n,r){void 0===t&&(t=[]),void 0===n&&(n=[]),void 0===r&&(r="");let i=(e,i,s)=>{let a={relativePath:void 0===s?e.path||"":s,caseSensitive:!0===e.caseSensitive,childrenIndex:i,route:e};a.relativePath.startsWith("/")&&(fy(a.relativePath.startsWith(r),'Absolute route path "'+a.relativePath+'" nested under path "'+r+'" is not valid. An absolute child route path must start with the combined path of all its parent routes.'),a.relativePath=a.relativePath.slice(r.length));let o=Vy([r,a.relativePath]),l=n.concat(a);e.children&&e.children.length>0&&(fy(!0!==e.index,'Index routes must not have child routes. Please remove all child routes from route path "'+o+'".'),Ey(e.children,t,l,o)),(null!=e.path||e.index)&&t.push({path:o,score:Py(o,e.index),routesMeta:l})};return e.forEach(((e,t)=>{var n;if(""!==e.path&&null!=(n=e.path)&&n.includes("?"))for(let r of Sy(e.path))i(e,t,r);else i(e,t)})),t}function Sy(e){let t=e.split("/");if(0===t.length)return[];let[n,...r]=t,i=n.endsWith("?"),s=n.replace(/\?$/,"");if(0===r.length)return i?[s,""]:[s];let a=Sy(r.join("/")),o=[];return o.push(...a.map((e=>""===e?s:[s,e].join("/")))),i&&o.push(...a),o.map((t=>e.startsWith("/")&&""===t?"/":t))}const ky=/^:\w+$/,Iy=3,Ty=2,Cy=1,xy=10,Ny=-2,Ay=e=>"*"===e;function Py(e,t){let n=e.split("/"),r=n.length;return n.some(Ay)&&(r+=Ny),t&&(r+=Ty),n.filter((e=>!Ay(e))).reduce(((e,t)=>e+(ky.test(t)?Iy:""===t?Cy:xy)),r)}function Ry(e,t){let{routesMeta:n}=e,r={},i="/",s=[];for(let a=0;a<n.length;++a){let e=n[a],o=a===n.length-1,l="/"===i?t:t.slice(i.length)||"/",c=Dy({path:e.relativePath,caseSensitive:e.caseSensitive,end:o},l);if(!c)return null;Object.assign(r,c.params);let u=e.route;s.push({params:r,pathname:Vy([i,c.pathname]),pathnameBase:By(Vy([i,c.pathnameBase])),route:u}),"/"!==c.pathnameBase&&(i=Vy([i,c.pathnameBase]))}return s}function Dy(e,t){"string"===typeof e&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=function(e,t,n){void 0===t&&(t=!1);void 0===n&&(n=!0);py("*"===e||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were "'+e.replace(/\*$/,"/*")+'" because the `*` character must always follow a `/` in the pattern. To get rid of this warning, please change the route path to "'+e.replace(/\*$/,"/*")+'".');let r=[],i="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:(\w+)(\?)?/g,((e,t,n)=>(r.push({paramName:t,isOptional:null!=n}),n?"/?([^\\/]+)?":"/([^\\/]+)")));e.endsWith("*")?(r.push({paramName:"*"}),i+="*"===e||"/*"===e?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?i+="\\/*$":""!==e&&"/"!==e&&(i+="(?:(?=\\/|$))");let s=new RegExp(i,t?void 0:"i");return[s,r]}(e.path,e.caseSensitive,e.end),i=t.match(n);if(!i)return null;let s=i[0],a=s.replace(/(.)\/+$/,"$1"),o=i.slice(1);return{params:r.reduce(((e,t,n)=>{let{paramName:r,isOptional:i}=t;if("*"===r){let e=o[n]||"";a=s.slice(0,s.length-e.length).replace(/(.)\/+$/,"$1")}const l=o[n];return e[r]=i&&!l?void 0:function(e,t){try{return decodeURIComponent(e)}catch(n){return py(!1,'The value for the URL param "'+t+'" will not be decoded because the string "'+e+'" is a malformed URL segment. This is probably due to a bad percent encoding ('+n+")."),e}}(l||"",r),e}),{}),pathname:s,pathnameBase:a,pattern:e}}function Oy(e){try{return decodeURI(e)}catch(t){return py(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent encoding ('+t+")."),e}}function Ly(e,t){if("/"===t)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&"/"!==r?null:e.slice(n)||"/"}function My(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified `to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the `to."+n+'` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.'}function jy(e){return e.filter(((e,t)=>0===t||e.route.path&&e.route.path.length>0))}function Fy(e){return jy(e).map(((t,n)=>n===e.length-1?t.pathname:t.pathnameBase))}function Uy(e,t,n,r){let i;void 0===r&&(r=!1),"string"===typeof e?i=yy(e):(i=uy({},e),fy(!i.pathname||!i.pathname.includes("?"),My("?","pathname","search",i)),fy(!i.pathname||!i.pathname.includes("#"),My("#","pathname","hash",i)),fy(!i.search||!i.search.includes("#"),My("#","search","hash",i)));let s,a=""===e||""===i.pathname,o=a?"/":i.pathname;if(null==o)s=n;else if(r){let e=t[t.length-1].replace(/^\//,"").split("/");if(o.startsWith("..")){let t=o.split("/");for(;".."===t[0];)t.shift(),e.pop();i.pathname=t.join("/")}s="/"+e.join("/")}else{let e=t.length-1;if(o.startsWith("..")){let t=o.split("/");for(;".."===t[0];)t.shift(),e-=1;i.pathname=t.join("/")}s=e>=0?t[e]:"/"}let l=function(e,t){void 0===t&&(t="/");let{pathname:n,search:r="",hash:i=""}="string"===typeof e?yy(e):e,s=n?n.startsWith("/")?n:function(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach((e=>{".."===e?n.length>1&&n.pop():"."!==e&&n.push(e)})),n.length>1?n.join("/"):"/"}(n,t):t;return{pathname:s,search:zy(r),hash:qy(i)}}(i,s),c=o&&"/"!==o&&o.endsWith("/"),u=(a||"."===o)&&n.endsWith("/");return l.pathname.endsWith("/")||!c&&!u||(l.pathname+="/"),l}const Vy=e=>e.join("/").replace(/\/\/+/g,"/"),By=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),zy=e=>e&&"?"!==e?e.startsWith("?")?e:"?"+e:"",qy=e=>e&&"#"!==e?e.startsWith("#")?e:"#"+e:"";Error;function Hy(e){return null!=e&&"number"===typeof e.status&&"string"===typeof e.statusText&&"boolean"===typeof e.internal&&"data"in e}const Wy=["post","put","patch","delete"],Ky=(new Set(Wy),["get",...Wy]);new Set(Ky),new Set([301,302,303,307,308]),new Set([307,308]);Symbol("deferred");function Gy(){return Gy=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Gy.apply(this,arguments)}const Qy=e.createContext(null);const $y=e.createContext(null);const Yy=e.createContext(null);const Xy=e.createContext(null);const Jy=e.createContext({outlet:null,matches:[],isDataRoute:!1});const Zy=e.createContext(null);function ew(){return null!=e.useContext(Xy)}function tw(){return ew()||fy(!1),e.useContext(Xy).location}function nw(t){e.useContext(Yy).static||e.useLayoutEffect(t)}function rw(){let{isDataRoute:t}=e.useContext(Jy);return t?function(){let{router:t}=fw(hw.UseNavigateStable),n=mw(dw.UseNavigateStable),r=e.useRef(!1);nw((()=>{r.current=!0}));let i=e.useCallback((function(e,i){void 0===i&&(i={}),r.current&&("number"===typeof e?t.navigate(e):t.navigate(e,Gy({fromRouteId:n},i)))}),[t,n]);return i}():function(){ew()||fy(!1);let t=e.useContext(Qy),{basename:n,navigator:r}=e.useContext(Yy),{matches:i}=e.useContext(Jy),{pathname:s}=tw(),a=JSON.stringify(Fy(i)),o=e.useRef(!1);return nw((()=>{o.current=!0})),e.useCallback((function(e,i){if(void 0===i&&(i={}),!o.current)return;if("number"===typeof e)return void r.go(e);let l=Uy(e,JSON.parse(a),s,"path"===i.relative);null==t&&"/"!==n&&(l.pathname="/"===l.pathname?n:Vy([n,l.pathname])),(i.replace?r.replace:r.push)(l,i.state,i)}),[n,r,a,s,t])}()}function iw(t,n){let{relative:r}=void 0===n?{}:n,{matches:i}=e.useContext(Jy),{pathname:s}=tw(),a=JSON.stringify(Fy(i));return e.useMemo((()=>Uy(t,JSON.parse(a),s,"path"===r)),[t,a,s,r])}function sw(t,n,r){ew()||fy(!1);let{navigator:i}=e.useContext(Yy),{matches:s}=e.useContext(Jy),a=s[s.length-1],o=a?a.params:{},l=(a&&a.pathname,a?a.pathnameBase:"/");a&&a.route;let c,u=tw();if(n){var h;let e="string"===typeof n?yy(n):n;"/"===l||(null==(h=e.pathname)?void 0:h.startsWith(l))||fy(!1),c=e}else c=u;let d=c.pathname||"/",f=_y(t,{pathname:"/"===l?d:d.slice(l.length)||"/"});let p=uw(f&&f.map((e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:Vy([l,i.encodeLocation?i.encodeLocation(e.pathname).pathname:e.pathname]),pathnameBase:"/"===e.pathnameBase?l:Vy([l,i.encodeLocation?i.encodeLocation(e.pathnameBase).pathname:e.pathnameBase])}))),s,r);return n&&p?e.createElement(Xy.Provider,{value:{location:Gy({pathname:"/",search:"",hash:"",state:null,key:"default"},c),navigationType:hy.Pop}},p):p}function aw(){let t=function(){var t;let n=e.useContext(Zy),r=pw(dw.UseRouteError),i=mw(dw.UseRouteError);if(n)return n;return null==(t=r.errors)?void 0:t[i]}(),n=Hy(t)?t.status+" "+t.statusText:t instanceof Error?t.message:JSON.stringify(t),r=t instanceof Error?t.stack:null,i="rgba(200,200,200, 0.5)",s={padding:"0.5rem",backgroundColor:i};return e.createElement(e.Fragment,null,e.createElement("h2",null,"Unexpected Application Error!"),e.createElement("h3",{style:{fontStyle:"italic"}},n),r?e.createElement("pre",{style:s},r):null,null)}const ow=e.createElement(aw,null);class lw extends e.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||"idle"!==t.revalidation&&"idle"===e.revalidation?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error||t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){console.error("React Router caught the following error during render",e,t)}render(){return this.state.error?e.createElement(Jy.Provider,{value:this.props.routeContext},e.createElement(Zy.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function cw(t){let{routeContext:n,match:r,children:i}=t,s=e.useContext(Qy);return s&&s.static&&s.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=r.route.id),e.createElement(Jy.Provider,{value:n},i)}function uw(t,n,r){var i;if(void 0===n&&(n=[]),void 0===r&&(r=null),null==t){var s;if(null==(s=r)||!s.errors)return null;t=r.matches}let a=t,o=null==(i=r)?void 0:i.errors;if(null!=o){let e=a.findIndex((e=>e.route.id&&(null==o?void 0:o[e.route.id])));e>=0||fy(!1),a=a.slice(0,Math.min(a.length,e+1))}return a.reduceRight(((t,i,s)=>{let l=i.route.id?null==o?void 0:o[i.route.id]:null,c=null;r&&(c=i.route.errorElement||ow);let u=n.concat(a.slice(0,s+1)),h=()=>{let n;return n=l?c:i.route.Component?e.createElement(i.route.Component,null):i.route.element?i.route.element:t,e.createElement(cw,{match:i,routeContext:{outlet:t,matches:u,isDataRoute:null!=r},children:n})};return r&&(i.route.ErrorBoundary||i.route.errorElement||0===s)?e.createElement(lw,{location:r.location,revalidation:r.revalidation,component:c,error:l,children:h(),routeContext:{outlet:null,matches:u,isDataRoute:!0}}):h()}),null)}var hw=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(hw||{}),dw=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(dw||{});function fw(t){let n=e.useContext(Qy);return n||fy(!1),n}function pw(t){let n=e.useContext($y);return n||fy(!1),n}function mw(t){let n=function(t){let n=e.useContext(Jy);return n||fy(!1),n}(),r=n.matches[n.matches.length-1];return r.route.id||fy(!1),r.route.id}t.startTransition;function gw(e){fy(!1)}function vw(t){let{basename:n="/",children:r=null,location:i,navigationType:s=hy.Pop,navigator:a,static:o=!1}=t;ew()&&fy(!1);let l=n.replace(/^\/*/,"/"),c=e.useMemo((()=>({basename:l,navigator:a,static:o})),[l,a,o]);"string"===typeof i&&(i=yy(i));let{pathname:u="/",search:h="",hash:d="",state:f=null,key:p="default"}=i,m=e.useMemo((()=>{let e=Ly(u,l);return null==e?null:{location:{pathname:e,search:h,hash:d,state:f,key:p},navigationType:s}}),[l,u,h,d,f,p,s]);return null==m?null:e.createElement(Yy.Provider,{value:c},e.createElement(Xy.Provider,{children:r,value:m}))}function yw(e){let{children:t,location:n}=e;return sw(ww(t),n)}new Promise((()=>{}));e.Component;function ww(t,n){void 0===n&&(n=[]);let r=[];return e.Children.forEach(t,((t,i)=>{if(!e.isValidElement(t))return;let s=[...n,i];if(t.type===e.Fragment)return void r.push.apply(r,ww(t.props.children,s));t.type!==gw&&fy(!1),t.props.index&&t.props.children&&fy(!1);let a={id:t.props.id||s.join("-"),caseSensitive:t.props.caseSensitive,element:t.props.element,Component:t.props.Component,index:t.props.index,path:t.props.path,loader:t.props.loader,action:t.props.action,errorElement:t.props.errorElement,ErrorBoundary:t.props.ErrorBoundary,hasErrorBoundary:null!=t.props.ErrorBoundary||null!=t.props.errorElement,shouldRevalidate:t.props.shouldRevalidate,handle:t.props.handle,lazy:t.props.lazy};t.props.children&&(a.children=ww(t.props.children,s)),r.push(a)})),r}const bw="SignIn_signIn__3t4GY",_w="SignIn_signInTransition__DVaCC",Ew="SignIn_signInLabel__6itNQ",Sw="SignIn_swapSignIn__WlTGP";var kw=n(184);const Iw=()=>{var t;const[n,r]=(0,e.useState)(""),[i,s]=(0,e.useState)(""),[a,o]=(0,e.useState)(!1);console.log(null===ly||void 0===ly||null===(t=ly.currentUser)||void 0===t?void 0:t.email);const l=rw();return(0,e.useEffect)((()=>{const e=setTimeout((()=>{o(!0)}),2);return()=>clearTimeout(e)}),[]),(0,kw.jsxs)("div",{className:"".concat(bw," ").concat(a?"":_w),children:[(0,kw.jsx)("div",{className:Ew,children:"Sign in"}),(0,kw.jsx)("input",{type:"text",placeholder:"Email or Number",onChange:e=>r(e.target.value)}),(0,kw.jsx)("input",{type:"password",placeholder:"password",id:"",onChange:e=>s(e.target.value)}),(0,kw.jsx)("button",{onClick:async()=>{try{await async function(e,t,n){const r=Br(e),i=Gr(r,{returnSecureToken:!0,email:t,password:n,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",fi),s=await i.catch((t=>{throw t.code==="auth/".concat("password-does-not-meet-requirements")&&_i(e),t})),a=await pi._fromIdTokenResponse(r,"signIn",s);return await r._updateCurrentUser(a.user),a}(ly,n,i)}catch(e){console.error(e)}},children:"Sign In"}),(0,kw.jsx)("div",{children:(0,kw.jsx)("div",{onClick:()=>{l("/Friendly-Betting/CreateAccount")},className:Sw,children:"Don't have account? Create One!"})}),(0,kw.jsx)("br",{}),(0,kw.jsx)("br",{}),(0,kw.jsx)("button",{onClick:async()=>{try{await function(e){return O(e).signOut()}(ly)}catch(e){console.error(e)}},children:"Log Out"})]})},Tw=()=>{const[t,n]=(0,e.useState)(!1),r=rw();return(0,e.useEffect)((()=>{const e=setTimeout((()=>{n(!0)}),2);return()=>clearTimeout(e)}),[]),(0,kw.jsxs)("div",{className:"".concat(bw," ").concat(t?"":_w),children:[(0,kw.jsx)("div",{className:Ew,children:"Create Account"}),(0,kw.jsx)("input",{type:"text",placeholder:"Email"}),(0,kw.jsx)("input",{type:"text",placeholder:"Phone"}),(0,kw.jsx)("br",{}),(0,kw.jsx)("input",{type:"password",placeholder:"password",name:"",id:""}),(0,kw.jsx)("input",{type:"password",placeholder:"confirm password",name:"",id:""}),(0,kw.jsx)("button",{children:"Create Account"}),(0,kw.jsx)("div",{children:(0,kw.jsx)("div",{onClick:()=>{r("/Friendly-Betting/SignIn")},className:Sw,children:"Already have account? Sign in!"})})]})};var Cw=n(164),xw=n.t(Cw,2);function Nw(){return Nw=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Nw.apply(this,arguments)}function Aw(e,t){if(null==e)return{};var n,r,i={},s=Object.keys(e);for(r=0;r<s.length;r++)n=s[r],t.indexOf(n)>=0||(i[n]=e[n]);return i}new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);const Pw=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","unstable_viewTransition"];new Map;const Rw=t.startTransition;xw.flushSync;function Dw(t){let{basename:n,children:r,future:i,window:s}=t,a=e.useRef();var o;null==a.current&&(a.current=(void 0===(o={window:s,v5Compat:!0})&&(o={}),wy((function(e,t){let{pathname:n,search:r,hash:i}=e.location;return gy("",{pathname:n,search:r,hash:i},t.state&&t.state.usr||null,t.state&&t.state.key||"default")}),(function(e,t){return"string"===typeof t?t:vy(t)}),null,o)));let l=a.current,[c,u]=e.useState({action:l.action,location:l.location}),{v7_startTransition:h}=i||{},d=e.useCallback((e=>{h&&Rw?Rw((()=>u(e))):u(e)}),[u,h]);return e.useLayoutEffect((()=>l.listen(d)),[l,d]),e.createElement(vw,{basename:n,children:r,location:c.location,navigationType:c.action,navigator:l})}const Ow="undefined"!==typeof window&&"undefined"!==typeof window.document&&"undefined"!==typeof window.document.createElement,Lw=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Mw=e.forwardRef((function(t,n){let r,{onClick:i,relative:s,reloadDocument:a,replace:o,state:l,target:c,to:u,preventScrollReset:h,unstable_viewTransition:d}=t,f=Aw(t,Pw),{basename:p}=e.useContext(Yy),m=!1;if("string"===typeof u&&Lw.test(u)&&(r=u,Ow))try{let e=new URL(window.location.href),t=u.startsWith("//")?new URL(e.protocol+u):new URL(u),n=Ly(t.pathname,p);t.origin===e.origin&&null!=n?u=n+t.search+t.hash:m=!0}catch(y){}let g=function(t,n){let{relative:r}=void 0===n?{}:n;ew()||fy(!1);let{basename:i,navigator:s}=e.useContext(Yy),{hash:a,pathname:o,search:l}=iw(t,{relative:r}),c=o;return"/"!==i&&(c="/"===o?i:Vy([i,o])),s.createHref({pathname:c,search:l,hash:a})}(u,{relative:s}),v=function(t,n){let{target:r,replace:i,state:s,preventScrollReset:a,relative:o,unstable_viewTransition:l}=void 0===n?{}:n,c=rw(),u=tw(),h=iw(t,{relative:o});return e.useCallback((e=>{if(function(e,t){return 0===e.button&&(!t||"_self"===t)&&!function(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}(e)}(e,r)){e.preventDefault();let n=void 0!==i?i:vy(u)===vy(h);c(t,{replace:n,state:s,preventScrollReset:a,relative:o,unstable_viewTransition:l})}}),[u,c,h,i,s,r,t,a,o,l])}(u,{replace:o,state:l,target:c,preventScrollReset:h,relative:s,unstable_viewTransition:d});return e.createElement("a",Nw({},f,{href:r||g,onClick:m||a?i:function(e){i&&i(e),e.defaultPrevented||v(e)},ref:n,target:c}))}));var jw,Fw;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(jw||(jw={})),function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"}(Fw||(Fw={}));const Uw=()=>{const e=tw();return(0,kw.jsxs)("div",{className:"header",children:[(0,kw.jsx)("div",{className:"x1",children:(0,kw.jsx)("div",{className:"logo",children:(0,kw.jsx)(Mw,{className:"Link",to:"Friendly-Betting/",children:"logo"})})}),(0,kw.jsx)("div",{className:"x1",children:"Friendly Bets"}),(0,kw.jsxs)("div",{className:"flex pages x1",children:["/SignIn"!==e.pathname?(0,kw.jsx)(Mw,{className:"Link",to:"Friendly-Betting/SignIn",children:"Sign In"}):(0,kw.jsx)(Mw,{className:"Link",to:"/",children:"Sign In"}),(0,kw.jsx)(Mw,{className:"Link",to:"Friendly-Betting/Bet",children:"Bets"}),(0,kw.jsx)(Mw,{className:"Link",to:"Friendly-Betting/Friends",children:"Friends"})]})]})},Vw=()=>(0,kw.jsxs)("div",{children:[(0,kw.jsx)("h1",{children:"404"}),(0,kw.jsx)("p",{children:"Page not found!"})]}),Bw=()=>{var t;const[n,r]=(0,e.useState)(!0);console.log(null===ly||void 0===ly||null===(t=ly.currentUser)||void 0===t?void 0:t.email),(0,e.useEffect)((()=>{i()}),[]);const i=()=>{var e;const t=null===ly||void 0===ly||null===(e=ly.currentUser)||void 0===e?void 0:e.email;r(void 0!==t)};return(0,kw.jsx)("div",{className:"p-12",children:n?(0,kw.jsxs)("div",{children:[(0,kw.jsx)("h1",{children:"Welcome, User!"}),(0,kw.jsx)("p",{children:"This is the authenticated content."})]}):(0,kw.jsxs)("div",{children:[(0,kw.jsx)("h1",{children:"Please sign in to access this content."}),(0,kw.jsx)(Mw,{className:"Link",to:"Friendly-Betting/SignIn",children:"Sign In"})]})})},zw="MoneyLine_MoneyLine__GZY-g",qw="MoneyLine_betContainer__MPUkR",Hw="MoneyLine_betTextArea__Q9aMH",Ww="MoneyLine_contestantInput__RtHW6",Kw="MoneyLine_label__SXs1d",Gw="MoneyLine_odds__5UKBZ",Qw="MoneyLine_betLabel__xK-Pn",$w={disable:"Players_disable__2Lrxc",friends:"Players_friends__S-rHI",addFiendForm:"Players_addFiendForm__No56b",x:"Players_x__50IpE",shareBet:"Players_shareBet__IEGN8",friendsLabel:"Players_friendsLabel__doMbx",container:"Players_container__wuYC4",checkmark:"Players_checkmark__OI0Ce"},Yw=t=>{const[n,r]=(0,e.useState)(""),[i,s]=(0,e.useState)(""),[a,o]=(0,e.useState)(""),[l,c]=(0,e.useState)("");return(0,kw.jsxs)("form",{className:$w.addFiendForm,onSubmit:e=>{e.preventDefault(),""!==l&&""!==a&&""!==i&&t.addNewPlayers({name:l,email:a,phone:i})},children:[(0,kw.jsx)("div",{className:"flex justify-center mb-2",children:(0,kw.jsx)("span",{className:$w.x,onClick:t.disable,children:"x"})}),(0,kw.jsxs)("label",{children:[(0,kw.jsx)("span",{children:"Account Number:"}),(0,kw.jsx)("input",{type:"text",value:n,onChange:e=>{r(e.target.value)}})]}),(0,kw.jsx)("br",{}),(0,kw.jsx)("br",{}),(0,kw.jsx)("div",{className:"flex justify-center items-center text-center",children:"or"}),(0,kw.jsx)("br",{}),(0,kw.jsxs)("label",{children:[(0,kw.jsx)("span",{children:"Name:"}),(0,kw.jsx)("input",{type:"text",value:l,onChange:e=>{c(e.target.value)}})]}),(0,kw.jsx)("br",{}),(0,kw.jsxs)("label",{children:["Email:",(0,kw.jsx)("input",{type:"email",value:a,onChange:e=>{o(e.target.value)}})]}),(0,kw.jsx)("br",{}),(0,kw.jsxs)("label",{children:[(0,kw.jsx)("span",{children:"Phone:"}),(0,kw.jsx)("input",{type:"phone",value:i,onChange:e=>{s(e.target.value)}})]}),(0,kw.jsx)("br",{}),(0,kw.jsx)("button",{type:"submit",children:"Add Friend"})]})},Xw=()=>{const[t,n]=(0,e.useState)({friends:[{name:"John",email:"johnRyan@gmail.com",phone:"1234567890"},{name:"Jack",email:"JackRyan@gmail.com",phone:"1234567890"},{name:"Another Person",email:"Person@gmail.com",phone:"1234567890"}]}),[r,i]=(0,e.useState)(!1),s=()=>{i((e=>!e))};return(0,kw.jsx)("div",{className:"pt-12 sticky top-0 bottom-0 right-0 left-0",children:(0,kw.jsxs)("div",{className:$w.friends,children:[t.friends.map(((e,t)=>(0,kw.jsxs)("div",{children:[(0,kw.jsx)("h3",{children:e.name}),(0,kw.jsxs)("p",{children:["Email: ",e.email]}),(0,kw.jsxs)("p",{children:["Phone: ",e.phone]})]},t))),(0,kw.jsx)("div",{children:r?(0,kw.jsxs)("div",{children:[(0,kw.jsx)(Yw,{addNewPlayers:e=>{n((t=>({...t,friends:[...t.friends,e]}))),s()},disable:s}),(0,kw.jsx)("button",{className:$w.disable,children:"Add Friend"})]}):(0,kw.jsx)("button",{onClick:s,children:"Add Friend"})})]})})},Jw=t=>{const[n,r]=(0,e.useState)({friends:[{name:"John",email:"johnRyan@gmail.com",phone:"1234567890"},{name:"Jack",email:"JackRyan@gmail.com",phone:"1234567890"},{name:"Another Person",email:"Person@gmail.com",phone:"1234567890"}]});return(0,kw.jsxs)("div",{className:$w.shareBet,children:[(0,kw.jsx)("div",{className:"flex justify-center mb-2",children:(0,kw.jsx)("span",{className:$w.x,onClick:t.display,children:"x"})}),(0,kw.jsx)("div",{className:$w.friendsLabel,children:(0,kw.jsx)("span",{children:"friends"})}),(0,kw.jsxs)("form",{onSubmit:e=>{e.preventDefault(),console.log("Sharing bet")},children:[n.friends.map((e=>(0,kw.jsxs)("label",{className:$w.container,children:[e.name,(0,kw.jsx)("input",{className:$w.input,type:"checkbox",name:"",id:""}),(0,kw.jsx)("span",{className:$w.checkmark})]}))),(0,kw.jsx)("button",{type:"submit",children:"Send"})]})]})},Zw=()=>{const[t,n]=(0,e.useState)(""),[r,i]=(0,e.useState)(""),[s,a]=(0,e.useState)(""),[o,l]=(0,e.useState)(0),[c,u]=(0,e.useState)(0),[h,d]=(0,e.useState)(!1),f=()=>{d((e=>!e))};return(0,kw.jsxs)("div",{className:"flex",children:[(0,kw.jsx)("div",{className:"x2",children:(0,kw.jsxs)("form",{className:zw,onSubmit:async e=>{e.preventDefault(),f();try{await sy(cv(cy,"bets"),{type:"Money Line",bet:t}),await sy(cv(cy,"MoneyLineBets"),{bet:t,contestant1:r,contestant1Odds:o,contestant2:s,contestant2Odds:c})}catch(e){console.error(e)}console.log("Creating moneyline bet:")},children:[(0,kw.jsxs)("div",{className:"pb-8 ".concat(qw),children:["Bet:",(0,kw.jsx)("div",{className:"pl-8",children:(0,kw.jsx)("textarea",{className:Hw,type:"text",name:"",id:"",onChange:e=>n(e.target.value)})})]}),(0,kw.jsxs)("div",{className:"flex",children:[(0,kw.jsxs)("div",{className:"flex flex-col my-4 mx-8",children:[(0,kw.jsx)("div",{children:(0,kw.jsx)("span",{className:Kw,children:"Contestant 1"})}),(0,kw.jsx)("input",{type:"text",name:"",value:r,className:Ww,onChange:e=>i(e.target.value)}),(0,kw.jsxs)("div",{className:Gw,children:[(0,kw.jsx)("span",{children:"(+ or - odds)"}),(0,kw.jsx)("input",{className:"justify-center items-center",type:"number",onChange:e=>l(Number(e.target.value))})]})]}),(0,kw.jsxs)("div",{className:"flex flex-col my-4 mx-8",children:[(0,kw.jsx)("div",{children:(0,kw.jsx)("span",{className:Kw,children:"Contestant 2"})}),(0,kw.jsx)("input",{type:"text",name:"",value:s,className:Ww,onChange:e=>a(e.target.value)}),(0,kw.jsxs)("div",{className:"flex justify-center items-center gap-2 p-2",children:[(0,kw.jsx)("span",{className:Gw,children:"(+ or - odds)"}),(0,kw.jsx)("input",{type:"number",onChange:e=>u(Number(e.target.value))})]})]})]}),(0,kw.jsx)("button",{type:"submit",children:"Create Bet"})]})}),(0,kw.jsx)("div",{className:"x1",children:(0,kw.jsx)(Xw,{})}),(0,kw.jsx)("div",{children:h?(0,kw.jsx)(Jw,{display:f}):null})]})},eb=()=>(0,kw.jsxs)("div",{className:"p-12",children:[(0,kw.jsx)("h1",{children:"Money Line Bets"}),(0,kw.jsx)(Zw,{})]}),tb={OverUnder:"OverUnder_OverUnder__lZCyp",betContainer:"OverUnder_betContainer__GC+uq",BetTextArea:"OverUnder_BetTextArea__Y0xal",betLabel:"OverUnder_betLabel__fUG2h",lineLabel:"OverUnder_lineLabel__uLemh",line:"OverUnder_line__xiV+Z",actualLine:"OverUnder_actualLine__NevcO"},nb=()=>{const[t,n]=(0,e.useState)(""),[r,i]=(0,e.useState)(0),[s,a]=(0,e.useState)(!1),o=()=>{a((e=>!e))};return(0,kw.jsxs)("div",{className:"flex",children:[(0,kw.jsx)("div",{className:tb.OverUnder,children:(0,kw.jsxs)("form",{onSubmit:async e=>{e.preventDefault(),o();try{await sy(cv(cy,"bets"),{type:"Over Under",bet:t}),await sy(cv(cy,"OverUnderBets"),{bet:t,line:r})}catch(e){console.error(e)}console.log("Creating over under bet")},children:[(0,kw.jsxs)("div",{className:"flex flex-col gap-4 pb-8 ".concat(tb.betContainer),children:["Proposition:",(0,kw.jsx)("div",{className:tb.bet,children:(0,kw.jsx)("textarea",{className:tb.BetTextArea,type:"text",onChange:e=>{n(e.target.value)}})})]}),(0,kw.jsx)("div",{children:(0,kw.jsxs)("div",{className:"flex items-center gap-4 m-2",children:[(0,kw.jsx)("span",{className:tb.label,children:"Line:"}),(0,kw.jsx)("input",{className:"h-6 w-12",type:"number",step:"0.5",onChange:e=>{i(Number(e.target.value))}})]})}),(0,kw.jsx)("button",{type:"submit",children:"Create bet"})]})}),(0,kw.jsx)("div",{className:"x1",children:(0,kw.jsx)(Xw,{})}),(0,kw.jsx)("div",{children:s?(0,kw.jsx)(Jw,{display:o}):null})]})},rb=()=>(0,kw.jsxs)("div",{className:"p-12",children:[(0,kw.jsx)("h1",{children:"OverUnder Component"}),(0,kw.jsx)(nb,{})]}),ib={prop:"Prop_prop__DRZFt",betContainer:"Prop_betContainer__KSYFf",betTextarea:"Prop_betTextarea__fXQn9",PreSetBetting:"Prop_PreSetBetting__MzpqW",settings:"Prop_settings__9dmn0",title:"Prop_title__GEvyW",label:"Prop_label__zDU93",x:"Prop_x__tu9O2",optionInput:"Prop_optionInput__MuLBG"},sb=t=>{const[n,r]=(0,e.useState)(0),[i,s]=(0,e.useState)([]),[a,o]=(0,e.useState)([]);(0,e.useEffect)((()=>{let e=[];for(let t=0;t<n;t++)e.push(t);s(e)}),[n]);return(0,kw.jsxs)("div",{className:ib.PreSetBetting,children:[(0,kw.jsx)("div",{className:"flex justify-center mb-2",children:(0,kw.jsx)("span",{className:"x",onClick:t.display,children:"x"})}),(0,kw.jsx)("div",{className:ib.title,children:(0,kw.jsx)("span",{children:"Preset Betting Options"})}),(0,kw.jsxs)("form",{onSubmit:e=>{e.preventDefault(),t.setOptions(a),console.log("Saving preset betting options")},children:[i.map(((e,t)=>(0,kw.jsxs)("div",{className:"flex justify-center items-center gap-2 p-2",children:[(0,kw.jsxs)("span",{className:ib.label,children:[e+1,":"]}),(0,kw.jsx)("input",{className:ib.optionInput,type:"text",onChange:e=>((e,t)=>{o((n=>(a[t]=e.target.value,a)))})(e,t),placeholder:"Who or what"})]},t))),(0,kw.jsx)("button",{type:"submit",children:"Save"})]}),(0,kw.jsx)("button",{onClick:()=>{r(n+1)},children:"Add Option"})]})},ab=()=>{const[t,n]=(0,e.useState)(""),[r,i]=(0,e.useState)([]),[s,a]=(0,e.useState)(!1),[o,l]=(0,e.useState)(!1),c=()=>{l((e=>!e))},u=e=>{a(e.target.checked)};return(0,kw.jsxs)("div",{className:"flex",children:[(0,kw.jsx)("div",{className:ib.prop,children:(0,kw.jsxs)("form",{onSubmit:async e=>{e.preventDefault(),c();try{await sy(cv(cy,"bets"),{type:"Prop",bet:t}),await sy(cv(cy,"PropBets"),{bet:t,options:r})}catch(e){console.error(e)}console.log("Creating prop bet")},children:[(0,kw.jsxs)("div",{className:"flex flex-col gap-4 pb-8 ".concat(ib.betContainer),children:["Proposition:",(0,kw.jsx)("div",{children:(0,kw.jsx)("textarea",{className:"betTextarea",type:"text",onChange:e=>{n(e.target.value)}})})]}),(0,kw.jsxs)("div",{className:"flex gap-4 m-4",children:[(0,kw.jsx)("input",{type:"checkbox",id:"preSetBetting",checked:s,onChange:u}),(0,kw.jsx)("label",{className:ib.settings,htmlFor:"preSetBetting",children:"Pre Set Betting Options"})]}),(0,kw.jsx)("button",{type:"submit",children:"Create bet"})]})}),(0,kw.jsx)("div",{children:s?(0,kw.jsx)(sb,{setOptions:e=>{i(e)},display:u}):null}),(0,kw.jsx)("div",{className:"x1",children:(0,kw.jsx)(Xw,{})}),(0,kw.jsx)("div",{children:o?(0,kw.jsx)(Jw,{display:c}):null})]})},ob=()=>(0,kw.jsxs)("div",{className:"p-12",children:[(0,kw.jsx)("h1",{children:"Prop Bets"}),(0,kw.jsx)(ab,{})]}),lb="Components_greenButtons__FGl7E",cb="Components_redSpring__YTemv",ub="Components_DeleteButton__X+vUS",hb=e=>{const t="greenButton"===e.a?lb:cb;e.size;return(0,kw.jsx)("div",{className:t,children:(0,kw.jsx)("div",{children:e.text})})},db=e=>{const t=rw(),n=tw(),{bet:r}=n.state;return(0,kw.jsx)("div",{className:"flex justify-center items-center",children:(0,kw.jsx)("button",{className:ub,onClick:()=>{(async()=>{try{await iy(uv(cy,e.collection,e.docId)),await iy(uv(cy,"bets",r.id)),t("/Friendly-Betting/Bet")}catch(n){console.error(n)}})()},children:"Delete"})})},fb=()=>{const[t,n]=(0,e.useState)([]),[r,i]=(0,e.useState)(""),s="MoneyLineBets",a=tw(),{bet:o}=a.state;return(0,e.useEffect)((()=>{(async()=>{try{const e=zv(cv(cy,s),Hv("bet","==",o.bet)),t=await ry(e);n(t.docs[0].data()),i(t.docs[0].id)}catch(e){console.error(e)}})()}),[]),(0,kw.jsxs)("div",{className:"flex p-12",children:[(0,kw.jsx)("div",{className:"x2",children:(0,kw.jsxs)("div",{children:[(0,kw.jsxs)("div",{className:"flex justify-around",children:[(0,kw.jsx)("h1",{className:"pb-4 bl-4 ".concat(Qw),children:t.bet}),(0,kw.jsx)(db,{collection:s,docId:r})]}),(0,kw.jsxs)("div",{className:"blob",children:[(0,kw.jsxs)("div",{className:"flex justify-center items-center gap-8 my-4 mx-8 ",children:[(0,kw.jsx)(hb,{text:"Bet",a:"greenButton",size:"big"}),(0,kw.jsxs)("h2",{children:[t.contestant1," "]}),t.contestant1Odds>0?(0,kw.jsxs)("p",{className:"green",children:["(+",t.contestant1Odds,")"]}):(0,kw.jsxs)("p",{className:"red",children:["(",t.contestant1Odds,")"]})]}),(0,kw.jsx)("hr",{}),(0,kw.jsxs)("div",{className:"flex justify-center items-center gap-8 my-4 mx-8",children:[(0,kw.jsx)(hb,{text:"Bet",a:"greenButton",size:"big"}),(0,kw.jsxs)("h2",{children:[t.contestant2," "]}),t.contestant2Odds>0?(0,kw.jsxs)("p",{className:"green",children:["(+",t.contestant2Odds,")"]}):(0,kw.jsxs)("p",{className:"red",children:["(",t.contestant2Odds,")"]})]})]})]})}),(0,kw.jsx)("div",{className:"flex-1",children:(0,kw.jsx)(Xw,{})})]})},pb=()=>{const[t,n]=(0,e.useState)([]),[r,i]=(0,e.useState)(""),s=tw(),{bet:a}=s.state;return(0,e.useEffect)((()=>{(async()=>{try{const e=zv(cv(cy,"OverUnderBets"),Hv("bet","==",a.bet)),t=await ry(e);n(t.docs[0].data()),i(t.docs[0].id)}catch(e){console.error(e)}})()}),[]),(0,kw.jsxs)("div",{className:"flex p-12",children:[(0,kw.jsx)("div",{className:"x2",children:(0,kw.jsxs)("div",{children:[(0,kw.jsxs)("div",{className:"flex justify-around",children:[(0,kw.jsx)("h1",{className:tb.betLabel,children:t.bet}),(0,kw.jsx)(db,{collection:"OverUnderBets",docId:r})]}),(0,kw.jsxs)("div",{className:"blob row p-16",children:[(0,kw.jsxs)("div",{className:"flex flex-col justify-center items-center",children:[(0,kw.jsx)(hb,{text:"Under",a:"greenButton",size:"big"}),(0,kw.jsx)("p",{children:"8 others have taken the under"})]}),(0,kw.jsxs)("div",{className:tb.line,children:[(0,kw.jsx)("div",{className:tb.lineLabel,children:(0,kw.jsx)("span",{children:"Line"})}),(0,kw.jsx)("div",{className:tb.actualLine,children:t.line}),(0,kw.jsx)("div",{className:"flex justify-center items-center break-words text-center",children:"3 people have not voted"})]}),(0,kw.jsxs)("div",{className:"flex flex-col justify-center items-center",children:[(0,kw.jsx)(hb,{text:"Over",a:"greenButton",size:"big"}),(0,kw.jsx)("p",{className:"text-center",children:"12 others have taken the over"})]})]})]})}),(0,kw.jsx)("div",{className:"x1",children:(0,kw.jsx)(Xw,{})})]})},mb=()=>{const[t,n]=(0,e.useState)([]),[r,i]=(0,e.useState)(0),[s,a]=(0,e.useState)(""),o=tw(),{bet:l}=o.state;return(0,e.useEffect)((()=>{(async()=>{try{const e=zv(cv(cy,"PropBets"),Hv("bet","==",l.bet)),t=await ry(e);n(t.docs[0].data()),i(t.docs[0].data().options.length),a(t.docs[0].id)}catch(e){console.error(e)}})()}),[]),(0,kw.jsx)("div",{children:(0,kw.jsxs)("div",{className:"flex p-12",children:[(0,kw.jsx)("div",{className:"x2",children:(0,kw.jsxs)("div",{children:[(0,kw.jsxs)("div",{className:"flex justify-around",children:[(0,kw.jsx)("h1",{className:ib.betLabel,children:t.bet}),(0,kw.jsx)(db,{collection:"PropBets",docId:s})]}),r>0?(0,kw.jsxs)("div",{children:[(0,kw.jsx)("h4",{children:(0,kw.jsx)("span",{children:"Betting"})}),(0,kw.jsx)("div",{className:"pl-8",children:t.options.map(((e,t)=>(0,kw.jsx)("div",{children:(0,kw.jsx)("p",{children:e})},t)))})]}):null]})}),(0,kw.jsx)("div",{className:"x1",children:(0,kw.jsx)(Xw,{})})]})})},gb="Bets_betNav__NdIy7",vb="Bets_BettingLinks__UtSL7",yb="Bets_x__IOVNi",wb="Bets_bet__pvKP6",bb="Bets_link__ibFCG",_b=e=>{const t=rw();return(0,kw.jsxs)("div",{className:gb,children:[(0,kw.jsx)("div",{className:yb,children:(0,kw.jsx)("span",{onClick:e.swap,children:"x"})}),(0,kw.jsx)("h1",{children:(0,kw.jsx)("span",{children:"Bets"})}),(0,kw.jsxs)("div",{className:vb,children:[(0,kw.jsx)("div",{children:(0,kw.jsx)("div",{onClick:()=>{t("/Friendly-Betting/MoneyLineBets")},className:"Link",children:"Money Line Bets"})}),(0,kw.jsx)("div",{children:(0,kw.jsx)("div",{onClick:()=>{t("/Friendly-Betting/OverUnderBets")},className:"Link",children:"Over / Under Bets"})}),(0,kw.jsx)("div",{children:(0,kw.jsx)("div",{onClick:()=>{t("/Friendly-Betting/PropBets")},className:"Link",children:"Prop Bets"})})]})]})},Eb=e=>{const t=()=>"Money Line"===e.bet.type?"MoneyLineBets/":"Over Under"===e.bet.type?"OverUnderBets/":"Prop"===e.bet.type?"PropBets/":void 0;return(0,kw.jsx)("div",{onClick:t,children:(0,kw.jsx)(Mw,{to:"/Friendly-Betting/Bet/".concat(t()),state:{bet:e.bet},className:bb,children:(0,kw.jsxs)("div",{className:wb,children:[(0,kw.jsx)("h4",{children:e.bet.type}),(0,kw.jsx)("p",{children:e.bet.bet})]},e.bet.id)})})},Sb=()=>{const[t,n]=(0,e.useState)(""),[r,i]=(0,e.useState)(!1),[s,a]=(0,e.useState)([]);(0,e.useEffect)((()=>{(async()=>{try{const e=(await ry(cv(cy,"bets"))).docs.map((e=>({...e.data(),id:e.id})));a(e)}catch(e){console.error(e)}})()}),[]);const o=()=>{i((e=>!e))};return(0,kw.jsxs)("div",{className:"flex p-12",children:[(0,kw.jsx)("div",{className:"x2",children:s.length<1?(0,kw.jsxs)("div",{children:[(0,kw.jsx)("h3",{children:"You are not in any bets yet"}),(0,kw.jsx)("button",{onClick:o,children:"Create One!"}),r?(0,kw.jsx)(_b,{swap:o}):null]}):(0,kw.jsxs)("div",{children:[s.map(((e,t)=>(0,kw.jsx)(Eb,{bet:e},t))),(0,kw.jsx)("button",{onClick:o,children:"Create One!"}),r?(0,kw.jsx)(_b,{swap:o}):null]})}),(0,kw.jsx)("div",{className:"x1",children:(0,kw.jsx)(Xw,{})})]})};const kb=function(){return(0,kw.jsx)("div",{children:(0,kw.jsx)("h1",{children:"Friends"})})};const Ib=function(){return(0,kw.jsxs)(Dw,{children:[(0,kw.jsx)(Uw,{}),(0,kw.jsxs)(yw,{children:[(0,kw.jsx)(gw,{path:"Friendly-Betting/",element:(0,kw.jsx)(Bw,{})}),(0,kw.jsx)(gw,{path:"Friendly-Betting/SignIn",element:(0,kw.jsx)(Iw,{})}),(0,kw.jsx)(gw,{path:"Friendly-Betting/CreateAccount",element:(0,kw.jsx)(Tw,{})}),(0,kw.jsx)(gw,{path:"Friendly-Betting/Bet",element:(0,kw.jsx)(Sb,{})}),(0,kw.jsx)(gw,{path:"Friendly-Betting/Friends",element:(0,kw.jsx)(kb,{})}),(0,kw.jsx)(gw,{path:"Friendly-Betting/MoneyLineBets",element:(0,kw.jsx)(eb,{})}),(0,kw.jsx)(gw,{path:"Friendly-Betting/OverUnderBets",element:(0,kw.jsx)(rb,{})}),(0,kw.jsx)(gw,{path:"Friendly-Betting/PropBets",element:(0,kw.jsx)(ob,{})}),(0,kw.jsx)(gw,{path:"/Friendly-Betting/Bet/MoneyLineBets/",element:(0,kw.jsx)(fb,{})}),(0,kw.jsx)(gw,{path:"/Friendly-Betting/Bet/OverUnderBets/",element:(0,kw.jsx)(pb,{})}),(0,kw.jsx)(gw,{path:"/Friendly-Betting/Bet/PropBets/",element:(0,kw.jsx)(mb,{})}),(0,kw.jsx)(gw,{path:"/*",element:(0,kw.jsx)(Vw,{})})]})]})},Tb=e=>{e&&e instanceof Function&&n.e(787).then(n.bind(n,787)).then((t=>{let{getCLS:n,getFID:r,getFCP:i,getLCP:s,getTTFB:a}=t;n(e),r(e),i(e),s(e),a(e)}))};r.createRoot(document.getElementById("root")).render((0,kw.jsx)(e.StrictMode,{children:(0,kw.jsx)(Ib,{})})),Tb()})()})(); +//# sourceMappingURL=main.fc2a7381.js.map \ No newline at end of file diff --git a/static/js/main.e9c9ba71.js.LICENSE.txt b/static/js/main.fc2a7381.js.LICENSE.txt similarity index 100% rename from static/js/main.e9c9ba71.js.LICENSE.txt rename to static/js/main.fc2a7381.js.LICENSE.txt diff --git a/static/js/main.fc2a7381.js.map b/static/js/main.fc2a7381.js.map new file mode 100644 index 0000000..1a1c9a1 --- /dev/null +++ b/static/js/main.fc2a7381.js.map @@ -0,0 +1 @@ +{"version":3,"file":"static/js/main.fc2a7381.js","mappings":";wCAYa,IAAIA,EAAGC,EAAQ,KAASC,EAAGD,EAAQ,KAAa,SAASE,EAAEC,GAAG,IAAI,IAAIC,EAAE,yDAAyDD,EAAEE,EAAE,EAAEA,EAAEC,UAAUC,OAAOF,IAAID,GAAG,WAAWI,mBAAmBF,UAAUD,IAAI,MAAM,yBAAyBF,EAAE,WAAWC,EAAE,gHAAgH,CAAC,IAAIK,EAAG,IAAIC,IAAIC,EAAG,CAAC,EAAE,SAASC,EAAG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AQ,WAI7C,ECxCA,GAZwB0G,IAClBA,GAAeA,aAAuB7pG,UACxC,6BAAqB1nB,MAAKo2B,IAAkD,IAAjD,OAAEo7F,EAAM,OAAEC,EAAM,OAAEC,EAAM,OAAEC,EAAM,QAAEC,GAASx7F,EACpEo7F,EAAOD,GACPE,EAAOF,GACPG,EAAOH,GACPI,EAAOJ,GACPK,EAAQL,EAAY,GAExB,ECHWtI,EAAAA,WAAoBvzI,SAASm8I,eAAe,SACpD72I,QACHwtI,EAAAA,GAAAA,KAAChG,EAAAA,WAAgB,CAAAtkI,UACfsqI,EAAAA,GAAAA,KAACsJ,GAAG,OAORC","sources":["../node_modules/react-dom/cjs/react-dom.production.min.js","../node_modules/react-dom/client.js","../node_modules/react-dom/index.js","../node_modules/react/cjs/react-jsx-runtime.production.min.js","../node_modules/react/cjs/react.production.min.js","../node_modules/react/index.js","../node_modules/react/jsx-runtime.js","../node_modules/scheduler/cjs/scheduler.production.min.js","../node_modules/scheduler/index.js","../webpack/bootstrap","../webpack/runtime/create fake namespace object","../webpack/runtime/define property getters","../webpack/runtime/ensure chunk","../webpack/runtime/get javascript chunk filename","../webpack/runtime/get mini-css chunk filename","../webpack/runtime/global","../webpack/runtime/hasOwnProperty shorthand","../webpack/runtime/load script","../webpack/runtime/make namespace object","../webpack/runtime/publicPath","../webpack/runtime/jsonp chunk loading","../node_modules/@firebase/util/src/constants.ts","../node_modules/@firebase/util/src/crypt.ts","../node_modules/@firebase/util/src/defaults.ts","../node_modules/@firebase/util/src/global.ts","../node_modules/@firebase/util/src/deferred.ts","../node_modules/@firebase/util/src/environment.ts","../node_modules/@firebase/util/src/errors.ts","../node_modules/@firebase/util/src/obj.ts","../node_modules/@firebase/util/src/query.ts","../node_modules/@firebase/util/src/subscribe.ts","../node_modules/@firebase/util/src/utf8.ts","../node_modules/@firebase/util/src/exponential_backoff.ts","../node_modules/@firebase/util/src/compat.ts","../node_modules/@firebase/component/src/component.ts","../node_modules/@firebase/component/src/constants.ts","../node_modules/@firebase/component/src/provider.ts","../node_modules/@firebase/component/src/component_container.ts","../node_modules/@firebase/logger/src/logger.ts","../node_modules/idb/build/wrap-idb-value.js","../node_modules/idb/build/index.js","../node_modules/@firebase/app/src/platformLoggerService.ts","../node_modules/@firebase/app/src/logger.ts","../node_modules/@firebase/app/src/constants.ts","../node_modules/@firebase/app/src/internal.ts","../node_modules/@firebase/app/src/errors.ts","../node_modules/@firebase/app/src/firebaseApp.ts","../node_modules/@firebase/app/src/api.ts","../node_modules/@firebase/app/src/indexeddb.ts","../node_modules/@firebase/app/src/heartbeatService.ts","../node_modules/@firebase/app/src/registerCoreComponents.ts","../node_modules/@firebase/app/src/index.ts","../node_modules/firebase/app/index.ts","../node_modules/@firebase/installations/node_modules/idb/build/wrap-idb-value.js","../node_modules/@firebase/installations/node_modules/idb/build/index.js","../node_modules/@firebase/installations/src/util/constants.ts","../node_modules/@firebase/installations/src/util/errors.ts","../node_modules/@firebase/installations/src/functions/common.ts","../node_modules/@firebase/installations/src/util/sleep.ts","../node_modules/@firebase/installations/src/helpers/generate-fid.ts","../node_modules/@firebase/installations/src/helpers/buffer-to-base64-url-safe.ts","../node_modules/@firebase/installations/src/util/get-key.ts","../node_modules/@firebase/installations/src/helpers/fid-changed.ts","../node_modules/@firebase/installations/src/helpers/idb-manager.ts","../node_modules/@firebase/installations/src/helpers/get-installation-entry.ts","../node_modules/@firebase/installations/src/functions/create-installation-request.ts","../node_modules/@firebase/installations/src/functions/generate-auth-token-request.ts","../node_modules/@firebase/installations/src/helpers/refresh-auth-token.ts","../node_modules/@firebase/installations/src/api/get-token.ts","../node_modules/@firebase/installations/src/helpers/extract-app-config.ts","../node_modules/@firebase/installations/src/functions/config.ts","../node_modules/@firebase/installations/src/api/get-id.ts","../node_modules/@firebase/installations/src/index.ts","../node_modules/@firebase/analytics/src/constants.ts","../node_modules/@firebase/analytics/src/logger.ts","../node_modules/@firebase/analytics/src/errors.ts","../node_modules/@firebase/analytics/src/helpers.ts","../node_modules/@firebase/analytics/src/get-config.ts","../node_modules/@firebase/analytics/src/functions.ts","../node_modules/@firebase/analytics/src/initialize-analytics.ts","../node_modules/@firebase/analytics/src/factory.ts","../node_modules/@firebase/analytics/src/api.ts","../node_modules/@firebase/analytics/src/index.ts","../node_modules/tslib/tslib.es6.mjs","../node_modules/@firebase/auth/src/core/errors.ts","../node_modules/@firebase/auth/src/core/util/log.ts","../node_modules/@firebase/auth/src/core/util/assert.ts","../node_modules/@firebase/auth/src/core/util/location.ts","../node_modules/@firebase/auth/src/core/util/delay.ts","../node_modules/@firebase/auth/src/core/util/navigator.ts","../node_modules/@firebase/auth/src/core/util/emulator.ts","../node_modules/@firebase/auth/src/core/util/fetch_provider.ts","../node_modules/@firebase/auth/src/api/errors.ts","../node_modules/@firebase/auth/src/api/index.ts","../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha.ts","../node_modules/@firebase/auth/src/api/authentication/recaptcha.ts","../node_modules/@firebase/auth/src/core/util/time.ts","../node_modules/@firebase/auth/src/core/user/id_token_result.ts","../node_modules/@firebase/auth/src/core/user/invalidation.ts","../node_modules/@firebase/auth/src/core/user/proactive_refresh.ts","../node_modules/@firebase/auth/src/core/user/user_metadata.ts","../node_modules/@firebase/auth/src/core/user/reload.ts","../node_modules/@firebase/auth/src/api/account_management/account.ts","../node_modules/@firebase/auth/src/core/user/token_manager.ts","../node_modules/@firebase/auth/src/api/authentication/token.ts","../node_modules/@firebase/auth/src/core/user/user_impl.ts","../node_modules/@firebase/auth/src/core/util/instantiator.ts","../node_modules/@firebase/auth/src/core/persistence/in_memory.ts","../node_modules/@firebase/auth/src/core/persistence/persistence_user_manager.ts","../node_modules/@firebase/auth/src/core/util/browser.ts","../node_modules/@firebase/auth/src/core/util/version.ts","../node_modules/@firebase/auth/src/core/auth/middleware.ts","../node_modules/@firebase/auth/src/core/auth/password_policy_impl.ts","../node_modules/@firebase/auth/src/core/auth/auth_impl.ts","../node_modules/@firebase/auth/src/api/password_policy/get_password_policy.ts","../node_modules/@firebase/auth/src/platform_browser/load_js.ts","../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha_enterprise_verifier.ts","../node_modules/@firebase/auth/src/core/auth/emulator.ts","../node_modules/@firebase/auth/src/core/credentials/auth_credential.ts","../node_modules/@firebase/auth/src/api/account_management/email_and_password.ts","../node_modules/@firebase/auth/src/api/authentication/email_and_password.ts","../node_modules/@firebase/auth/src/core/credentials/email.ts","../node_modules/@firebase/auth/src/api/authentication/email_link.ts","../node_modules/@firebase/auth/src/api/authentication/idp.ts","../node_modules/@firebase/auth/src/core/credentials/oauth.ts","../node_modules/@firebase/auth/src/api/authentication/sms.ts","../node_modules/@firebase/auth/src/core/credentials/phone.ts","../node_modules/@firebase/auth/src/core/action_code_url.ts","../node_modules/@firebase/auth/src/core/providers/email.ts","../node_modules/@firebase/auth/src/core/providers/federated.ts","../node_modules/@firebase/auth/src/core/providers/oauth.ts","../node_modules/@firebase/auth/src/core/providers/facebook.ts","../node_modules/@firebase/auth/src/core/providers/google.ts","../node_modules/@firebase/auth/src/core/providers/github.ts","../node_modules/@firebase/auth/src/core/providers/twitter.ts","../node_modules/@firebase/auth/src/api/authentication/sign_up.ts","../node_modules/@firebase/auth/src/core/user/user_credential_impl.ts","../node_modules/@firebase/auth/src/mfa/mfa_error.ts","../node_modules/@firebase/auth/src/core/user/link_unlink.ts","../node_modules/@firebase/auth/src/core/user/reauthenticate.ts","../node_modules/@firebase/auth/src/core/strategies/credential.ts","../node_modules/@firebase/auth/src/core/strategies/email_and_password.ts","../node_modules/@firebase/auth/src/mfa/mfa_user.ts","../node_modules/@firebase/auth/src/core/persistence/index.ts","../node_modules/@firebase/auth/src/platform_browser/persistence/browser.ts","../node_modules/@firebase/auth/src/platform_browser/persistence/local_storage.ts","../node_modules/@firebase/auth/src/platform_browser/persistence/session_storage.ts","../node_modules/@firebase/auth/src/platform_browser/messagechannel/receiver.ts","../node_modules/@firebase/auth/src/platform_browser/messagechannel/promise.ts","../node_modules/@firebase/auth/src/core/util/event_id.ts","../node_modules/@firebase/auth/src/platform_browser/messagechannel/sender.ts","../node_modules/@firebase/auth/src/platform_browser/auth_window.ts","../node_modules/@firebase/auth/src/platform_browser/util/worker.ts","../node_modules/@firebase/auth/src/platform_browser/persistence/indexed_db.ts","../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha_loader.ts","../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha_verifier.ts","../node_modules/@firebase/auth/src/platform_browser/strategies/phone.ts","../node_modules/@firebase/auth/src/api/account_management/mfa.ts","../node_modules/@firebase/auth/src/api/authentication/mfa.ts","../node_modules/@firebase/auth/src/platform_browser/providers/phone.ts","../node_modules/@firebase/auth/src/core/util/resolver.ts","../node_modules/@firebase/auth/src/core/strategies/idp.ts","../node_modules/@firebase/auth/src/core/strategies/abstract_popup_redirect_operation.ts","../node_modules/@firebase/auth/src/platform_browser/strategies/popup.ts","../node_modules/@firebase/auth/src/core/strategies/redirect.ts","../node_modules/@firebase/auth/src/platform_browser/strategies/redirect.ts","../node_modules/@firebase/auth/src/core/auth/auth_event_manager.ts","../node_modules/@firebase/auth/src/core/util/validate_origin.ts","../node_modules/@firebase/auth/src/api/project_config/get_project_config.ts","../node_modules/@firebase/auth/src/platform_browser/iframe/gapi.ts","../node_modules/@firebase/auth/src/platform_browser/iframe/iframe.ts","../node_modules/@firebase/auth/src/platform_browser/util/popup.ts","../node_modules/@firebase/auth/src/core/util/handler.ts","../node_modules/@firebase/auth/src/platform_browser/popup_redirect.ts","../node_modules/@firebase/auth/src/core/auth/firebase_internal.ts","../node_modules/@firebase/auth/src/platform_browser/index.ts","../node_modules/@firebase/auth/src/core/auth/register.ts","../node_modules/@firebase/auth/src/core/auth/initialize.ts","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/base.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/disposable/disposable.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/array/array.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/event.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/browserfeature.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/string/internal.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/useragent/util.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/reflect/reflect.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/useragent/useragent.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/useragent/browser.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/useragent/engine.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/browserevent.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/eventtype.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listenable.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listenablekey.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listener.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listenermap.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/object/object.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/events.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/eventtarget.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/json/json.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/workqueue.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/run.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/freelist.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/string/string.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/xhrio.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/throwexception.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/timer/timer.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/throttle.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/eventhandler.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/webchanneldebug.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/requeststats.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/errorcode.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/eventtype.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/xmlhttpfactory.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/xmlhttp.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/channelrequest.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/environment.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/webchannelbase.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/uri/uri.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/disposable/dispose.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/wirev8.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/forwardchannelrequestpool.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/structs/structs.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/uri/utils.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/wire.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/json/nativejsonprocessor.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/functions/functions.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/netutils.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/fetchxmlhttpfactory.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/json/hybrid.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/httpstatus.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/rpc/httpcors.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/webchannelbasetransport.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/crypt/md5.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/crypt/hash.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/math/integer.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchanneltransport.js","../node_modules/@firebase/webchannel-wrapper/dist/temp/src/index.js","../node_modules/@firebase/webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchanneltransportfactory.js","../node_modules/@firebase/firestore/src/auth/user.ts","../node_modules/@firebase/firestore/src/core/version.ts","../node_modules/@firebase/firestore/src/util/log.ts","../node_modules/@firebase/firestore/src/platform/browser/format_json.ts","../node_modules/@firebase/firestore/src/util/assert.ts","../node_modules/@firebase/firestore/src/util/error.ts","../node_modules/@firebase/firestore/src/util/promise.ts","../node_modules/@firebase/firestore/src/api/credentials.ts","../node_modules/@firebase/firestore/src/platform/browser/random_bytes.ts","../node_modules/@firebase/firestore/src/util/misc.ts","../node_modules/@firebase/firestore/src/lite-api/timestamp.ts","../node_modules/@firebase/firestore/src/core/snapshot_version.ts","../node_modules/@firebase/firestore/src/model/path.ts","../node_modules/@firebase/firestore/src/model/document_key.ts","../node_modules/@firebase/firestore/src/model/field_index.ts","../node_modules/@firebase/firestore/src/local/persistence_transaction.ts","../node_modules/@firebase/firestore/src/local/local_store.ts","../node_modules/@firebase/firestore/src/local/persistence_promise.ts","../node_modules/@firebase/firestore/src/local/simple_db.ts","../node_modules/@firebase/firestore/src/core/listen_sequence.ts","../node_modules/@firebase/firestore/src/util/types.ts","../node_modules/@firebase/firestore/src/local/indexeddb_sentinels.ts","../node_modules/@firebase/firestore/src/local/indexeddb_schema_legacy.ts","../node_modules/@firebase/firestore/src/util/obj.ts","../node_modules/@firebase/firestore/src/util/sorted_map.ts","../node_modules/@firebase/firestore/src/util/sorted_set.ts","../node_modules/@firebase/firestore/src/model/field_mask.ts","../node_modules/@firebase/firestore/src/util/base64_decode_error.ts","../node_modules/@firebase/firestore/src/util/byte_string.ts","../node_modules/@firebase/firestore/src/platform/browser/base64.ts","../node_modules/@firebase/firestore/src/model/normalize.ts","../node_modules/@firebase/firestore/src/model/server_timestamps.ts","../node_modules/@firebase/firestore/src/core/database_info.ts","../node_modules/@firebase/firestore/src/model/values.ts","../node_modules/@firebase/firestore/src/model/object_value.ts","../node_modules/@firebase/firestore/src/model/document.ts","../node_modules/@firebase/firestore/src/core/bound.ts","../node_modules/@firebase/firestore/src/core/order_by.ts","../node_modules/@firebase/firestore/src/core/filter.ts","../node_modules/@firebase/firestore/src/core/target.ts","../node_modules/@firebase/firestore/src/core/query.ts","../node_modules/@firebase/firestore/src/util/obj_map.ts","../node_modules/@firebase/firestore/src/model/collections.ts","../node_modules/@firebase/firestore/src/remote/number_serializer.ts","../node_modules/@firebase/firestore/src/model/transform_operation.ts","../node_modules/@firebase/firestore/src/model/mutation.ts","../node_modules/@firebase/firestore/src/model/mutation_batch.ts","../node_modules/@firebase/firestore/src/model/overlay.ts","../node_modules/@firebase/firestore/src/remote/existence_filter.ts","../node_modules/@firebase/firestore/src/remote/rpc_error.ts","../node_modules/@firebase/firestore/src/util/testing_hooks_spi.ts","../node_modules/@firebase/firestore/src/platform/browser/text_serializer.ts","../node_modules/@firebase/firestore/src/remote/bloom_filter.ts","../node_modules/@firebase/firestore/src/remote/remote_event.ts","../node_modules/@firebase/firestore/src/remote/watch_change.ts","../node_modules/@firebase/firestore/src/remote/serializer.ts","../node_modules/@firebase/firestore/src/local/target_data.ts","../node_modules/@firebase/firestore/src/local/local_serializer.ts","../node_modules/@firebase/firestore/src/index/firestore_index_value_writer.ts","../node_modules/@firebase/firestore/src/local/memory_index_manager.ts","../node_modules/@firebase/firestore/src/local/indexeddb_index_manager.ts","../node_modules/@firebase/firestore/src/local/lru_garbage_collector.ts","../node_modules/@firebase/firestore/src/core/target_id_generator.ts","../node_modules/@firebase/firestore/src/local/remote_document_change_buffer.ts","../node_modules/@firebase/firestore/src/local/overlayed_document.ts","../node_modules/@firebase/firestore/src/local/local_documents_view.ts","../node_modules/@firebase/firestore/src/local/memory_bundle_cache.ts","../node_modules/@firebase/firestore/src/local/memory_document_overlay_cache.ts","../node_modules/@firebase/firestore/src/local/reference_set.ts","../node_modules/@firebase/firestore/src/local/memory_mutation_queue.ts","../node_modules/@firebase/firestore/src/local/memory_remote_document_cache.ts","../node_modules/@firebase/firestore/src/local/memory_target_cache.ts","../node_modules/@firebase/firestore/src/local/memory_persistence.ts","../node_modules/@firebase/firestore/src/local/local_view_changes.ts","../node_modules/@firebase/firestore/src/local/query_context.ts","../node_modules/@firebase/firestore/src/local/query_engine.ts","../node_modules/@firebase/firestore/src/local/local_store_impl.ts","../node_modules/@firebase/firestore/src/local/shared_client_state.ts","../node_modules/@firebase/firestore/src/remote/connectivity_monitor_noop.ts","../node_modules/@firebase/firestore/src/platform/browser/connectivity_monitor.ts","../node_modules/@firebase/firestore/src/util/debug_uid.ts","../node_modules/@firebase/firestore/src/remote/rest_connection.ts","../node_modules/@firebase/firestore/src/remote/stream_bridge.ts","../node_modules/@firebase/firestore/src/platform/browser/webchannel_connection.ts","../node_modules/@firebase/firestore/src/platform/browser/dom.ts","../node_modules/@firebase/firestore/src/platform/browser/serializer.ts","../node_modules/@firebase/firestore/src/remote/backoff.ts","../node_modules/@firebase/firestore/src/remote/persistent_stream.ts","../node_modules/@firebase/firestore/src/remote/datastore.ts","../node_modules/@firebase/firestore/src/remote/online_state_tracker.ts","../node_modules/@firebase/firestore/src/remote/remote_store.ts","../node_modules/@firebase/firestore/src/util/async_queue.ts","../node_modules/@firebase/firestore/src/model/document_set.ts","../node_modules/@firebase/firestore/src/core/view_snapshot.ts","../node_modules/@firebase/firestore/src/core/event_manager.ts","../node_modules/@firebase/firestore/src/core/view.ts","../node_modules/@firebase/firestore/src/core/sync_engine_impl.ts","../node_modules/@firebase/firestore/src/core/component_provider.ts","../node_modules/@firebase/firestore/src/platform/browser/connection.ts","../node_modules/@firebase/firestore/src/util/async_observer.ts","../node_modules/@firebase/firestore/src/core/firestore_client.ts","../node_modules/@firebase/firestore/src/api/long_polling_options.ts","../node_modules/@firebase/firestore/src/lite-api/components.ts","../node_modules/@firebase/firestore/src/util/input_validation.ts","../node_modules/@firebase/firestore/src/lite-api/settings.ts","../node_modules/@firebase/firestore/src/local/lru_garbage_collector_impl.ts","../node_modules/@firebase/firestore/src/lite-api/database.ts","../node_modules/@firebase/util/src/emulator.ts","../node_modules/@firebase/firestore/src/lite-api/reference.ts","../node_modules/@firebase/firestore/src/util/async_queue_impl.ts","../node_modules/@firebase/firestore/src/api/database.ts","../node_modules/@firebase/firestore/src/lite-api/bytes.ts","../node_modules/@firebase/firestore/src/lite-api/field_path.ts","../node_modules/@firebase/firestore/src/lite-api/field_value.ts","../node_modules/@firebase/firestore/src/lite-api/geo_point.ts","../node_modules/@firebase/firestore/src/lite-api/user_data_reader.ts","../node_modules/@firebase/firestore/src/lite-api/snapshot.ts","../node_modules/@firebase/firestore/src/lite-api/query.ts","../node_modules/@firebase/firestore/src/lite-api/user_data_writer.ts","../node_modules/@firebase/firestore/src/lite-api/reference_impl.ts","../node_modules/@firebase/firestore/src/api/snapshot.ts","../node_modules/@firebase/firestore/src/api/reference_impl.ts","../node_modules/@firebase/firestore/src/api/persistent_cache_index_manager.ts","../node_modules/@firebase/firestore/src/register.ts","../node_modules/@firebase/firestore/src/index.ts","Config/firebase-config.js","../node_modules/@firebase/auth/src/core/index.ts","../node_modules/@remix-run/router/history.ts","../node_modules/@remix-run/router/utils.ts","../node_modules/@remix-run/router/router.ts","../node_modules/react-router/lib/context.ts","../node_modules/react-router/lib/hooks.tsx","../node_modules/react-router/lib/components.tsx","webpack://friendlybetting/./src/Components/SignInPage/SignIn.module.css?a8d9","Components/SignInPage/SignIn.jsx","Components/SignInPage/CreateAccount.jsx","../node_modules/react-router-dom/dom.ts","../node_modules/react-router-dom/index.tsx","Components/Header.jsx","Components/NotFound.jsx","Components/Welcome.jsx","webpack://friendlybetting/./src/Components/Bets/MoneyLineBets/MoneyLine.module.css?5dfc","webpack://friendlybetting/./src/Components/Bets/Players/Players.module.css?ca9c","Components/Bets/Players/AddFriend.jsx","Components/Bets/Players/Players.jsx","Components/Bets/Players/ShareBet.jsx","Components/Bets/MoneyLineBets/CreateMoneyLine.jsx","Components/Bets/MoneyLineBets/MoneyLine.jsx","webpack://friendlybetting/./src/Components/Bets/OverUnderBets/OverUnder.module.css?b5a4","Components/Bets/OverUnderBets/CreateOverUnder.jsx","Components/Bets/OverUnderBets/OverUnder.jsx","webpack://friendlybetting/./src/Components/Bets/PropBets/Prop.module.css?4924","Components/Bets/PropBets/PreSetBettingOptions.jsx","Components/Bets/PropBets/CreateProp.jsx","Components/Bets/PropBets/Prop.jsx","webpack://friendlybetting/./src/Components/Components/Components.module.css?7d21","Components/Components/Buttons.jsx","Components/Components/DeleteButton.jsx","Components/Bets/MoneyLineBets/ViewMoneyLine.jsx","Components/Bets/OverUnderBets/ViewOverUnder.jsx","Components/Bets/PropBets/ViewProp.jsx","webpack://friendlybetting/./src/Components/Bets/Bets.module.css?8472","Components/Bets/BetNav.jsx","Components/Bets/DisplayBet.jsx","Components/Bets/DisplayAllBets.jsx","Components/Friends/Friends.jsx","App.js","reportWebVitals.js","index.js"],"sourcesContent":["/**\n * @license React\n * react-dom.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n'use strict';var aa=require(\"react\"),ca=require(\"scheduler\");function p(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;c<arguments.length;c++)b+=\"&args[]=\"+encodeURIComponent(arguments[c]);return\"Minified React error #\"+a+\"; visit \"+b+\" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.\"}var da=new Set,ea={};function fa(a,b){ha(a,b);ha(a+\"Capture\",b)}\nfunction ha(a,b){ea[a]=b;for(a=0;a<b.length;a++)da.add(b[a])}\nvar ia=!(\"undefined\"===typeof window||\"undefined\"===typeof window.document||\"undefined\"===typeof window.document.createElement),ja=Object.prototype.hasOwnProperty,ka=/^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$/,la=\n{},ma={};function oa(a){if(ja.call(ma,a))return!0;if(ja.call(la,a))return!1;if(ka.test(a))return ma[a]=!0;la[a]=!0;return!1}function pa(a,b,c,d){if(null!==c&&0===c.type)return!1;switch(typeof b){case \"function\":case \"symbol\":return!0;case \"boolean\":if(d)return!1;if(null!==c)return!c.acceptsBooleans;a=a.toLowerCase().slice(0,5);return\"data-\"!==a&&\"aria-\"!==a;default:return!1}}\nfunction qa(a,b,c,d){if(null===b||\"undefined\"===typeof b||pa(a,b,c,d))return!0;if(d)return!1;if(null!==c)switch(c.type){case 3:return!b;case 4:return!1===b;case 5:return isNaN(b);case 6:return isNaN(b)||1>b}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});\"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope\".split(\" \").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}\n\"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height\".split(\" \").forEach(function(a){var b=a.replace(ra,\nsa);z[b]=new v(b,1,!1,a,null,!1,!1)});\"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type\".split(\" \").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/1999/xlink\",!1,!1)});[\"xml:base\",\"xml:lang\",\"xml:space\"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});\nz.xlinkHref=new v(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2<b.length)||\"o\"!==b[0]&&\"O\"!==b[0]||\"n\"!==b[1]&&\"N\"!==b[1])qa(b,c,e,d)&&(c=null),d||null===e?oa(b)&&(null===c?a.removeAttribute(b):a.setAttribute(b,\"\"+c)):e.mustUseProperty?a[e.propertyName]=null===c?3===e.type?!1:\"\":c:(b=e.attributeName,d=e.attributeNamespace,null===c?a.removeAttribute(b):(e=e.type,c=3===e||4===e&&!0===c?\"\":\"\"+c,d?a.setAttributeNS(d,b,c):a.setAttribute(b,c)))}\nvar ua=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,va=Symbol.for(\"react.element\"),wa=Symbol.for(\"react.portal\"),ya=Symbol.for(\"react.fragment\"),za=Symbol.for(\"react.strict_mode\"),Aa=Symbol.for(\"react.profiler\"),Ba=Symbol.for(\"react.provider\"),Ca=Symbol.for(\"react.context\"),Da=Symbol.for(\"react.forward_ref\"),Ea=Symbol.for(\"react.suspense\"),Fa=Symbol.for(\"react.suspense_list\"),Ga=Symbol.for(\"react.memo\"),Ha=Symbol.for(\"react.lazy\");Symbol.for(\"react.scope\");Symbol.for(\"react.debug_trace_mode\");\nvar Ia=Symbol.for(\"react.offscreen\");Symbol.for(\"react.legacy_hidden\");Symbol.for(\"react.cache\");Symbol.for(\"react.tracing_marker\");var Ja=Symbol.iterator;function Ka(a){if(null===a||\"object\"!==typeof a)return null;a=Ja&&a[Ja]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}var A=Object.assign,La;function Ma(a){if(void 0===La)try{throw Error();}catch(c){var b=c.stack.trim().match(/\\n( *(at )?)/);La=b&&b[1]||\"\"}return\"\\n\"+La+a}var Na=!1;\nfunction Oa(a,b){if(!a||Na)return\"\";Na=!0;var c=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(b)if(b=function(){throw Error();},Object.defineProperty(b.prototype,\"props\",{set:function(){throw Error();}}),\"object\"===typeof Reflect&&Reflect.construct){try{Reflect.construct(b,[])}catch(l){var d=l}Reflect.construct(a,[],b)}else{try{b.call()}catch(l){d=l}a.call(b.prototype)}else{try{throw Error();}catch(l){d=l}a()}}catch(l){if(l&&d&&\"string\"===typeof l.stack){for(var e=l.stack.split(\"\\n\"),\nf=d.stack.split(\"\\n\"),g=e.length-1,h=f.length-1;1<=g&&0<=h&&e[g]!==f[h];)h--;for(;1<=g&&0<=h;g--,h--)if(e[g]!==f[h]){if(1!==g||1!==h){do if(g--,h--,0>h||e[g]!==f[h]){var k=\"\\n\"+e[g].replace(\" at new \",\" at \");a.displayName&&k.includes(\"<anonymous>\")&&(k=k.replace(\"<anonymous>\",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Ma(a):\"\"}\nfunction Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma(\"Lazy\");case 13:return Ma(\"Suspense\");case 19:return Ma(\"SuspenseList\");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return\"\"}}\nfunction Qa(a){if(null==a)return null;if(\"function\"===typeof a)return a.displayName||a.name||null;if(\"string\"===typeof a)return a;switch(a){case ya:return\"Fragment\";case wa:return\"Portal\";case Aa:return\"Profiler\";case za:return\"StrictMode\";case Ea:return\"Suspense\";case Fa:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||\"Context\")+\".Consumer\";case Ba:return(a._context.displayName||\"Context\")+\".Provider\";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||\nb.name||\"\",a=\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||\"Memo\";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}\nfunction Ra(a){var b=a.type;switch(a.tag){case 24:return\"Cache\";case 9:return(b.displayName||\"Context\")+\".Consumer\";case 10:return(b._context.displayName||\"Context\")+\".Provider\";case 18:return\"DehydratedFragment\";case 11:return a=b.render,a=a.displayName||a.name||\"\",b.displayName||(\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");case 7:return\"Fragment\";case 5:return b;case 4:return\"Portal\";case 3:return\"Root\";case 6:return\"Text\";case 16:return Qa(b);case 8:return b===za?\"StrictMode\":\"Mode\";case 22:return\"Offscreen\";\ncase 12:return\"Profiler\";case 21:return\"Scope\";case 13:return\"Suspense\";case 19:return\"SuspenseList\";case 25:return\"TracingMarker\";case 1:case 0:case 17:case 2:case 14:case 15:if(\"function\"===typeof b)return b.displayName||b.name||null;if(\"string\"===typeof b)return b}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"string\":case \"undefined\":return a;case \"object\":return a;default:return\"\"}}\nfunction Ta(a){var b=a.type;return(a=a.nodeName)&&\"input\"===a.toLowerCase()&&(\"checkbox\"===b||\"radio\"===b)}\nfunction Ua(a){var b=Ta(a)?\"checked\":\"value\",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=\"\"+a[b];if(!a.hasOwnProperty(b)&&\"undefined\"!==typeof c&&\"function\"===typeof c.get&&\"function\"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=\"\"+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=\"\"+a},stopTracking:function(){a._valueTracker=\nnull;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d=\"\";a&&(d=Ta(a)?a.checked?\"true\":\"false\":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||(\"undefined\"!==typeof document?document:void 0);if(\"undefined\"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}\nfunction Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?\"\":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:\"checkbox\"===b.type||\"radio\"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,\"checked\",b,!1)}\nfunction bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if(\"number\"===d){if(0===c&&\"\"===a.value||a.value!=c)a.value=\"\"+c}else a.value!==\"\"+c&&(a.value=\"\"+c);else if(\"submit\"===d||\"reset\"===d){a.removeAttribute(\"value\");return}b.hasOwnProperty(\"value\")?cb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction db(a,b,c){if(b.hasOwnProperty(\"value\")||b.hasOwnProperty(\"defaultValue\")){var d=b.type;if(!(\"submit\"!==d&&\"reset\"!==d||void 0!==b.value&&null!==b.value))return;b=\"\"+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;\"\"!==c&&(a.name=\"\");a.defaultChecked=!!a._wrapperState.initialChecked;\"\"!==c&&(a.name=c)}\nfunction cb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}var eb=Array.isArray;\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e<c.length;e++)b[\"$\"+c[e]]=!0;for(c=0;c<a.length;c++)e=b.hasOwnProperty(\"$\"+a[c].value),a[c].selected!==e&&(a[c].selected=e),e&&d&&(a[c].defaultSelected=!0)}else{c=\"\"+Sa(c);b=null;for(e=0;e<a.length;e++){if(a[e].value===c){a[e].selected=!0;d&&(a[e].defaultSelected=!0);return}null!==b||a[e].disabled||(b=a[e])}null!==b&&(b.selected=!0)}}\nfunction gb(a,b){if(null!=b.dangerouslySetInnerHTML)throw Error(p(91));return A({},b,{value:void 0,defaultValue:void 0,children:\"\"+a._wrapperState.initialValue})}function hb(a,b){var c=b.value;if(null==c){c=b.children;b=b.defaultValue;if(null!=c){if(null!=b)throw Error(p(92));if(eb(c)){if(1<c.length)throw Error(p(93));c=c[0]}b=c}null==b&&(b=\"\");c=b}a._wrapperState={initialValue:Sa(c)}}\nfunction ib(a,b){var c=Sa(b.value),d=Sa(b.defaultValue);null!=c&&(c=\"\"+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=\"\"+d)}function jb(a){var b=a.textContent;b===a._wrapperState.initialValue&&\"\"!==b&&null!==b&&(a.value=b)}function kb(a){switch(a){case \"svg\":return\"http://www.w3.org/2000/svg\";case \"math\":return\"http://www.w3.org/1998/Math/MathML\";default:return\"http://www.w3.org/1999/xhtml\"}}\nfunction lb(a,b){return null==a||\"http://www.w3.org/1999/xhtml\"===a?kb(b):\"http://www.w3.org/2000/svg\"===a&&\"foreignObject\"===b?\"http://www.w3.org/1999/xhtml\":a}\nvar mb,nb=function(a){return\"undefined\"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,c,d,e)})}:a}(function(a,b){if(\"http://www.w3.org/2000/svg\"!==a.namespaceURI||\"innerHTML\"in a)a.innerHTML=b;else{mb=mb||document.createElement(\"div\");mb.innerHTML=\"<svg>\"+b.valueOf().toString()+\"</svg>\";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,\nzoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(\"\"+b).trim():b+\"px\"}\nfunction sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=rb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});\nfunction ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if(\"object\"!==typeof b.dangerouslySetInnerHTML||!(\"__html\"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(p(62));}}\nfunction vb(a,b){if(-1===a.indexOf(\"-\"))return\"string\"===typeof b.is;switch(a){case \"annotation-xml\":case \"color-profile\":case \"font-face\":case \"font-face-src\":case \"font-face-uri\":case \"font-face-format\":case \"font-face-name\":case \"missing-glyph\":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;\nfunction Bb(a){if(a=Cb(a)){if(\"function\"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a<b.length;a++)Bb(b[a])}}function Gb(a,b){return a(b)}function Hb(){}var Ib=!1;function Jb(a,b,c){if(Ib)return a(b,c);Ib=!0;try{return Gb(a,b,c)}finally{if(Ib=!1,null!==zb||null!==Ab)Hb(),Fb()}}\nfunction Kb(a,b){var c=a.stateNode;if(null===c)return null;var d=Db(c);if(null===d)return null;c=d[b];a:switch(b){case \"onClick\":case \"onClickCapture\":case \"onDoubleClick\":case \"onDoubleClickCapture\":case \"onMouseDown\":case \"onMouseDownCapture\":case \"onMouseMove\":case \"onMouseMoveCapture\":case \"onMouseUp\":case \"onMouseUpCapture\":case \"onMouseEnter\":(d=!d.disabled)||(a=a.type,d=!(\"button\"===a||\"input\"===a||\"select\"===a||\"textarea\"===a));a=!d;break a;default:a=!1}if(a)return null;if(c&&\"function\"!==\ntypeof c)throw Error(p(231,b,typeof c));return c}var Lb=!1;if(ia)try{var Mb={};Object.defineProperty(Mb,\"passive\",{get:function(){Lb=!0}});window.addEventListener(\"test\",Mb,Mb);window.removeEventListener(\"test\",Mb,Mb)}catch(a){Lb=!1}function Nb(a,b,c,d,e,f,g,h,k){var l=Array.prototype.slice.call(arguments,3);try{b.apply(c,l)}catch(m){this.onError(m)}}var Ob=!1,Pb=null,Qb=!1,Rb=null,Sb={onError:function(a){Ob=!0;Pb=a}};function Tb(a,b,c,d,e,f,g,h,k){Ob=!1;Pb=null;Nb.apply(Sb,arguments)}\nfunction Ub(a,b,c,d,e,f,g,h,k){Tb.apply(this,arguments);if(Ob){if(Ob){var l=Pb;Ob=!1;Pb=null}else throw Error(p(198));Qb||(Qb=!0,Rb=l)}}function Vb(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else{a=b;do b=a,0!==(b.flags&4098)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function Wb(a){if(13===a.tag){var b=a.memoizedState;null===b&&(a=a.alternate,null!==a&&(b=a.memoizedState));if(null!==b)return b.dehydrated}return null}function Xb(a){if(Vb(a)!==a)throw Error(p(188));}\nfunction Yb(a){var b=a.alternate;if(!b){b=Vb(a);if(null===b)throw Error(p(188));return b!==a?null:a}for(var c=a,d=b;;){var e=c.return;if(null===e)break;var f=e.alternate;if(null===f){d=e.return;if(null!==d){c=d;continue}break}if(e.child===f.child){for(f=e.child;f;){if(f===c)return Xb(e),a;if(f===d)return Xb(e),b;f=f.sibling}throw Error(p(188));}if(c.return!==d.return)c=e,d=f;else{for(var g=!1,h=e.child;h;){if(h===c){g=!0;c=e;d=f;break}if(h===d){g=!0;d=e;c=f;break}h=h.sibling}if(!g){for(h=f.child;h;){if(h===\nc){g=!0;c=f;d=e;break}if(h===d){g=!0;d=f;c=e;break}h=h.sibling}if(!g)throw Error(p(189));}}if(c.alternate!==d)throw Error(p(190));}if(3!==c.tag)throw Error(p(188));return c.stateNode.current===c?a:b}function Zb(a){a=Yb(a);return null!==a?$b(a):null}function $b(a){if(5===a.tag||6===a.tag)return a;for(a=a.child;null!==a;){var b=$b(a);if(null!==b)return b;a=a.sibling}return null}\nvar ac=ca.unstable_scheduleCallback,bc=ca.unstable_cancelCallback,cc=ca.unstable_shouldYield,dc=ca.unstable_requestPaint,B=ca.unstable_now,ec=ca.unstable_getCurrentPriorityLevel,fc=ca.unstable_ImmediatePriority,gc=ca.unstable_UserBlockingPriority,hc=ca.unstable_NormalPriority,ic=ca.unstable_LowPriority,jc=ca.unstable_IdlePriority,kc=null,lc=null;function mc(a){if(lc&&\"function\"===typeof lc.onCommitFiberRoot)try{lc.onCommitFiberRoot(kc,a,void 0,128===(a.current.flags&128))}catch(b){}}\nvar oc=Math.clz32?Math.clz32:nc,pc=Math.log,qc=Math.LN2;function nc(a){a>>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;\nfunction tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;\ndefault:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0<b;)c=31-oc(b),e=1<<c,d|=a[c],b&=~e;return d}\nfunction vc(a,b){switch(a){case 1:case 2:case 4:return b+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return b+5E3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}\nfunction wc(a,b){for(var c=a.suspendedLanes,d=a.pingedLanes,e=a.expirationTimes,f=a.pendingLanes;0<f;){var g=31-oc(f),h=1<<g,k=e[g];if(-1===k){if(0===(h&c)||0!==(h&d))e[g]=vc(h,b)}else k<=b&&(a.expiredLanes|=h);f&=~h}}function xc(a){a=a.pendingLanes&-1073741825;return 0!==a?a:a&1073741824?1073741824:0}function yc(){var a=rc;rc<<=1;0===(rc&4194240)&&(rc=64);return a}function zc(a){for(var b=[],c=0;31>c;c++)b.push(a);return b}\nfunction Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0<c;){var e=31-oc(c),f=1<<e;b[e]=0;d[e]=-1;a[e]=-1;c&=~f}}\nfunction Cc(a,b){var c=a.entangledLanes|=b;for(a=a.entanglements;c;){var d=31-oc(c),e=1<<d;e&b|a[d]&b&&(a[d]|=b);c&=~e}}var C=0;function Dc(a){a&=-a;return 1<a?4<a?0!==(a&268435455)?16:536870912:4:1}var Ec,Fc,Gc,Hc,Ic,Jc=!1,Kc=[],Lc=null,Mc=null,Nc=null,Oc=new Map,Pc=new Map,Qc=[],Rc=\"mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit\".split(\" \");\nfunction Sc(a,b){switch(a){case \"focusin\":case \"focusout\":Lc=null;break;case \"dragenter\":case \"dragleave\":Mc=null;break;case \"mouseover\":case \"mouseout\":Nc=null;break;case \"pointerover\":case \"pointerout\":Oc.delete(b.pointerId);break;case \"gotpointercapture\":case \"lostpointercapture\":Pc.delete(b.pointerId)}}\nfunction Tc(a,b,c,d,e,f){if(null===a||a.nativeEvent!==f)return a={blockedOn:b,domEventName:c,eventSystemFlags:d,nativeEvent:f,targetContainers:[e]},null!==b&&(b=Cb(b),null!==b&&Fc(b)),a;a.eventSystemFlags|=d;b=a.targetContainers;null!==e&&-1===b.indexOf(e)&&b.push(e);return a}\nfunction Uc(a,b,c,d,e){switch(b){case \"focusin\":return Lc=Tc(Lc,a,b,c,d,e),!0;case \"dragenter\":return Mc=Tc(Mc,a,b,c,d,e),!0;case \"mouseover\":return Nc=Tc(Nc,a,b,c,d,e),!0;case \"pointerover\":var f=e.pointerId;Oc.set(f,Tc(Oc.get(f)||null,a,b,c,d,e));return!0;case \"gotpointercapture\":return f=e.pointerId,Pc.set(f,Tc(Pc.get(f)||null,a,b,c,d,e)),!0}return!1}\nfunction Vc(a){var b=Wc(a.target);if(null!==b){var c=Vb(b);if(null!==c)if(b=c.tag,13===b){if(b=Wb(c),null!==b){a.blockedOn=b;Ic(a.priority,function(){Gc(c)});return}}else if(3===b&&c.stateNode.current.memoizedState.isDehydrated){a.blockedOn=3===c.tag?c.stateNode.containerInfo:null;return}}a.blockedOn=null}\nfunction Xc(a){if(null!==a.blockedOn)return!1;for(var b=a.targetContainers;0<b.length;){var c=Yc(a.domEventName,a.eventSystemFlags,b[0],a.nativeEvent);if(null===c){c=a.nativeEvent;var d=new c.constructor(c.type,c);wb=d;c.target.dispatchEvent(d);wb=null}else return b=Cb(c),null!==b&&Fc(b),a.blockedOn=c,!1;b.shift()}return!0}function Zc(a,b,c){Xc(a)&&c.delete(b)}function $c(){Jc=!1;null!==Lc&&Xc(Lc)&&(Lc=null);null!==Mc&&Xc(Mc)&&(Mc=null);null!==Nc&&Xc(Nc)&&(Nc=null);Oc.forEach(Zc);Pc.forEach(Zc)}\nfunction ad(a,b){a.blockedOn===b&&(a.blockedOn=null,Jc||(Jc=!0,ca.unstable_scheduleCallback(ca.unstable_NormalPriority,$c)))}\nfunction bd(a){function b(b){return ad(b,a)}if(0<Kc.length){ad(Kc[0],a);for(var c=1;c<Kc.length;c++){var d=Kc[c];d.blockedOn===a&&(d.blockedOn=null)}}null!==Lc&&ad(Lc,a);null!==Mc&&ad(Mc,a);null!==Nc&&ad(Nc,a);Oc.forEach(b);Pc.forEach(b);for(c=0;c<Qc.length;c++)d=Qc[c],d.blockedOn===a&&(d.blockedOn=null);for(;0<Qc.length&&(c=Qc[0],null===c.blockedOn);)Vc(c),null===c.blockedOn&&Qc.shift()}var cd=ua.ReactCurrentBatchConfig,dd=!0;\nfunction ed(a,b,c,d){var e=C,f=cd.transition;cd.transition=null;try{C=1,fd(a,b,c,d)}finally{C=e,cd.transition=f}}function gd(a,b,c,d){var e=C,f=cd.transition;cd.transition=null;try{C=4,fd(a,b,c,d)}finally{C=e,cd.transition=f}}\nfunction fd(a,b,c,d){if(dd){var e=Yc(a,b,c,d);if(null===e)hd(a,b,d,id,c),Sc(a,d);else if(Uc(e,a,b,c,d))d.stopPropagation();else if(Sc(a,d),b&4&&-1<Rc.indexOf(a)){for(;null!==e;){var f=Cb(e);null!==f&&Ec(f);f=Yc(a,b,c,d);null===f&&hd(a,b,d,id,c);if(f===e)break;e=f}null!==e&&d.stopPropagation()}else hd(a,b,d,null,c)}}var id=null;\nfunction Yc(a,b,c,d){id=null;a=xb(d);a=Wc(a);if(null!==a)if(b=Vb(a),null===b)a=null;else if(c=b.tag,13===c){a=Wb(b);if(null!==a)return a;a=null}else if(3===c){if(b.stateNode.current.memoizedState.isDehydrated)return 3===b.tag?b.stateNode.containerInfo:null;a=null}else b!==a&&(a=null);id=a;return null}\nfunction jd(a){switch(a){case \"cancel\":case \"click\":case \"close\":case \"contextmenu\":case \"copy\":case \"cut\":case \"auxclick\":case \"dblclick\":case \"dragend\":case \"dragstart\":case \"drop\":case \"focusin\":case \"focusout\":case \"input\":case \"invalid\":case \"keydown\":case \"keypress\":case \"keyup\":case \"mousedown\":case \"mouseup\":case \"paste\":case \"pause\":case \"play\":case \"pointercancel\":case \"pointerdown\":case \"pointerup\":case \"ratechange\":case \"reset\":case \"resize\":case \"seeked\":case \"submit\":case \"touchcancel\":case \"touchend\":case \"touchstart\":case \"volumechange\":case \"change\":case \"selectionchange\":case \"textInput\":case \"compositionstart\":case \"compositionend\":case \"compositionupdate\":case \"beforeblur\":case \"afterblur\":case \"beforeinput\":case \"blur\":case \"fullscreenchange\":case \"focus\":case \"hashchange\":case \"popstate\":case \"select\":case \"selectstart\":return 1;case \"drag\":case \"dragenter\":case \"dragexit\":case \"dragleave\":case \"dragover\":case \"mousemove\":case \"mouseout\":case \"mouseover\":case \"pointermove\":case \"pointerout\":case \"pointerover\":case \"scroll\":case \"toggle\":case \"touchmove\":case \"wheel\":case \"mouseenter\":case \"mouseleave\":case \"pointerenter\":case \"pointerleave\":return 4;\ncase \"message\":switch(ec()){case fc:return 1;case gc:return 4;case hc:case ic:return 16;case jc:return 536870912;default:return 16}default:return 16}}var kd=null,ld=null,md=null;function nd(){if(md)return md;var a,b=ld,c=b.length,d,e=\"value\"in kd?kd.value:kd.textContent,f=e.length;for(a=0;a<c&&b[a]===e[a];a++);var g=c-a;for(d=1;d<=g&&b[c-d]===e[f-d];d++);return md=e.slice(a,1<d?1-d:void 0)}\nfunction od(a){var b=a.keyCode;\"charCode\"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;10===a&&(a=13);return 32<=a||13===a?a:0}function pd(){return!0}function qd(){return!1}\nfunction rd(a){function b(b,d,e,f,g){this._reactName=b;this._targetInst=e;this.type=d;this.nativeEvent=f;this.target=g;this.currentTarget=null;for(var c in a)a.hasOwnProperty(c)&&(b=a[c],this[c]=b?b(f):f[c]);this.isDefaultPrevented=(null!=f.defaultPrevented?f.defaultPrevented:!1===f.returnValue)?pd:qd;this.isPropagationStopped=qd;return this}A(b.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():\"unknown\"!==typeof a.returnValue&&\n(a.returnValue=!1),this.isDefaultPrevented=pd)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():\"unknown\"!==typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=pd)},persist:function(){},isPersistent:pd});return b}\nvar sd={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},td=rd(sd),ud=A({},sd,{view:0,detail:0}),vd=rd(ud),wd,xd,yd,Ad=A({},ud,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:zd,button:0,buttons:0,relatedTarget:function(a){return void 0===a.relatedTarget?a.fromElement===a.srcElement?a.toElement:a.fromElement:a.relatedTarget},movementX:function(a){if(\"movementX\"in\na)return a.movementX;a!==yd&&(yd&&\"mousemove\"===a.type?(wd=a.screenX-yd.screenX,xd=a.screenY-yd.screenY):xd=wd=0,yd=a);return wd},movementY:function(a){return\"movementY\"in a?a.movementY:xd}}),Bd=rd(Ad),Cd=A({},Ad,{dataTransfer:0}),Dd=rd(Cd),Ed=A({},ud,{relatedTarget:0}),Fd=rd(Ed),Gd=A({},sd,{animationName:0,elapsedTime:0,pseudoElement:0}),Hd=rd(Gd),Id=A({},sd,{clipboardData:function(a){return\"clipboardData\"in a?a.clipboardData:window.clipboardData}}),Jd=rd(Id),Kd=A({},sd,{data:0}),Ld=rd(Kd),Md={Esc:\"Escape\",\nSpacebar:\" \",Left:\"ArrowLeft\",Up:\"ArrowUp\",Right:\"ArrowRight\",Down:\"ArrowDown\",Del:\"Delete\",Win:\"OS\",Menu:\"ContextMenu\",Apps:\"ContextMenu\",Scroll:\"ScrollLock\",MozPrintableKey:\"Unidentified\"},Nd={8:\"Backspace\",9:\"Tab\",12:\"Clear\",13:\"Enter\",16:\"Shift\",17:\"Control\",18:\"Alt\",19:\"Pause\",20:\"CapsLock\",27:\"Escape\",32:\" \",33:\"PageUp\",34:\"PageDown\",35:\"End\",36:\"Home\",37:\"ArrowLeft\",38:\"ArrowUp\",39:\"ArrowRight\",40:\"ArrowDown\",45:\"Insert\",46:\"Delete\",112:\"F1\",113:\"F2\",114:\"F3\",115:\"F4\",116:\"F5\",117:\"F6\",118:\"F7\",\n119:\"F8\",120:\"F9\",121:\"F10\",122:\"F11\",123:\"F12\",144:\"NumLock\",145:\"ScrollLock\",224:\"Meta\"},Od={Alt:\"altKey\",Control:\"ctrlKey\",Meta:\"metaKey\",Shift:\"shiftKey\"};function Pd(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):(a=Od[a])?!!b[a]:!1}function zd(){return Pd}\nvar Qd=A({},ud,{key:function(a){if(a.key){var b=Md[a.key]||a.key;if(\"Unidentified\"!==b)return b}return\"keypress\"===a.type?(a=od(a),13===a?\"Enter\":String.fromCharCode(a)):\"keydown\"===a.type||\"keyup\"===a.type?Nd[a.keyCode]||\"Unidentified\":\"\"},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:zd,charCode:function(a){return\"keypress\"===a.type?od(a):0},keyCode:function(a){return\"keydown\"===a.type||\"keyup\"===a.type?a.keyCode:0},which:function(a){return\"keypress\"===\na.type?od(a):\"keydown\"===a.type||\"keyup\"===a.type?a.keyCode:0}}),Rd=rd(Qd),Sd=A({},Ad,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Td=rd(Sd),Ud=A({},ud,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:zd}),Vd=rd(Ud),Wd=A({},sd,{propertyName:0,elapsedTime:0,pseudoElement:0}),Xd=rd(Wd),Yd=A({},Ad,{deltaX:function(a){return\"deltaX\"in a?a.deltaX:\"wheelDeltaX\"in a?-a.wheelDeltaX:0},\ndeltaY:function(a){return\"deltaY\"in a?a.deltaY:\"wheelDeltaY\"in a?-a.wheelDeltaY:\"wheelDelta\"in a?-a.wheelDelta:0},deltaZ:0,deltaMode:0}),Zd=rd(Yd),$d=[9,13,27,32],ae=ia&&\"CompositionEvent\"in window,be=null;ia&&\"documentMode\"in document&&(be=document.documentMode);var ce=ia&&\"TextEvent\"in window&&!be,de=ia&&(!ae||be&&8<be&&11>=be),ee=String.fromCharCode(32),fe=!1;\nfunction ge(a,b){switch(a){case \"keyup\":return-1!==$d.indexOf(b.keyCode);case \"keydown\":return 229!==b.keyCode;case \"keypress\":case \"mousedown\":case \"focusout\":return!0;default:return!1}}function he(a){a=a.detail;return\"object\"===typeof a&&\"data\"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case \"compositionend\":return he(b);case \"keypress\":if(32!==b.which)return null;fe=!0;return ee;case \"textInput\":return a=b.data,a===ee&&fe?null:a;default:return null}}\nfunction ke(a,b){if(ie)return\"compositionend\"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case \"paste\":return null;case \"keypress\":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1<b.char.length)return b.char;if(b.which)return String.fromCharCode(b.which)}return null;case \"compositionend\":return de&&\"ko\"!==b.locale?null:b.data;default:return null}}\nvar le={color:!0,date:!0,datetime:!0,\"datetime-local\":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function me(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return\"input\"===b?!!le[a.type]:\"textarea\"===b?!0:!1}function ne(a,b,c,d){Eb(d);b=oe(b,\"onChange\");0<b.length&&(c=new td(\"onChange\",\"change\",null,c,d),a.push({event:c,listeners:b}))}var pe=null,qe=null;function re(a){se(a,0)}function te(a){var b=ue(a);if(Wa(b))return a}\nfunction ve(a,b){if(\"change\"===a)return b}var we=!1;if(ia){var xe;if(ia){var ye=\"oninput\"in document;if(!ye){var ze=document.createElement(\"div\");ze.setAttribute(\"oninput\",\"return;\");ye=\"function\"===typeof ze.oninput}xe=ye}else xe=!1;we=xe&&(!document.documentMode||9<document.documentMode)}function Ae(){pe&&(pe.detachEvent(\"onpropertychange\",Be),qe=pe=null)}function Be(a){if(\"value\"===a.propertyName&&te(qe)){var b=[];ne(b,qe,a,xb(a));Jb(re,b)}}\nfunction Ce(a,b,c){\"focusin\"===a?(Ae(),pe=b,qe=c,pe.attachEvent(\"onpropertychange\",Be)):\"focusout\"===a&&Ae()}function De(a){if(\"selectionchange\"===a||\"keyup\"===a||\"keydown\"===a)return te(qe)}function Ee(a,b){if(\"click\"===a)return te(b)}function Fe(a,b){if(\"input\"===a||\"change\"===a)return te(b)}function Ge(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var He=\"function\"===typeof Object.is?Object.is:Ge;\nfunction Ie(a,b){if(He(a,b))return!0;if(\"object\"!==typeof a||null===a||\"object\"!==typeof b||null===b)return!1;var c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return!1;for(d=0;d<c.length;d++){var e=c[d];if(!ja.call(b,e)||!He(a[e],b[e]))return!1}return!0}function Je(a){for(;a&&a.firstChild;)a=a.firstChild;return a}\nfunction Ke(a,b){var c=Je(a);a=0;for(var d;c;){if(3===c.nodeType){d=a+c.textContent.length;if(a<=b&&d>=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c=\"string\"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&(\"input\"===b&&(\"text\"===a.type||\"search\"===a.type||\"tel\"===a.type||\"url\"===a.type||\"password\"===a.type)||\"textarea\"===b||\"true\"===a.contentEditable)}\nfunction Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),\"selectionStart\"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,\nd);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});\"function\"===typeof c.focus&&c.focus();for(c=0;c<b.length;c++)a=b[c],a.element.scrollLeft=a.left,a.element.scrollTop=a.top}}\nvar Pe=ia&&\"documentMode\"in document&&11>=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;\nfunction Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,\"selectionStart\"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0<d.length&&(b=new td(\"onSelect\",\"select\",null,b,c),a.push({event:b,listeners:d}),b.target=Qe)))}\nfunction Ve(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c[\"Webkit\"+a]=\"webkit\"+b;c[\"Moz\"+a]=\"moz\"+b;return c}var We={animationend:Ve(\"Animation\",\"AnimationEnd\"),animationiteration:Ve(\"Animation\",\"AnimationIteration\"),animationstart:Ve(\"Animation\",\"AnimationStart\"),transitionend:Ve(\"Transition\",\"TransitionEnd\")},Xe={},Ye={};\nia&&(Ye=document.createElement(\"div\").style,\"AnimationEvent\"in window||(delete We.animationend.animation,delete We.animationiteration.animation,delete We.animationstart.animation),\"TransitionEvent\"in window||delete We.transitionend.transition);function Ze(a){if(Xe[a])return Xe[a];if(!We[a])return a;var b=We[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in Ye)return Xe[a]=b[c];return a}var $e=Ze(\"animationend\"),af=Ze(\"animationiteration\"),bf=Ze(\"animationstart\"),cf=Ze(\"transitionend\"),df=new Map,ef=\"abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel\".split(\" \");\nfunction ff(a,b){df.set(a,b);fa(b,[a])}for(var gf=0;gf<ef.length;gf++){var hf=ef[gf],jf=hf.toLowerCase(),kf=hf[0].toUpperCase()+hf.slice(1);ff(jf,\"on\"+kf)}ff($e,\"onAnimationEnd\");ff(af,\"onAnimationIteration\");ff(bf,\"onAnimationStart\");ff(\"dblclick\",\"onDoubleClick\");ff(\"focusin\",\"onFocus\");ff(\"focusout\",\"onBlur\");ff(cf,\"onTransitionEnd\");ha(\"onMouseEnter\",[\"mouseout\",\"mouseover\"]);ha(\"onMouseLeave\",[\"mouseout\",\"mouseover\"]);ha(\"onPointerEnter\",[\"pointerout\",\"pointerover\"]);\nha(\"onPointerLeave\",[\"pointerout\",\"pointerover\"]);fa(\"onChange\",\"change click focusin focusout input keydown keyup selectionchange\".split(\" \"));fa(\"onSelect\",\"focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange\".split(\" \"));fa(\"onBeforeInput\",[\"compositionend\",\"keypress\",\"textInput\",\"paste\"]);fa(\"onCompositionEnd\",\"compositionend focusout keydown keypress keyup mousedown\".split(\" \"));fa(\"onCompositionStart\",\"compositionstart focusout keydown keypress keyup mousedown\".split(\" \"));\nfa(\"onCompositionUpdate\",\"compositionupdate focusout keydown keypress keyup mousedown\".split(\" \"));var lf=\"abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting\".split(\" \"),mf=new Set(\"cancel close invalid load scroll toggle\".split(\" \").concat(lf));\nfunction nf(a,b,c){var d=a.type||\"unknown-event\";a.currentTarget=c;Ub(d,b,void 0,a);a.currentTarget=null}\nfunction se(a,b){b=0!==(b&4);for(var c=0;c<a.length;c++){var d=a[c],e=d.event;d=d.listeners;a:{var f=void 0;if(b)for(var g=d.length-1;0<=g;g--){var h=d[g],k=h.instance,l=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;nf(e,h,l);f=k}else for(g=0;g<d.length;g++){h=d[g];k=h.instance;l=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;nf(e,h,l);f=k}}}if(Qb)throw a=Rb,Qb=!1,Rb=null,a;}\nfunction D(a,b){var c=b[of];void 0===c&&(c=b[of]=new Set);var d=a+\"__bubble\";c.has(d)||(pf(b,a,2,!1),c.add(d))}function qf(a,b,c){var d=0;b&&(d|=4);pf(c,a,d,b)}var rf=\"_reactListening\"+Math.random().toString(36).slice(2);function sf(a){if(!a[rf]){a[rf]=!0;da.forEach(function(b){\"selectionchange\"!==b&&(mf.has(b)||qf(b,!1,a),qf(b,!0,a))});var b=9===a.nodeType?a:a.ownerDocument;null===b||b[rf]||(b[rf]=!0,qf(\"selectionchange\",!1,b))}}\nfunction pf(a,b,c,d){switch(jd(b)){case 1:var e=ed;break;case 4:e=gd;break;default:e=fd}c=e.bind(null,b,c,a);e=void 0;!Lb||\"touchstart\"!==b&&\"touchmove\"!==b&&\"wheel\"!==b||(e=!0);d?void 0!==e?a.addEventListener(b,c,{capture:!0,passive:e}):a.addEventListener(b,c,!0):void 0!==e?a.addEventListener(b,c,{passive:e}):a.addEventListener(b,c,!1)}\nfunction hd(a,b,c,d,e){var f=d;if(0===(b&1)&&0===(b&2)&&null!==d)a:for(;;){if(null===d)return;var g=d.tag;if(3===g||4===g){var h=d.stateNode.containerInfo;if(h===e||8===h.nodeType&&h.parentNode===e)break;if(4===g)for(g=d.return;null!==g;){var k=g.tag;if(3===k||4===k)if(k=g.stateNode.containerInfo,k===e||8===k.nodeType&&k.parentNode===e)return;g=g.return}for(;null!==h;){g=Wc(h);if(null===g)return;k=g.tag;if(5===k||6===k){d=f=g;continue a}h=h.parentNode}}d=d.return}Jb(function(){var d=f,e=xb(c),g=[];\na:{var h=df.get(a);if(void 0!==h){var k=td,n=a;switch(a){case \"keypress\":if(0===od(c))break a;case \"keydown\":case \"keyup\":k=Rd;break;case \"focusin\":n=\"focus\";k=Fd;break;case \"focusout\":n=\"blur\";k=Fd;break;case \"beforeblur\":case \"afterblur\":k=Fd;break;case \"click\":if(2===c.button)break a;case \"auxclick\":case \"dblclick\":case \"mousedown\":case \"mousemove\":case \"mouseup\":case \"mouseout\":case \"mouseover\":case \"contextmenu\":k=Bd;break;case \"drag\":case \"dragend\":case \"dragenter\":case \"dragexit\":case \"dragleave\":case \"dragover\":case \"dragstart\":case \"drop\":k=\nDd;break;case \"touchcancel\":case \"touchend\":case \"touchmove\":case \"touchstart\":k=Vd;break;case $e:case af:case bf:k=Hd;break;case cf:k=Xd;break;case \"scroll\":k=vd;break;case \"wheel\":k=Zd;break;case \"copy\":case \"cut\":case \"paste\":k=Jd;break;case \"gotpointercapture\":case \"lostpointercapture\":case \"pointercancel\":case \"pointerdown\":case \"pointermove\":case \"pointerout\":case \"pointerover\":case \"pointerup\":k=Td}var t=0!==(b&4),J=!t&&\"scroll\"===a,x=t?null!==h?h+\"Capture\":null:h;t=[];for(var w=d,u;null!==\nw;){u=w;var F=u.stateNode;5===u.tag&&null!==F&&(u=F,null!==x&&(F=Kb(w,x),null!=F&&t.push(tf(w,F,u))));if(J)break;w=w.return}0<t.length&&(h=new k(h,n,null,c,e),g.push({event:h,listeners:t}))}}if(0===(b&7)){a:{h=\"mouseover\"===a||\"pointerover\"===a;k=\"mouseout\"===a||\"pointerout\"===a;if(h&&c!==wb&&(n=c.relatedTarget||c.fromElement)&&(Wc(n)||n[uf]))break a;if(k||h){h=e.window===e?e:(h=e.ownerDocument)?h.defaultView||h.parentWindow:window;if(k){if(n=c.relatedTarget||c.toElement,k=d,n=n?Wc(n):null,null!==\nn&&(J=Vb(n),n!==J||5!==n.tag&&6!==n.tag))n=null}else k=null,n=d;if(k!==n){t=Bd;F=\"onMouseLeave\";x=\"onMouseEnter\";w=\"mouse\";if(\"pointerout\"===a||\"pointerover\"===a)t=Td,F=\"onPointerLeave\",x=\"onPointerEnter\",w=\"pointer\";J=null==k?h:ue(k);u=null==n?h:ue(n);h=new t(F,w+\"leave\",k,c,e);h.target=J;h.relatedTarget=u;F=null;Wc(e)===d&&(t=new t(x,w+\"enter\",n,c,e),t.target=u,t.relatedTarget=J,F=t);J=F;if(k&&n)b:{t=k;x=n;w=0;for(u=t;u;u=vf(u))w++;u=0;for(F=x;F;F=vf(F))u++;for(;0<w-u;)t=vf(t),w--;for(;0<u-w;)x=\nvf(x),u--;for(;w--;){if(t===x||null!==x&&t===x.alternate)break b;t=vf(t);x=vf(x)}t=null}else t=null;null!==k&&wf(g,h,k,t,!1);null!==n&&null!==J&&wf(g,J,n,t,!0)}}}a:{h=d?ue(d):window;k=h.nodeName&&h.nodeName.toLowerCase();if(\"select\"===k||\"input\"===k&&\"file\"===h.type)var na=ve;else if(me(h))if(we)na=Fe;else{na=De;var xa=Ce}else(k=h.nodeName)&&\"input\"===k.toLowerCase()&&(\"checkbox\"===h.type||\"radio\"===h.type)&&(na=Ee);if(na&&(na=na(a,d))){ne(g,na,c,e);break a}xa&&xa(a,h,d);\"focusout\"===a&&(xa=h._wrapperState)&&\nxa.controlled&&\"number\"===h.type&&cb(h,\"number\",h.value)}xa=d?ue(d):window;switch(a){case \"focusin\":if(me(xa)||\"true\"===xa.contentEditable)Qe=xa,Re=d,Se=null;break;case \"focusout\":Se=Re=Qe=null;break;case \"mousedown\":Te=!0;break;case \"contextmenu\":case \"mouseup\":case \"dragend\":Te=!1;Ue(g,c,e);break;case \"selectionchange\":if(Pe)break;case \"keydown\":case \"keyup\":Ue(g,c,e)}var $a;if(ae)b:{switch(a){case \"compositionstart\":var ba=\"onCompositionStart\";break b;case \"compositionend\":ba=\"onCompositionEnd\";\nbreak b;case \"compositionupdate\":ba=\"onCompositionUpdate\";break b}ba=void 0}else ie?ge(a,c)&&(ba=\"onCompositionEnd\"):\"keydown\"===a&&229===c.keyCode&&(ba=\"onCompositionStart\");ba&&(de&&\"ko\"!==c.locale&&(ie||\"onCompositionStart\"!==ba?\"onCompositionEnd\"===ba&&ie&&($a=nd()):(kd=e,ld=\"value\"in kd?kd.value:kd.textContent,ie=!0)),xa=oe(d,ba),0<xa.length&&(ba=new Ld(ba,a,null,c,e),g.push({event:ba,listeners:xa}),$a?ba.data=$a:($a=he(c),null!==$a&&(ba.data=$a))));if($a=ce?je(a,c):ke(a,c))d=oe(d,\"onBeforeInput\"),\n0<d.length&&(e=new Ld(\"onBeforeInput\",\"beforeinput\",null,c,e),g.push({event:e,listeners:d}),e.data=$a)}se(g,b)})}function tf(a,b,c){return{instance:a,listener:b,currentTarget:c}}function oe(a,b){for(var c=b+\"Capture\",d=[];null!==a;){var e=a,f=e.stateNode;5===e.tag&&null!==f&&(e=f,f=Kb(a,c),null!=f&&d.unshift(tf(a,f,e)),f=Kb(a,b),null!=f&&d.push(tf(a,f,e)));a=a.return}return d}function vf(a){if(null===a)return null;do a=a.return;while(a&&5!==a.tag);return a?a:null}\nfunction wf(a,b,c,d,e){for(var f=b._reactName,g=[];null!==c&&c!==d;){var h=c,k=h.alternate,l=h.stateNode;if(null!==k&&k===d)break;5===h.tag&&null!==l&&(h=l,e?(k=Kb(c,f),null!=k&&g.unshift(tf(c,k,h))):e||(k=Kb(c,f),null!=k&&g.push(tf(c,k,h))));c=c.return}0!==g.length&&a.push({event:b,listeners:g})}var xf=/\\r\\n?/g,yf=/\\u0000|\\uFFFD/g;function zf(a){return(\"string\"===typeof a?a:\"\"+a).replace(xf,\"\\n\").replace(yf,\"\")}function Af(a,b,c){b=zf(b);if(zf(a)!==b&&c)throw Error(p(425));}function Bf(){}\nvar Cf=null,Df=null;function Ef(a,b){return\"textarea\"===a||\"noscript\"===a||\"string\"===typeof b.children||\"number\"===typeof b.children||\"object\"===typeof b.dangerouslySetInnerHTML&&null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html}\nvar Ff=\"function\"===typeof setTimeout?setTimeout:void 0,Gf=\"function\"===typeof clearTimeout?clearTimeout:void 0,Hf=\"function\"===typeof Promise?Promise:void 0,Jf=\"function\"===typeof queueMicrotask?queueMicrotask:\"undefined\"!==typeof Hf?function(a){return Hf.resolve(null).then(a).catch(If)}:Ff;function If(a){setTimeout(function(){throw a;})}\nfunction Kf(a,b){var c=b,d=0;do{var e=c.nextSibling;a.removeChild(c);if(e&&8===e.nodeType)if(c=e.data,\"/$\"===c){if(0===d){a.removeChild(e);bd(b);return}d--}else\"$\"!==c&&\"$?\"!==c&&\"$!\"!==c||d++;c=e}while(c);bd(b)}function Lf(a){for(;null!=a;a=a.nextSibling){var b=a.nodeType;if(1===b||3===b)break;if(8===b){b=a.data;if(\"$\"===b||\"$!\"===b||\"$?\"===b)break;if(\"/$\"===b)return null}}return a}\nfunction Mf(a){a=a.previousSibling;for(var b=0;a;){if(8===a.nodeType){var c=a.data;if(\"$\"===c||\"$!\"===c||\"$?\"===c){if(0===b)return a;b--}else\"/$\"===c&&b++}a=a.previousSibling}return null}var Nf=Math.random().toString(36).slice(2),Of=\"__reactFiber$\"+Nf,Pf=\"__reactProps$\"+Nf,uf=\"__reactContainer$\"+Nf,of=\"__reactEvents$\"+Nf,Qf=\"__reactListeners$\"+Nf,Rf=\"__reactHandles$\"+Nf;\nfunction Wc(a){var b=a[Of];if(b)return b;for(var c=a.parentNode;c;){if(b=c[uf]||c[Of]){c=b.alternate;if(null!==b.child||null!==c&&null!==c.child)for(a=Mf(a);null!==a;){if(c=a[Of])return c;a=Mf(a)}return b}a=c;c=a.parentNode}return null}function Cb(a){a=a[Of]||a[uf];return!a||5!==a.tag&&6!==a.tag&&13!==a.tag&&3!==a.tag?null:a}function ue(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(p(33));}function Db(a){return a[Pf]||null}var Sf=[],Tf=-1;function Uf(a){return{current:a}}\nfunction E(a){0>Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}\nfunction Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||\"Unknown\",e));return A({},c,d)}\nfunction cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}\nfunction jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a<c.length;a++){var d=c[a];do d=d(!0);while(null!==d)}eg=null;fg=!1}catch(e){throw null!==eg&&(eg=eg.slice(a+1)),ac(fc,jg),e;}finally{C=b,gg=!1}}return null}var kg=[],lg=0,mg=null,ng=0,og=[],pg=0,qg=null,rg=1,sg=\"\";function tg(a,b){kg[lg++]=ng;kg[lg++]=mg;mg=a;ng=b}\nfunction ug(a,b,c){og[pg++]=rg;og[pg++]=sg;og[pg++]=qg;qg=a;var d=rg;a=sg;var e=32-oc(d)-1;d&=~(1<<e);c+=1;var f=32-oc(b)+e;if(30<f){var g=e-e%5;f=(d&(1<<g)-1).toString(32);d>>=g;e-=g;rg=1<<32-oc(b)+e|c<<e|d;sg=f+a}else rg=1<<f|c<<e|d,sg=a}function vg(a){null!==a.return&&(tg(a,1),ug(a,1,0))}function wg(a){for(;a===mg;)mg=kg[--lg],kg[lg]=null,ng=kg[--lg],kg[lg]=null;for(;a===qg;)qg=og[--pg],og[pg]=null,sg=og[--pg],og[pg]=null,rg=og[--pg],og[pg]=null}var xg=null,yg=null,I=!1,zg=null;\nfunction Ag(a,b){var c=Bg(5,null,null,0);c.elementType=\"DELETED\";c.stateNode=b;c.return=a;b=a.deletions;null===b?(a.deletions=[c],a.flags|=16):b.push(c)}\nfunction Cg(a,b){switch(a.tag){case 5:var c=a.type;b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b;return null!==b?(a.stateNode=b,xg=a,yg=Lf(b.firstChild),!0):!1;case 6:return b=\"\"===a.pendingProps||3!==b.nodeType?null:b,null!==b?(a.stateNode=b,xg=a,yg=null,!0):!1;case 13:return b=8!==b.nodeType?null:b,null!==b?(c=null!==qg?{id:rg,overflow:sg}:null,a.memoizedState={dehydrated:b,treeContext:c,retryLane:1073741824},c=Bg(18,null,null,0),c.stateNode=b,c.return=a,a.child=c,xg=a,yg=\nnull,!0):!1;default:return!1}}function Dg(a){return 0!==(a.mode&1)&&0===(a.flags&128)}function Eg(a){if(I){var b=yg;if(b){var c=b;if(!Cg(a,b)){if(Dg(a))throw Error(p(418));b=Lf(c.nextSibling);var d=xg;b&&Cg(a,b)?Ag(d,c):(a.flags=a.flags&-4097|2,I=!1,xg=a)}}else{if(Dg(a))throw Error(p(418));a.flags=a.flags&-4097|2;I=!1;xg=a}}}function Fg(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&13!==a.tag;)a=a.return;xg=a}\nfunction Gg(a){if(a!==xg)return!1;if(!I)return Fg(a),I=!0,!1;var b;(b=3!==a.tag)&&!(b=5!==a.tag)&&(b=a.type,b=\"head\"!==b&&\"body\"!==b&&!Ef(a.type,a.memoizedProps));if(b&&(b=yg)){if(Dg(a))throw Hg(),Error(p(418));for(;b;)Ag(a,b),b=Lf(b.nextSibling)}Fg(a);if(13===a.tag){a=a.memoizedState;a=null!==a?a.dehydrated:null;if(!a)throw Error(p(317));a:{a=a.nextSibling;for(b=0;a;){if(8===a.nodeType){var c=a.data;if(\"/$\"===c){if(0===b){yg=Lf(a.nextSibling);break a}b--}else\"$\"!==c&&\"$!\"!==c&&\"$?\"!==c||b++}a=a.nextSibling}yg=\nnull}}else yg=xg?Lf(a.stateNode.nextSibling):null;return!0}function Hg(){for(var a=yg;a;)a=Lf(a.nextSibling)}function Ig(){yg=xg=null;I=!1}function Jg(a){null===zg?zg=[a]:zg.push(a)}var Kg=ua.ReactCurrentBatchConfig;function Lg(a,b){if(a&&a.defaultProps){b=A({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c]);return b}return b}var Mg=Uf(null),Ng=null,Og=null,Pg=null;function Qg(){Pg=Og=Ng=null}function Rg(a){var b=Mg.current;E(Mg);a._currentValue=b}\nfunction Sg(a,b,c){for(;null!==a;){var d=a.alternate;(a.childLanes&b)!==b?(a.childLanes|=b,null!==d&&(d.childLanes|=b)):null!==d&&(d.childLanes&b)!==b&&(d.childLanes|=b);if(a===c)break;a=a.return}}function Tg(a,b){Ng=a;Pg=Og=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(0!==(a.lanes&b)&&(Ug=!0),a.firstContext=null)}\nfunction Vg(a){var b=a._currentValue;if(Pg!==a)if(a={context:a,memoizedValue:b,next:null},null===Og){if(null===Ng)throw Error(p(308));Og=a;Ng.dependencies={lanes:0,firstContext:a}}else Og=Og.next=a;return b}var Wg=null;function Xg(a){null===Wg?Wg=[a]:Wg.push(a)}function Yg(a,b,c,d){var e=b.interleaved;null===e?(c.next=c,Xg(b)):(c.next=e.next,e.next=c);b.interleaved=c;return Zg(a,d)}\nfunction Zg(a,b){a.lanes|=b;var c=a.alternate;null!==c&&(c.lanes|=b);c=a;for(a=a.return;null!==a;)a.childLanes|=b,c=a.alternate,null!==c&&(c.childLanes|=b),c=a,a=a.return;return 3===c.tag?c.stateNode:null}var $g=!1;function ah(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}\nfunction bh(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function ch(a,b){return{eventTime:a,lane:b,tag:0,payload:null,callback:null,next:null}}\nfunction dh(a,b,c){var d=a.updateQueue;if(null===d)return null;d=d.shared;if(0!==(K&2)){var e=d.pending;null===e?b.next=b:(b.next=e.next,e.next=b);d.pending=b;return Zg(a,c)}e=d.interleaved;null===e?(b.next=b,Xg(d)):(b.next=e.next,e.next=b);d.interleaved=b;return Zg(a,c)}function eh(a,b,c){b=b.updateQueue;if(null!==b&&(b=b.shared,0!==(c&4194240))){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nfunction fh(a,b){var c=a.updateQueue,d=a.alternate;if(null!==d&&(d=d.updateQueue,c===d)){var e=null,f=null;c=c.firstBaseUpdate;if(null!==c){do{var g={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};null===f?e=f=g:f=f.next=g;c=c.next}while(null!==c);null===f?e=f=b:f=f.next=b}else e=f=b;c={baseState:d.baseState,firstBaseUpdate:e,lastBaseUpdate:f,shared:d.shared,effects:d.effects};a.updateQueue=c;return}a=c.lastBaseUpdate;null===a?c.firstBaseUpdate=b:a.next=\nb;c.lastBaseUpdate=b}\nfunction gh(a,b,c,d){var e=a.updateQueue;$g=!1;var f=e.firstBaseUpdate,g=e.lastBaseUpdate,h=e.shared.pending;if(null!==h){e.shared.pending=null;var k=h,l=k.next;k.next=null;null===g?f=l:g.next=l;g=k;var m=a.alternate;null!==m&&(m=m.updateQueue,h=m.lastBaseUpdate,h!==g&&(null===h?m.firstBaseUpdate=l:h.next=l,m.lastBaseUpdate=k))}if(null!==f){var q=e.baseState;g=0;m=l=k=null;h=f;do{var r=h.lane,y=h.eventTime;if((d&r)===r){null!==m&&(m=m.next={eventTime:y,lane:0,tag:h.tag,payload:h.payload,callback:h.callback,\nnext:null});a:{var n=a,t=h;r=b;y=c;switch(t.tag){case 1:n=t.payload;if(\"function\"===typeof n){q=n.call(y,q,r);break a}q=n;break a;case 3:n.flags=n.flags&-65537|128;case 0:n=t.payload;r=\"function\"===typeof n?n.call(y,q,r):n;if(null===r||void 0===r)break a;q=A({},q,r);break a;case 2:$g=!0}}null!==h.callback&&0!==h.lane&&(a.flags|=64,r=e.effects,null===r?e.effects=[h]:r.push(h))}else y={eventTime:y,lane:r,tag:h.tag,payload:h.payload,callback:h.callback,next:null},null===m?(l=m=y,k=q):m=m.next=y,g|=r;\nh=h.next;if(null===h)if(h=e.shared.pending,null===h)break;else r=h,h=r.next,r.next=null,e.lastBaseUpdate=r,e.shared.pending=null}while(1);null===m&&(k=q);e.baseState=k;e.firstBaseUpdate=l;e.lastBaseUpdate=m;b=e.shared.interleaved;if(null!==b){e=b;do g|=e.lane,e=e.next;while(e!==b)}else null===f&&(e.shared.lanes=0);hh|=g;a.lanes=g;a.memoizedState=q}}\nfunction ih(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;b<a.length;b++){var d=a[b],e=d.callback;if(null!==e){d.callback=null;d=c;if(\"function\"!==typeof e)throw Error(p(191,e));e.call(d)}}}var jh=(new aa.Component).refs;function kh(a,b,c,d){b=a.memoizedState;c=c(d,b);c=null===c||void 0===c?b:A({},b,c);a.memoizedState=c;0===a.lanes&&(a.updateQueue.baseState=c)}\nvar nh={isMounted:function(a){return(a=a._reactInternals)?Vb(a)===a:!1},enqueueSetState:function(a,b,c){a=a._reactInternals;var d=L(),e=lh(a),f=ch(d,e);f.payload=b;void 0!==c&&null!==c&&(f.callback=c);b=dh(a,f,e);null!==b&&(mh(b,a,e,d),eh(b,a,e))},enqueueReplaceState:function(a,b,c){a=a._reactInternals;var d=L(),e=lh(a),f=ch(d,e);f.tag=1;f.payload=b;void 0!==c&&null!==c&&(f.callback=c);b=dh(a,f,e);null!==b&&(mh(b,a,e,d),eh(b,a,e))},enqueueForceUpdate:function(a,b){a=a._reactInternals;var c=L(),d=\nlh(a),e=ch(c,d);e.tag=2;void 0!==b&&null!==b&&(e.callback=b);b=dh(a,e,d);null!==b&&(mh(b,a,d,c),eh(b,a,d))}};function oh(a,b,c,d,e,f,g){a=a.stateNode;return\"function\"===typeof a.shouldComponentUpdate?a.shouldComponentUpdate(d,f,g):b.prototype&&b.prototype.isPureReactComponent?!Ie(c,d)||!Ie(e,f):!0}\nfunction ph(a,b,c){var d=!1,e=Vf;var f=b.contextType;\"object\"===typeof f&&null!==f?f=Vg(f):(e=Zf(b)?Xf:H.current,d=b.contextTypes,f=(d=null!==d&&void 0!==d)?Yf(a,e):Vf);b=new b(c,f);a.memoizedState=null!==b.state&&void 0!==b.state?b.state:null;b.updater=nh;a.stateNode=b;b._reactInternals=a;d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=e,a.__reactInternalMemoizedMaskedChildContext=f);return b}\nfunction qh(a,b,c,d){a=b.state;\"function\"===typeof b.componentWillReceiveProps&&b.componentWillReceiveProps(c,d);\"function\"===typeof b.UNSAFE_componentWillReceiveProps&&b.UNSAFE_componentWillReceiveProps(c,d);b.state!==a&&nh.enqueueReplaceState(b,b.state,null)}\nfunction rh(a,b,c,d){var e=a.stateNode;e.props=c;e.state=a.memoizedState;e.refs=jh;ah(a);var f=b.contextType;\"object\"===typeof f&&null!==f?e.context=Vg(f):(f=Zf(b)?Xf:H.current,e.context=Yf(a,f));e.state=a.memoizedState;f=b.getDerivedStateFromProps;\"function\"===typeof f&&(kh(a,b,f,c),e.state=a.memoizedState);\"function\"===typeof b.getDerivedStateFromProps||\"function\"===typeof e.getSnapshotBeforeUpdate||\"function\"!==typeof e.UNSAFE_componentWillMount&&\"function\"!==typeof e.componentWillMount||(b=e.state,\n\"function\"===typeof e.componentWillMount&&e.componentWillMount(),\"function\"===typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),b!==e.state&&nh.enqueueReplaceState(e,e.state,null),gh(a,c,e,d),e.state=a.memoizedState);\"function\"===typeof e.componentDidMount&&(a.flags|=4194308)}\nfunction sh(a,b,c){a=c.ref;if(null!==a&&\"function\"!==typeof a&&\"object\"!==typeof a){if(c._owner){c=c._owner;if(c){if(1!==c.tag)throw Error(p(309));var d=c.stateNode}if(!d)throw Error(p(147,a));var e=d,f=\"\"+a;if(null!==b&&null!==b.ref&&\"function\"===typeof b.ref&&b.ref._stringRef===f)return b.ref;b=function(a){var b=e.refs;b===jh&&(b=e.refs={});null===a?delete b[f]:b[f]=a};b._stringRef=f;return b}if(\"string\"!==typeof a)throw Error(p(284));if(!c._owner)throw Error(p(290,a));}return a}\nfunction th(a,b){a=Object.prototype.toString.call(b);throw Error(p(31,\"[object Object]\"===a?\"object with keys {\"+Object.keys(b).join(\", \")+\"}\":a));}function uh(a){var b=a._init;return b(a._payload)}\nfunction vh(a){function b(b,c){if(a){var d=b.deletions;null===d?(b.deletions=[c],b.flags|=16):d.push(c)}}function c(c,d){if(!a)return null;for(;null!==d;)b(c,d),d=d.sibling;return null}function d(a,b){for(a=new Map;null!==b;)null!==b.key?a.set(b.key,b):a.set(b.index,b),b=b.sibling;return a}function e(a,b){a=wh(a,b);a.index=0;a.sibling=null;return a}function f(b,c,d){b.index=d;if(!a)return b.flags|=1048576,c;d=b.alternate;if(null!==d)return d=d.index,d<c?(b.flags|=2,c):d;b.flags|=2;return c}function g(b){a&&\nnull===b.alternate&&(b.flags|=2);return b}function h(a,b,c,d){if(null===b||6!==b.tag)return b=xh(c,a.mode,d),b.return=a,b;b=e(b,c);b.return=a;return b}function k(a,b,c,d){var f=c.type;if(f===ya)return m(a,b,c.props.children,d,c.key);if(null!==b&&(b.elementType===f||\"object\"===typeof f&&null!==f&&f.$$typeof===Ha&&uh(f)===b.type))return d=e(b,c.props),d.ref=sh(a,b,c),d.return=a,d;d=yh(c.type,c.key,c.props,null,a.mode,d);d.ref=sh(a,b,c);d.return=a;return d}function l(a,b,c,d){if(null===b||4!==b.tag||\nb.stateNode.containerInfo!==c.containerInfo||b.stateNode.implementation!==c.implementation)return b=zh(c,a.mode,d),b.return=a,b;b=e(b,c.children||[]);b.return=a;return b}function m(a,b,c,d,f){if(null===b||7!==b.tag)return b=Ah(c,a.mode,d,f),b.return=a,b;b=e(b,c);b.return=a;return b}function q(a,b,c){if(\"string\"===typeof b&&\"\"!==b||\"number\"===typeof b)return b=xh(\"\"+b,a.mode,c),b.return=a,b;if(\"object\"===typeof b&&null!==b){switch(b.$$typeof){case va:return c=yh(b.type,b.key,b.props,null,a.mode,c),\nc.ref=sh(a,null,b),c.return=a,c;case wa:return b=zh(b,a.mode,c),b.return=a,b;case Ha:var d=b._init;return q(a,d(b._payload),c)}if(eb(b)||Ka(b))return b=Ah(b,a.mode,c,null),b.return=a,b;th(a,b)}return null}function r(a,b,c,d){var e=null!==b?b.key:null;if(\"string\"===typeof c&&\"\"!==c||\"number\"===typeof c)return null!==e?null:h(a,b,\"\"+c,d);if(\"object\"===typeof c&&null!==c){switch(c.$$typeof){case va:return c.key===e?k(a,b,c,d):null;case wa:return c.key===e?l(a,b,c,d):null;case Ha:return e=c._init,r(a,\nb,e(c._payload),d)}if(eb(c)||Ka(c))return null!==e?null:m(a,b,c,d,null);th(a,c)}return null}function y(a,b,c,d,e){if(\"string\"===typeof d&&\"\"!==d||\"number\"===typeof d)return a=a.get(c)||null,h(b,a,\"\"+d,e);if(\"object\"===typeof d&&null!==d){switch(d.$$typeof){case va:return a=a.get(null===d.key?c:d.key)||null,k(b,a,d,e);case wa:return a=a.get(null===d.key?c:d.key)||null,l(b,a,d,e);case Ha:var f=d._init;return y(a,b,c,f(d._payload),e)}if(eb(d)||Ka(d))return a=a.get(c)||null,m(b,a,d,e,null);th(b,d)}return null}\nfunction n(e,g,h,k){for(var l=null,m=null,u=g,w=g=0,x=null;null!==u&&w<h.length;w++){u.index>w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;w<h.length;w++)u=q(e,h[w],k),null!==u&&(g=f(u,g,w),null===m?l=u:m.sibling=u,m=u);I&&tg(e,w);return l}for(u=d(e,u);w<h.length;w++)x=y(u,e,w,h[w],k),null!==x&&(a&&null!==x.alternate&&u.delete(null===\nx.key?w:x.key),g=f(x,g,w),null===m?l=x:m.sibling=x,m=x);a&&u.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function t(e,g,h,k){var l=Ka(h);if(\"function\"!==typeof l)throw Error(p(150));h=l.call(h);if(null==h)throw Error(p(151));for(var u=l=null,m=g,w=g=0,x=null,n=h.next();null!==m&&!n.done;w++,n=h.next()){m.index>w?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,\nm),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){\"object\"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if(\"object\"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=\nf.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||\"object\"===typeof k&&null!==k&&k.$$typeof===Ha&&uh(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=sh(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Ah(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=yh(f.type,f.key,f.props,null,a.mode,h),h.ref=sh(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!==\nd;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=zh(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);th(a,f)}return\"string\"===typeof f&&\"\"!==f||\"number\"===typeof f?(f=\"\"+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):\n(c(a,d),d=xh(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Bh=vh(!0),Ch=vh(!1),Dh={},Eh=Uf(Dh),Fh=Uf(Dh),Gh=Uf(Dh);function Hh(a){if(a===Dh)throw Error(p(174));return a}function Ih(a,b){G(Gh,b);G(Fh,a);G(Eh,Dh);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:lb(null,\"\");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=lb(b,a)}E(Eh);G(Eh,b)}function Jh(){E(Eh);E(Fh);E(Gh)}\nfunction Kh(a){Hh(Gh.current);var b=Hh(Eh.current);var c=lb(b,a.type);b!==c&&(G(Fh,a),G(Eh,c))}function Lh(a){Fh.current===a&&(E(Eh),E(Fh))}var M=Uf(0);\nfunction Mh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||\"$?\"===c.data||\"$!\"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}var Nh=[];\nfunction Oh(){for(var a=0;a<Nh.length;a++)Nh[a]._workInProgressVersionPrimary=null;Nh.length=0}var Ph=ua.ReactCurrentDispatcher,Qh=ua.ReactCurrentBatchConfig,Rh=0,N=null,O=null,P=null,Sh=!1,Th=!1,Uh=0,Vh=0;function Q(){throw Error(p(321));}function Wh(a,b){if(null===b)return!1;for(var c=0;c<b.length&&c<a.length;c++)if(!He(a[c],b[c]))return!1;return!0}\nfunction Xh(a,b,c,d,e,f){Rh=f;N=b;b.memoizedState=null;b.updateQueue=null;b.lanes=0;Ph.current=null===a||null===a.memoizedState?Yh:Zh;a=c(d,e);if(Th){f=0;do{Th=!1;Uh=0;if(25<=f)throw Error(p(301));f+=1;P=O=null;b.updateQueue=null;Ph.current=$h;a=c(d,e)}while(Th)}Ph.current=ai;b=null!==O&&null!==O.next;Rh=0;P=O=N=null;Sh=!1;if(b)throw Error(p(300));return a}function bi(){var a=0!==Uh;Uh=0;return a}\nfunction ci(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};null===P?N.memoizedState=P=a:P=P.next=a;return P}function di(){if(null===O){var a=N.alternate;a=null!==a?a.memoizedState:null}else a=O.next;var b=null===P?N.memoizedState:P.next;if(null!==b)P=b,O=a;else{if(null===a)throw Error(p(310));O=a;a={memoizedState:O.memoizedState,baseState:O.baseState,baseQueue:O.baseQueue,queue:O.queue,next:null};null===P?N.memoizedState=P=a:P=P.next=a}return P}\nfunction ei(a,b){return\"function\"===typeof b?b(a):b}\nfunction fi(a){var b=di(),c=b.queue;if(null===c)throw Error(p(311));c.lastRenderedReducer=a;var d=O,e=d.baseQueue,f=c.pending;if(null!==f){if(null!==e){var g=e.next;e.next=f.next;f.next=g}d.baseQueue=e=f;c.pending=null}if(null!==e){f=e.next;d=d.baseState;var h=g=null,k=null,l=f;do{var m=l.lane;if((Rh&m)===m)null!==k&&(k=k.next={lane:0,action:l.action,hasEagerState:l.hasEagerState,eagerState:l.eagerState,next:null}),d=l.hasEagerState?l.eagerState:a(d,l.action);else{var q={lane:m,action:l.action,hasEagerState:l.hasEagerState,\neagerState:l.eagerState,next:null};null===k?(h=k=q,g=d):k=k.next=q;N.lanes|=m;hh|=m}l=l.next}while(null!==l&&l!==f);null===k?g=d:k.next=h;He(d,b.memoizedState)||(Ug=!0);b.memoizedState=d;b.baseState=g;b.baseQueue=k;c.lastRenderedState=d}a=c.interleaved;if(null!==a){e=a;do f=e.lane,N.lanes|=f,hh|=f,e=e.next;while(e!==a)}else null===e&&(c.lanes=0);return[b.memoizedState,c.dispatch]}\nfunction gi(a){var b=di(),c=b.queue;if(null===c)throw Error(p(311));c.lastRenderedReducer=a;var d=c.dispatch,e=c.pending,f=b.memoizedState;if(null!==e){c.pending=null;var g=e=e.next;do f=a(f,g.action),g=g.next;while(g!==e);He(f,b.memoizedState)||(Ug=!0);b.memoizedState=f;null===b.baseQueue&&(b.baseState=f);c.lastRenderedState=f}return[f,d]}function hi(){}\nfunction ii(a,b){var c=N,d=di(),e=b(),f=!He(d.memoizedState,e);f&&(d.memoizedState=e,Ug=!0);d=d.queue;ji(ki.bind(null,c,d,a),[a]);if(d.getSnapshot!==b||f||null!==P&&P.memoizedState.tag&1){c.flags|=2048;li(9,mi.bind(null,c,d,e,b),void 0,null);if(null===R)throw Error(p(349));0!==(Rh&30)||ni(c,b,e)}return e}function ni(a,b,c){a.flags|=16384;a={getSnapshot:b,value:c};b=N.updateQueue;null===b?(b={lastEffect:null,stores:null},N.updateQueue=b,b.stores=[a]):(c=b.stores,null===c?b.stores=[a]:c.push(a))}\nfunction mi(a,b,c,d){b.value=c;b.getSnapshot=d;oi(b)&&pi(a)}function ki(a,b,c){return c(function(){oi(b)&&pi(a)})}function oi(a){var b=a.getSnapshot;a=a.value;try{var c=b();return!He(a,c)}catch(d){return!0}}function pi(a){var b=Zg(a,1);null!==b&&mh(b,a,1,-1)}\nfunction qi(a){var b=ci();\"function\"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:ei,lastRenderedState:a};b.queue=a;a=a.dispatch=ri.bind(null,N,a);return[b.memoizedState,a]}\nfunction li(a,b,c,d){a={tag:a,create:b,destroy:c,deps:d,next:null};b=N.updateQueue;null===b?(b={lastEffect:null,stores:null},N.updateQueue=b,b.lastEffect=a.next=a):(c=b.lastEffect,null===c?b.lastEffect=a.next=a:(d=c.next,c.next=a,a.next=d,b.lastEffect=a));return a}function si(){return di().memoizedState}function ti(a,b,c,d){var e=ci();N.flags|=a;e.memoizedState=li(1|b,c,void 0,void 0===d?null:d)}\nfunction ui(a,b,c,d){var e=di();d=void 0===d?null:d;var f=void 0;if(null!==O){var g=O.memoizedState;f=g.destroy;if(null!==d&&Wh(d,g.deps)){e.memoizedState=li(b,c,f,d);return}}N.flags|=a;e.memoizedState=li(1|b,c,f,d)}function vi(a,b){return ti(8390656,8,a,b)}function ji(a,b){return ui(2048,8,a,b)}function wi(a,b){return ui(4,2,a,b)}function xi(a,b){return ui(4,4,a,b)}\nfunction yi(a,b){if(\"function\"===typeof b)return a=a(),b(a),function(){b(null)};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null}}function zi(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ui(4,4,yi.bind(null,b,a),c)}function Ai(){}function Bi(a,b){var c=di();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Wh(b,d[1]))return d[0];c.memoizedState=[a,b];return a}\nfunction Ci(a,b){var c=di();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Wh(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a}function Di(a,b,c){if(0===(Rh&21))return a.baseState&&(a.baseState=!1,Ug=!0),a.memoizedState=c;He(c,b)||(c=yc(),N.lanes|=c,hh|=c,a.baseState=!0);return b}function Ei(a,b){var c=C;C=0!==c&&4>c?c:4;a(!0);var d=Qh.transition;Qh.transition={};try{a(!1),b()}finally{C=c,Qh.transition=d}}function Fi(){return di().memoizedState}\nfunction Gi(a,b,c){var d=lh(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,c);else if(c=Yg(a,b,c,d),null!==c){var e=L();mh(c,a,d,e);Ji(c,b,d)}}\nfunction ri(a,b,c){var d=lh(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,Xg(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=Yg(a,b,e,d);null!==c&&(e=L(),mh(c,a,d,e),Ji(c,b,d))}}\nfunction Hi(a){var b=a.alternate;return a===N||null!==b&&b===N}function Ii(a,b){Th=Sh=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Ji(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nvar ai={readContext:Vg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useInsertionEffect:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useDeferredValue:Q,useTransition:Q,useMutableSource:Q,useSyncExternalStore:Q,useId:Q,unstable_isNewReconciler:!1},Yh={readContext:Vg,useCallback:function(a,b){ci().memoizedState=[a,void 0===b?null:b];return a},useContext:Vg,useEffect:vi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ti(4194308,\n4,yi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ti(4194308,4,a,b)},useInsertionEffect:function(a,b){return ti(4,2,a,b)},useMemo:function(a,b){var c=ci();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=ci();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=Gi.bind(null,N,a);return[d.memoizedState,a]},useRef:function(a){var b=\nci();a={current:a};return b.memoizedState=a},useState:qi,useDebugValue:Ai,useDeferredValue:function(a){return ci().memoizedState=a},useTransition:function(){var a=qi(!1),b=a[0];a=Ei.bind(null,a[1]);ci().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=N,e=ci();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===R)throw Error(p(349));0!==(Rh&30)||ni(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;vi(ki.bind(null,d,\nf,a),[a]);d.flags|=2048;li(9,mi.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=ci(),b=R.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=\":\"+b+\"R\"+c;c=Uh++;0<c&&(b+=\"H\"+c.toString(32));b+=\":\"}else c=Vh++,b=\":\"+b+\"r\"+c.toString(32)+\":\";return a.memoizedState=b},unstable_isNewReconciler:!1},Zh={readContext:Vg,useCallback:Bi,useContext:Vg,useEffect:ji,useImperativeHandle:zi,useInsertionEffect:wi,useLayoutEffect:xi,useMemo:Ci,useReducer:fi,useRef:si,useState:function(){return fi(ei)},\nuseDebugValue:Ai,useDeferredValue:function(a){var b=di();return Di(b,O.memoizedState,a)},useTransition:function(){var a=fi(ei)[0],b=di().memoizedState;return[a,b]},useMutableSource:hi,useSyncExternalStore:ii,useId:Fi,unstable_isNewReconciler:!1},$h={readContext:Vg,useCallback:Bi,useContext:Vg,useEffect:ji,useImperativeHandle:zi,useInsertionEffect:wi,useLayoutEffect:xi,useMemo:Ci,useReducer:gi,useRef:si,useState:function(){return gi(ei)},useDebugValue:Ai,useDeferredValue:function(a){var b=di();return null===\nO?b.memoizedState=a:Di(b,O.memoizedState,a)},useTransition:function(){var a=gi(ei)[0],b=di().memoizedState;return[a,b]},useMutableSource:hi,useSyncExternalStore:ii,useId:Fi,unstable_isNewReconciler:!1};function Ki(a,b){try{var c=\"\",d=b;do c+=Pa(d),d=d.return;while(d);var e=c}catch(f){e=\"\\nError generating stack: \"+f.message+\"\\n\"+f.stack}return{value:a,source:b,stack:e,digest:null}}function Li(a,b,c){return{value:a,source:null,stack:null!=c?c:null,digest:null!=b?b:null}}\nfunction Mi(a,b){try{console.error(b.value)}catch(c){setTimeout(function(){throw c;})}}var Ni=\"function\"===typeof WeakMap?WeakMap:Map;function Oi(a,b,c){c=ch(-1,c);c.tag=3;c.payload={element:null};var d=b.value;c.callback=function(){Pi||(Pi=!0,Qi=d);Mi(a,b)};return c}\nfunction Ri(a,b,c){c=ch(-1,c);c.tag=3;var d=a.type.getDerivedStateFromError;if(\"function\"===typeof d){var e=b.value;c.payload=function(){return d(e)};c.callback=function(){Mi(a,b)}}var f=a.stateNode;null!==f&&\"function\"===typeof f.componentDidCatch&&(c.callback=function(){Mi(a,b);\"function\"!==typeof d&&(null===Si?Si=new Set([this]):Si.add(this));var c=b.stack;this.componentDidCatch(b.value,{componentStack:null!==c?c:\"\"})});return c}\nfunction Ti(a,b,c){var d=a.pingCache;if(null===d){d=a.pingCache=new Ni;var e=new Set;d.set(b,e)}else e=d.get(b),void 0===e&&(e=new Set,d.set(b,e));e.has(c)||(e.add(c),a=Ui.bind(null,a,b,c),b.then(a,a))}function Vi(a){do{var b;if(b=13===a.tag)b=a.memoizedState,b=null!==b?null!==b.dehydrated?!0:!1:!0;if(b)return a;a=a.return}while(null!==a);return null}\nfunction Wi(a,b,c,d,e){if(0===(a.mode&1))return a===b?a.flags|=65536:(a.flags|=128,c.flags|=131072,c.flags&=-52805,1===c.tag&&(null===c.alternate?c.tag=17:(b=ch(-1,1),b.tag=2,dh(c,b,1))),c.lanes|=1),a;a.flags|=65536;a.lanes=e;return a}var Xi=ua.ReactCurrentOwner,Ug=!1;function Yi(a,b,c,d){b.child=null===a?Ch(b,null,c,d):Bh(b,a.child,c,d)}\nfunction Zi(a,b,c,d,e){c=c.render;var f=b.ref;Tg(b,e);d=Xh(a,b,c,d,f,e);c=bi();if(null!==a&&!Ug)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,$i(a,b,e);I&&c&&vg(b);b.flags|=1;Yi(a,b,d,e);return b.child}\nfunction aj(a,b,c,d,e){if(null===a){var f=c.type;if(\"function\"===typeof f&&!bj(f)&&void 0===f.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=f,cj(a,b,f,d,e);a=yh(c.type,null,d,b,b.mode,e);a.ref=b.ref;a.return=b;return b.child=a}f=a.child;if(0===(a.lanes&e)){var g=f.memoizedProps;c=c.compare;c=null!==c?c:Ie;if(c(g,d)&&a.ref===b.ref)return $i(a,b,e)}b.flags|=1;a=wh(f,d);a.ref=b.ref;a.return=b;return b.child=a}\nfunction cj(a,b,c,d,e){if(null!==a){var f=a.memoizedProps;if(Ie(f,d)&&a.ref===b.ref)if(Ug=!1,b.pendingProps=d=f,0!==(a.lanes&e))0!==(a.flags&131072)&&(Ug=!0);else return b.lanes=a.lanes,$i(a,b,e)}return dj(a,b,c,d,e)}\nfunction ej(a,b,c){var d=b.pendingProps,e=d.children,f=null!==a?a.memoizedState:null;if(\"hidden\"===d.mode)if(0===(b.mode&1))b.memoizedState={baseLanes:0,cachePool:null,transitions:null},G(fj,gj),gj|=c;else{if(0===(c&1073741824))return a=null!==f?f.baseLanes|c:c,b.lanes=b.childLanes=1073741824,b.memoizedState={baseLanes:a,cachePool:null,transitions:null},b.updateQueue=null,G(fj,gj),gj|=a,null;b.memoizedState={baseLanes:0,cachePool:null,transitions:null};d=null!==f?f.baseLanes:c;G(fj,gj);gj|=d}else null!==\nf?(d=f.baseLanes|c,b.memoizedState=null):d=c,G(fj,gj),gj|=d;Yi(a,b,e,c);return b.child}function hj(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.flags|=512,b.flags|=2097152}function dj(a,b,c,d,e){var f=Zf(c)?Xf:H.current;f=Yf(b,f);Tg(b,e);c=Xh(a,b,c,d,f,e);d=bi();if(null!==a&&!Ug)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,$i(a,b,e);I&&d&&vg(b);b.flags|=1;Yi(a,b,c,e);return b.child}\nfunction ij(a,b,c,d,e){if(Zf(c)){var f=!0;cg(b)}else f=!1;Tg(b,e);if(null===b.stateNode)jj(a,b),ph(b,c,d),rh(b,c,d,e),d=!0;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var k=g.context,l=c.contextType;\"object\"===typeof l&&null!==l?l=Vg(l):(l=Zf(c)?Xf:H.current,l=Yf(b,l));var m=c.getDerivedStateFromProps,q=\"function\"===typeof m||\"function\"===typeof g.getSnapshotBeforeUpdate;q||\"function\"!==typeof g.UNSAFE_componentWillReceiveProps&&\"function\"!==typeof g.componentWillReceiveProps||\n(h!==d||k!==l)&&qh(b,g,d,l);$g=!1;var r=b.memoizedState;g.state=r;gh(b,d,g,e);k=b.memoizedState;h!==d||r!==k||Wf.current||$g?(\"function\"===typeof m&&(kh(b,c,m,d),k=b.memoizedState),(h=$g||oh(b,c,h,d,r,k,l))?(q||\"function\"!==typeof g.UNSAFE_componentWillMount&&\"function\"!==typeof g.componentWillMount||(\"function\"===typeof g.componentWillMount&&g.componentWillMount(),\"function\"===typeof g.UNSAFE_componentWillMount&&g.UNSAFE_componentWillMount()),\"function\"===typeof g.componentDidMount&&(b.flags|=4194308)):\n(\"function\"===typeof g.componentDidMount&&(b.flags|=4194308),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=l,d=h):(\"function\"===typeof g.componentDidMount&&(b.flags|=4194308),d=!1)}else{g=b.stateNode;bh(a,b);h=b.memoizedProps;l=b.type===b.elementType?h:Lg(b.type,h);g.props=l;q=b.pendingProps;r=g.context;k=c.contextType;\"object\"===typeof k&&null!==k?k=Vg(k):(k=Zf(c)?Xf:H.current,k=Yf(b,k));var y=c.getDerivedStateFromProps;(m=\"function\"===typeof y||\"function\"===typeof g.getSnapshotBeforeUpdate)||\n\"function\"!==typeof g.UNSAFE_componentWillReceiveProps&&\"function\"!==typeof g.componentWillReceiveProps||(h!==q||r!==k)&&qh(b,g,d,k);$g=!1;r=b.memoizedState;g.state=r;gh(b,d,g,e);var n=b.memoizedState;h!==q||r!==n||Wf.current||$g?(\"function\"===typeof y&&(kh(b,c,y,d),n=b.memoizedState),(l=$g||oh(b,c,l,d,r,n,k)||!1)?(m||\"function\"!==typeof g.UNSAFE_componentWillUpdate&&\"function\"!==typeof g.componentWillUpdate||(\"function\"===typeof g.componentWillUpdate&&g.componentWillUpdate(d,n,k),\"function\"===typeof g.UNSAFE_componentWillUpdate&&\ng.UNSAFE_componentWillUpdate(d,n,k)),\"function\"===typeof g.componentDidUpdate&&(b.flags|=4),\"function\"===typeof g.getSnapshotBeforeUpdate&&(b.flags|=1024)):(\"function\"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=4),\"function\"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),b.memoizedProps=d,b.memoizedState=n),g.props=d,g.state=n,g.context=k,d=l):(\"function\"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===\na.memoizedState||(b.flags|=4),\"function\"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),d=!1)}return kj(a,b,c,d,f,e)}\nfunction kj(a,b,c,d,e,f){hj(a,b);var g=0!==(b.flags&128);if(!d&&!g)return e&&dg(b,c,!1),$i(a,b,f);d=b.stateNode;Xi.current=b;var h=g&&\"function\"!==typeof c.getDerivedStateFromError?null:d.render();b.flags|=1;null!==a&&g?(b.child=Bh(b,a.child,null,f),b.child=Bh(b,null,h,f)):Yi(a,b,h,f);b.memoizedState=d.state;e&&dg(b,c,!0);return b.child}function lj(a){var b=a.stateNode;b.pendingContext?ag(a,b.pendingContext,b.pendingContext!==b.context):b.context&&ag(a,b.context,!1);Ih(a,b.containerInfo)}\nfunction mj(a,b,c,d,e){Ig();Jg(e);b.flags|=256;Yi(a,b,c,d);return b.child}var nj={dehydrated:null,treeContext:null,retryLane:0};function oj(a){return{baseLanes:a,cachePool:null,transitions:null}}\nfunction pj(a,b,c){var d=b.pendingProps,e=M.current,f=!1,g=0!==(b.flags&128),h;(h=g)||(h=null!==a&&null===a.memoizedState?!1:0!==(e&2));if(h)f=!0,b.flags&=-129;else if(null===a||null!==a.memoizedState)e|=1;G(M,e&1);if(null===a){Eg(b);a=b.memoizedState;if(null!==a&&(a=a.dehydrated,null!==a))return 0===(b.mode&1)?b.lanes=1:\"$!\"===a.data?b.lanes=8:b.lanes=1073741824,null;g=d.children;a=d.fallback;return f?(d=b.mode,f=b.child,g={mode:\"hidden\",children:g},0===(d&1)&&null!==f?(f.childLanes=0,f.pendingProps=\ng):f=qj(g,d,0,null),a=Ah(a,d,c,null),f.return=b,a.return=b,f.sibling=a,b.child=f,b.child.memoizedState=oj(c),b.memoizedState=nj,a):rj(b,g)}e=a.memoizedState;if(null!==e&&(h=e.dehydrated,null!==h))return sj(a,b,g,d,h,e,c);if(f){f=d.fallback;g=b.mode;e=a.child;h=e.sibling;var k={mode:\"hidden\",children:d.children};0===(g&1)&&b.child!==e?(d=b.child,d.childLanes=0,d.pendingProps=k,b.deletions=null):(d=wh(e,k),d.subtreeFlags=e.subtreeFlags&14680064);null!==h?f=wh(h,f):(f=Ah(f,g,c,null),f.flags|=2);f.return=\nb;d.return=b;d.sibling=f;b.child=d;d=f;f=b.child;g=a.child.memoizedState;g=null===g?oj(c):{baseLanes:g.baseLanes|c,cachePool:null,transitions:g.transitions};f.memoizedState=g;f.childLanes=a.childLanes&~c;b.memoizedState=nj;return d}f=a.child;a=f.sibling;d=wh(f,{mode:\"visible\",children:d.children});0===(b.mode&1)&&(d.lanes=c);d.return=b;d.sibling=null;null!==a&&(c=b.deletions,null===c?(b.deletions=[a],b.flags|=16):c.push(a));b.child=d;b.memoizedState=null;return d}\nfunction rj(a,b){b=qj({mode:\"visible\",children:b},a.mode,0,null);b.return=a;return a.child=b}function tj(a,b,c,d){null!==d&&Jg(d);Bh(b,a.child,null,c);a=rj(b,b.pendingProps.children);a.flags|=2;b.memoizedState=null;return a}\nfunction sj(a,b,c,d,e,f,g){if(c){if(b.flags&256)return b.flags&=-257,d=Li(Error(p(422))),tj(a,b,g,d);if(null!==b.memoizedState)return b.child=a.child,b.flags|=128,null;f=d.fallback;e=b.mode;d=qj({mode:\"visible\",children:d.children},e,0,null);f=Ah(f,e,g,null);f.flags|=2;d.return=b;f.return=b;d.sibling=f;b.child=d;0!==(b.mode&1)&&Bh(b,a.child,null,g);b.child.memoizedState=oj(g);b.memoizedState=nj;return f}if(0===(b.mode&1))return tj(a,b,g,null);if(\"$!\"===e.data){d=e.nextSibling&&e.nextSibling.dataset;\nif(d)var h=d.dgst;d=h;f=Error(p(419));d=Li(f,d,void 0);return tj(a,b,g,d)}h=0!==(g&a.childLanes);if(Ug||h){d=R;if(null!==d){switch(g&-g){case 4:e=2;break;case 16:e=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:e=32;break;case 536870912:e=268435456;break;default:e=0}e=0!==(e&(d.suspendedLanes|g))?0:e;\n0!==e&&e!==f.retryLane&&(f.retryLane=e,Zg(a,e),mh(d,a,e,-1))}uj();d=Li(Error(p(421)));return tj(a,b,g,d)}if(\"$?\"===e.data)return b.flags|=128,b.child=a.child,b=vj.bind(null,a),e._reactRetry=b,null;a=f.treeContext;yg=Lf(e.nextSibling);xg=b;I=!0;zg=null;null!==a&&(og[pg++]=rg,og[pg++]=sg,og[pg++]=qg,rg=a.id,sg=a.overflow,qg=b);b=rj(b,d.children);b.flags|=4096;return b}function wj(a,b,c){a.lanes|=b;var d=a.alternate;null!==d&&(d.lanes|=b);Sg(a.return,b,c)}\nfunction xj(a,b,c,d,e){var f=a.memoizedState;null===f?a.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:d,tail:c,tailMode:e}:(f.isBackwards=b,f.rendering=null,f.renderingStartTime=0,f.last=d,f.tail=c,f.tailMode=e)}\nfunction yj(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;Yi(a,b,d.children,c);d=M.current;if(0!==(d&2))d=d&1|2,b.flags|=128;else{if(null!==a&&0!==(a.flags&128))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&wj(a,c,b);else if(19===a.tag)wj(a,c,b);else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===b)break a;for(;null===a.sibling;){if(null===a.return||a.return===b)break a;a=a.return}a.sibling.return=a.return;a=a.sibling}d&=1}G(M,d);if(0===(b.mode&1))b.memoizedState=\nnull;else switch(e){case \"forwards\":c=b.child;for(e=null;null!==c;)a=c.alternate,null!==a&&null===Mh(a)&&(e=c),c=c.sibling;c=e;null===c?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null);xj(b,!1,e,c,f);break;case \"backwards\":c=null;e=b.child;for(b.child=null;null!==e;){a=e.alternate;if(null!==a&&null===Mh(a)){b.child=e;break}a=e.sibling;e.sibling=c;c=e;e=a}xj(b,!0,c,null,f);break;case \"together\":xj(b,!1,null,null,void 0);break;default:b.memoizedState=null}return b.child}\nfunction jj(a,b){0===(b.mode&1)&&null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2)}function $i(a,b,c){null!==a&&(b.dependencies=a.dependencies);hh|=b.lanes;if(0===(c&b.childLanes))return null;if(null!==a&&b.child!==a.child)throw Error(p(153));if(null!==b.child){a=b.child;c=wh(a,a.pendingProps);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=wh(a,a.pendingProps),c.return=b;c.sibling=null}return b.child}\nfunction zj(a,b,c){switch(b.tag){case 3:lj(b);Ig();break;case 5:Kh(b);break;case 1:Zf(b.type)&&cg(b);break;case 4:Ih(b,b.stateNode.containerInfo);break;case 10:var d=b.type._context,e=b.memoizedProps.value;G(Mg,d._currentValue);d._currentValue=e;break;case 13:d=b.memoizedState;if(null!==d){if(null!==d.dehydrated)return G(M,M.current&1),b.flags|=128,null;if(0!==(c&b.child.childLanes))return pj(a,b,c);G(M,M.current&1);a=$i(a,b,c);return null!==a?a.sibling:null}G(M,M.current&1);break;case 19:d=0!==(c&\nb.childLanes);if(0!==(a.flags&128)){if(d)return yj(a,b,c);b.flags|=128}e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null,e.lastEffect=null);G(M,M.current);if(d)break;else return null;case 22:case 23:return b.lanes=0,ej(a,b,c)}return $i(a,b,c)}var Aj,Bj,Cj,Dj;\nAj=function(a,b){for(var c=b.child;null!==c;){if(5===c.tag||6===c.tag)a.appendChild(c.stateNode);else if(4!==c.tag&&null!==c.child){c.child.return=c;c=c.child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return}c.sibling.return=c.return;c=c.sibling}};Bj=function(){};\nCj=function(a,b,c,d){var e=a.memoizedProps;if(e!==d){a=b.stateNode;Hh(Eh.current);var f=null;switch(c){case \"input\":e=Ya(a,e);d=Ya(a,d);f=[];break;case \"select\":e=A({},e,{value:void 0});d=A({},d,{value:void 0});f=[];break;case \"textarea\":e=gb(a,e);d=gb(a,d);f=[];break;default:\"function\"!==typeof e.onClick&&\"function\"===typeof d.onClick&&(a.onclick=Bf)}ub(c,d);var g;c=null;for(l in e)if(!d.hasOwnProperty(l)&&e.hasOwnProperty(l)&&null!=e[l])if(\"style\"===l){var h=e[l];for(g in h)h.hasOwnProperty(g)&&\n(c||(c={}),c[g]=\"\")}else\"dangerouslySetInnerHTML\"!==l&&\"children\"!==l&&\"suppressContentEditableWarning\"!==l&&\"suppressHydrationWarning\"!==l&&\"autoFocus\"!==l&&(ea.hasOwnProperty(l)?f||(f=[]):(f=f||[]).push(l,null));for(l in d){var k=d[l];h=null!=e?e[l]:void 0;if(d.hasOwnProperty(l)&&k!==h&&(null!=k||null!=h))if(\"style\"===l)if(h){for(g in h)!h.hasOwnProperty(g)||k&&k.hasOwnProperty(g)||(c||(c={}),c[g]=\"\");for(g in k)k.hasOwnProperty(g)&&h[g]!==k[g]&&(c||(c={}),c[g]=k[g])}else c||(f||(f=[]),f.push(l,\nc)),c=k;else\"dangerouslySetInnerHTML\"===l?(k=k?k.__html:void 0,h=h?h.__html:void 0,null!=k&&h!==k&&(f=f||[]).push(l,k)):\"children\"===l?\"string\"!==typeof k&&\"number\"!==typeof k||(f=f||[]).push(l,\"\"+k):\"suppressContentEditableWarning\"!==l&&\"suppressHydrationWarning\"!==l&&(ea.hasOwnProperty(l)?(null!=k&&\"onScroll\"===l&&D(\"scroll\",a),f||h===k||(f=[])):(f=f||[]).push(l,k))}c&&(f=f||[]).push(\"style\",c);var l=f;if(b.updateQueue=l)b.flags|=4}};Dj=function(a,b,c,d){c!==d&&(b.flags|=4)};\nfunction Ej(a,b){if(!I)switch(a.tailMode){case \"hidden\":b=a.tail;for(var c=null;null!==b;)null!==b.alternate&&(c=b),b=b.sibling;null===c?a.tail=null:c.sibling=null;break;case \"collapsed\":c=a.tail;for(var d=null;null!==c;)null!==c.alternate&&(d=c),c=c.sibling;null===d?b||null===a.tail?a.tail=null:a.tail.sibling=null:d.sibling=null}}\nfunction S(a){var b=null!==a.alternate&&a.alternate.child===a.child,c=0,d=0;if(b)for(var e=a.child;null!==e;)c|=e.lanes|e.childLanes,d|=e.subtreeFlags&14680064,d|=e.flags&14680064,e.return=a,e=e.sibling;else for(e=a.child;null!==e;)c|=e.lanes|e.childLanes,d|=e.subtreeFlags,d|=e.flags,e.return=a,e=e.sibling;a.subtreeFlags|=d;a.childLanes=c;return b}\nfunction Fj(a,b,c){var d=b.pendingProps;wg(b);switch(b.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return S(b),null;case 1:return Zf(b.type)&&$f(),S(b),null;case 3:d=b.stateNode;Jh();E(Wf);E(H);Oh();d.pendingContext&&(d.context=d.pendingContext,d.pendingContext=null);if(null===a||null===a.child)Gg(b)?b.flags|=4:null===a||a.memoizedState.isDehydrated&&0===(b.flags&256)||(b.flags|=1024,null!==zg&&(Gj(zg),zg=null));Bj(a,b);S(b);return null;case 5:Lh(b);var e=Hh(Gh.current);\nc=b.type;if(null!==a&&null!=b.stateNode)Cj(a,b,c,d,e),a.ref!==b.ref&&(b.flags|=512,b.flags|=2097152);else{if(!d){if(null===b.stateNode)throw Error(p(166));S(b);return null}a=Hh(Eh.current);if(Gg(b)){d=b.stateNode;c=b.type;var f=b.memoizedProps;d[Of]=b;d[Pf]=f;a=0!==(b.mode&1);switch(c){case \"dialog\":D(\"cancel\",d);D(\"close\",d);break;case \"iframe\":case \"object\":case \"embed\":D(\"load\",d);break;case \"video\":case \"audio\":for(e=0;e<lf.length;e++)D(lf[e],d);break;case \"source\":D(\"error\",d);break;case \"img\":case \"image\":case \"link\":D(\"error\",\nd);D(\"load\",d);break;case \"details\":D(\"toggle\",d);break;case \"input\":Za(d,f);D(\"invalid\",d);break;case \"select\":d._wrapperState={wasMultiple:!!f.multiple};D(\"invalid\",d);break;case \"textarea\":hb(d,f),D(\"invalid\",d)}ub(c,f);e=null;for(var g in f)if(f.hasOwnProperty(g)){var h=f[g];\"children\"===g?\"string\"===typeof h?d.textContent!==h&&(!0!==f.suppressHydrationWarning&&Af(d.textContent,h,a),e=[\"children\",h]):\"number\"===typeof h&&d.textContent!==\"\"+h&&(!0!==f.suppressHydrationWarning&&Af(d.textContent,\nh,a),e=[\"children\",\"\"+h]):ea.hasOwnProperty(g)&&null!=h&&\"onScroll\"===g&&D(\"scroll\",d)}switch(c){case \"input\":Va(d);db(d,f,!0);break;case \"textarea\":Va(d);jb(d);break;case \"select\":case \"option\":break;default:\"function\"===typeof f.onClick&&(d.onclick=Bf)}d=e;b.updateQueue=d;null!==d&&(b.flags|=4)}else{g=9===e.nodeType?e:e.ownerDocument;\"http://www.w3.org/1999/xhtml\"===a&&(a=kb(c));\"http://www.w3.org/1999/xhtml\"===a?\"script\"===c?(a=g.createElement(\"div\"),a.innerHTML=\"<script>\\x3c/script>\",a=a.removeChild(a.firstChild)):\n\"string\"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),\"select\"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;Aj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case \"dialog\":D(\"cancel\",a);D(\"close\",a);e=d;break;case \"iframe\":case \"object\":case \"embed\":D(\"load\",a);e=d;break;case \"video\":case \"audio\":for(e=0;e<lf.length;e++)D(lf[e],a);e=d;break;case \"source\":D(\"error\",a);e=d;break;case \"img\":case \"image\":case \"link\":D(\"error\",\na);D(\"load\",a);e=d;break;case \"details\":D(\"toggle\",a);e=d;break;case \"input\":Za(a,d);e=Ya(a,d);D(\"invalid\",a);break;case \"option\":e=d;break;case \"select\":a._wrapperState={wasMultiple:!!d.multiple};e=A({},d,{value:void 0});D(\"invalid\",a);break;case \"textarea\":hb(a,d);e=gb(a,d);D(\"invalid\",a);break;default:e=d}ub(c,e);h=e;for(f in h)if(h.hasOwnProperty(f)){var k=h[f];\"style\"===f?sb(a,k):\"dangerouslySetInnerHTML\"===f?(k=k?k.__html:void 0,null!=k&&nb(a,k)):\"children\"===f?\"string\"===typeof k?(\"textarea\"!==\nc||\"\"!==k)&&ob(a,k):\"number\"===typeof k&&ob(a,\"\"+k):\"suppressContentEditableWarning\"!==f&&\"suppressHydrationWarning\"!==f&&\"autoFocus\"!==f&&(ea.hasOwnProperty(f)?null!=k&&\"onScroll\"===f&&D(\"scroll\",a):null!=k&&ta(a,f,k,g))}switch(c){case \"input\":Va(a);db(a,d,!1);break;case \"textarea\":Va(a);jb(a);break;case \"option\":null!=d.value&&a.setAttribute(\"value\",\"\"+Sa(d.value));break;case \"select\":a.multiple=!!d.multiple;f=d.value;null!=f?fb(a,!!d.multiple,f,!1):null!=d.defaultValue&&fb(a,!!d.multiple,d.defaultValue,\n!0);break;default:\"function\"===typeof e.onClick&&(a.onclick=Bf)}switch(c){case \"button\":case \"input\":case \"select\":case \"textarea\":d=!!d.autoFocus;break a;case \"img\":d=!0;break a;default:d=!1}}d&&(b.flags|=4)}null!==b.ref&&(b.flags|=512,b.flags|=2097152)}S(b);return null;case 6:if(a&&null!=b.stateNode)Dj(a,b,a.memoizedProps,d);else{if(\"string\"!==typeof d&&null===b.stateNode)throw Error(p(166));c=Hh(Gh.current);Hh(Eh.current);if(Gg(b)){d=b.stateNode;c=b.memoizedProps;d[Of]=b;if(f=d.nodeValue!==c)if(a=\nxg,null!==a)switch(a.tag){case 3:Af(d.nodeValue,c,0!==(a.mode&1));break;case 5:!0!==a.memoizedProps.suppressHydrationWarning&&Af(d.nodeValue,c,0!==(a.mode&1))}f&&(b.flags|=4)}else d=(9===c.nodeType?c:c.ownerDocument).createTextNode(d),d[Of]=b,b.stateNode=d}S(b);return null;case 13:E(M);d=b.memoizedState;if(null===a||null!==a.memoizedState&&null!==a.memoizedState.dehydrated){if(I&&null!==yg&&0!==(b.mode&1)&&0===(b.flags&128))Hg(),Ig(),b.flags|=98560,f=!1;else if(f=Gg(b),null!==d&&null!==d.dehydrated){if(null===\na){if(!f)throw Error(p(318));f=b.memoizedState;f=null!==f?f.dehydrated:null;if(!f)throw Error(p(317));f[Of]=b}else Ig(),0===(b.flags&128)&&(b.memoizedState=null),b.flags|=4;S(b);f=!1}else null!==zg&&(Gj(zg),zg=null),f=!0;if(!f)return b.flags&65536?b:null}if(0!==(b.flags&128))return b.lanes=c,b;d=null!==d;d!==(null!==a&&null!==a.memoizedState)&&d&&(b.child.flags|=8192,0!==(b.mode&1)&&(null===a||0!==(M.current&1)?0===T&&(T=3):uj()));null!==b.updateQueue&&(b.flags|=4);S(b);return null;case 4:return Jh(),\nBj(a,b),null===a&&sf(b.stateNode.containerInfo),S(b),null;case 10:return Rg(b.type._context),S(b),null;case 17:return Zf(b.type)&&$f(),S(b),null;case 19:E(M);f=b.memoizedState;if(null===f)return S(b),null;d=0!==(b.flags&128);g=f.rendering;if(null===g)if(d)Ej(f,!1);else{if(0!==T||null!==a&&0!==(a.flags&128))for(a=b.child;null!==a;){g=Mh(a);if(null!==g){b.flags|=128;Ej(f,!1);d=g.updateQueue;null!==d&&(b.updateQueue=d,b.flags|=4);b.subtreeFlags=0;d=c;for(c=b.child;null!==c;)f=c,a=d,f.flags&=14680066,\ng=f.alternate,null===g?(f.childLanes=0,f.lanes=a,f.child=null,f.subtreeFlags=0,f.memoizedProps=null,f.memoizedState=null,f.updateQueue=null,f.dependencies=null,f.stateNode=null):(f.childLanes=g.childLanes,f.lanes=g.lanes,f.child=g.child,f.subtreeFlags=0,f.deletions=null,f.memoizedProps=g.memoizedProps,f.memoizedState=g.memoizedState,f.updateQueue=g.updateQueue,f.type=g.type,a=g.dependencies,f.dependencies=null===a?null:{lanes:a.lanes,firstContext:a.firstContext}),c=c.sibling;G(M,M.current&1|2);return b.child}a=\na.sibling}null!==f.tail&&B()>Hj&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304)}else{if(!d)if(a=Mh(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Ej(f,!0),null===f.tail&&\"hidden\"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Hj&&1073741824!==c&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=\nb,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=M.current,G(M,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Ij(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(gj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}\nfunction Jj(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return Jh(),E(Wf),E(H),Oh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Lh(b),null;case 13:E(M);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(M),null;case 4:return Jh(),null;case 10:return Rg(b.type._context),null;case 22:case 23:return Ij(),\nnull;case 24:return null;default:return null}}var Kj=!1,U=!1,Lj=\"function\"===typeof WeakSet?WeakSet:Set,V=null;function Mj(a,b){var c=a.ref;if(null!==c)if(\"function\"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Nj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Oj=!1;\nfunction Pj(a,b){Cf=dd;a=Me();if(Ne(a)){if(\"selectionStart\"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=\nq.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;\ncase 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Lg(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent=\"\":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Oj;Oj=!1;return n}\nfunction Qj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Nj(b,c,f)}e=e.next}while(e!==d)}}function Rj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Sj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}\"function\"===typeof b?b(a):b.current=a}}\nfunction Tj(a){var b=a.alternate;null!==b&&(a.alternate=null,Tj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Uj(a){return 5===a.tag||3===a.tag||4===a.tag}\nfunction Vj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Uj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}\nfunction Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling}\nfunction Xj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Xj(a,b,c),a=a.sibling;null!==a;)Xj(a,b,c),a=a.sibling}var X=null,Yj=!1;function Zj(a,b,c){for(c=c.child;null!==c;)ak(a,b,c),c=c.sibling}\nfunction ak(a,b,c){if(lc&&\"function\"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Mj(c,b);case 6:var d=X,e=Yj;X=null;Zj(a,b,c);X=d;Yj=e;null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Yj;X=c.stateNode.containerInfo;Yj=!0;\nZj(a,b,c);X=d;Yj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Nj(c,b,g):0!==(f&4)&&Nj(c,b,g));e=e.next}while(e!==d)}Zj(a,b,c);break;case 1:if(!U&&(Mj(c,b),d=c.stateNode,\"function\"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Zj(a,b,c);break;case 21:Zj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==\nc.memoizedState,Zj(a,b,c),U=d):Zj(a,b,c);break;default:Zj(a,b,c)}}function bk(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Lj);b.forEach(function(b){var d=ck.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}\nfunction dk(a,b){var c=b.deletions;if(null!==c)for(var d=0;d<c.length;d++){var e=c[d];try{var f=a,g=b,h=g;a:for(;null!==h;){switch(h.tag){case 5:X=h.stateNode;Yj=!1;break a;case 3:X=h.stateNode.containerInfo;Yj=!0;break a;case 4:X=h.stateNode.containerInfo;Yj=!0;break a}h=h.return}if(null===X)throw Error(p(160));ak(f,g,e);X=null;Yj=!1;var k=e.alternate;null!==k&&(k.return=null);e.return=null}catch(l){W(e,b,l)}}if(b.subtreeFlags&12854)for(b=b.child;null!==b;)ek(b,a),b=b.sibling}\nfunction ek(a,b){var c=a.alternate,d=a.flags;switch(a.tag){case 0:case 11:case 14:case 15:dk(b,a);fk(a);if(d&4){try{Qj(3,a,a.return),Rj(3,a)}catch(t){W(a,a.return,t)}try{Qj(5,a,a.return)}catch(t){W(a,a.return,t)}}break;case 1:dk(b,a);fk(a);d&512&&null!==c&&Mj(c,c.return);break;case 5:dk(b,a);fk(a);d&512&&null!==c&&Mj(c,c.return);if(a.flags&32){var e=a.stateNode;try{ob(e,\"\")}catch(t){W(a,a.return,t)}}if(d&4&&(e=a.stateNode,null!=e)){var f=a.memoizedProps,g=null!==c?c.memoizedProps:f,h=a.type,k=a.updateQueue;\na.updateQueue=null;if(null!==k)try{\"input\"===h&&\"radio\"===f.type&&null!=f.name&&ab(e,f);vb(h,g);var l=vb(h,f);for(g=0;g<k.length;g+=2){var m=k[g],q=k[g+1];\"style\"===m?sb(e,q):\"dangerouslySetInnerHTML\"===m?nb(e,q):\"children\"===m?ob(e,q):ta(e,m,q,l)}switch(h){case \"input\":bb(e,f);break;case \"textarea\":ib(e,f);break;case \"select\":var r=e._wrapperState.wasMultiple;e._wrapperState.wasMultiple=!!f.multiple;var y=f.value;null!=y?fb(e,!!f.multiple,y,!1):r!==!!f.multiple&&(null!=f.defaultValue?fb(e,!!f.multiple,\nf.defaultValue,!0):fb(e,!!f.multiple,f.multiple?[]:\"\",!1))}e[Pf]=f}catch(t){W(a,a.return,t)}}break;case 6:dk(b,a);fk(a);if(d&4){if(null===a.stateNode)throw Error(p(162));e=a.stateNode;f=a.memoizedProps;try{e.nodeValue=f}catch(t){W(a,a.return,t)}}break;case 3:dk(b,a);fk(a);if(d&4&&null!==c&&c.memoizedState.isDehydrated)try{bd(b.containerInfo)}catch(t){W(a,a.return,t)}break;case 4:dk(b,a);fk(a);break;case 13:dk(b,a);fk(a);e=a.child;e.flags&8192&&(f=null!==e.memoizedState,e.stateNode.isHidden=f,!f||\nnull!==e.alternate&&null!==e.alternate.memoizedState||(gk=B()));d&4&&bk(a);break;case 22:m=null!==c&&null!==c.memoizedState;a.mode&1?(U=(l=U)||m,dk(b,a),U=l):dk(b,a);fk(a);if(d&8192){l=null!==a.memoizedState;if((a.stateNode.isHidden=l)&&!m&&0!==(a.mode&1))for(V=a,m=a.child;null!==m;){for(q=V=m;null!==V;){r=V;y=r.child;switch(r.tag){case 0:case 11:case 14:case 15:Qj(4,r,r.return);break;case 1:Mj(r,r.return);var n=r.stateNode;if(\"function\"===typeof n.componentWillUnmount){d=r;c=r.return;try{b=d,n.props=\nb.memoizedProps,n.state=b.memoizedState,n.componentWillUnmount()}catch(t){W(d,c,t)}}break;case 5:Mj(r,r.return);break;case 22:if(null!==r.memoizedState){hk(q);continue}}null!==y?(y.return=r,V=y):hk(q)}m=m.sibling}a:for(m=null,q=a;;){if(5===q.tag){if(null===m){m=q;try{e=q.stateNode,l?(f=e.style,\"function\"===typeof f.setProperty?f.setProperty(\"display\",\"none\",\"important\"):f.display=\"none\"):(h=q.stateNode,k=q.memoizedProps.style,g=void 0!==k&&null!==k&&k.hasOwnProperty(\"display\")?k.display:null,h.style.display=\nrb(\"display\",g))}catch(t){W(a,a.return,t)}}}else if(6===q.tag){if(null===m)try{q.stateNode.nodeValue=l?\"\":q.memoizedProps}catch(t){W(a,a.return,t)}}else if((22!==q.tag&&23!==q.tag||null===q.memoizedState||q===a)&&null!==q.child){q.child.return=q;q=q.child;continue}if(q===a)break a;for(;null===q.sibling;){if(null===q.return||q.return===a)break a;m===q&&(m=null);q=q.return}m===q&&(m=null);q.sibling.return=q.return;q=q.sibling}}break;case 19:dk(b,a);fk(a);d&4&&bk(a);break;case 21:break;default:dk(b,\na),fk(a)}}function fk(a){var b=a.flags;if(b&2){try{a:{for(var c=a.return;null!==c;){if(Uj(c)){var d=c;break a}c=c.return}throw Error(p(160));}switch(d.tag){case 5:var e=d.stateNode;d.flags&32&&(ob(e,\"\"),d.flags&=-33);var f=Vj(a);Xj(a,f,e);break;case 3:case 4:var g=d.stateNode.containerInfo,h=Vj(a);Wj(a,h,g);break;default:throw Error(p(161));}}catch(k){W(a,a.return,k)}a.flags&=-3}b&4096&&(a.flags&=-4097)}function ik(a,b,c){V=a;jk(a,b,c)}\nfunction jk(a,b,c){for(var d=0!==(a.mode&1);null!==V;){var e=V,f=e.child;if(22===e.tag&&d){var g=null!==e.memoizedState||Kj;if(!g){var h=e.alternate,k=null!==h&&null!==h.memoizedState||U;h=Kj;var l=U;Kj=g;if((U=k)&&!l)for(V=e;null!==V;)g=V,k=g.child,22===g.tag&&null!==g.memoizedState?kk(e):null!==k?(k.return=g,V=k):kk(e);for(;null!==f;)V=f,jk(f,b,c),f=f.sibling;V=e;Kj=h;U=l}lk(a,b,c)}else 0!==(e.subtreeFlags&8772)&&null!==f?(f.return=e,V=f):lk(a,b,c)}}\nfunction lk(a){for(;null!==V;){var b=V;if(0!==(b.flags&8772)){var c=b.alternate;try{if(0!==(b.flags&8772))switch(b.tag){case 0:case 11:case 15:U||Rj(5,b);break;case 1:var d=b.stateNode;if(b.flags&4&&!U)if(null===c)d.componentDidMount();else{var e=b.elementType===b.type?c.memoizedProps:Lg(b.type,c.memoizedProps);d.componentDidUpdate(e,c.memoizedState,d.__reactInternalSnapshotBeforeUpdate)}var f=b.updateQueue;null!==f&&ih(b,f,d);break;case 3:var g=b.updateQueue;if(null!==g){c=null;if(null!==b.child)switch(b.child.tag){case 5:c=\nb.child.stateNode;break;case 1:c=b.child.stateNode}ih(b,g,c)}break;case 5:var h=b.stateNode;if(null===c&&b.flags&4){c=h;var k=b.memoizedProps;switch(b.type){case \"button\":case \"input\":case \"select\":case \"textarea\":k.autoFocus&&c.focus();break;case \"img\":k.src&&(c.src=k.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(null===b.memoizedState){var l=b.alternate;if(null!==l){var m=l.memoizedState;if(null!==m){var q=m.dehydrated;null!==q&&bd(q)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;\ndefault:throw Error(p(163));}U||b.flags&512&&Sj(b)}catch(r){W(b,b.return,r)}}if(b===a){V=null;break}c=b.sibling;if(null!==c){c.return=b.return;V=c;break}V=b.return}}function hk(a){for(;null!==V;){var b=V;if(b===a){V=null;break}var c=b.sibling;if(null!==c){c.return=b.return;V=c;break}V=b.return}}\nfunction kk(a){for(;null!==V;){var b=V;try{switch(b.tag){case 0:case 11:case 15:var c=b.return;try{Rj(4,b)}catch(k){W(b,c,k)}break;case 1:var d=b.stateNode;if(\"function\"===typeof d.componentDidMount){var e=b.return;try{d.componentDidMount()}catch(k){W(b,e,k)}}var f=b.return;try{Sj(b)}catch(k){W(b,f,k)}break;case 5:var g=b.return;try{Sj(b)}catch(k){W(b,g,k)}}}catch(k){W(b,b.return,k)}if(b===a){V=null;break}var h=b.sibling;if(null!==h){h.return=b.return;V=h;break}V=b.return}}\nvar mk=Math.ceil,nk=ua.ReactCurrentDispatcher,ok=ua.ReactCurrentOwner,pk=ua.ReactCurrentBatchConfig,K=0,R=null,Y=null,Z=0,gj=0,fj=Uf(0),T=0,qk=null,hh=0,rk=0,sk=0,tk=null,uk=null,gk=0,Hj=Infinity,vk=null,Pi=!1,Qi=null,Si=null,wk=!1,xk=null,yk=0,zk=0,Ak=null,Bk=-1,Ck=0;function L(){return 0!==(K&6)?B():-1!==Bk?Bk:Bk=B()}\nfunction lh(a){if(0===(a.mode&1))return 1;if(0!==(K&2)&&0!==Z)return Z&-Z;if(null!==Kg.transition)return 0===Ck&&(Ck=yc()),Ck;a=C;if(0!==a)return a;a=window.event;a=void 0===a?16:jd(a.type);return a}function mh(a,b,c,d){if(50<zk)throw zk=0,Ak=null,Error(p(185));Ac(a,c,d);if(0===(K&2)||a!==R)a===R&&(0===(K&2)&&(rk|=c),4===T&&Dk(a,Z)),Ek(a,d),1===c&&0===K&&0===(b.mode&1)&&(Hj=B()+500,fg&&jg())}\nfunction Ek(a,b){var c=a.callbackNode;wc(a,b);var d=uc(a,a===R?Z:0);if(0===d)null!==c&&bc(c),a.callbackNode=null,a.callbackPriority=0;else if(b=d&-d,a.callbackPriority!==b){null!=c&&bc(c);if(1===b)0===a.tag?ig(Fk.bind(null,a)):hg(Fk.bind(null,a)),Jf(function(){0===(K&6)&&jg()}),c=null;else{switch(Dc(d)){case 1:c=fc;break;case 4:c=gc;break;case 16:c=hc;break;case 536870912:c=jc;break;default:c=hc}c=Gk(c,Hk.bind(null,a))}a.callbackPriority=b;a.callbackNode=c}}\nfunction Hk(a,b){Bk=-1;Ck=0;if(0!==(K&6))throw Error(p(327));var c=a.callbackNode;if(Ik()&&a.callbackNode!==c)return null;var d=uc(a,a===R?Z:0);if(0===d)return null;if(0!==(d&30)||0!==(d&a.expiredLanes)||b)b=Jk(a,d);else{b=d;var e=K;K|=2;var f=Kk();if(R!==a||Z!==b)vk=null,Hj=B()+500,Lk(a,b);do try{Mk();break}catch(h){Nk(a,h)}while(1);Qg();nk.current=f;K=e;null!==Y?b=0:(R=null,Z=0,b=T)}if(0!==b){2===b&&(e=xc(a),0!==e&&(d=e,b=Ok(a,e)));if(1===b)throw c=qk,Lk(a,0),Dk(a,d),Ek(a,B()),c;if(6===b)Dk(a,d);\nelse{e=a.current.alternate;if(0===(d&30)&&!Pk(e)&&(b=Jk(a,d),2===b&&(f=xc(a),0!==f&&(d=f,b=Ok(a,f))),1===b))throw c=qk,Lk(a,0),Dk(a,d),Ek(a,B()),c;a.finishedWork=e;a.finishedLanes=d;switch(b){case 0:case 1:throw Error(p(345));case 2:Qk(a,uk,vk);break;case 3:Dk(a,d);if((d&130023424)===d&&(b=gk+500-B(),10<b)){if(0!==uc(a,0))break;e=a.suspendedLanes;if((e&d)!==d){L();a.pingedLanes|=a.suspendedLanes&e;break}a.timeoutHandle=Ff(Qk.bind(null,a,uk,vk),b);break}Qk(a,uk,vk);break;case 4:Dk(a,d);if((d&4194240)===\nd)break;b=a.eventTimes;for(e=-1;0<d;){var g=31-oc(d);f=1<<g;g=b[g];g>e&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*mk(d/1960))-d;if(10<d){a.timeoutHandle=Ff(Qk.bind(null,a,uk,vk),d);break}Qk(a,uk,vk);break;case 5:Qk(a,uk,vk);break;default:throw Error(p(329));}}}Ek(a,B());return a.callbackNode===c?Hk.bind(null,a):null}\nfunction Ok(a,b){var c=tk;a.current.memoizedState.isDehydrated&&(Lk(a,b).flags|=256);a=Jk(a,b);2!==a&&(b=uk,uk=c,null!==b&&Gj(b));return a}function Gj(a){null===uk?uk=a:uk.push.apply(uk,a)}\nfunction Pk(a){for(var b=a;;){if(b.flags&16384){var c=b.updateQueue;if(null!==c&&(c=c.stores,null!==c))for(var d=0;d<c.length;d++){var e=c[d],f=e.getSnapshot;e=e.value;try{if(!He(f(),e))return!1}catch(g){return!1}}}c=b.child;if(b.subtreeFlags&16384&&null!==c)c.return=b,b=c;else{if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return!0;b=b.return}b.sibling.return=b.return;b=b.sibling}}return!0}\nfunction Dk(a,b){b&=~sk;b&=~rk;a.suspendedLanes|=b;a.pingedLanes&=~b;for(a=a.expirationTimes;0<b;){var c=31-oc(b),d=1<<c;a[c]=-1;b&=~d}}function Fk(a){if(0!==(K&6))throw Error(p(327));Ik();var b=uc(a,0);if(0===(b&1))return Ek(a,B()),null;var c=Jk(a,b);if(0!==a.tag&&2===c){var d=xc(a);0!==d&&(b=d,c=Ok(a,d))}if(1===c)throw c=qk,Lk(a,0),Dk(a,b),Ek(a,B()),c;if(6===c)throw Error(p(345));a.finishedWork=a.current.alternate;a.finishedLanes=b;Qk(a,uk,vk);Ek(a,B());return null}\nfunction Rk(a,b){var c=K;K|=1;try{return a(b)}finally{K=c,0===K&&(Hj=B()+500,fg&&jg())}}function Sk(a){null!==xk&&0===xk.tag&&0===(K&6)&&Ik();var b=K;K|=1;var c=pk.transition,d=C;try{if(pk.transition=null,C=1,a)return a()}finally{C=d,pk.transition=c,K=b,0===(K&6)&&jg()}}function Ij(){gj=fj.current;E(fj)}\nfunction Lk(a,b){a.finishedWork=null;a.finishedLanes=0;var c=a.timeoutHandle;-1!==c&&(a.timeoutHandle=-1,Gf(c));if(null!==Y)for(c=Y.return;null!==c;){var d=c;wg(d);switch(d.tag){case 1:d=d.type.childContextTypes;null!==d&&void 0!==d&&$f();break;case 3:Jh();E(Wf);E(H);Oh();break;case 5:Lh(d);break;case 4:Jh();break;case 13:E(M);break;case 19:E(M);break;case 10:Rg(d.type._context);break;case 22:case 23:Ij()}c=c.return}R=a;Y=a=wh(a.current,null);Z=gj=b;T=0;qk=null;sk=rk=hh=0;uk=tk=null;if(null!==Wg){for(b=\n0;b<Wg.length;b++)if(c=Wg[b],d=c.interleaved,null!==d){c.interleaved=null;var e=d.next,f=c.pending;if(null!==f){var g=f.next;f.next=e;d.next=g}c.pending=d}Wg=null}return a}\nfunction Nk(a,b){do{var c=Y;try{Qg();Ph.current=ai;if(Sh){for(var d=N.memoizedState;null!==d;){var e=d.queue;null!==e&&(e.pending=null);d=d.next}Sh=!1}Rh=0;P=O=N=null;Th=!1;Uh=0;ok.current=null;if(null===c||null===c.return){T=1;qk=b;Y=null;break}a:{var f=a,g=c.return,h=c,k=b;b=Z;h.flags|=32768;if(null!==k&&\"object\"===typeof k&&\"function\"===typeof k.then){var l=k,m=h,q=m.tag;if(0===(m.mode&1)&&(0===q||11===q||15===q)){var r=m.alternate;r?(m.updateQueue=r.updateQueue,m.memoizedState=r.memoizedState,\nm.lanes=r.lanes):(m.updateQueue=null,m.memoizedState=null)}var y=Vi(g);if(null!==y){y.flags&=-257;Wi(y,g,h,f,b);y.mode&1&&Ti(f,l,b);b=y;k=l;var n=b.updateQueue;if(null===n){var t=new Set;t.add(k);b.updateQueue=t}else n.add(k);break a}else{if(0===(b&1)){Ti(f,l,b);uj();break a}k=Error(p(426))}}else if(I&&h.mode&1){var J=Vi(g);if(null!==J){0===(J.flags&65536)&&(J.flags|=256);Wi(J,g,h,f,b);Jg(Ki(k,h));break a}}f=k=Ki(k,h);4!==T&&(T=2);null===tk?tk=[f]:tk.push(f);f=g;do{switch(f.tag){case 3:f.flags|=65536;\nb&=-b;f.lanes|=b;var x=Oi(f,k,b);fh(f,x);break a;case 1:h=k;var w=f.type,u=f.stateNode;if(0===(f.flags&128)&&(\"function\"===typeof w.getDerivedStateFromError||null!==u&&\"function\"===typeof u.componentDidCatch&&(null===Si||!Si.has(u)))){f.flags|=65536;b&=-b;f.lanes|=b;var F=Ri(f,h,b);fh(f,F);break a}}f=f.return}while(null!==f)}Tk(c)}catch(na){b=na;Y===c&&null!==c&&(Y=c=c.return);continue}break}while(1)}function Kk(){var a=nk.current;nk.current=ai;return null===a?ai:a}\nfunction uj(){if(0===T||3===T||2===T)T=4;null===R||0===(hh&268435455)&&0===(rk&268435455)||Dk(R,Z)}function Jk(a,b){var c=K;K|=2;var d=Kk();if(R!==a||Z!==b)vk=null,Lk(a,b);do try{Uk();break}catch(e){Nk(a,e)}while(1);Qg();K=c;nk.current=d;if(null!==Y)throw Error(p(261));R=null;Z=0;return T}function Uk(){for(;null!==Y;)Vk(Y)}function Mk(){for(;null!==Y&&!cc();)Vk(Y)}function Vk(a){var b=Wk(a.alternate,a,gj);a.memoizedProps=a.pendingProps;null===b?Tk(a):Y=b;ok.current=null}\nfunction Tk(a){var b=a;do{var c=b.alternate;a=b.return;if(0===(b.flags&32768)){if(c=Fj(c,b,gj),null!==c){Y=c;return}}else{c=Jj(c,b);if(null!==c){c.flags&=32767;Y=c;return}if(null!==a)a.flags|=32768,a.subtreeFlags=0,a.deletions=null;else{T=6;Y=null;return}}b=b.sibling;if(null!==b){Y=b;return}Y=b=a}while(null!==b);0===T&&(T=5)}function Qk(a,b,c){var d=C,e=pk.transition;try{pk.transition=null,C=1,Xk(a,b,c,d)}finally{pk.transition=e,C=d}return null}\nfunction Xk(a,b,c,d){do Ik();while(null!==xk);if(0!==(K&6))throw Error(p(327));c=a.finishedWork;var e=a.finishedLanes;if(null===c)return null;a.finishedWork=null;a.finishedLanes=0;if(c===a.current)throw Error(p(177));a.callbackNode=null;a.callbackPriority=0;var f=c.lanes|c.childLanes;Bc(a,f);a===R&&(Y=R=null,Z=0);0===(c.subtreeFlags&2064)&&0===(c.flags&2064)||wk||(wk=!0,Gk(hc,function(){Ik();return null}));f=0!==(c.flags&15990);if(0!==(c.subtreeFlags&15990)||f){f=pk.transition;pk.transition=null;\nvar g=C;C=1;var h=K;K|=4;ok.current=null;Pj(a,c);ek(c,a);Oe(Df);dd=!!Cf;Df=Cf=null;a.current=c;ik(c,a,e);dc();K=h;C=g;pk.transition=f}else a.current=c;wk&&(wk=!1,xk=a,yk=e);f=a.pendingLanes;0===f&&(Si=null);mc(c.stateNode,d);Ek(a,B());if(null!==b)for(d=a.onRecoverableError,c=0;c<b.length;c++)e=b[c],d(e.value,{componentStack:e.stack,digest:e.digest});if(Pi)throw Pi=!1,a=Qi,Qi=null,a;0!==(yk&1)&&0!==a.tag&&Ik();f=a.pendingLanes;0!==(f&1)?a===Ak?zk++:(zk=0,Ak=a):zk=0;jg();return null}\nfunction Ik(){if(null!==xk){var a=Dc(yk),b=pk.transition,c=C;try{pk.transition=null;C=16>a?16:a;if(null===xk)var d=!1;else{a=xk;xk=null;yk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;k<h.length;k++){var l=h[k];for(V=l;null!==V;){var m=V;switch(m.tag){case 0:case 11:case 15:Qj(8,m,f)}var q=m.child;if(null!==q)q.return=m,V=q;else for(;null!==V;){m=V;var r=m.sibling,y=m.return;Tj(m);if(m===\nl){V=null;break}if(null!==r){r.return=y;V=r;break}V=y}}}var n=f.alternate;if(null!==n){var t=n.child;if(null!==t){n.child=null;do{var J=t.sibling;t.sibling=null;t=J}while(null!==t)}}V=f}}if(0!==(f.subtreeFlags&2064)&&null!==g)g.return=f,V=g;else b:for(;null!==V;){f=V;if(0!==(f.flags&2048))switch(f.tag){case 0:case 11:case 15:Qj(9,f,f.return)}var x=f.sibling;if(null!==x){x.return=f.return;V=x;break b}V=f.return}}var w=a.current;for(V=w;null!==V;){g=V;var u=g.child;if(0!==(g.subtreeFlags&2064)&&null!==\nu)u.return=g,V=u;else b:for(g=w;null!==V;){h=V;if(0!==(h.flags&2048))try{switch(h.tag){case 0:case 11:case 15:Rj(9,h)}}catch(na){W(h,h.return,na)}if(h===g){V=null;break b}var F=h.sibling;if(null!==F){F.return=h.return;V=F;break b}V=h.return}}K=e;jg();if(lc&&\"function\"===typeof lc.onPostCommitFiberRoot)try{lc.onPostCommitFiberRoot(kc,a)}catch(na){}d=!0}return d}finally{C=c,pk.transition=b}}return!1}function Yk(a,b,c){b=Ki(c,b);b=Oi(a,b,1);a=dh(a,b,1);b=L();null!==a&&(Ac(a,1,b),Ek(a,b))}\nfunction W(a,b,c){if(3===a.tag)Yk(a,a,c);else for(;null!==b;){if(3===b.tag){Yk(b,a,c);break}else if(1===b.tag){var d=b.stateNode;if(\"function\"===typeof b.type.getDerivedStateFromError||\"function\"===typeof d.componentDidCatch&&(null===Si||!Si.has(d))){a=Ki(c,a);a=Ri(b,a,1);b=dh(b,a,1);a=L();null!==b&&(Ac(b,1,a),Ek(b,a));break}}b=b.return}}\nfunction Ui(a,b,c){var d=a.pingCache;null!==d&&d.delete(b);b=L();a.pingedLanes|=a.suspendedLanes&c;R===a&&(Z&c)===c&&(4===T||3===T&&(Z&130023424)===Z&&500>B()-gk?Lk(a,0):sk|=c);Ek(a,b)}function Zk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=L();a=Zg(a,b);null!==a&&(Ac(a,b,c),Ek(a,c))}function vj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Zk(a,c)}\nfunction ck(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Zk(a,c)}var Wk;\nWk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)Ug=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return Ug=!1,zj(a,b,c);Ug=0!==(a.flags&131072)?!0:!1}else Ug=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;jj(a,b);a=b.pendingProps;var e=Yf(b,H.current);Tg(b,c);e=Xh(null,b,d,a,e,c);var f=bi();b.flags|=1;\"object\"===typeof e&&null!==e&&\"function\"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=\nnull,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,ah(b),e.updater=nh,b.stateNode=e,e._reactInternals=b,rh(b,d,a,c),b=kj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Yi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{jj(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=$k(d);a=Lg(d,a);switch(e){case 0:b=dj(null,b,d,a,c);break a;case 1:b=ij(null,b,d,a,c);break a;case 11:b=Zi(null,b,d,a,c);break a;case 14:b=aj(null,b,d,Lg(d.type,a),c);break a}throw Error(p(306,\nd,\"\"));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),dj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),ij(a,b,d,e,c);case 3:a:{lj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;bh(a,b);gh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=\nf,b.memoizedState=f,b.flags&256){e=Ki(Error(p(423)),b);b=mj(a,b,d,c,e);break a}else if(d!==e){e=Ki(Error(p(424)),b);b=mj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Ch(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=$i(a,b,c);break a}Yi(a,b,d,c)}b=b.child}return b;case 5:return Kh(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),\nhj(a,b),Yi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return pj(a,b,c);case 4:return Ih(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Bh(b,null,d,c):Yi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),Zi(a,b,d,e,c);case 7:return Yi(a,b,b.pendingProps,c),b.child;case 8:return Yi(a,b,b.pendingProps.children,c),b.child;case 12:return Yi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;\ng=e.value;G(Mg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=$i(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=ch(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);Sg(f.return,\nc,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);Sg(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Yi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,Tg(b,c),e=Vg(e),d=d(e),b.flags|=1,Yi(a,b,d,c),\nb.child;case 14:return d=b.type,e=Lg(d,b.pendingProps),e=Lg(d.type,e),aj(a,b,d,e,c);case 15:return cj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),jj(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,Tg(b,c),ph(b,d,e),rh(b,d,e,c),kj(null,b,d,!0,a,c);case 19:return yj(a,b,c);case 22:return ej(a,b,c)}throw Error(p(156,b.tag));};function Gk(a,b){return ac(a,b)}\nfunction al(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new al(a,b,c,d)}function bj(a){a=a.prototype;return!(!a||!a.isReactComponent)}\nfunction $k(a){if(\"function\"===typeof a)return bj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}\nfunction wh(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};\nc.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}\nfunction yh(a,b,c,d,e,f){var g=2;d=a;if(\"function\"===typeof a)bj(a)&&(g=1);else if(\"string\"===typeof a)g=5;else a:switch(a){case ya:return Ah(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return qj(c,e,f,b);default:if(\"object\"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;\nbreak a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,\"\"));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Ah(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function qj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function xh(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}\nfunction zh(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}\nfunction bl(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=\nnull}function cl(a,b,c,d,e,f,g,h,k){a=new bl(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};ah(f);return a}function dl(a,b,c){var d=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:wa,key:null==d?null:\"\"+d,children:a,containerInfo:b,implementation:c}}\nfunction el(a){if(!a)return Vf;a=a._reactInternals;a:{if(Vb(a)!==a||1!==a.tag)throw Error(p(170));var b=a;do{switch(b.tag){case 3:b=b.stateNode.context;break a;case 1:if(Zf(b.type)){b=b.stateNode.__reactInternalMemoizedMergedChildContext;break a}}b=b.return}while(null!==b);throw Error(p(171));}if(1===a.tag){var c=a.type;if(Zf(c))return bg(a,c,b)}return b}\nfunction fl(a,b,c,d,e,f,g,h,k){a=cl(c,d,!0,a,e,f,g,h,k);a.context=el(null);c=a.current;d=L();e=lh(c);f=ch(d,e);f.callback=void 0!==b&&null!==b?b:null;dh(c,f,e);a.current.lanes=e;Ac(a,e,d);Ek(a,d);return a}function gl(a,b,c,d){var e=b.current,f=L(),g=lh(e);c=el(c);null===b.context?b.context=c:b.pendingContext=c;b=ch(f,g);b.payload={element:a};d=void 0===d?null:d;null!==d&&(b.callback=d);a=dh(e,b,g);null!==a&&(mh(a,e,g,f),eh(a,e,g));return g}\nfunction hl(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function il(a,b){a=a.memoizedState;if(null!==a&&null!==a.dehydrated){var c=a.retryLane;a.retryLane=0!==c&&c<b?c:b}}function jl(a,b){il(a,b);(a=a.alternate)&&il(a,b)}function kl(){return null}var ll=\"function\"===typeof reportError?reportError:function(a){console.error(a)};function ml(a){this._internalRoot=a}\nnl.prototype.render=ml.prototype.render=function(a){var b=this._internalRoot;if(null===b)throw Error(p(409));gl(a,b,null,null)};nl.prototype.unmount=ml.prototype.unmount=function(){var a=this._internalRoot;if(null!==a){this._internalRoot=null;var b=a.containerInfo;Sk(function(){gl(null,a,null,null)});b[uf]=null}};function nl(a){this._internalRoot=a}\nnl.prototype.unstable_scheduleHydration=function(a){if(a){var b=Hc();a={blockedOn:null,target:a,priority:b};for(var c=0;c<Qc.length&&0!==b&&b<Qc[c].priority;c++);Qc.splice(c,0,a);0===c&&Vc(a)}};function ol(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType)}function pl(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType&&(8!==a.nodeType||\" react-mount-point-unstable \"!==a.nodeValue))}function ql(){}\nfunction rl(a,b,c,d,e){if(e){if(\"function\"===typeof d){var f=d;d=function(){var a=hl(g);f.call(a)}}var g=fl(b,d,a,0,null,!1,!1,\"\",ql);a._reactRootContainer=g;a[uf]=g.current;sf(8===a.nodeType?a.parentNode:a);Sk();return g}for(;e=a.lastChild;)a.removeChild(e);if(\"function\"===typeof d){var h=d;d=function(){var a=hl(k);h.call(a)}}var k=cl(a,0,!1,null,null,!1,!1,\"\",ql);a._reactRootContainer=k;a[uf]=k.current;sf(8===a.nodeType?a.parentNode:a);Sk(function(){gl(b,k,c,d)});return k}\nfunction sl(a,b,c,d,e){var f=c._reactRootContainer;if(f){var g=f;if(\"function\"===typeof e){var h=e;e=function(){var a=hl(g);h.call(a)}}gl(b,g,a,e)}else g=rl(c,b,a,e,d);return hl(g)}Ec=function(a){switch(a.tag){case 3:var b=a.stateNode;if(b.current.memoizedState.isDehydrated){var c=tc(b.pendingLanes);0!==c&&(Cc(b,c|1),Ek(b,B()),0===(K&6)&&(Hj=B()+500,jg()))}break;case 13:Sk(function(){var b=Zg(a,1);if(null!==b){var c=L();mh(b,a,1,c)}}),jl(a,1)}};\nFc=function(a){if(13===a.tag){var b=Zg(a,134217728);if(null!==b){var c=L();mh(b,a,134217728,c)}jl(a,134217728)}};Gc=function(a){if(13===a.tag){var b=lh(a),c=Zg(a,b);if(null!==c){var d=L();mh(c,a,b,d)}jl(a,b)}};Hc=function(){return C};Ic=function(a,b){var c=C;try{return C=a,b()}finally{C=c}};\nyb=function(a,b,c){switch(b){case \"input\":bb(a,c);b=c.name;if(\"radio\"===c.type&&null!=b){for(c=a;c.parentNode;)c=c.parentNode;c=c.querySelectorAll(\"input[name=\"+JSON.stringify(\"\"+b)+'][type=\"radio\"]');for(b=0;b<c.length;b++){var d=c[b];if(d!==a&&d.form===a.form){var e=Db(d);if(!e)throw Error(p(90));Wa(d);bb(d,e)}}}break;case \"textarea\":ib(a,c);break;case \"select\":b=c.value,null!=b&&fb(a,!!c.multiple,b,!1)}};Gb=Rk;Hb=Sk;\nvar tl={usingClientEntryPoint:!1,Events:[Cb,ue,Db,Eb,Fb,Rk]},ul={findFiberByHostInstance:Wc,bundleType:0,version:\"18.2.0\",rendererPackageName:\"react-dom\"};\nvar vl={bundleType:ul.bundleType,version:ul.version,rendererPackageName:ul.rendererPackageName,rendererConfig:ul.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:ua.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){a=Zb(a);return null===a?null:a.stateNode},findFiberByHostInstance:ul.findFiberByHostInstance||\nkl,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:\"18.2.0-next-9e3b772b8-20220608\"};if(\"undefined\"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__){var wl=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!wl.isDisabled&&wl.supportsFiber)try{kc=wl.inject(vl),lc=wl}catch(a){}}exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=tl;\nexports.createPortal=function(a,b){var c=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!ol(b))throw Error(p(200));return dl(a,b,null,c)};exports.createRoot=function(a,b){if(!ol(a))throw Error(p(299));var c=!1,d=\"\",e=ll;null!==b&&void 0!==b&&(!0===b.unstable_strictMode&&(c=!0),void 0!==b.identifierPrefix&&(d=b.identifierPrefix),void 0!==b.onRecoverableError&&(e=b.onRecoverableError));b=cl(a,1,!1,null,null,c,!1,d,e);a[uf]=b.current;sf(8===a.nodeType?a.parentNode:a);return new ml(b)};\nexports.findDOMNode=function(a){if(null==a)return null;if(1===a.nodeType)return a;var b=a._reactInternals;if(void 0===b){if(\"function\"===typeof a.render)throw Error(p(188));a=Object.keys(a).join(\",\");throw Error(p(268,a));}a=Zb(b);a=null===a?null:a.stateNode;return a};exports.flushSync=function(a){return Sk(a)};exports.hydrate=function(a,b,c){if(!pl(b))throw Error(p(200));return sl(null,a,b,!0,c)};\nexports.hydrateRoot=function(a,b,c){if(!ol(a))throw Error(p(405));var d=null!=c&&c.hydratedSources||null,e=!1,f=\"\",g=ll;null!==c&&void 0!==c&&(!0===c.unstable_strictMode&&(e=!0),void 0!==c.identifierPrefix&&(f=c.identifierPrefix),void 0!==c.onRecoverableError&&(g=c.onRecoverableError));b=fl(b,null,a,1,null!=c?c:null,e,!1,f,g);a[uf]=b.current;sf(a);if(d)for(a=0;a<d.length;a++)c=d[a],e=c._getVersion,e=e(c._source),null==b.mutableSourceEagerHydrationData?b.mutableSourceEagerHydrationData=[c,e]:b.mutableSourceEagerHydrationData.push(c,\ne);return new nl(b)};exports.render=function(a,b,c){if(!pl(b))throw Error(p(200));return sl(null,a,b,!1,c)};exports.unmountComponentAtNode=function(a){if(!pl(a))throw Error(p(40));return a._reactRootContainer?(Sk(function(){sl(null,null,a,!1,function(){a._reactRootContainer=null;a[uf]=null})}),!0):!1};exports.unstable_batchedUpdates=Rk;\nexports.unstable_renderSubtreeIntoContainer=function(a,b,c,d){if(!pl(c))throw Error(p(200));if(null==a||void 0===a._reactInternals)throw Error(p(38));return sl(a,b,c,!1,d)};exports.version=\"18.2.0-next-9e3b772b8-20220608\";\n","'use strict';\n\nvar m = require('react-dom');\nif (process.env.NODE_ENV === 'production') {\n exports.createRoot = m.createRoot;\n exports.hydrateRoot = m.hydrateRoot;\n} else {\n var i = m.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n exports.createRoot = function(c, o) {\n i.usingClientEntryPoint = true;\n try {\n return m.createRoot(c, o);\n } finally {\n i.usingClientEntryPoint = false;\n }\n };\n exports.hydrateRoot = function(c, h, o) {\n i.usingClientEntryPoint = true;\n try {\n return m.hydrateRoot(c, h, o);\n } finally {\n i.usingClientEntryPoint = false;\n }\n };\n}\n","'use strict';\n\nfunction checkDCE() {\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\n if (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'\n ) {\n return;\n }\n if (process.env.NODE_ENV !== 'production') {\n // This branch is unreachable because this function is only called\n // in production, but the condition is true only in development.\n // Therefore if the branch is still here, dead code elimination wasn't\n // properly applied.\n // Don't change the message. React DevTools relies on it. Also make sure\n // this message doesn't occur elsewhere in this function, or it will cause\n // a false positive.\n throw new Error('^_^');\n }\n try {\n // Verify that the code above has been dead code eliminated (DCE'd).\n __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);\n } catch (err) {\n // DevTools shouldn't crash React, no matter what.\n // We should still report in case we break this code.\n console.error(err);\n }\n}\n\nif (process.env.NODE_ENV === 'production') {\n // DCE check should happen before ReactDOM bundle executes so that\n // DevTools can report bad minification during injection.\n checkDCE();\n module.exports = require('./cjs/react-dom.production.min.js');\n} else {\n module.exports = require('./cjs/react-dom.development.js');\n}\n","/**\n * @license React\n * react-jsx-runtime.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var f=require(\"react\"),k=Symbol.for(\"react.element\"),l=Symbol.for(\"react.fragment\"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};\nfunction q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=\"\"+g);void 0!==a.key&&(e=\"\"+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}exports.Fragment=l;exports.jsx=q;exports.jsxs=q;\n","/**\n * @license React\n * react.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var l=Symbol.for(\"react.element\"),n=Symbol.for(\"react.portal\"),p=Symbol.for(\"react.fragment\"),q=Symbol.for(\"react.strict_mode\"),r=Symbol.for(\"react.profiler\"),t=Symbol.for(\"react.provider\"),u=Symbol.for(\"react.context\"),v=Symbol.for(\"react.forward_ref\"),w=Symbol.for(\"react.suspense\"),x=Symbol.for(\"react.memo\"),y=Symbol.for(\"react.lazy\"),z=Symbol.iterator;function A(a){if(null===a||\"object\"!==typeof a)return null;a=z&&a[z]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}\nvar B={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}E.prototype.isReactComponent={};\nE.prototype.setState=function(a,b){if(\"object\"!==typeof a&&\"function\"!==typeof a&&null!=a)throw Error(\"setState(...): takes an object of state variables to update or a function which returns an object of state variables.\");this.updater.enqueueSetState(this,a,b,\"setState\")};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,\"forceUpdate\")};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}var H=G.prototype=new F;\nH.constructor=G;C(H,E.prototype);H.isPureReactComponent=!0;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:!0,ref:!0,__self:!0,__source:!0};\nfunction M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=\"\"+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1<g){for(var f=Array(g),m=0;m<g;m++)f[m]=arguments[m+2];c.children=f}if(a&&a.defaultProps)for(d in g=a.defaultProps,g)void 0===c[d]&&(c[d]=g[d]);return{$$typeof:l,type:a,key:k,ref:h,props:c,_owner:K.current}}\nfunction N(a,b){return{$$typeof:l,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}function O(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===l}function escape(a){var b={\"=\":\"=0\",\":\":\"=2\"};return\"$\"+a.replace(/[=:]/g,function(a){return b[a]})}var P=/\\/+/g;function Q(a,b){return\"object\"===typeof a&&null!==a&&null!=a.key?escape(\"\"+a.key):b.toString(36)}\nfunction R(a,b,e,d,c){var k=typeof a;if(\"undefined\"===k||\"boolean\"===k)a=null;var h=!1;if(null===a)h=!0;else switch(k){case \"string\":case \"number\":h=!0;break;case \"object\":switch(a.$$typeof){case l:case n:h=!0}}if(h)return h=a,c=c(h),a=\"\"===d?\".\"+Q(h,0):d,I(c)?(e=\"\",null!=a&&(e=a.replace(P,\"$&/\")+\"/\"),R(c,b,e,\"\",function(a){return a})):null!=c&&(O(c)&&(c=N(c,e+(!c.key||h&&h.key===c.key?\"\":(\"\"+c.key).replace(P,\"$&/\")+\"/\")+a)),b.push(c)),1;h=0;d=\"\"===d?\".\":d+\":\";if(I(a))for(var g=0;g<a.length;g++){k=\na[g];var f=d+Q(k,g);h+=R(k,b,e,f,c)}else if(f=A(a),\"function\"===typeof f)for(a=f.call(a),g=0;!(k=a.next()).done;)k=k.value,f=d+Q(k,g++),h+=R(k,b,e,f,c);else if(\"object\"===k)throw b=String(a),Error(\"Objects are not valid as a React child (found: \"+(\"[object Object]\"===b?\"object with keys {\"+Object.keys(a).join(\", \")+\"}\":b)+\"). If you meant to render a collection of children, use an array instead.\");return h}\nfunction S(a,b,e){if(null==a)return a;var d=[],c=0;R(a,d,\"\",\"\",function(a){return b.call(e,a,c++)});return d}function T(a){if(-1===a._status){var b=a._result;b=b();b.then(function(b){if(0===a._status||-1===a._status)a._status=1,a._result=b},function(b){if(0===a._status||-1===a._status)a._status=2,a._result=b});-1===a._status&&(a._status=0,a._result=b)}if(1===a._status)return a._result.default;throw a._result;}\nvar U={current:null},V={transition:null},W={ReactCurrentDispatcher:U,ReactCurrentBatchConfig:V,ReactCurrentOwner:K};exports.Children={map:S,forEach:function(a,b,e){S(a,function(){b.apply(this,arguments)},e)},count:function(a){var b=0;S(a,function(){b++});return b},toArray:function(a){return S(a,function(a){return a})||[]},only:function(a){if(!O(a))throw Error(\"React.Children.only expected to receive a single React element child.\");return a}};exports.Component=E;exports.Fragment=p;\nexports.Profiler=r;exports.PureComponent=G;exports.StrictMode=q;exports.Suspense=w;exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=W;\nexports.cloneElement=function(a,b,e){if(null===a||void 0===a)throw Error(\"React.cloneElement(...): The argument must be a React element, but you passed \"+a+\".\");var d=C({},a.props),c=a.key,k=a.ref,h=a._owner;if(null!=b){void 0!==b.ref&&(k=b.ref,h=K.current);void 0!==b.key&&(c=\"\"+b.key);if(a.type&&a.type.defaultProps)var g=a.type.defaultProps;for(f in b)J.call(b,f)&&!L.hasOwnProperty(f)&&(d[f]=void 0===b[f]&&void 0!==g?g[f]:b[f])}var f=arguments.length-2;if(1===f)d.children=e;else if(1<f){g=Array(f);\nfor(var m=0;m<f;m++)g[m]=arguments[m+2];d.children=g}return{$$typeof:l,type:a.type,key:c,ref:k,props:d,_owner:h}};exports.createContext=function(a){a={$$typeof:u,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};a.Provider={$$typeof:t,_context:a};return a.Consumer=a};exports.createElement=M;exports.createFactory=function(a){var b=M.bind(null,a);b.type=a;return b};exports.createRef=function(){return{current:null}};\nexports.forwardRef=function(a){return{$$typeof:v,render:a}};exports.isValidElement=O;exports.lazy=function(a){return{$$typeof:y,_payload:{_status:-1,_result:a},_init:T}};exports.memo=function(a,b){return{$$typeof:x,type:a,compare:void 0===b?null:b}};exports.startTransition=function(a){var b=V.transition;V.transition={};try{a()}finally{V.transition=b}};exports.unstable_act=function(){throw Error(\"act(...) is not supported in production builds of React.\");};\nexports.useCallback=function(a,b){return U.current.useCallback(a,b)};exports.useContext=function(a){return U.current.useContext(a)};exports.useDebugValue=function(){};exports.useDeferredValue=function(a){return U.current.useDeferredValue(a)};exports.useEffect=function(a,b){return U.current.useEffect(a,b)};exports.useId=function(){return U.current.useId()};exports.useImperativeHandle=function(a,b,e){return U.current.useImperativeHandle(a,b,e)};\nexports.useInsertionEffect=function(a,b){return U.current.useInsertionEffect(a,b)};exports.useLayoutEffect=function(a,b){return U.current.useLayoutEffect(a,b)};exports.useMemo=function(a,b){return U.current.useMemo(a,b)};exports.useReducer=function(a,b,e){return U.current.useReducer(a,b,e)};exports.useRef=function(a){return U.current.useRef(a)};exports.useState=function(a){return U.current.useState(a)};exports.useSyncExternalStore=function(a,b,e){return U.current.useSyncExternalStore(a,b,e)};\nexports.useTransition=function(){return U.current.useTransition()};exports.version=\"18.2.0\";\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react.production.min.js');\n} else {\n module.exports = require('./cjs/react.development.js');\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.min.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","/**\n * @license React\n * scheduler.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';function f(a,b){var c=a.length;a.push(b);a:for(;0<c;){var d=c-1>>>1,e=a[d];if(0<g(e,b))a[d]=b,a[c]=e,c=d;else break a}}function h(a){return 0===a.length?null:a[0]}function k(a){if(0===a.length)return null;var b=a[0],c=a.pop();if(c!==b){a[0]=c;a:for(var d=0,e=a.length,w=e>>>1;d<w;){var m=2*(d+1)-1,C=a[m],n=m+1,x=a[n];if(0>g(C,c))n<e&&0>g(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(n<e&&0>g(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}\nfunction g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if(\"object\"===typeof performance&&\"function\"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D=\"function\"===typeof setTimeout?setTimeout:null,E=\"function\"===typeof clearTimeout?clearTimeout:null,F=\"undefined\"!==typeof setImmediate?setImmediate:null;\n\"undefined\"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}\nfunction J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if(\"function\"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;\nfunction M(){return exports.unstable_now()-Q<P?!1:!0}function R(){if(null!==O){var a=exports.unstable_now();Q=a;var b=!0;try{b=O(!0,a)}finally{b?S():(N=!1,O=null)}}else N=!1}var S;if(\"function\"===typeof F)S=function(){F(R)};else if(\"undefined\"!==typeof MessageChannel){var T=new MessageChannel,U=T.port2;T.port1.onmessage=R;S=function(){U.postMessage(null)}}else S=function(){D(R,0)};function I(a){O=a;N||(N=!0,S())}function K(a,b){L=D(function(){a(exports.unstable_now())},b)}\nexports.unstable_IdlePriority=5;exports.unstable_ImmediatePriority=1;exports.unstable_LowPriority=4;exports.unstable_NormalPriority=3;exports.unstable_Profiling=null;exports.unstable_UserBlockingPriority=2;exports.unstable_cancelCallback=function(a){a.callback=null};exports.unstable_continueExecution=function(){A||z||(A=!0,I(J))};\nexports.unstable_forceFrameRate=function(a){0>a||125<a?console.error(\"forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported\"):P=0<a?Math.floor(1E3/a):5};exports.unstable_getCurrentPriorityLevel=function(){return y};exports.unstable_getFirstCallbackNode=function(){return h(r)};exports.unstable_next=function(a){switch(y){case 1:case 2:case 3:var b=3;break;default:b=y}var c=y;y=b;try{return a()}finally{y=c}};exports.unstable_pauseExecution=function(){};\nexports.unstable_requestPaint=function(){};exports.unstable_runWithPriority=function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=y;y=a;try{return b()}finally{y=c}};\nexports.unstable_scheduleCallback=function(a,b,c){var d=exports.unstable_now();\"object\"===typeof c&&null!==c?(c=c.delay,c=\"number\"===typeof c&&0<c?d+c:d):c=d;switch(a){case 1:var e=-1;break;case 2:e=250;break;case 5:e=1073741823;break;case 4:e=1E4;break;default:e=5E3}e=c+e;a={id:u++,callback:b,priorityLevel:a,startTime:c,expirationTime:e,sortIndex:-1};c>d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};\nexports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"static/js/\" + chunkId + \".\" + \"7e4c938d\" + \".chunk.js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","var inProgress = {};\nvar dataWebpackPrefix = \"friendlybetting:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tscript.timeout = 120;\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.p = \"/Friendly-Betting/\";","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t179: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n// no on chunks loaded\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar chunkIds = data[0];\n\tvar moreModules = data[1];\n\tvar runtime = data[2];\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkfriendlybetting\"] = self[\"webpackChunkfriendlybetting\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\n */\n\nexport const CONSTANTS = {\n /**\n * @define {boolean} Whether this is the client Node.js SDK.\n */\n NODE_CLIENT: false,\n /**\n * @define {boolean} Whether this is the Admin Node.js SDK.\n */\n NODE_ADMIN: false,\n\n /**\n * Firebase SDK Version\n */\n SDK_VERSION: '${JSCORE_VERSION}'\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst stringToByteArray = function (str: string): number[] {\n // TODO(user): Use native implementations if/when available\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (\n (c & 0xfc00) === 0xd800 &&\n i + 1 < str.length &&\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n ) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes: number[]): string {\n // TODO(user): Use native implementations if/when available\n const out: string[] = [];\n let pos = 0,\n c = 0;\n while (pos < bytes.length) {\n const c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n } else if (c1 > 191 && c1 < 224) {\n const c2 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n } else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n const c4 = bytes[pos++];\n const u =\n (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n 0x10000;\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n } else {\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n out[c++] = String.fromCharCode(\n ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n );\n }\n }\n return out.join('');\n};\n\ninterface Base64 {\n byteToCharMap_: { [key: number]: string } | null;\n charToByteMap_: { [key: string]: number } | null;\n byteToCharMapWebSafe_: { [key: number]: string } | null;\n charToByteMapWebSafe_: { [key: string]: number } | null;\n ENCODED_VALS_BASE: string;\n readonly ENCODED_VALS: string;\n readonly ENCODED_VALS_WEBSAFE: string;\n HAS_NATIVE_SUPPORT: boolean;\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n encodeString(input: string, webSafe?: boolean): string;\n decodeString(input: string, webSafe: boolean): string;\n decodeStringToByteArray(input: string, webSafe: boolean): number[];\n init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\nexport const base64: Base64 = {\n /**\n * Maps bytes to characters.\n */\n byteToCharMap_: null,\n\n /**\n * Maps characters to bytes.\n */\n charToByteMap_: null,\n\n /**\n * Maps bytes to websafe characters.\n * @private\n */\n byteToCharMapWebSafe_: null,\n\n /**\n * Maps websafe characters to bytes.\n * @private\n */\n charToByteMapWebSafe_: null,\n\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n */\n ENCODED_VALS_BASE:\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n\n /**\n * Our websafe alphabet.\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n /**\n * Base64-encode an array of bytes.\n *\n * @param input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n\n this.init_();\n\n const byteToCharMap = webSafe\n ? this.byteToCharMapWebSafe_!\n : this.byteToCharMap_!;\n\n const output = [];\n\n for (let i = 0; i < input.length; i += 3) {\n const byte1 = input[i];\n const haveByte2 = i + 1 < input.length;\n const byte2 = haveByte2 ? input[i + 1] : 0;\n const haveByte3 = i + 2 < input.length;\n const byte3 = haveByte3 ? input[i + 2] : 0;\n\n const outByte1 = byte1 >> 2;\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n let outByte4 = byte3 & 0x3f;\n\n if (!haveByte3) {\n outByte4 = 64;\n\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n\n output.push(\n byteToCharMap[outByte1],\n byteToCharMap[outByte2],\n byteToCharMap[outByte3],\n byteToCharMap[outByte4]\n );\n }\n\n return output.join('');\n },\n\n /**\n * Base64-encode a string.\n *\n * @param input A string to encode.\n * @param webSafe If true, we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeString(input: string, webSafe?: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), webSafe);\n },\n\n /**\n * Base64-decode a string.\n *\n * @param input to decode.\n * @param webSafe True if we should use the\n * alternative alphabet.\n * @return string representing the decoded value.\n */\n decodeString(input: string, webSafe: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n },\n\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param input Input to decode.\n * @param webSafe True if we should use the web-safe alphabet.\n * @return bytes representing the decoded value.\n */\n decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n this.init_();\n\n const charToByteMap = webSafe\n ? this.charToByteMapWebSafe_!\n : this.charToByteMap_!;\n\n const output: number[] = [];\n\n for (let i = 0; i < input.length; ) {\n const byte1 = charToByteMap[input.charAt(i++)];\n\n const haveByte2 = i < input.length;\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n\n const haveByte3 = i < input.length;\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n const haveByte4 = i < input.length;\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw new DecodeBase64StringError();\n }\n\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n\n if (byte3 !== 64) {\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n\n if (byte4 !== 64) {\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n\n return output;\n },\n\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_() {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n\n // We want quick mappings back and forth, so we precompute two maps.\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class DecodeBase64StringError extends Error {\n readonly name = 'DecodeBase64StringError';\n}\n\n/**\n * URL-safe base64 encoding\n */\nexport const base64Encode = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n return base64.encodeByteArray(utf8Bytes, true);\n};\n\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n // Use base64url encoding and remove padding in the end (dot characters).\n return base64Encode(str).replace(/\\./g, '');\n};\n\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function (str: string): string | null {\n try {\n return base64.decodeString(str, true);\n } catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { getGlobal } from './global';\n\n/**\n * Keys for experimental properties on the `FirebaseDefaults` object.\n * @public\n */\nexport type ExperimentalKey = 'authTokenSyncURL' | 'authIdTokenMaxAge';\n\n/**\n * An object that can be injected into the environment as __FIREBASE_DEFAULTS__,\n * either as a property of globalThis, a shell environment variable, or a\n * cookie.\n *\n * This object can be used to automatically configure and initialize\n * a Firebase app as well as any emulators.\n *\n * @public\n */\nexport interface FirebaseDefaults {\n config?: Record<string, string>;\n emulatorHosts?: Record<string, string>;\n _authTokenSyncURL?: string;\n _authIdTokenMaxAge?: number;\n /**\n * Override Firebase's runtime environment detection and\n * force the SDK to act as if it were in the specified environment.\n */\n forceEnvironment?: 'browser' | 'node';\n [key: string]: unknown;\n}\n\ndeclare global {\n // Need `var` for this to work.\n // eslint-disable-next-line no-var\n var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined;\n}\n\nconst getDefaultsFromGlobal = (): FirebaseDefaults | undefined =>\n getGlobal().__FIREBASE_DEFAULTS__;\n\n/**\n * Attempt to read defaults from a JSON string provided to\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\n * The dots are in parens because certain compilers (Vite?) cannot\n * handle seeing that variable in comments.\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\n */\nconst getDefaultsFromEnvVariable = (): FirebaseDefaults | undefined => {\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\n return;\n }\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\n if (defaultsJsonString) {\n return JSON.parse(defaultsJsonString);\n }\n};\n\nconst getDefaultsFromCookie = (): FirebaseDefaults | undefined => {\n if (typeof document === 'undefined') {\n return;\n }\n let match;\n try {\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\n } catch (e) {\n // Some environments such as Angular Universal SSR have a\n // `document` object but error on accessing `document.cookie`.\n return;\n }\n const decoded = match && base64Decode(match[1]);\n return decoded && JSON.parse(decoded);\n};\n\n/**\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\n * (1) if such an object exists as a property of `globalThis`\n * (2) if such an object was provided on a shell environment variable\n * (3) if such an object exists in a cookie\n * @public\n */\nexport const getDefaults = (): FirebaseDefaults | undefined => {\n try {\n return (\n getDefaultsFromGlobal() ||\n getDefaultsFromEnvVariable() ||\n getDefaultsFromCookie()\n );\n } catch (e) {\n /**\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\n * to any environment case we have not accounted for. Log to\n * info instead of swallowing so we can find these unknown cases\n * and add paths for them if needed.\n */\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\n return;\n }\n};\n\n/**\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\n * @public\n */\nexport const getDefaultEmulatorHost = (\n productName: string\n): string | undefined => getDefaults()?.emulatorHosts?.[productName];\n\n/**\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\n * @public\n */\nexport const getDefaultEmulatorHostnameAndPort = (\n productName: string\n): [hostname: string, port: number] | undefined => {\n const host = getDefaultEmulatorHost(productName);\n if (!host) {\n return undefined;\n }\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\n }\n // eslint-disable-next-line no-restricted-globals\n const port = parseInt(host.substring(separatorIndex + 1), 10);\n if (host[0] === '[') {\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\n return [host.substring(1, separatorIndex - 1), port];\n } else {\n return [host.substring(0, separatorIndex), port];\n }\n};\n\n/**\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\n * @public\n */\nexport const getDefaultAppConfig = (): Record<string, string> | undefined =>\n getDefaults()?.config;\n\n/**\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\n * prefixed by \"_\")\n * @public\n */\nexport const getExperimentalSetting = <T extends ExperimentalKey>(\n name: T\n): FirebaseDefaults[`_${T}`] =>\n getDefaults()?.[`_${name}`] as FirebaseDefaults[`_${T}`];\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Polyfill for `globalThis` object.\n * @returns the `globalThis` object for the given environment.\n * @public\n */\nexport function getGlobal(): typeof globalThis {\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('Unable to locate global object.');\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<R> {\n promise: Promise<R>;\n reject: (value?: unknown) => void = () => {};\n resolve: (value?: unknown) => void = () => {};\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve as (value?: unknown) => void;\n this.reject = reject as (value?: unknown) => void;\n });\n }\n\n /**\n * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\n */\n wrapCallback(\n callback?: (error?: unknown, value?: unknown) => void\n ): (error: unknown, value?: unknown) => void {\n return (error, value?) => {\n if (error) {\n this.reject(error);\n } else {\n this.resolve(value);\n }\n if (typeof callback === 'function') {\n // Attaching noop handler just in case developer wasn't expecting\n // promises\n this.promise.catch(() => {});\n\n // Some of our callbacks don't expect a value and our own tests\n // assert that the parameter length is 1\n if (callback.length === 1) {\n callback(error);\n } else {\n callback(error, value);\n }\n }\n };\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './constants';\nimport { getDefaults } from './defaults';\n\n/**\n * Returns navigator.userAgent string or '' if it's not defined.\n * @return user agent string\n */\nexport function getUA(): string {\n if (\n typeof navigator !== 'undefined' &&\n typeof navigator['userAgent'] === 'string'\n ) {\n return navigator['userAgent'];\n } else {\n return '';\n }\n}\n\n/**\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\n *\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\n * wait for a callback.\n */\nexport function isMobileCordova(): boolean {\n return (\n typeof window !== 'undefined' &&\n // @ts-ignore Setting up an broadly applicable index signature for Window\n // just to deal with this case would probably be a bad idea.\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())\n );\n}\n\n/**\n * Detect Node.js.\n *\n * @return true if Node.js environment is detected or specified.\n */\n// Node detection logic from: https://github.com/iliakan/detect-node/\nexport function isNode(): boolean {\n const forceEnvironment = getDefaults()?.forceEnvironment;\n if (forceEnvironment === 'node') {\n return true;\n } else if (forceEnvironment === 'browser') {\n return false;\n }\n\n try {\n return (\n Object.prototype.toString.call(global.process) === '[object process]'\n );\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Detect Browser Environment\n */\nexport function isBrowser(): boolean {\n return typeof self === 'object' && self.self === self;\n}\n\n/**\n * Detect browser extensions (Chrome and Firefox at least).\n */\ninterface BrowserRuntime {\n id?: unknown;\n}\ndeclare const chrome: { runtime?: BrowserRuntime };\ndeclare const browser: { runtime?: BrowserRuntime };\nexport function isBrowserExtension(): boolean {\n const runtime =\n typeof chrome === 'object'\n ? chrome.runtime\n : typeof browser === 'object'\n ? browser.runtime\n : undefined;\n return typeof runtime === 'object' && runtime.id !== undefined;\n}\n\n/**\n * Detect React Native.\n *\n * @return true if ReactNative environment is detected.\n */\nexport function isReactNative(): boolean {\n return (\n typeof navigator === 'object' && navigator['product'] === 'ReactNative'\n );\n}\n\n/** Detects Electron apps. */\nexport function isElectron(): boolean {\n return getUA().indexOf('Electron/') >= 0;\n}\n\n/** Detects Internet Explorer. */\nexport function isIE(): boolean {\n const ua = getUA();\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\n}\n\n/** Detects Universal Windows Platform apps. */\nexport function isUWP(): boolean {\n return getUA().indexOf('MSAppHost/') >= 0;\n}\n\n/**\n * Detect whether the current SDK build is the Node version.\n *\n * @return true if it's the Node SDK build.\n */\nexport function isNodeSdk(): boolean {\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\n}\n\n/** Returns true if we are running in Safari. */\nexport function isSafari(): boolean {\n return (\n !isNode() &&\n navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome')\n );\n}\n\n/**\n * This method checks if indexedDB is supported by current browser/service worker context\n * @return true if indexedDB is supported by current browser/service worker context\n */\nexport function isIndexedDBAvailable(): boolean {\n try {\n return typeof indexedDB === 'object';\n } catch (e) {\n return false;\n }\n}\n\n/**\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\n * if errors occur during the database open operation.\n *\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\n * private browsing)\n */\nexport function validateIndexedDBOpenable(): Promise<boolean> {\n return new Promise((resolve, reject) => {\n try {\n let preExist: boolean = true;\n const DB_CHECK_NAME =\n 'validate-browser-context-for-indexeddb-analytics-module';\n const request = self.indexedDB.open(DB_CHECK_NAME);\n request.onsuccess = () => {\n request.result.close();\n // delete database only when it doesn't pre-exist\n if (!preExist) {\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\n }\n resolve(true);\n };\n request.onupgradeneeded = () => {\n preExist = false;\n };\n\n request.onerror = () => {\n reject(request.error?.message || '');\n };\n } catch (error) {\n reject(error);\n }\n });\n}\n\n/**\n *\n * This method checks whether cookie is enabled within current browser\n * @return true if cookie is enabled within current browser\n */\nexport function areCookiesEnabled(): boolean {\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\n return false;\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n * // Typescript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map<Err, string> = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory<Err>('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\n\nexport type ErrorMap<ErrorCode extends string> = {\n readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n toString(): string;\n}\n\nexport interface ErrorData {\n [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n /** The custom name for all FirebaseErrors. */\n readonly name: string = ERROR_NAME;\n\n constructor(\n /** The error code for this error. */\n readonly code: string,\n message: string,\n /** Custom data for this error. */\n public customData?: Record<string, unknown>\n ) {\n super(message);\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, FirebaseError.prototype);\n\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\n\nexport class ErrorFactory<\n ErrorCode extends string,\n ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n constructor(\n private readonly service: string,\n private readonly serviceName: string,\n private readonly errors: ErrorMap<ErrorCode>\n ) {}\n\n create<K extends ErrorCode>(\n code: K,\n ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n ): FirebaseError {\n const customData = (data[0] as ErrorData) || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n const error = new FirebaseError(fullCode, fullMessage, customData);\n\n return error;\n }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n return template.replace(PATTERN, (_, key) => {\n const value = data[key];\n return value != null ? String(value) : `<${key}?>`;\n });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function contains<T extends object>(obj: T, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function safeGet<T extends object, K extends keyof T>(\n obj: T,\n key: K\n): T[K] | undefined {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return obj[key];\n } else {\n return undefined;\n }\n}\n\nexport function isEmpty(obj: object): obj is {} {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n\nexport function map<K extends string, V, U>(\n obj: { [key in K]: V },\n fn: (value: V, key: K, obj: { [key in K]: V }) => U,\n contextObj?: unknown\n): { [key in K]: U } {\n const res: Partial<{ [key in K]: U }> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n res[key] = fn.call(contextObj, obj[key], key, obj);\n }\n }\n return res as { [key in K]: U };\n}\n\n/**\n * Deep equal two objects. Support Arrays and Objects.\n */\nexport function deepEqual(a: object, b: object): boolean {\n if (a === b) {\n return true;\n }\n\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n for (const k of aKeys) {\n if (!bKeys.includes(k)) {\n return false;\n }\n\n const aProp = (a as Record<string, unknown>)[k];\n const bProp = (b as Record<string, unknown>)[k];\n if (isObject(aProp) && isObject(bProp)) {\n if (!deepEqual(aProp, bProp)) {\n return false;\n }\n } else if (aProp !== bProp) {\n return false;\n }\n }\n\n for (const k of bKeys) {\n if (!aKeys.includes(k)) {\n return false;\n }\n }\n return true;\n}\n\nfunction isObject(thing: unknown): thing is object {\n return thing !== null && typeof thing === 'object';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\n * params object (e.g. {arg: 'val', arg2: 'val2'})\n * Note: You must prepend it with ? when adding it to a URL.\n */\nexport function querystring(querystringParams: {\n [key: string]: string | number;\n}): string {\n const params = [];\n for (const [key, value] of Object.entries(querystringParams)) {\n if (Array.isArray(value)) {\n value.forEach(arrayVal => {\n params.push(\n encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal)\n );\n });\n } else {\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n }\n }\n return params.length ? '&' + params.join('&') : '';\n}\n\n/**\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\n * (e.g. {arg: 'val', arg2: 'val2'})\n */\nexport function querystringDecode(querystring: string): Record<string, string> {\n const obj: Record<string, string> = {};\n const tokens = querystring.replace(/^\\?/, '').split('&');\n\n tokens.forEach(token => {\n if (token) {\n const [key, value] = token.split('=');\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\n }\n });\n return obj;\n}\n\n/**\n * Extract the query string part of a URL, including the leading question mark (if present).\n */\nexport function extractQuerystring(url: string): string {\n const queryStart = url.indexOf('?');\n if (!queryStart) {\n return '';\n }\n const fragmentStart = url.indexOf('#', queryStart);\n return url.substring(\n queryStart,\n fragmentStart > 0 ? fragmentStart : undefined\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport type NextFn<T> = (value: T) => void;\nexport type ErrorFn = (error: Error) => void;\nexport type CompleteFn = () => void;\n\nexport interface Observer<T> {\n // Called once for each value in a stream of values.\n next: NextFn<T>;\n\n // A stream terminates by a single call to EITHER error() or complete().\n error: ErrorFn;\n\n // No events will be sent to next() once complete() is called.\n complete: CompleteFn;\n}\n\nexport type PartialObserver<T> = Partial<Observer<T>>;\n\n// TODO: Support also Unsubscribe.unsubscribe?\nexport type Unsubscribe = () => void;\n\n/**\n * The Subscribe interface has two forms - passing the inline function\n * callbacks, or a object interface with callback properties.\n */\nexport interface Subscribe<T> {\n (next?: NextFn<T>, error?: ErrorFn, complete?: CompleteFn): Unsubscribe;\n (observer: PartialObserver<T>): Unsubscribe;\n}\n\nexport interface Observable<T> {\n // Subscribe method\n subscribe: Subscribe<T>;\n}\n\nexport type Executor<T> = (observer: Observer<T>) => void;\n\n/**\n * Helper to make a Subscribe function (just like Promise helps make a\n * Thenable).\n *\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\nexport function createSubscribe<T>(\n executor: Executor<T>,\n onNoObservers?: Executor<T>\n): Subscribe<T> {\n const proxy = new ObserverProxy<T>(executor, onNoObservers);\n return proxy.subscribe.bind(proxy);\n}\n\n/**\n * Implement fan-out for any number of Observers attached via a subscribe\n * function.\n */\nclass ObserverProxy<T> implements Observer<T> {\n private observers: Array<Observer<T>> | undefined = [];\n private unsubscribes: Unsubscribe[] = [];\n private onNoObservers: Executor<T> | undefined;\n private observerCount = 0;\n // Micro-task scheduling by calling task.then().\n private task = Promise.resolve();\n private finalized = false;\n private finalError?: Error;\n\n /**\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\n constructor(executor: Executor<T>, onNoObservers?: Executor<T>) {\n this.onNoObservers = onNoObservers;\n // Call the executor asynchronously so subscribers that are called\n // synchronously after the creation of the subscribe function\n // can still receive the very first value generated in the executor.\n this.task\n .then(() => {\n executor(this);\n })\n .catch(e => {\n this.error(e);\n });\n }\n\n next(value: T): void {\n this.forEachObserver((observer: Observer<T>) => {\n observer.next(value);\n });\n }\n\n error(error: Error): void {\n this.forEachObserver((observer: Observer<T>) => {\n observer.error(error);\n });\n this.close(error);\n }\n\n complete(): void {\n this.forEachObserver((observer: Observer<T>) => {\n observer.complete();\n });\n this.close();\n }\n\n /**\n * Subscribe function that can be used to add an Observer to the fan-out list.\n *\n * - We require that no event is sent to a subscriber sychronously to their\n * call to subscribe().\n */\n subscribe(\n nextOrObserver?: NextFn<T> | PartialObserver<T>,\n error?: ErrorFn,\n complete?: CompleteFn\n ): Unsubscribe {\n let observer: Observer<T>;\n\n if (\n nextOrObserver === undefined &&\n error === undefined &&\n complete === undefined\n ) {\n throw new Error('Missing Observer.');\n }\n\n // Assemble an Observer object when passed as callback functions.\n if (\n implementsAnyMethods(nextOrObserver as { [key: string]: unknown }, [\n 'next',\n 'error',\n 'complete'\n ])\n ) {\n observer = nextOrObserver as Observer<T>;\n } else {\n observer = {\n next: nextOrObserver as NextFn<T>,\n error,\n complete\n } as Observer<T>;\n }\n\n if (observer.next === undefined) {\n observer.next = noop as NextFn<T>;\n }\n if (observer.error === undefined) {\n observer.error = noop as ErrorFn;\n }\n if (observer.complete === undefined) {\n observer.complete = noop as CompleteFn;\n }\n\n const unsub = this.unsubscribeOne.bind(this, this.observers!.length);\n\n // Attempt to subscribe to a terminated Observable - we\n // just respond to the Observer with the final error or complete\n // event.\n if (this.finalized) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n try {\n if (this.finalError) {\n observer.error(this.finalError);\n } else {\n observer.complete();\n }\n } catch (e) {\n // nothing\n }\n return;\n });\n }\n\n this.observers!.push(observer as Observer<T>);\n\n return unsub;\n }\n\n // Unsubscribe is synchronous - we guarantee that no events are sent to\n // any unsubscribed Observer.\n private unsubscribeOne(i: number): void {\n if (this.observers === undefined || this.observers[i] === undefined) {\n return;\n }\n\n delete this.observers[i];\n\n this.observerCount -= 1;\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\n this.onNoObservers(this);\n }\n }\n\n private forEachObserver(fn: (observer: Observer<T>) => void): void {\n if (this.finalized) {\n // Already closed by previous event....just eat the additional values.\n return;\n }\n\n // Since sendOne calls asynchronously - there is no chance that\n // this.observers will become undefined.\n for (let i = 0; i < this.observers!.length; i++) {\n this.sendOne(i, fn);\n }\n }\n\n // Call the Observer via one of it's callback function. We are careful to\n // confirm that the observe has not been unsubscribed since this asynchronous\n // function had been queued.\n private sendOne(i: number, fn: (observer: Observer<T>) => void): void {\n // Execute the callback asynchronously\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n if (this.observers !== undefined && this.observers[i] !== undefined) {\n try {\n fn(this.observers[i]);\n } catch (e) {\n // Ignore exceptions raised in Observers or missing methods of an\n // Observer.\n // Log error to console. b/31404806\n if (typeof console !== 'undefined' && console.error) {\n console.error(e);\n }\n }\n }\n });\n }\n\n private close(err?: Error): void {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n if (err !== undefined) {\n this.finalError = err;\n }\n // Proxy is no longer needed - garbage collect references\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n this.observers = undefined;\n this.onNoObservers = undefined;\n });\n }\n}\n\n/** Turn synchronous function into one called asynchronously. */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function async(fn: Function, onError?: ErrorFn): Function {\n return (...args: unknown[]) => {\n Promise.resolve(true)\n .then(() => {\n fn(...args);\n })\n .catch((error: Error) => {\n if (onError) {\n onError(error);\n }\n });\n };\n}\n\n/**\n * Return true if the object passed in implements any of the named methods.\n */\nfunction implementsAnyMethods(\n obj: { [key: string]: unknown },\n methods: string[]\n): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n for (const method of methods) {\n if (method in obj && typeof obj[method] === 'function') {\n return true;\n }\n }\n\n return false;\n}\n\nfunction noop(): void {\n // do nothing\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from './assert';\n\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\n// so it's been modified.\n\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\n// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\n// pair).\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\n\n/**\n * @param {string} str\n * @return {Array}\n */\nexport const stringToByteArray = function (str: string): number[] {\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n\n // Is this the lead surrogate in a surrogate pair?\n if (c >= 0xd800 && c <= 0xdbff) {\n const high = c - 0xd800; // the high 10 bits.\n i++;\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\n c = 0x10000 + (high << 10) + low;\n }\n\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (c < 65536) {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Calculate length without actually converting; useful for doing cheaper validation.\n * @param {string} str\n * @return {number}\n */\nexport const stringLength = function (str: string): number {\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n const c = str.charCodeAt(i);\n if (c < 128) {\n p++;\n } else if (c < 2048) {\n p += 2;\n } else if (c >= 0xd800 && c <= 0xdbff) {\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\n p += 4;\n i++; // skip trail surrogate.\n } else {\n p += 3;\n }\n }\n return p;\n};\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The amount of milliseconds to exponentially increase.\n */\nconst DEFAULT_INTERVAL_MILLIS = 1000;\n\n/**\n * The factor to backoff by.\n * Should be a number greater than 1.\n */\nconst DEFAULT_BACKOFF_FACTOR = 2;\n\n/**\n * The maximum milliseconds to increase to.\n *\n * <p>Visible for testing\n */\nexport const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\n\n/**\n * The percentage of backoff time to randomize by.\n * See\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\n * for context.\n *\n * <p>Visible for testing\n */\nexport const RANDOM_FACTOR = 0.5;\n\n/**\n * Based on the backoff method from\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\n */\nexport function calculateBackoffMillis(\n backoffCount: number,\n intervalMillis: number = DEFAULT_INTERVAL_MILLIS,\n backoffFactor: number = DEFAULT_BACKOFF_FACTOR\n): number {\n // Calculates an exponentially increasing value.\n // Deviation: calculates value from count and a constant interval, so we only need to save value\n // and count to restore state.\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\n\n // A random \"fuzz\" to avoid waves of retries.\n // Deviation: randomFactor is required.\n const randomWait = Math.round(\n // A fraction of the backoff value to add/subtract.\n // Deviation: changes multiplication order to improve readability.\n RANDOM_FACTOR *\n currBaseValue *\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\n // if we add or subtract.\n (Math.random() - 0.5) *\n 2\n );\n\n // Limits backoff to max to avoid effectively permanent backoff.\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Compat<T> {\n _delegate: T;\n}\n\nexport function getModularInstance<ExpService>(\n service: Compat<ExpService> | ExpService\n): ExpService {\n if (service && (service as Compat<ExpService>)._delegate) {\n return (service as Compat<ExpService>)._delegate;\n } else {\n return service as ExpService;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n InstantiationMode,\n InstanceFactory,\n ComponentType,\n Dictionary,\n Name,\n onInstanceCreatedCallback\n} from './types';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nexport class Component<T extends Name = Name> {\n multipleInstances = false;\n /**\n * Properties to be added to the service namespace\n */\n serviceProps: Dictionary = {};\n\n instantiationMode = InstantiationMode.LAZY;\n\n onInstanceCreated: onInstanceCreatedCallback<T> | null = null;\n\n /**\n *\n * @param name The public service name, e.g. app, auth, firestore, database\n * @param instanceFactory Service factory responsible for creating the public interface\n * @param type whether the service provided by the component is public or private\n */\n constructor(\n readonly name: T,\n readonly instanceFactory: InstanceFactory<T>,\n readonly type: ComponentType\n ) {}\n\n setInstantiationMode(mode: InstantiationMode): this {\n this.instantiationMode = mode;\n return this;\n }\n\n setMultipleInstances(multipleInstances: boolean): this {\n this.multipleInstances = multipleInstances;\n return this;\n }\n\n setServiceProps(props: Dictionary): this {\n this.serviceProps = props;\n return this;\n }\n\n setInstanceCreatedCallback(callback: onInstanceCreatedCallback<T>): this {\n this.onInstanceCreated = callback;\n return this;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const DEFAULT_ENTRY_NAME = '[DEFAULT]';\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\nimport { ComponentContainer } from './component_container';\nimport { DEFAULT_ENTRY_NAME } from './constants';\nimport {\n InitializeOptions,\n InstantiationMode,\n Name,\n NameServiceMapping,\n OnInitCallBack\n} from './types';\nimport { Component } from './component';\n\n/**\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\n * NameServiceMapping[T] is an alias for the type of the instance\n */\nexport class Provider<T extends Name> {\n private component: Component<T> | null = null;\n private readonly instances: Map<string, NameServiceMapping[T]> = new Map();\n private readonly instancesDeferred: Map<\n string,\n Deferred<NameServiceMapping[T]>\n > = new Map();\n private readonly instancesOptions: Map<string, Record<string, unknown>> =\n new Map();\n private onInitCallbacks: Map<string, Set<OnInitCallBack<T>>> = new Map();\n\n constructor(\n private readonly name: T,\n private readonly container: ComponentContainer\n ) {}\n\n /**\n * @param identifier A provider can provide mulitple instances of a service\n * if this.component.multipleInstances is true.\n */\n get(identifier?: string): Promise<NameServiceMapping[T]> {\n // if multipleInstances is not supported, use the default name\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\n const deferred = new Deferred<NameServiceMapping[T]>();\n this.instancesDeferred.set(normalizedIdentifier, deferred);\n\n if (\n this.isInitialized(normalizedIdentifier) ||\n this.shouldAutoInitialize()\n ) {\n // initialize the service if it can be auto-initialized\n try {\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n });\n if (instance) {\n deferred.resolve(instance);\n }\n } catch (e) {\n // when the instance factory throws an exception during get(), it should not cause\n // a fatal error. We just return the unresolved promise in this case.\n }\n }\n }\n\n return this.instancesDeferred.get(normalizedIdentifier)!.promise;\n }\n\n /**\n *\n * @param options.identifier A provider can provide mulitple instances of a service\n * if this.component.multipleInstances is true.\n * @param options.optional If optional is false or not provided, the method throws an error when\n * the service is not immediately available.\n * If optional is true, the method returns null if the service is not immediately available.\n */\n getImmediate(options: {\n identifier?: string;\n optional: true;\n }): NameServiceMapping[T] | null;\n getImmediate(options?: {\n identifier?: string;\n optional?: false;\n }): NameServiceMapping[T];\n getImmediate(options?: {\n identifier?: string;\n optional?: boolean;\n }): NameServiceMapping[T] | null {\n // if multipleInstances is not supported, use the default name\n const normalizedIdentifier = this.normalizeInstanceIdentifier(\n options?.identifier\n );\n const optional = options?.optional ?? false;\n\n if (\n this.isInitialized(normalizedIdentifier) ||\n this.shouldAutoInitialize()\n ) {\n try {\n return this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n });\n } catch (e) {\n if (optional) {\n return null;\n } else {\n throw e;\n }\n }\n } else {\n // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw\n if (optional) {\n return null;\n } else {\n throw Error(`Service ${this.name} is not available`);\n }\n }\n }\n\n getComponent(): Component<T> | null {\n return this.component;\n }\n\n setComponent(component: Component<T>): void {\n if (component.name !== this.name) {\n throw Error(\n `Mismatching Component ${component.name} for Provider ${this.name}.`\n );\n }\n\n if (this.component) {\n throw Error(`Component for ${this.name} has already been provided`);\n }\n\n this.component = component;\n\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\n if (!this.shouldAutoInitialize()) {\n return;\n }\n\n // if the service is eager, initialize the default instance\n if (isComponentEager(component)) {\n try {\n this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\n } catch (e) {\n // when the instance factory for an eager Component throws an exception during the eager\n // initialization, it should not cause a fatal error.\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\n // a fatal error in this case?\n }\n }\n\n // Create service instances for the pending promises and resolve them\n // NOTE: if this.multipleInstances is false, only the default instance will be created\n // and all promises with resolve with it regardless of the identifier.\n for (const [\n instanceIdentifier,\n instanceDeferred\n ] of this.instancesDeferred.entries()) {\n const normalizedIdentifier =\n this.normalizeInstanceIdentifier(instanceIdentifier);\n\n try {\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n })!;\n instanceDeferred.resolve(instance);\n } catch (e) {\n // when the instance factory throws an exception, it should not cause\n // a fatal error. We just leave the promise unresolved.\n }\n }\n }\n\n clearInstance(identifier: string = DEFAULT_ENTRY_NAME): void {\n this.instancesDeferred.delete(identifier);\n this.instancesOptions.delete(identifier);\n this.instances.delete(identifier);\n }\n\n // app.delete() will call this method on every provider to delete the services\n // TODO: should we mark the provider as deleted?\n async delete(): Promise<void> {\n const services = Array.from(this.instances.values());\n\n await Promise.all([\n ...services\n .filter(service => 'INTERNAL' in service) // legacy services\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map(service => (service as any).INTERNAL!.delete()),\n ...services\n .filter(service => '_delete' in service) // modularized services\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map(service => (service as any)._delete())\n ]);\n }\n\n isComponentSet(): boolean {\n return this.component != null;\n }\n\n isInitialized(identifier: string = DEFAULT_ENTRY_NAME): boolean {\n return this.instances.has(identifier);\n }\n\n getOptions(identifier: string = DEFAULT_ENTRY_NAME): Record<string, unknown> {\n return this.instancesOptions.get(identifier) || {};\n }\n\n initialize(opts: InitializeOptions = {}): NameServiceMapping[T] {\n const { options = {} } = opts;\n const normalizedIdentifier = this.normalizeInstanceIdentifier(\n opts.instanceIdentifier\n );\n if (this.isInitialized(normalizedIdentifier)) {\n throw Error(\n `${this.name}(${normalizedIdentifier}) has already been initialized`\n );\n }\n\n if (!this.isComponentSet()) {\n throw Error(`Component ${this.name} has not been registered yet`);\n }\n\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier,\n options\n })!;\n\n // resolve any pending promise waiting for the service instance\n for (const [\n instanceIdentifier,\n instanceDeferred\n ] of this.instancesDeferred.entries()) {\n const normalizedDeferredIdentifier =\n this.normalizeInstanceIdentifier(instanceIdentifier);\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\n instanceDeferred.resolve(instance);\n }\n }\n\n return instance;\n }\n\n /**\n *\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\n *\n * @param identifier An optional instance identifier\n * @returns a function to unregister the callback\n */\n onInit(callback: OnInitCallBack<T>, identifier?: string): () => void {\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n const existingCallbacks =\n this.onInitCallbacks.get(normalizedIdentifier) ??\n new Set<OnInitCallBack<T>>();\n existingCallbacks.add(callback);\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\n\n const existingInstance = this.instances.get(normalizedIdentifier);\n if (existingInstance) {\n callback(existingInstance, normalizedIdentifier);\n }\n\n return () => {\n existingCallbacks.delete(callback);\n };\n }\n\n /**\n * Invoke onInit callbacks synchronously\n * @param instance the service instance`\n */\n private invokeOnInitCallbacks(\n instance: NameServiceMapping[T],\n identifier: string\n ): void {\n const callbacks = this.onInitCallbacks.get(identifier);\n if (!callbacks) {\n return;\n }\n for (const callback of callbacks) {\n try {\n callback(instance, identifier);\n } catch {\n // ignore errors in the onInit callback\n }\n }\n }\n\n private getOrInitializeService({\n instanceIdentifier,\n options = {}\n }: {\n instanceIdentifier: string;\n options?: Record<string, unknown>;\n }): NameServiceMapping[T] | null {\n let instance = this.instances.get(instanceIdentifier);\n if (!instance && this.component) {\n instance = this.component.instanceFactory(this.container, {\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\n options\n });\n this.instances.set(instanceIdentifier, instance);\n this.instancesOptions.set(instanceIdentifier, options);\n\n /**\n * Invoke onInit listeners.\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\n * while onInit listeners are registered by consumers of the provider.\n */\n this.invokeOnInitCallbacks(instance, instanceIdentifier);\n\n /**\n * Order is important\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\n * makes `isInitialized()` return true.\n */\n if (this.component.onInstanceCreated) {\n try {\n this.component.onInstanceCreated(\n this.container,\n instanceIdentifier,\n instance\n );\n } catch {\n // ignore errors in the onInstanceCreatedCallback\n }\n }\n }\n\n return instance || null;\n }\n\n private normalizeInstanceIdentifier(\n identifier: string = DEFAULT_ENTRY_NAME\n ): string {\n if (this.component) {\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\n } else {\n return identifier; // assume multiple instances are supported before the component is provided.\n }\n }\n\n private shouldAutoInitialize(): boolean {\n return (\n !!this.component &&\n this.component.instantiationMode !== InstantiationMode.EXPLICIT\n );\n }\n}\n\n// undefined should be passed to the service factory for the default instance\nfunction normalizeIdentifierForFactory(identifier: string): string | undefined {\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\n}\n\nfunction isComponentEager<T extends Name>(component: Component<T>): boolean {\n return component.instantiationMode === InstantiationMode.EAGER;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Provider } from './provider';\nimport { Component } from './component';\nimport { Name } from './types';\n\n/**\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\n */\nexport class ComponentContainer {\n private readonly providers = new Map<string, Provider<Name>>();\n\n constructor(private readonly name: string) {}\n\n /**\n *\n * @param component Component being added\n * @param overwrite When a component with the same name has already been registered,\n * if overwrite is true: overwrite the existing component with the new component and create a new\n * provider with the new component. It can be useful in tests where you want to use different mocks\n * for different tests.\n * if overwrite is false: throw an exception\n */\n addComponent<T extends Name>(component: Component<T>): void {\n const provider = this.getProvider(component.name);\n if (provider.isComponentSet()) {\n throw new Error(\n `Component ${component.name} has already been registered with ${this.name}`\n );\n }\n\n provider.setComponent(component);\n }\n\n addOrOverwriteComponent<T extends Name>(component: Component<T>): void {\n const provider = this.getProvider(component.name);\n if (provider.isComponentSet()) {\n // delete the existing provider from the container, so we can register the new component\n this.providers.delete(component.name);\n }\n\n this.addComponent(component);\n }\n\n /**\n * getProvider provides a type safe interface where it can only be called with a field name\n * present in NameServiceMapping interface.\n *\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\n * themselves.\n */\n getProvider<T extends Name>(name: T): Provider<T> {\n if (this.providers.has(name)) {\n return this.providers.get(name) as unknown as Provider<T>;\n }\n\n // create a Provider for a service that hasn't registered with Firebase\n const provider = new Provider<T>(name, this);\n this.providers.set(name, provider as unknown as Provider<Name>);\n\n return provider as Provider<T>;\n }\n\n getProviders(): Array<Provider<Name>> {\n return Array.from(this.providers.values());\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type LogLevelString =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'silent';\n\nexport interface LogOptions {\n level: LogLevelString;\n}\n\nexport type LogCallback = (callbackParams: LogCallbackParams) => void;\n\nexport interface LogCallbackParams {\n level: LogLevelString;\n message: string;\n args: unknown[];\n type: string;\n}\n\n/**\n * A container for all of the Logger instances\n */\nexport const instances: Logger[] = [];\n\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport enum LogLevel {\n DEBUG,\n VERBOSE,\n INFO,\n WARN,\n ERROR,\n SILENT\n}\n\nconst levelStringToEnum: { [key in LogLevelString]: LogLevel } = {\n 'debug': LogLevel.DEBUG,\n 'verbose': LogLevel.VERBOSE,\n 'info': LogLevel.INFO,\n 'warn': LogLevel.WARN,\n 'error': LogLevel.ERROR,\n 'silent': LogLevel.SILENT\n};\n\n/**\n * The default log level\n */\nconst defaultLogLevel: LogLevel = LogLevel.INFO;\n\n/**\n * We allow users the ability to pass their own log handler. We will pass the\n * type of log, the current log level, and any other arguments passed (i.e. the\n * messages that the user wants to log) to this function.\n */\nexport type LogHandler = (\n loggerInstance: Logger,\n logType: LogLevel,\n ...args: unknown[]\n) => void;\n\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n [LogLevel.DEBUG]: 'log',\n [LogLevel.VERBOSE]: 'log',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error'\n};\n\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler: LogHandler = (instance, logType, ...args): void => {\n if (logType < instance.logLevel) {\n return;\n }\n const now = new Date().toISOString();\n const method = ConsoleMethod[logType as keyof typeof ConsoleMethod];\n if (method) {\n console[method as 'log' | 'info' | 'warn' | 'error'](\n `[${now}] ${instance.name}:`,\n ...args\n );\n } else {\n throw new Error(\n `Attempted to log a message with an invalid logType (value: ${logType})`\n );\n }\n};\n\nexport class Logger {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n constructor(public name: string) {\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n\n /**\n * The log level of the given Logger instance.\n */\n private _logLevel = defaultLogLevel;\n\n get logLevel(): LogLevel {\n return this._logLevel;\n }\n\n set logLevel(val: LogLevel) {\n if (!(val in LogLevel)) {\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n }\n this._logLevel = val;\n }\n\n // Workaround for setter/getter having to be the same type.\n setLogLevel(val: LogLevel | LogLevelString): void {\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n }\n\n /**\n * The main (internal) log handler for the Logger instance.\n * Can be set to a new function in internal package code but not by user.\n */\n private _logHandler: LogHandler = defaultLogHandler;\n get logHandler(): LogHandler {\n return this._logHandler;\n }\n set logHandler(val: LogHandler) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n }\n\n /**\n * The optional, additional, user-defined log handler for the Logger instance.\n */\n private _userLogHandler: LogHandler | null = null;\n get userLogHandler(): LogHandler | null {\n return this._userLogHandler;\n }\n set userLogHandler(val: LogHandler | null) {\n this._userLogHandler = val;\n }\n\n /**\n * The functions below are all based on the `console` interface\n */\n\n debug(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n this._logHandler(this, LogLevel.DEBUG, ...args);\n }\n log(...args: unknown[]): void {\n this._userLogHandler &&\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n this._logHandler(this, LogLevel.VERBOSE, ...args);\n }\n info(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n this._logHandler(this, LogLevel.INFO, ...args);\n }\n warn(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n this._logHandler(this, LogLevel.WARN, ...args);\n }\n error(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n this._logHandler(this, LogLevel.ERROR, ...args);\n }\n}\n\nexport function setLogLevel(level: LogLevelString | LogLevel): void {\n instances.forEach(inst => {\n inst.setLogLevel(level);\n });\n}\n\nexport function setUserLogHandler(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n for (const instance of instances) {\n let customLogLevel: LogLevel | null = null;\n if (options && options.level) {\n customLogLevel = levelStringToEnum[options.level];\n }\n if (logCallback === null) {\n instance.userLogHandler = null;\n } else {\n instance.userLogHandler = (\n instance: Logger,\n level: LogLevel,\n ...args: unknown[]\n ) => {\n const message = args\n .map(arg => {\n if (arg == null) {\n return null;\n } else if (typeof arg === 'string') {\n return arg;\n } else if (typeof arg === 'number' || typeof arg === 'boolean') {\n return arg.toString();\n } else if (arg instanceof Error) {\n return arg.message;\n } else {\n try {\n return JSON.stringify(arg);\n } catch (ignored) {\n return null;\n }\n }\n })\n .filter(arg => arg)\n .join(' ');\n if (level >= (customLogLevel ?? instance.logLevel)) {\n logCallback({\n level: LogLevel[level].toLowerCase() as LogLevelString,\n message,\n args,\n type: instance.name\n });\n }\n };\n }\n }\n}\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n });\n }\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event.newVersion, event));\n }\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking) {\n db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n }\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event));\n }\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ComponentContainer,\n ComponentType,\n Provider,\n Name\n} from '@firebase/component';\nimport { PlatformLoggerService, VersionService } from './types';\n\nexport class PlatformLoggerServiceImpl implements PlatformLoggerService {\n constructor(private readonly container: ComponentContainer) {}\n // In initial implementation, this will be called by installations on\n // auth token refresh, and installations will send this string.\n getPlatformInfoString(): string {\n const providers = this.container.getProviders();\n // Loop through providers and get library/version pairs from any that are\n // version components.\n return providers\n .map(provider => {\n if (isVersionServiceProvider(provider)) {\n const service = provider.getImmediate() as VersionService;\n return `${service.library}/${service.version}`;\n } else {\n return null;\n }\n })\n .filter(logString => logString)\n .join(' ');\n }\n}\n/**\n *\n * @param provider check if this provider provides a VersionService\n *\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\n * provides VersionService. The provider is not necessarily a 'app-version'\n * provider.\n */\nfunction isVersionServiceProvider(provider: Provider<Name>): boolean {\n const component = provider.getComponent();\n return component?.type === ComponentType.VERSION;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/app');\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { name as appName } from '../package.json';\nimport { name as appCompatName } from '../../app-compat/package.json';\nimport { name as analyticsCompatName } from '../../../packages/analytics-compat/package.json';\nimport { name as analyticsName } from '../../../packages/analytics/package.json';\nimport { name as appCheckCompatName } from '../../../packages/app-check-compat/package.json';\nimport { name as appCheckName } from '../../../packages/app-check/package.json';\nimport { name as authName } from '../../../packages/auth/package.json';\nimport { name as authCompatName } from '../../../packages/auth-compat/package.json';\nimport { name as databaseName } from '../../../packages/database/package.json';\nimport { name as databaseCompatName } from '../../../packages/database-compat/package.json';\nimport { name as functionsName } from '../../../packages/functions/package.json';\nimport { name as functionsCompatName } from '../../../packages/functions-compat/package.json';\nimport { name as installationsName } from '../../../packages/installations/package.json';\nimport { name as installationsCompatName } from '../../../packages/installations-compat/package.json';\nimport { name as messagingName } from '../../../packages/messaging/package.json';\nimport { name as messagingCompatName } from '../../../packages/messaging-compat/package.json';\nimport { name as performanceName } from '../../../packages/performance/package.json';\nimport { name as performanceCompatName } from '../../../packages/performance-compat/package.json';\nimport { name as remoteConfigName } from '../../../packages/remote-config/package.json';\nimport { name as remoteConfigCompatName } from '../../../packages/remote-config-compat/package.json';\nimport { name as storageName } from '../../../packages/storage/package.json';\nimport { name as storageCompatName } from '../../../packages/storage-compat/package.json';\nimport { name as firestoreName } from '../../../packages/firestore/package.json';\nimport { name as firestoreCompatName } from '../../../packages/firestore-compat/package.json';\nimport { name as packageName } from '../../../packages/firebase/package.json';\n\n/**\n * The default app name\n *\n * @internal\n */\nexport const DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\nexport const PLATFORM_LOG_STRING = {\n [appName]: 'fire-core',\n [appCompatName]: 'fire-core-compat',\n [analyticsName]: 'fire-analytics',\n [analyticsCompatName]: 'fire-analytics-compat',\n [appCheckName]: 'fire-app-check',\n [appCheckCompatName]: 'fire-app-check-compat',\n [authName]: 'fire-auth',\n [authCompatName]: 'fire-auth-compat',\n [databaseName]: 'fire-rtdb',\n [databaseCompatName]: 'fire-rtdb-compat',\n [functionsName]: 'fire-fn',\n [functionsCompatName]: 'fire-fn-compat',\n [installationsName]: 'fire-iid',\n [installationsCompatName]: 'fire-iid-compat',\n [messagingName]: 'fire-fcm',\n [messagingCompatName]: 'fire-fcm-compat',\n [performanceName]: 'fire-perf',\n [performanceCompatName]: 'fire-perf-compat',\n [remoteConfigName]: 'fire-rc',\n [remoteConfigCompatName]: 'fire-rc-compat',\n [storageName]: 'fire-gcs',\n [storageCompatName]: 'fire-gcs-compat',\n [firestoreName]: 'fire-fst',\n [firestoreCompatName]: 'fire-fst-compat',\n 'fire-js': 'fire-js', // Platform identifier for JS SDK.\n [packageName]: 'fire-js-all'\n} as const;\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from './public-types';\nimport { Component, Provider, Name } from '@firebase/component';\nimport { logger } from './logger';\nimport { DEFAULT_ENTRY_NAME } from './constants';\nimport { FirebaseAppImpl } from './firebaseApp';\n\n/**\n * @internal\n */\nexport const _apps = new Map<string, FirebaseApp>();\n\n/**\n * Registered components.\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const _components = new Map<string, Component<any>>();\n\n/**\n * @param component - the component being added to this app's container\n *\n * @internal\n */\nexport function _addComponent<T extends Name>(\n app: FirebaseApp,\n component: Component<T>\n): void {\n try {\n (app as FirebaseAppImpl).container.addComponent(component);\n } catch (e) {\n logger.debug(\n `Component ${component.name} failed to register with FirebaseApp ${app.name}`,\n e\n );\n }\n}\n\n/**\n *\n * @internal\n */\nexport function _addOrOverwriteComponent(\n app: FirebaseApp,\n component: Component\n): void {\n (app as FirebaseAppImpl).container.addOrOverwriteComponent(component);\n}\n\n/**\n *\n * @param component - the component to register\n * @returns whether or not the component is registered successfully\n *\n * @internal\n */\nexport function _registerComponent<T extends Name>(\n component: Component<T>\n): boolean {\n const componentName = component.name;\n if (_components.has(componentName)) {\n logger.debug(\n `There were multiple attempts to register component ${componentName}.`\n );\n\n return false;\n }\n\n _components.set(componentName, component);\n\n // add the component to existing app instances\n for (const app of _apps.values()) {\n _addComponent(app as FirebaseAppImpl, component);\n }\n\n return true;\n}\n\n/**\n *\n * @param app - FirebaseApp instance\n * @param name - service name\n *\n * @returns the provider for the service with the matching name\n *\n * @internal\n */\nexport function _getProvider<T extends Name>(\n app: FirebaseApp,\n name: T\n): Provider<T> {\n const heartbeatController = (app as FirebaseAppImpl).container\n .getProvider('heartbeat')\n .getImmediate({ optional: true });\n if (heartbeatController) {\n void heartbeatController.triggerHeartbeat();\n }\n return (app as FirebaseAppImpl).container.getProvider(name);\n}\n\n/**\n *\n * @param app - FirebaseApp instance\n * @param name - service name\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\n *\n * @internal\n */\nexport function _removeServiceInstance<T extends Name>(\n app: FirebaseApp,\n name: T,\n instanceIdentifier: string = DEFAULT_ENTRY_NAME\n): void {\n _getProvider(app, name).clearInstance(instanceIdentifier);\n}\n\n/**\n * Test only\n *\n * @internal\n */\nexport function _clearComponents(): void {\n _components.clear();\n}\n\n/**\n * Exported in order to be used in app-compat package\n */\nexport { DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME };\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AppError {\n NO_APP = 'no-app',\n BAD_APP_NAME = 'bad-app-name',\n DUPLICATE_APP = 'duplicate-app',\n APP_DELETED = 'app-deleted',\n NO_OPTIONS = 'no-options',\n INVALID_APP_ARGUMENT = 'invalid-app-argument',\n INVALID_LOG_ARGUMENT = 'invalid-log-argument',\n IDB_OPEN = 'idb-open',\n IDB_GET = 'idb-get',\n IDB_WRITE = 'idb-set',\n IDB_DELETE = 'idb-delete'\n}\n\nconst ERRORS: ErrorMap<AppError> = {\n [AppError.NO_APP]:\n \"No Firebase App '{$appName}' has been created - \" +\n 'call initializeApp() first',\n [AppError.BAD_APP_NAME]: \"Illegal App name: '{$appName}\",\n [AppError.DUPLICATE_APP]:\n \"Firebase App named '{$appName}' already exists with different options or config\",\n [AppError.APP_DELETED]: \"Firebase App named '{$appName}' already deleted\",\n [AppError.NO_OPTIONS]:\n 'Need to provide options, when not being deployed to hosting via source.',\n [AppError.INVALID_APP_ARGUMENT]:\n 'firebase.{$appName}() takes either no argument or a ' +\n 'Firebase App instance.',\n [AppError.INVALID_LOG_ARGUMENT]:\n 'First argument to `onLog` must be null or a function.',\n [AppError.IDB_OPEN]:\n 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_GET]:\n 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_WRITE]:\n 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_DELETE]:\n 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.'\n};\n\ninterface ErrorParams {\n [AppError.NO_APP]: { appName: string };\n [AppError.BAD_APP_NAME]: { appName: string };\n [AppError.DUPLICATE_APP]: { appName: string };\n [AppError.APP_DELETED]: { appName: string };\n [AppError.INVALID_APP_ARGUMENT]: { appName: string };\n [AppError.IDB_OPEN]: { originalErrorMessage?: string };\n [AppError.IDB_GET]: { originalErrorMessage?: string };\n [AppError.IDB_WRITE]: { originalErrorMessage?: string };\n [AppError.IDB_DELETE]: { originalErrorMessage?: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<AppError, ErrorParams>(\n 'app',\n 'Firebase',\n ERRORS\n);\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseApp,\n FirebaseOptions,\n FirebaseAppSettings\n} from './public-types';\nimport {\n ComponentContainer,\n Component,\n ComponentType\n} from '@firebase/component';\nimport { ERROR_FACTORY, AppError } from './errors';\n\nexport class FirebaseAppImpl implements FirebaseApp {\n private readonly _options: FirebaseOptions;\n private readonly _name: string;\n /**\n * Original config values passed in as a constructor parameter.\n * It is only used to compare with another config object to support idempotent initializeApp().\n *\n * Updating automaticDataCollectionEnabled on the App instance will not change its value in _config.\n */\n private readonly _config: Required<FirebaseAppSettings>;\n private _automaticDataCollectionEnabled: boolean;\n private _isDeleted = false;\n private readonly _container: ComponentContainer;\n\n constructor(\n options: FirebaseOptions,\n config: Required<FirebaseAppSettings>,\n container: ComponentContainer\n ) {\n this._options = { ...options };\n this._config = { ...config };\n this._name = config.name;\n this._automaticDataCollectionEnabled =\n config.automaticDataCollectionEnabled;\n this._container = container;\n this.container.addComponent(\n new Component('app', () => this, ComponentType.PUBLIC)\n );\n }\n\n get automaticDataCollectionEnabled(): boolean {\n this.checkDestroyed();\n return this._automaticDataCollectionEnabled;\n }\n\n set automaticDataCollectionEnabled(val: boolean) {\n this.checkDestroyed();\n this._automaticDataCollectionEnabled = val;\n }\n\n get name(): string {\n this.checkDestroyed();\n return this._name;\n }\n\n get options(): FirebaseOptions {\n this.checkDestroyed();\n return this._options;\n }\n\n get config(): Required<FirebaseAppSettings> {\n this.checkDestroyed();\n return this._config;\n }\n\n get container(): ComponentContainer {\n return this._container;\n }\n\n get isDeleted(): boolean {\n return this._isDeleted;\n }\n\n set isDeleted(val: boolean) {\n this._isDeleted = val;\n }\n\n /**\n * This function will throw an Error if the App has already been deleted -\n * use before performing API actions on the App.\n */\n private checkDestroyed(): void {\n if (this.isDeleted) {\n throw ERROR_FACTORY.create(AppError.APP_DELETED, { appName: this._name });\n }\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseApp,\n FirebaseOptions,\n FirebaseAppSettings\n} from './public-types';\nimport { DEFAULT_ENTRY_NAME, PLATFORM_LOG_STRING } from './constants';\nimport { ERROR_FACTORY, AppError } from './errors';\nimport {\n ComponentContainer,\n Component,\n Name,\n ComponentType\n} from '@firebase/component';\nimport { version } from '../../firebase/package.json';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { _apps, _components, _registerComponent } from './internal';\nimport { logger } from './logger';\nimport {\n LogLevelString,\n setLogLevel as setLogLevelImpl,\n LogCallback,\n LogOptions,\n setUserLogHandler\n} from '@firebase/logger';\nimport { deepEqual, getDefaultAppConfig } from '@firebase/util';\n\nexport { FirebaseError } from '@firebase/util';\n\n/**\n * The current SDK version.\n *\n * @public\n */\nexport const SDK_VERSION = version;\n\n/**\n * Creates and initializes a {@link @firebase/app#FirebaseApp} instance.\n *\n * See\n * {@link\n * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app\n * | Add Firebase to your app} and\n * {@link\n * https://firebase.google.com/docs/web/setup#multiple-projects\n * | Initialize multiple projects} for detailed documentation.\n *\n * @example\n * ```javascript\n *\n * // Initialize default app\n * // Retrieve your own options values by adding a web app on\n * // https://console.firebase.google.com\n * initializeApp({\n * apiKey: \"AIza....\", // Auth / General Use\n * authDomain: \"YOUR_APP.firebaseapp.com\", // Auth with popup/redirect\n * databaseURL: \"https://YOUR_APP.firebaseio.com\", // Realtime Database\n * storageBucket: \"YOUR_APP.appspot.com\", // Storage\n * messagingSenderId: \"123456789\" // Cloud Messaging\n * });\n * ```\n *\n * @example\n * ```javascript\n *\n * // Initialize another app\n * const otherApp = initializeApp({\n * databaseURL: \"https://<OTHER_DATABASE_NAME>.firebaseio.com\",\n * storageBucket: \"<OTHER_STORAGE_BUCKET>.appspot.com\"\n * }, \"otherApp\");\n * ```\n *\n * @param options - Options to configure the app's services.\n * @param name - Optional name of the app to initialize. If no name\n * is provided, the default is `\"[DEFAULT]\"`.\n *\n * @returns The initialized app.\n *\n * @public\n */\nexport function initializeApp(\n options: FirebaseOptions,\n name?: string\n): FirebaseApp;\n/**\n * Creates and initializes a FirebaseApp instance.\n *\n * @param options - Options to configure the app's services.\n * @param config - FirebaseApp Configuration\n *\n * @public\n */\nexport function initializeApp(\n options: FirebaseOptions,\n config?: FirebaseAppSettings\n): FirebaseApp;\n/**\n * Creates and initializes a FirebaseApp instance.\n *\n * @public\n */\nexport function initializeApp(): FirebaseApp;\nexport function initializeApp(\n _options?: FirebaseOptions,\n rawConfig = {}\n): FirebaseApp {\n let options = _options;\n\n if (typeof rawConfig !== 'object') {\n const name = rawConfig;\n rawConfig = { name };\n }\n\n const config: Required<FirebaseAppSettings> = {\n name: DEFAULT_ENTRY_NAME,\n automaticDataCollectionEnabled: false,\n ...rawConfig\n };\n const name = config.name;\n\n if (typeof name !== 'string' || !name) {\n throw ERROR_FACTORY.create(AppError.BAD_APP_NAME, {\n appName: String(name)\n });\n }\n\n options ||= getDefaultAppConfig();\n\n if (!options) {\n throw ERROR_FACTORY.create(AppError.NO_OPTIONS);\n }\n\n const existingApp = _apps.get(name) as FirebaseAppImpl;\n if (existingApp) {\n // return the existing app if options and config deep equal the ones in the existing app.\n if (\n deepEqual(options, existingApp.options) &&\n deepEqual(config, existingApp.config)\n ) {\n return existingApp;\n } else {\n throw ERROR_FACTORY.create(AppError.DUPLICATE_APP, { appName: name });\n }\n }\n\n const container = new ComponentContainer(name);\n for (const component of _components.values()) {\n container.addComponent(component);\n }\n\n const newApp = new FirebaseAppImpl(options, config, container);\n\n _apps.set(name, newApp);\n\n return newApp;\n}\n\n/**\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\n *\n * When called with no arguments, the default app is returned. When an app name\n * is provided, the app corresponding to that name is returned.\n *\n * An exception is thrown if the app being retrieved has not yet been\n * initialized.\n *\n * @example\n * ```javascript\n * // Return the default app\n * const app = getApp();\n * ```\n *\n * @example\n * ```javascript\n * // Return a named app\n * const otherApp = getApp(\"otherApp\");\n * ```\n *\n * @param name - Optional name of the app to return. If no name is\n * provided, the default is `\"[DEFAULT]\"`.\n *\n * @returns The app corresponding to the provided app name.\n * If no app name is provided, the default app is returned.\n *\n * @public\n */\nexport function getApp(name: string = DEFAULT_ENTRY_NAME): FirebaseApp {\n const app = _apps.get(name);\n if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {\n return initializeApp();\n }\n if (!app) {\n throw ERROR_FACTORY.create(AppError.NO_APP, { appName: name });\n }\n\n return app;\n}\n\n/**\n * A (read-only) array of all initialized apps.\n * @public\n */\nexport function getApps(): FirebaseApp[] {\n return Array.from(_apps.values());\n}\n\n/**\n * Renders this app unusable and frees the resources of all associated\n * services.\n *\n * @example\n * ```javascript\n * deleteApp(app)\n * .then(function() {\n * console.log(\"App deleted successfully\");\n * })\n * .catch(function(error) {\n * console.log(\"Error deleting app:\", error);\n * });\n * ```\n *\n * @public\n */\nexport async function deleteApp(app: FirebaseApp): Promise<void> {\n const name = app.name;\n if (_apps.has(name)) {\n _apps.delete(name);\n await Promise.all(\n (app as FirebaseAppImpl).container\n .getProviders()\n .map(provider => provider.delete())\n );\n (app as FirebaseAppImpl).isDeleted = true;\n }\n}\n\n/**\n * Registers a library's name and version for platform logging purposes.\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\n * @param version - Current version of that library.\n * @param variant - Bundle variant, e.g., node, rn, etc.\n *\n * @public\n */\nexport function registerVersion(\n libraryKeyOrName: string,\n version: string,\n variant?: string\n): void {\n // TODO: We can use this check to whitelist strings when/if we set up\n // a good whitelist system.\n let library = PLATFORM_LOG_STRING[libraryKeyOrName] ?? libraryKeyOrName;\n if (variant) {\n library += `-${variant}`;\n }\n const libraryMismatch = library.match(/\\s|\\//);\n const versionMismatch = version.match(/\\s|\\//);\n if (libraryMismatch || versionMismatch) {\n const warning = [\n `Unable to register library \"${library}\" with version \"${version}\":`\n ];\n if (libraryMismatch) {\n warning.push(\n `library name \"${library}\" contains illegal characters (whitespace or \"/\")`\n );\n }\n if (libraryMismatch && versionMismatch) {\n warning.push('and');\n }\n if (versionMismatch) {\n warning.push(\n `version name \"${version}\" contains illegal characters (whitespace or \"/\")`\n );\n }\n logger.warn(warning.join(' '));\n return;\n }\n _registerComponent(\n new Component(\n `${library}-version` as Name,\n () => ({ library, version }),\n ComponentType.VERSION\n )\n );\n}\n\n/**\n * Sets log handler for all Firebase SDKs.\n * @param logCallback - An optional custom log handler that executes user code whenever\n * the Firebase SDK makes a logging call.\n *\n * @public\n */\nexport function onLog(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n if (logCallback !== null && typeof logCallback !== 'function') {\n throw ERROR_FACTORY.create(AppError.INVALID_LOG_ARGUMENT);\n }\n setUserLogHandler(logCallback, options);\n}\n\n/**\n * Sets log level for all Firebase SDKs.\n *\n * All of the log types above the current log level are captured (i.e. if\n * you set the log level to `info`, errors are logged, but `debug` and\n * `verbose` logs are not).\n *\n * @public\n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n setLogLevelImpl(logLevel);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { DBSchema, openDB, IDBPDatabase } from 'idb';\nimport { AppError, ERROR_FACTORY } from './errors';\nimport { FirebaseApp } from './public-types';\nimport { HeartbeatsInIndexedDB } from './types';\nimport { logger } from './logger';\n\nconst DB_NAME = 'firebase-heartbeat-database';\nconst DB_VERSION = 1;\nconst STORE_NAME = 'firebase-heartbeat-store';\n\ninterface AppDB extends DBSchema {\n 'firebase-heartbeat-store': {\n key: string;\n value: HeartbeatsInIndexedDB;\n };\n}\n\nlet dbPromise: Promise<IDBPDatabase<AppDB>> | null = null;\nfunction getDbPromise(): Promise<IDBPDatabase<AppDB>> {\n if (!dbPromise) {\n dbPromise = openDB<AppDB>(DB_NAME, DB_VERSION, {\n upgrade: (db, oldVersion) => {\n // We don't use 'break' in this switch statement, the fall-through\n // behavior is what we want, because if there are multiple versions between\n // the old version and the current version, we want ALL the migrations\n // that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (oldVersion) {\n case 0:\n db.createObjectStore(STORE_NAME);\n }\n }\n }).catch(e => {\n throw ERROR_FACTORY.create(AppError.IDB_OPEN, {\n originalErrorMessage: e.message\n });\n });\n }\n return dbPromise;\n}\n\nexport async function readHeartbeatsFromIndexedDB(\n app: FirebaseApp\n): Promise<HeartbeatsInIndexedDB | undefined> {\n try {\n const db = await getDbPromise();\n const result = await db\n .transaction(STORE_NAME)\n .objectStore(STORE_NAME)\n .get(computeKey(app));\n return result;\n } catch (e) {\n if (e instanceof FirebaseError) {\n logger.warn(e.message);\n } else {\n const idbGetError = ERROR_FACTORY.create(AppError.IDB_GET, {\n originalErrorMessage: (e as Error)?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\n\nexport async function writeHeartbeatsToIndexedDB(\n app: FirebaseApp,\n heartbeatObject: HeartbeatsInIndexedDB\n): Promise<void> {\n try {\n const db = await getDbPromise();\n const tx = db.transaction(STORE_NAME, 'readwrite');\n const objectStore = tx.objectStore(STORE_NAME);\n await objectStore.put(heartbeatObject, computeKey(app));\n await tx.done;\n } catch (e) {\n if (e instanceof FirebaseError) {\n logger.warn(e.message);\n } else {\n const idbGetError = ERROR_FACTORY.create(AppError.IDB_WRITE, {\n originalErrorMessage: (e as Error)?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\n\nfunction computeKey(app: FirebaseApp): string {\n return `${app.name}!${app.options.appId}`;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ComponentContainer } from '@firebase/component';\nimport {\n base64urlEncodeWithoutPadding,\n isIndexedDBAvailable,\n validateIndexedDBOpenable\n} from '@firebase/util';\nimport {\n readHeartbeatsFromIndexedDB,\n writeHeartbeatsToIndexedDB\n} from './indexeddb';\nimport { FirebaseApp } from './public-types';\nimport {\n HeartbeatsByUserAgent,\n HeartbeatService,\n HeartbeatsInIndexedDB,\n HeartbeatStorage,\n SingleDateHeartbeat\n} from './types';\n\nconst MAX_HEADER_BYTES = 1024;\n// 30 days\nconst STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;\n\nexport class HeartbeatServiceImpl implements HeartbeatService {\n /**\n * The persistence layer for heartbeats\n * Leave public for easier testing.\n */\n _storage: HeartbeatStorageImpl;\n\n /**\n * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\n * the header string.\n * Stores one record per date. This will be consolidated into the standard\n * format of one record per user agent string before being sent as a header.\n * Populated from indexedDB when the controller is instantiated and should\n * be kept in sync with indexedDB.\n * Leave public for easier testing.\n */\n _heartbeatsCache: HeartbeatsInIndexedDB | null = null;\n\n /**\n * the initialization promise for populating heartbeatCache.\n * If getHeartbeatsHeader() is called before the promise resolves\n * (hearbeatsCache == null), it should wait for this promise\n * Leave public for easier testing.\n */\n _heartbeatsCachePromise: Promise<HeartbeatsInIndexedDB>;\n constructor(private readonly container: ComponentContainer) {\n const app = this.container.getProvider('app').getImmediate();\n this._storage = new HeartbeatStorageImpl(app);\n this._heartbeatsCachePromise = this._storage.read().then(result => {\n this._heartbeatsCache = result;\n return result;\n });\n }\n\n /**\n * Called to report a heartbeat. The function will generate\n * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\n * to IndexedDB.\n * Note that we only store one heartbeat per day. So if a heartbeat for today is\n * already logged, subsequent calls to this function in the same day will be ignored.\n */\n async triggerHeartbeat(): Promise<void> {\n const platformLogger = this.container\n .getProvider('platform-logger')\n .getImmediate();\n\n // This is the \"Firebase user agent\" string from the platform logger\n // service, not the browser user agent.\n const agent = platformLogger.getPlatformInfoString();\n const date = getUTCDateString();\n if (this._heartbeatsCache?.heartbeats == null) {\n this._heartbeatsCache = await this._heartbeatsCachePromise;\n }\n // Do not store a heartbeat if one is already stored for this day\n // or if a header has already been sent today.\n if (\n this._heartbeatsCache.lastSentHeartbeatDate === date ||\n this._heartbeatsCache.heartbeats.some(\n singleDateHeartbeat => singleDateHeartbeat.date === date\n )\n ) {\n return;\n } else {\n // There is no entry for this date. Create one.\n this._heartbeatsCache.heartbeats.push({ date, agent });\n }\n // Remove entries older than 30 days.\n this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(\n singleDateHeartbeat => {\n const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\n const now = Date.now();\n return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\n }\n );\n return this._storage.overwrite(this._heartbeatsCache);\n }\n\n /**\n * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\n * It also clears all heartbeats from memory as well as in IndexedDB.\n *\n * NOTE: Consuming product SDKs should not send the header if this method\n * returns an empty string.\n */\n async getHeartbeatsHeader(): Promise<string> {\n if (this._heartbeatsCache === null) {\n await this._heartbeatsCachePromise;\n }\n // If it's still null or the array is empty, there is no data to send.\n if (\n this._heartbeatsCache?.heartbeats == null ||\n this._heartbeatsCache.heartbeats.length === 0\n ) {\n return '';\n }\n const date = getUTCDateString();\n // Extract as many heartbeats from the cache as will fit under the size limit.\n const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(\n this._heartbeatsCache.heartbeats\n );\n const headerString = base64urlEncodeWithoutPadding(\n JSON.stringify({ version: 2, heartbeats: heartbeatsToSend })\n );\n // Store last sent date to prevent another being logged/sent for the same day.\n this._heartbeatsCache.lastSentHeartbeatDate = date;\n if (unsentEntries.length > 0) {\n // Store any unsent entries if they exist.\n this._heartbeatsCache.heartbeats = unsentEntries;\n // This seems more likely than emptying the array (below) to lead to some odd state\n // since the cache isn't empty and this will be called again on the next request,\n // and is probably safest if we await it.\n await this._storage.overwrite(this._heartbeatsCache);\n } else {\n this._heartbeatsCache.heartbeats = [];\n // Do not wait for this, to reduce latency.\n void this._storage.overwrite(this._heartbeatsCache);\n }\n return headerString;\n }\n}\n\nfunction getUTCDateString(): string {\n const today = new Date();\n // Returns date format 'YYYY-MM-DD'\n return today.toISOString().substring(0, 10);\n}\n\nexport function extractHeartbeatsForHeader(\n heartbeatsCache: SingleDateHeartbeat[],\n maxSize = MAX_HEADER_BYTES\n): {\n heartbeatsToSend: HeartbeatsByUserAgent[];\n unsentEntries: SingleDateHeartbeat[];\n} {\n // Heartbeats grouped by user agent in the standard format to be sent in\n // the header.\n const heartbeatsToSend: HeartbeatsByUserAgent[] = [];\n // Single date format heartbeats that are not sent.\n let unsentEntries = heartbeatsCache.slice();\n for (const singleDateHeartbeat of heartbeatsCache) {\n // Look for an existing entry with the same user agent.\n const heartbeatEntry = heartbeatsToSend.find(\n hb => hb.agent === singleDateHeartbeat.agent\n );\n if (!heartbeatEntry) {\n // If no entry for this user agent exists, create one.\n heartbeatsToSend.push({\n agent: singleDateHeartbeat.agent,\n dates: [singleDateHeartbeat.date]\n });\n if (countBytes(heartbeatsToSend) > maxSize) {\n // If the header would exceed max size, remove the added heartbeat\n // entry and stop adding to the header.\n heartbeatsToSend.pop();\n break;\n }\n } else {\n heartbeatEntry.dates.push(singleDateHeartbeat.date);\n // If the header would exceed max size, remove the added date\n // and stop adding to the header.\n if (countBytes(heartbeatsToSend) > maxSize) {\n heartbeatEntry.dates.pop();\n break;\n }\n }\n // Pop unsent entry from queue. (Skipped if adding the entry exceeded\n // quota and the loop breaks early.)\n unsentEntries = unsentEntries.slice(1);\n }\n return {\n heartbeatsToSend,\n unsentEntries\n };\n}\n\nexport class HeartbeatStorageImpl implements HeartbeatStorage {\n private _canUseIndexedDBPromise: Promise<boolean>;\n constructor(public app: FirebaseApp) {\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\n }\n async runIndexedDBEnvironmentCheck(): Promise<boolean> {\n if (!isIndexedDBAvailable()) {\n return false;\n } else {\n return validateIndexedDBOpenable()\n .then(() => true)\n .catch(() => false);\n }\n }\n /**\n * Read all heartbeats.\n */\n async read(): Promise<HeartbeatsInIndexedDB> {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return { heartbeats: [] };\n } else {\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\n return idbHeartbeatObject || { heartbeats: [] };\n }\n }\n // overwrite the storage with the provided heartbeats\n async overwrite(heartbeatsObject: HeartbeatsInIndexedDB): Promise<void> {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n } else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate:\n heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: heartbeatsObject.heartbeats\n });\n }\n }\n // add heartbeats\n async add(heartbeatsObject: HeartbeatsInIndexedDB): Promise<void> {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n } else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate:\n heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: [\n ...existingHeartbeatsObject.heartbeats,\n ...heartbeatsObject.heartbeats\n ]\n });\n }\n }\n}\n\n/**\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\n * in a platform logging header JSON object, stringified, and converted\n * to base 64.\n */\nexport function countBytes(heartbeatsCache: HeartbeatsByUserAgent[]): number {\n // base64 has a restricted set of characters, all of which should be 1 byte.\n return base64urlEncodeWithoutPadding(\n // heartbeatsCache wrapper properties\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })\n ).length;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Component, ComponentType } from '@firebase/component';\nimport { PlatformLoggerServiceImpl } from './platformLoggerService';\nimport { name, version } from '../package.json';\nimport { _registerComponent } from './internal';\nimport { registerVersion } from './api';\nimport { HeartbeatServiceImpl } from './heartbeatService';\n\nexport function registerCoreComponents(variant?: string): void {\n _registerComponent(\n new Component(\n 'platform-logger',\n container => new PlatformLoggerServiceImpl(container),\n ComponentType.PRIVATE\n )\n );\n _registerComponent(\n new Component(\n 'heartbeat',\n container => new HeartbeatServiceImpl(container),\n ComponentType.PRIVATE\n )\n );\n\n // Register `app` package.\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n // Register platform SDK identifier (no version).\n registerVersion('fire-js', '');\n}\n","/**\n * Firebase App\n *\n * @remarks This package coordinates the communication between the different Firebase components\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerCoreComponents } from './registerCoreComponents';\n\nexport * from './api';\nexport * from './internal';\nexport * from './public-types';\n\nregisterCoreComponents('__RUNTIME_ENV__');\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { registerVersion } from '@firebase/app';\nimport { name, version } from '../package.json';\n\nregisterVersion(name, version, 'app');\nexport * from '@firebase/app';\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));\n });\n }\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking)\n db.addEventListener('versionchange', () => blocking());\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { version } from '../../package.json';\n\nexport const PENDING_TIMEOUT_MS = 10000;\n\nexport const PACKAGE_VERSION = `w:${version}`;\nexport const INTERNAL_AUTH_VERSION = 'FIS_v2';\n\nexport const INSTALLATIONS_API_URL =\n 'https://firebaseinstallations.googleapis.com/v1';\n\nexport const TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour\n\nexport const SERVICE = 'installations';\nexport const SERVICE_NAME = 'Installations';\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { SERVICE, SERVICE_NAME } from './constants';\n\nexport const enum ErrorCode {\n MISSING_APP_CONFIG_VALUES = 'missing-app-config-values',\n NOT_REGISTERED = 'not-registered',\n INSTALLATION_NOT_FOUND = 'installation-not-found',\n REQUEST_FAILED = 'request-failed',\n APP_OFFLINE = 'app-offline',\n DELETE_PENDING_REGISTRATION = 'delete-pending-registration'\n}\n\nconst ERROR_DESCRIPTION_MAP: { readonly [key in ErrorCode]: string } = {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]:\n 'Missing App configuration value: \"{$valueName}\"',\n [ErrorCode.NOT_REGISTERED]: 'Firebase Installation is not registered.',\n [ErrorCode.INSTALLATION_NOT_FOUND]: 'Firebase Installation not found.',\n [ErrorCode.REQUEST_FAILED]:\n '{$requestName} request failed with error \"{$serverCode} {$serverStatus}: {$serverMessage}\"',\n [ErrorCode.APP_OFFLINE]: 'Could not process request. Application offline.',\n [ErrorCode.DELETE_PENDING_REGISTRATION]:\n \"Can't delete installation while there is a pending registration request.\"\n};\n\ninterface ErrorParams {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]: {\n valueName: string;\n };\n [ErrorCode.REQUEST_FAILED]: {\n requestName: string;\n [index: string]: string | number; // to make Typescript 3.8 happy\n } & ServerErrorData;\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<ErrorCode, ErrorParams>(\n SERVICE,\n SERVICE_NAME,\n ERROR_DESCRIPTION_MAP\n);\n\nexport interface ServerErrorData {\n serverCode: number;\n serverMessage: string;\n serverStatus: string;\n}\n\nexport type ServerError = FirebaseError & { customData: ServerErrorData };\n\n/** Returns true if error is a FirebaseError that is based on an error from the server. */\nexport function isServerError(error: unknown): error is ServerError {\n return (\n error instanceof FirebaseError &&\n error.code.includes(ErrorCode.REQUEST_FAILED)\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { GenerateAuthTokenResponse } from '../interfaces/api-response';\nimport {\n CompletedAuthToken,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport {\n INSTALLATIONS_API_URL,\n INTERNAL_AUTH_VERSION\n} from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport { AppConfig } from '../interfaces/installation-impl';\n\nexport function getInstallationsEndpoint({ projectId }: AppConfig): string {\n return `${INSTALLATIONS_API_URL}/projects/${projectId}/installations`;\n}\n\nexport function extractAuthTokenInfoFromResponse(\n response: GenerateAuthTokenResponse\n): CompletedAuthToken {\n return {\n token: response.token,\n requestStatus: RequestStatus.COMPLETED,\n expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),\n creationTime: Date.now()\n };\n}\n\nexport async function getErrorFromResponse(\n requestName: string,\n response: Response\n): Promise<FirebaseError> {\n const responseJson: ErrorResponse = await response.json();\n const errorData = responseJson.error;\n return ERROR_FACTORY.create(ErrorCode.REQUEST_FAILED, {\n requestName,\n serverCode: errorData.code,\n serverMessage: errorData.message,\n serverStatus: errorData.status\n });\n}\n\nexport function getHeaders({ apiKey }: AppConfig): Headers {\n return new Headers({\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'x-goog-api-key': apiKey\n });\n}\n\nexport function getHeadersWithAuth(\n appConfig: AppConfig,\n { refreshToken }: RegisteredInstallationEntry\n): Headers {\n const headers = getHeaders(appConfig);\n headers.append('Authorization', getAuthorizationHeader(refreshToken));\n return headers;\n}\n\nexport interface ErrorResponse {\n error: {\n code: number;\n message: string;\n status: string;\n };\n}\n\n/**\n * Calls the passed in fetch wrapper and returns the response.\n * If the returned response has a status of 5xx, re-runs the function once and\n * returns the response.\n */\nexport async function retryIfServerError(\n fn: () => Promise<Response>\n): Promise<Response> {\n const result = await fn();\n\n if (result.status >= 500 && result.status < 600) {\n // Internal Server Error. Retry request.\n return fn();\n }\n\n return result;\n}\n\nfunction getExpiresInFromResponseExpiresIn(responseExpiresIn: string): number {\n // This works because the server will never respond with fractions of a second.\n return Number(responseExpiresIn.replace('s', '000'));\n}\n\nfunction getAuthorizationHeader(refreshToken: string): string {\n return `${INTERNAL_AUTH_VERSION} ${refreshToken}`;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Returns a promise that resolves after given time passes. */\nexport function sleep(ms: number): Promise<void> {\n return new Promise<void>(resolve => {\n setTimeout(resolve, ms);\n });\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bufferToBase64UrlSafe } from './buffer-to-base64-url-safe';\n\nexport const VALID_FID_PATTERN = /^[cdef][\\w-]{21}$/;\nexport const INVALID_FID = '';\n\n/**\n * Generates a new FID using random values from Web Crypto API.\n * Returns an empty string if FID generation fails for any reason.\n */\nexport function generateFid(): string {\n try {\n // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5\n // bytes. our implementation generates a 17 byte array instead.\n const fidByteArray = new Uint8Array(17);\n const crypto =\n self.crypto || (self as unknown as { msCrypto: Crypto }).msCrypto;\n crypto.getRandomValues(fidByteArray);\n\n // Replace the first 4 random bits with the constant FID header of 0b0111.\n fidByteArray[0] = 0b01110000 + (fidByteArray[0] % 0b00010000);\n\n const fid = encode(fidByteArray);\n\n return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;\n } catch {\n // FID generation errored\n return INVALID_FID;\n }\n}\n\n/** Converts a FID Uint8Array to a base64 string representation. */\nfunction encode(fidByteArray: Uint8Array): string {\n const b64String = bufferToBase64UrlSafe(fidByteArray);\n\n // Remove the 23rd character that was added because of the extra 4 bits at the\n // end of our 17 byte array, and the '=' padding.\n return b64String.substr(0, 22);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function bufferToBase64UrlSafe(array: Uint8Array): string {\n const b64 = btoa(String.fromCharCode(...array));\n return b64.replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppConfig } from '../interfaces/installation-impl';\n\n/** Returns a string key that can be used to identify the app. */\nexport function getKey(appConfig: AppConfig): string {\n return `${appConfig.appName}!${appConfig.appId}`;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getKey } from '../util/get-key';\nimport { AppConfig } from '../interfaces/installation-impl';\nimport { IdChangeCallbackFn } from '../api';\n\nconst fidChangeCallbacks: Map<string, Set<IdChangeCallbackFn>> = new Map();\n\n/**\n * Calls the onIdChange callbacks with the new FID value, and broadcasts the\n * change to other tabs.\n */\nexport function fidChanged(appConfig: AppConfig, fid: string): void {\n const key = getKey(appConfig);\n\n callFidChangeCallbacks(key, fid);\n broadcastFidChange(key, fid);\n}\n\nexport function addCallback(\n appConfig: AppConfig,\n callback: IdChangeCallbackFn\n): void {\n // Open the broadcast channel if it's not already open,\n // to be able to listen to change events from other tabs.\n getBroadcastChannel();\n\n const key = getKey(appConfig);\n\n let callbackSet = fidChangeCallbacks.get(key);\n if (!callbackSet) {\n callbackSet = new Set();\n fidChangeCallbacks.set(key, callbackSet);\n }\n callbackSet.add(callback);\n}\n\nexport function removeCallback(\n appConfig: AppConfig,\n callback: IdChangeCallbackFn\n): void {\n const key = getKey(appConfig);\n\n const callbackSet = fidChangeCallbacks.get(key);\n\n if (!callbackSet) {\n return;\n }\n\n callbackSet.delete(callback);\n if (callbackSet.size === 0) {\n fidChangeCallbacks.delete(key);\n }\n\n // Close broadcast channel if there are no more callbacks.\n closeBroadcastChannel();\n}\n\nfunction callFidChangeCallbacks(key: string, fid: string): void {\n const callbacks = fidChangeCallbacks.get(key);\n if (!callbacks) {\n return;\n }\n\n for (const callback of callbacks) {\n callback(fid);\n }\n}\n\nfunction broadcastFidChange(key: string, fid: string): void {\n const channel = getBroadcastChannel();\n if (channel) {\n channel.postMessage({ key, fid });\n }\n closeBroadcastChannel();\n}\n\nlet broadcastChannel: BroadcastChannel | null = null;\n/** Opens and returns a BroadcastChannel if it is supported by the browser. */\nfunction getBroadcastChannel(): BroadcastChannel | null {\n if (!broadcastChannel && 'BroadcastChannel' in self) {\n broadcastChannel = new BroadcastChannel('[Firebase] FID Change');\n broadcastChannel.onmessage = e => {\n callFidChangeCallbacks(e.data.key, e.data.fid);\n };\n }\n return broadcastChannel;\n}\n\nfunction closeBroadcastChannel(): void {\n if (fidChangeCallbacks.size === 0 && broadcastChannel) {\n broadcastChannel.close();\n broadcastChannel = null;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DBSchema, IDBPDatabase, openDB } from 'idb';\nimport { AppConfig } from '../interfaces/installation-impl';\nimport { InstallationEntry } from '../interfaces/installation-entry';\nimport { getKey } from '../util/get-key';\nimport { fidChanged } from './fid-changed';\n\nconst DATABASE_NAME = 'firebase-installations-database';\nconst DATABASE_VERSION = 1;\nconst OBJECT_STORE_NAME = 'firebase-installations-store';\n\ninterface InstallationsDB extends DBSchema {\n 'firebase-installations-store': {\n key: string;\n value: InstallationEntry | undefined;\n };\n}\n\nlet dbPromise: Promise<IDBPDatabase<InstallationsDB>> | null = null;\nfunction getDbPromise(): Promise<IDBPDatabase<InstallationsDB>> {\n if (!dbPromise) {\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\n upgrade: (db, oldVersion) => {\n // We don't use 'break' in this switch statement, the fall-through\n // behavior is what we want, because if there are multiple versions between\n // the old version and the current version, we want ALL the migrations\n // that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (oldVersion) {\n case 0:\n db.createObjectStore(OBJECT_STORE_NAME);\n }\n }\n });\n }\n return dbPromise;\n}\n\n/** Gets record(s) from the objectStore that match the given key. */\nexport async function get(\n appConfig: AppConfig\n): Promise<InstallationEntry | undefined> {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n return db\n .transaction(OBJECT_STORE_NAME)\n .objectStore(OBJECT_STORE_NAME)\n .get(key) as Promise<InstallationEntry>;\n}\n\n/** Assigns or overwrites the record for the given key with the given value. */\nexport async function set<ValueType extends InstallationEntry>(\n appConfig: AppConfig,\n value: ValueType\n): Promise<ValueType> {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n const objectStore = tx.objectStore(OBJECT_STORE_NAME);\n const oldValue = (await objectStore.get(key)) as InstallationEntry;\n await objectStore.put(value, key);\n await tx.done;\n\n if (!oldValue || oldValue.fid !== value.fid) {\n fidChanged(appConfig, value.fid);\n }\n\n return value;\n}\n\n/** Removes record(s) from the objectStore that match the given key. */\nexport async function remove(appConfig: AppConfig): Promise<void> {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\n await tx.done;\n}\n\n/**\n * Atomically updates a record with the result of updateFn, which gets\n * called with the current value. If newValue is undefined, the record is\n * deleted instead.\n * @return Updated value\n */\nexport async function update<ValueType extends InstallationEntry | undefined>(\n appConfig: AppConfig,\n updateFn: (previousValue: InstallationEntry | undefined) => ValueType\n): Promise<ValueType> {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n const store = tx.objectStore(OBJECT_STORE_NAME);\n const oldValue: InstallationEntry | undefined = (await store.get(\n key\n )) as InstallationEntry;\n const newValue = updateFn(oldValue);\n\n if (newValue === undefined) {\n await store.delete(key);\n } else {\n await store.put(newValue, key);\n }\n await tx.done;\n\n if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {\n fidChanged(appConfig, newValue.fid);\n }\n\n return newValue;\n}\n\nexport async function clear(): Promise<void> {\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n await tx.objectStore(OBJECT_STORE_NAME).clear();\n await tx.done;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createInstallationRequest } from '../functions/create-installation-request';\nimport {\n AppConfig,\n FirebaseInstallationsImpl\n} from '../interfaces/installation-impl';\nimport {\n InProgressInstallationEntry,\n InstallationEntry,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport { PENDING_TIMEOUT_MS } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode, isServerError } from '../util/errors';\nimport { sleep } from '../util/sleep';\nimport { generateFid, INVALID_FID } from './generate-fid';\nimport { remove, set, update } from './idb-manager';\n\nexport interface InstallationEntryWithRegistrationPromise {\n installationEntry: InstallationEntry;\n /** Exist iff the installationEntry is not registered. */\n registrationPromise?: Promise<RegisteredInstallationEntry>;\n}\n\n/**\n * Updates and returns the InstallationEntry from the database.\n * Also triggers a registration request if it is necessary and possible.\n */\nexport async function getInstallationEntry(\n installations: FirebaseInstallationsImpl\n): Promise<InstallationEntryWithRegistrationPromise> {\n let registrationPromise: Promise<RegisteredInstallationEntry> | undefined;\n\n const installationEntry = await update(installations.appConfig, oldEntry => {\n const installationEntry = updateOrCreateInstallationEntry(oldEntry);\n const entryWithPromise = triggerRegistrationIfNecessary(\n installations,\n installationEntry\n );\n registrationPromise = entryWithPromise.registrationPromise;\n return entryWithPromise.installationEntry;\n });\n\n if (installationEntry.fid === INVALID_FID) {\n // FID generation failed. Waiting for the FID from the server.\n return { installationEntry: await registrationPromise! };\n }\n\n return {\n installationEntry,\n registrationPromise\n };\n}\n\n/**\n * Creates a new Installation Entry if one does not exist.\n * Also clears timed out pending requests.\n */\nfunction updateOrCreateInstallationEntry(\n oldEntry: InstallationEntry | undefined\n): InstallationEntry {\n const entry: InstallationEntry = oldEntry || {\n fid: generateFid(),\n registrationStatus: RequestStatus.NOT_STARTED\n };\n\n return clearTimedOutRequest(entry);\n}\n\n/**\n * If the Firebase Installation is not registered yet, this will trigger the\n * registration and return an InProgressInstallationEntry.\n *\n * If registrationPromise does not exist, the installationEntry is guaranteed\n * to be registered.\n */\nfunction triggerRegistrationIfNecessary(\n installations: FirebaseInstallationsImpl,\n installationEntry: InstallationEntry\n): InstallationEntryWithRegistrationPromise {\n if (installationEntry.registrationStatus === RequestStatus.NOT_STARTED) {\n if (!navigator.onLine) {\n // Registration required but app is offline.\n const registrationPromiseWithError = Promise.reject(\n ERROR_FACTORY.create(ErrorCode.APP_OFFLINE)\n );\n return {\n installationEntry,\n registrationPromise: registrationPromiseWithError\n };\n }\n\n // Try registering. Change status to IN_PROGRESS.\n const inProgressEntry: InProgressInstallationEntry = {\n fid: installationEntry.fid,\n registrationStatus: RequestStatus.IN_PROGRESS,\n registrationTime: Date.now()\n };\n const registrationPromise = registerInstallation(\n installations,\n inProgressEntry\n );\n return { installationEntry: inProgressEntry, registrationPromise };\n } else if (\n installationEntry.registrationStatus === RequestStatus.IN_PROGRESS\n ) {\n return {\n installationEntry,\n registrationPromise: waitUntilFidRegistration(installations)\n };\n } else {\n return { installationEntry };\n }\n}\n\n/** This will be executed only once for each new Firebase Installation. */\nasync function registerInstallation(\n installations: FirebaseInstallationsImpl,\n installationEntry: InProgressInstallationEntry\n): Promise<RegisteredInstallationEntry> {\n try {\n const registeredInstallationEntry = await createInstallationRequest(\n installations,\n installationEntry\n );\n return set(installations.appConfig, registeredInstallationEntry);\n } catch (e) {\n if (isServerError(e) && e.customData.serverCode === 409) {\n // Server returned a \"FID can not be used\" error.\n // Generate a new ID next time.\n await remove(installations.appConfig);\n } else {\n // Registration failed. Set FID as not registered.\n await set(installations.appConfig, {\n fid: installationEntry.fid,\n registrationStatus: RequestStatus.NOT_STARTED\n });\n }\n throw e;\n }\n}\n\n/** Call if FID registration is pending in another request. */\nasync function waitUntilFidRegistration(\n installations: FirebaseInstallationsImpl\n): Promise<RegisteredInstallationEntry> {\n // Unfortunately, there is no way of reliably observing when a value in\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\n // so we need to poll.\n\n let entry: InstallationEntry = await updateInstallationRequest(\n installations.appConfig\n );\n while (entry.registrationStatus === RequestStatus.IN_PROGRESS) {\n // createInstallation request still in progress.\n await sleep(100);\n\n entry = await updateInstallationRequest(installations.appConfig);\n }\n\n if (entry.registrationStatus === RequestStatus.NOT_STARTED) {\n // The request timed out or failed in a different call. Try again.\n const { installationEntry, registrationPromise } =\n await getInstallationEntry(installations);\n\n if (registrationPromise) {\n return registrationPromise;\n } else {\n // if there is no registrationPromise, entry is registered.\n return installationEntry as RegisteredInstallationEntry;\n }\n }\n\n return entry;\n}\n\n/**\n * Called only if there is a CreateInstallation request in progress.\n *\n * Updates the InstallationEntry in the DB based on the status of the\n * CreateInstallation request.\n *\n * Returns the updated InstallationEntry.\n */\nfunction updateInstallationRequest(\n appConfig: AppConfig\n): Promise<InstallationEntry> {\n return update(appConfig, oldEntry => {\n if (!oldEntry) {\n throw ERROR_FACTORY.create(ErrorCode.INSTALLATION_NOT_FOUND);\n }\n return clearTimedOutRequest(oldEntry);\n });\n}\n\nfunction clearTimedOutRequest(entry: InstallationEntry): InstallationEntry {\n if (hasInstallationRequestTimedOut(entry)) {\n return {\n fid: entry.fid,\n registrationStatus: RequestStatus.NOT_STARTED\n };\n }\n\n return entry;\n}\n\nfunction hasInstallationRequestTimedOut(\n installationEntry: InstallationEntry\n): boolean {\n return (\n installationEntry.registrationStatus === RequestStatus.IN_PROGRESS &&\n installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now()\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CreateInstallationResponse } from '../interfaces/api-response';\nimport {\n InProgressInstallationEntry,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport { INTERNAL_AUTH_VERSION, PACKAGE_VERSION } from '../util/constants';\nimport {\n extractAuthTokenInfoFromResponse,\n getErrorFromResponse,\n getHeaders,\n getInstallationsEndpoint,\n retryIfServerError\n} from './common';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\n\nexport async function createInstallationRequest(\n { appConfig, heartbeatServiceProvider }: FirebaseInstallationsImpl,\n { fid }: InProgressInstallationEntry\n): Promise<RegisteredInstallationEntry> {\n const endpoint = getInstallationsEndpoint(appConfig);\n\n const headers = getHeaders(appConfig);\n\n // If heartbeat service exists, add the heartbeat string to the header.\n const heartbeatService = heartbeatServiceProvider.getImmediate({\n optional: true\n });\n if (heartbeatService) {\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers.append('x-firebase-client', heartbeatsHeader);\n }\n }\n\n const body = {\n fid,\n authVersion: INTERNAL_AUTH_VERSION,\n appId: appConfig.appId,\n sdkVersion: PACKAGE_VERSION\n };\n\n const request: RequestInit = {\n method: 'POST',\n headers,\n body: JSON.stringify(body)\n };\n\n const response = await retryIfServerError(() => fetch(endpoint, request));\n if (response.ok) {\n const responseValue: CreateInstallationResponse = await response.json();\n const registeredInstallationEntry: RegisteredInstallationEntry = {\n fid: responseValue.fid || fid,\n registrationStatus: RequestStatus.COMPLETED,\n refreshToken: responseValue.refreshToken,\n authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)\n };\n return registeredInstallationEntry;\n } else {\n throw await getErrorFromResponse('Create Installation', response);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GenerateAuthTokenResponse } from '../interfaces/api-response';\nimport {\n CompletedAuthToken,\n RegisteredInstallationEntry\n} from '../interfaces/installation-entry';\nimport { PACKAGE_VERSION } from '../util/constants';\nimport {\n extractAuthTokenInfoFromResponse,\n getErrorFromResponse,\n getHeadersWithAuth,\n getInstallationsEndpoint,\n retryIfServerError\n} from './common';\nimport {\n FirebaseInstallationsImpl,\n AppConfig\n} from '../interfaces/installation-impl';\n\nexport async function generateAuthTokenRequest(\n { appConfig, heartbeatServiceProvider }: FirebaseInstallationsImpl,\n installationEntry: RegisteredInstallationEntry\n): Promise<CompletedAuthToken> {\n const endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);\n\n const headers = getHeadersWithAuth(appConfig, installationEntry);\n\n // If heartbeat service exists, add the heartbeat string to the header.\n const heartbeatService = heartbeatServiceProvider.getImmediate({\n optional: true\n });\n if (heartbeatService) {\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers.append('x-firebase-client', heartbeatsHeader);\n }\n }\n\n const body = {\n installation: {\n sdkVersion: PACKAGE_VERSION,\n appId: appConfig.appId\n }\n };\n\n const request: RequestInit = {\n method: 'POST',\n headers,\n body: JSON.stringify(body)\n };\n\n const response = await retryIfServerError(() => fetch(endpoint, request));\n if (response.ok) {\n const responseValue: GenerateAuthTokenResponse = await response.json();\n const completedAuthToken: CompletedAuthToken =\n extractAuthTokenInfoFromResponse(responseValue);\n return completedAuthToken;\n } else {\n throw await getErrorFromResponse('Generate Auth Token', response);\n }\n}\n\nfunction getGenerateAuthTokenEndpoint(\n appConfig: AppConfig,\n { fid }: RegisteredInstallationEntry\n): string {\n return `${getInstallationsEndpoint(appConfig)}/${fid}/authTokens:generate`;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { generateAuthTokenRequest } from '../functions/generate-auth-token-request';\nimport {\n AppConfig,\n FirebaseInstallationsImpl\n} from '../interfaces/installation-impl';\nimport {\n AuthToken,\n CompletedAuthToken,\n InProgressAuthToken,\n InstallationEntry,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport { PENDING_TIMEOUT_MS, TOKEN_EXPIRATION_BUFFER } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode, isServerError } from '../util/errors';\nimport { sleep } from '../util/sleep';\nimport { remove, set, update } from './idb-manager';\n\n/**\n * Returns a valid authentication token for the installation. Generates a new\n * token if one doesn't exist, is expired or about to expire.\n *\n * Should only be called if the Firebase Installation is registered.\n */\nexport async function refreshAuthToken(\n installations: FirebaseInstallationsImpl,\n forceRefresh = false\n): Promise<CompletedAuthToken> {\n let tokenPromise: Promise<CompletedAuthToken> | undefined;\n const entry = await update(installations.appConfig, oldEntry => {\n if (!isEntryRegistered(oldEntry)) {\n throw ERROR_FACTORY.create(ErrorCode.NOT_REGISTERED);\n }\n\n const oldAuthToken = oldEntry.authToken;\n if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {\n // There is a valid token in the DB.\n return oldEntry;\n } else if (oldAuthToken.requestStatus === RequestStatus.IN_PROGRESS) {\n // There already is a token request in progress.\n tokenPromise = waitUntilAuthTokenRequest(installations, forceRefresh);\n return oldEntry;\n } else {\n // No token or token expired.\n if (!navigator.onLine) {\n throw ERROR_FACTORY.create(ErrorCode.APP_OFFLINE);\n }\n\n const inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);\n tokenPromise = fetchAuthTokenFromServer(installations, inProgressEntry);\n return inProgressEntry;\n }\n });\n\n const authToken = tokenPromise\n ? await tokenPromise\n : (entry.authToken as CompletedAuthToken);\n return authToken;\n}\n\n/**\n * Call only if FID is registered and Auth Token request is in progress.\n *\n * Waits until the current pending request finishes. If the request times out,\n * tries once in this thread as well.\n */\nasync function waitUntilAuthTokenRequest(\n installations: FirebaseInstallationsImpl,\n forceRefresh: boolean\n): Promise<CompletedAuthToken> {\n // Unfortunately, there is no way of reliably observing when a value in\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\n // so we need to poll.\n\n let entry = await updateAuthTokenRequest(installations.appConfig);\n while (entry.authToken.requestStatus === RequestStatus.IN_PROGRESS) {\n // generateAuthToken still in progress.\n await sleep(100);\n\n entry = await updateAuthTokenRequest(installations.appConfig);\n }\n\n const authToken = entry.authToken;\n if (authToken.requestStatus === RequestStatus.NOT_STARTED) {\n // The request timed out or failed in a different call. Try again.\n return refreshAuthToken(installations, forceRefresh);\n } else {\n return authToken;\n }\n}\n\n/**\n * Called only if there is a GenerateAuthToken request in progress.\n *\n * Updates the InstallationEntry in the DB based on the status of the\n * GenerateAuthToken request.\n *\n * Returns the updated InstallationEntry.\n */\nfunction updateAuthTokenRequest(\n appConfig: AppConfig\n): Promise<RegisteredInstallationEntry> {\n return update(appConfig, oldEntry => {\n if (!isEntryRegistered(oldEntry)) {\n throw ERROR_FACTORY.create(ErrorCode.NOT_REGISTERED);\n }\n\n const oldAuthToken = oldEntry.authToken;\n if (hasAuthTokenRequestTimedOut(oldAuthToken)) {\n return {\n ...oldEntry,\n authToken: { requestStatus: RequestStatus.NOT_STARTED }\n };\n }\n\n return oldEntry;\n });\n}\n\nasync function fetchAuthTokenFromServer(\n installations: FirebaseInstallationsImpl,\n installationEntry: RegisteredInstallationEntry\n): Promise<CompletedAuthToken> {\n try {\n const authToken = await generateAuthTokenRequest(\n installations,\n installationEntry\n );\n const updatedInstallationEntry: RegisteredInstallationEntry = {\n ...installationEntry,\n authToken\n };\n await set(installations.appConfig, updatedInstallationEntry);\n return authToken;\n } catch (e) {\n if (\n isServerError(e) &&\n (e.customData.serverCode === 401 || e.customData.serverCode === 404)\n ) {\n // Server returned a \"FID not found\" or a \"Invalid authentication\" error.\n // Generate a new ID next time.\n await remove(installations.appConfig);\n } else {\n const updatedInstallationEntry: RegisteredInstallationEntry = {\n ...installationEntry,\n authToken: { requestStatus: RequestStatus.NOT_STARTED }\n };\n await set(installations.appConfig, updatedInstallationEntry);\n }\n throw e;\n }\n}\n\nfunction isEntryRegistered(\n installationEntry: InstallationEntry | undefined\n): installationEntry is RegisteredInstallationEntry {\n return (\n installationEntry !== undefined &&\n installationEntry.registrationStatus === RequestStatus.COMPLETED\n );\n}\n\nfunction isAuthTokenValid(authToken: AuthToken): boolean {\n return (\n authToken.requestStatus === RequestStatus.COMPLETED &&\n !isAuthTokenExpired(authToken)\n );\n}\n\nfunction isAuthTokenExpired(authToken: CompletedAuthToken): boolean {\n const now = Date.now();\n return (\n now < authToken.creationTime ||\n authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER\n );\n}\n\n/** Returns an updated InstallationEntry with an InProgressAuthToken. */\nfunction makeAuthTokenRequestInProgressEntry(\n oldEntry: RegisteredInstallationEntry\n): RegisteredInstallationEntry {\n const inProgressAuthToken: InProgressAuthToken = {\n requestStatus: RequestStatus.IN_PROGRESS,\n requestTime: Date.now()\n };\n return {\n ...oldEntry,\n authToken: inProgressAuthToken\n };\n}\n\nfunction hasAuthTokenRequestTimedOut(authToken: AuthToken): boolean {\n return (\n authToken.requestStatus === RequestStatus.IN_PROGRESS &&\n authToken.requestTime + PENDING_TIMEOUT_MS < Date.now()\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getInstallationEntry } from '../helpers/get-installation-entry';\nimport { refreshAuthToken } from '../helpers/refresh-auth-token';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { Installations } from '../interfaces/public-types';\n\n/**\n * Returns a Firebase Installations auth token, identifying the current\n * Firebase Installation.\n * @param installations - The `Installations` instance.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport async function getToken(\n installations: Installations,\n forceRefresh = false\n): Promise<string> {\n const installationsImpl = installations as FirebaseInstallationsImpl;\n await completeInstallationRegistration(installationsImpl);\n\n // At this point we either have a Registered Installation in the DB, or we've\n // already thrown an error.\n const authToken = await refreshAuthToken(installationsImpl, forceRefresh);\n return authToken.token;\n}\n\nasync function completeInstallationRegistration(\n installations: FirebaseInstallationsImpl\n): Promise<void> {\n const { registrationPromise } = await getInstallationEntry(installations);\n\n if (registrationPromise) {\n // A createInstallation request is in progress. Wait until it finishes.\n await registrationPromise;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, FirebaseOptions } from '@firebase/app';\nimport { FirebaseError } from '@firebase/util';\nimport { AppConfig } from '../interfaces/installation-impl';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nexport function extractAppConfig(app: FirebaseApp): AppConfig {\n if (!app || !app.options) {\n throw getMissingValueError('App Configuration');\n }\n\n if (!app.name) {\n throw getMissingValueError('App Name');\n }\n\n // Required app config keys\n const configKeys: Array<keyof FirebaseOptions> = [\n 'projectId',\n 'apiKey',\n 'appId'\n ];\n\n for (const keyName of configKeys) {\n if (!app.options[keyName]) {\n throw getMissingValueError(keyName);\n }\n }\n\n return {\n appName: app.name,\n projectId: app.options.projectId!,\n apiKey: app.options.apiKey!,\n appId: app.options.appId!\n };\n}\n\nfunction getMissingValueError(valueName: string): FirebaseError {\n return ERROR_FACTORY.create(ErrorCode.MISSING_APP_CONFIG_VALUES, {\n valueName\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _registerComponent, _getProvider } from '@firebase/app';\nimport {\n Component,\n ComponentType,\n InstanceFactory,\n ComponentContainer\n} from '@firebase/component';\nimport { getId, getToken } from '../api/index';\nimport { _FirebaseInstallationsInternal } from '../interfaces/public-types';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { extractAppConfig } from '../helpers/extract-app-config';\n\nconst INSTALLATIONS_NAME = 'installations';\nconst INSTALLATIONS_NAME_INTERNAL = 'installations-internal';\n\nconst publicFactory: InstanceFactory<'installations'> = (\n container: ComponentContainer\n) => {\n const app = container.getProvider('app').getImmediate();\n // Throws if app isn't configured properly.\n const appConfig = extractAppConfig(app);\n const heartbeatServiceProvider = _getProvider(app, 'heartbeat');\n\n const installationsImpl: FirebaseInstallationsImpl = {\n app,\n appConfig,\n heartbeatServiceProvider,\n _delete: () => Promise.resolve()\n };\n return installationsImpl;\n};\n\nconst internalFactory: InstanceFactory<'installations-internal'> = (\n container: ComponentContainer\n) => {\n const app = container.getProvider('app').getImmediate();\n // Internal FIS instance relies on public FIS instance.\n const installations = _getProvider(app, INSTALLATIONS_NAME).getImmediate();\n\n const installationsInternal: _FirebaseInstallationsInternal = {\n getId: () => getId(installations),\n getToken: (forceRefresh?: boolean) => getToken(installations, forceRefresh)\n };\n return installationsInternal;\n};\n\nexport function registerInstallations(): void {\n _registerComponent(\n new Component(INSTALLATIONS_NAME, publicFactory, ComponentType.PUBLIC)\n );\n _registerComponent(\n new Component(\n INSTALLATIONS_NAME_INTERNAL,\n internalFactory,\n ComponentType.PRIVATE\n )\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getInstallationEntry } from '../helpers/get-installation-entry';\nimport { refreshAuthToken } from '../helpers/refresh-auth-token';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { Installations } from '../interfaces/public-types';\n\n/**\n * Creates a Firebase Installation if there isn't one for the app and\n * returns the Installation ID.\n * @param installations - The `Installations` instance.\n *\n * @public\n */\nexport async function getId(installations: Installations): Promise<string> {\n const installationsImpl = installations as FirebaseInstallationsImpl;\n const { installationEntry, registrationPromise } = await getInstallationEntry(\n installationsImpl\n );\n\n if (registrationPromise) {\n registrationPromise.catch(console.error);\n } else {\n // If the installation is already registered, update the authentication\n // token if needed.\n refreshAuthToken(installationsImpl).catch(console.error);\n }\n\n return installationEntry.fid;\n}\n","/**\n * Firebase Installations\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerInstallations } from './functions/config';\nimport { registerVersion } from '@firebase/app';\nimport { name, version } from '../package.json';\n\nexport * from './api';\nexport * from './interfaces/public-types';\n\nregisterInstallations();\nregisterVersion(name, version);\n// BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\nregisterVersion(name, version, '__BUILD_TARGET__');\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Type constant for Firebase Analytics.\n */\nexport const ANALYTICS_TYPE = 'analytics';\n\n// Key to attach FID to in gtag params.\nexport const GA_FID_KEY = 'firebase_id';\nexport const ORIGIN_KEY = 'origin';\n\nexport const FETCH_TIMEOUT_MILLIS = 60 * 1000;\n\nexport const DYNAMIC_CONFIG_URL =\n 'https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig';\n\nexport const GTAG_URL = 'https://www.googletagmanager.com/gtag/js';\n\nexport const enum GtagCommand {\n EVENT = 'event',\n SET = 'set',\n CONFIG = 'config',\n CONSENT = 'consent',\n GET = 'get'\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/analytics');\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AnalyticsError {\n ALREADY_EXISTS = 'already-exists',\n ALREADY_INITIALIZED = 'already-initialized',\n ALREADY_INITIALIZED_SETTINGS = 'already-initialized-settings',\n INTEROP_COMPONENT_REG_FAILED = 'interop-component-reg-failed',\n INVALID_ANALYTICS_CONTEXT = 'invalid-analytics-context',\n INDEXEDDB_UNAVAILABLE = 'indexeddb-unavailable',\n FETCH_THROTTLE = 'fetch-throttle',\n CONFIG_FETCH_FAILED = 'config-fetch-failed',\n NO_API_KEY = 'no-api-key',\n NO_APP_ID = 'no-app-id',\n NO_CLIENT_ID = 'no-client-id',\n INVALID_GTAG_RESOURCE = 'invalid-gtag-resource'\n}\n\nconst ERRORS: ErrorMap<AnalyticsError> = {\n [AnalyticsError.ALREADY_EXISTS]:\n 'A Firebase Analytics instance with the appId {$id} ' +\n ' already exists. ' +\n 'Only one Firebase Analytics instance can be created for each appId.',\n [AnalyticsError.ALREADY_INITIALIZED]:\n 'initializeAnalytics() cannot be called again with different options than those ' +\n 'it was initially called with. It can be called again with the same options to ' +\n 'return the existing instance, or getAnalytics() can be used ' +\n 'to get a reference to the already-intialized instance.',\n [AnalyticsError.ALREADY_INITIALIZED_SETTINGS]:\n 'Firebase Analytics has already been initialized.' +\n 'settings() must be called before initializing any Analytics instance' +\n 'or it will have no effect.',\n [AnalyticsError.INTEROP_COMPONENT_REG_FAILED]:\n 'Firebase Analytics Interop Component failed to instantiate: {$reason}',\n [AnalyticsError.INVALID_ANALYTICS_CONTEXT]:\n 'Firebase Analytics is not supported in this environment. ' +\n 'Wrap initialization of analytics in analytics.isSupported() ' +\n 'to prevent initialization in unsupported environments. Details: {$errorInfo}',\n [AnalyticsError.INDEXEDDB_UNAVAILABLE]:\n 'IndexedDB unavailable or restricted in this environment. ' +\n 'Wrap initialization of analytics in analytics.isSupported() ' +\n 'to prevent initialization in unsupported environments. Details: {$errorInfo}',\n [AnalyticsError.FETCH_THROTTLE]:\n 'The config fetch request timed out while in an exponential backoff state.' +\n ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',\n [AnalyticsError.CONFIG_FETCH_FAILED]:\n 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}',\n [AnalyticsError.NO_API_KEY]:\n 'The \"apiKey\" field is empty in the local Firebase config. Firebase Analytics requires this field to' +\n 'contain a valid API key.',\n [AnalyticsError.NO_APP_ID]:\n 'The \"appId\" field is empty in the local Firebase config. Firebase Analytics requires this field to' +\n 'contain a valid app ID.',\n [AnalyticsError.NO_CLIENT_ID]: 'The \"client_id\" field is empty.',\n [AnalyticsError.INVALID_GTAG_RESOURCE]:\n 'Trusted Types detected an invalid gtag resource: {$gtagURL}.'\n};\n\ninterface ErrorParams {\n [AnalyticsError.ALREADY_EXISTS]: { id: string };\n [AnalyticsError.INTEROP_COMPONENT_REG_FAILED]: { reason: Error };\n [AnalyticsError.FETCH_THROTTLE]: { throttleEndTimeMillis: number };\n [AnalyticsError.CONFIG_FETCH_FAILED]: {\n httpStatus: number;\n responseMessage: string;\n };\n [AnalyticsError.INVALID_ANALYTICS_CONTEXT]: { errorInfo: string };\n [AnalyticsError.INDEXEDDB_UNAVAILABLE]: { errorInfo: string };\n [AnalyticsError.INVALID_GTAG_RESOURCE]: { gtagURL: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<AnalyticsError, ErrorParams>(\n 'analytics',\n 'Analytics',\n ERRORS\n);\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CustomParams,\n ControlParams,\n EventParams,\n ConsentSettings\n} from './public-types';\nimport { DynamicConfig, DataLayer, Gtag, MinimalDynamicConfig } from './types';\nimport { GtagCommand, GTAG_URL } from './constants';\nimport { logger } from './logger';\nimport { AnalyticsError, ERROR_FACTORY } from './errors';\n\n// Possible parameter types for gtag 'event' and 'config' commands\ntype GtagConfigOrEventParams = ControlParams & EventParams & CustomParams;\n\n/**\n * Verifies and creates a TrustedScriptURL.\n */\nexport function createGtagTrustedTypesScriptURL(url: string): string {\n if (!url.startsWith(GTAG_URL)) {\n const err = ERROR_FACTORY.create(AnalyticsError.INVALID_GTAG_RESOURCE, {\n gtagURL: url\n });\n logger.warn(err.message);\n return '';\n }\n return url;\n}\n\n/**\n * Makeshift polyfill for Promise.allSettled(). Resolves when all promises\n * have either resolved or rejected.\n *\n * @param promises Array of promises to wait for.\n */\nexport function promiseAllSettled<T>(\n promises: Array<Promise<T>>\n): Promise<T[]> {\n return Promise.all(promises.map(promise => promise.catch(e => e)));\n}\n\n/**\n * Creates a TrustedTypePolicy object that implements the rules passed as policyOptions.\n *\n * @param policyName A string containing the name of the policy\n * @param policyOptions Object containing implementations of instance methods for TrustedTypesPolicy, see {@link https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicy#instance_methods\n * | the TrustedTypePolicy reference documentation}.\n */\nexport function createTrustedTypesPolicy(\n policyName: string,\n policyOptions: Partial<TrustedTypePolicyOptions>\n): Partial<TrustedTypePolicy> | undefined {\n // Create a TrustedTypes policy that we can use for updating src\n // properties\n let trustedTypesPolicy: Partial<TrustedTypePolicy> | undefined;\n if (window.trustedTypes) {\n trustedTypesPolicy = window.trustedTypes.createPolicy(\n policyName,\n policyOptions\n );\n }\n return trustedTypesPolicy;\n}\n\n/**\n * Inserts gtag script tag into the page to asynchronously download gtag.\n * @param dataLayerName Name of datalayer (most often the default, \"_dataLayer\").\n */\nexport function insertScriptTag(\n dataLayerName: string,\n measurementId: string\n): void {\n const trustedTypesPolicy = createTrustedTypesPolicy(\n 'firebase-js-sdk-policy',\n {\n createScriptURL: createGtagTrustedTypesScriptURL\n }\n );\n\n const script = document.createElement('script');\n // We are not providing an analyticsId in the URL because it would trigger a `page_view`\n // without fid. We will initialize ga-id using gtag (config) command together with fid.\n\n const gtagScriptURL = `${GTAG_URL}?l=${dataLayerName}&id=${measurementId}`;\n (script.src as string | TrustedScriptURL) = trustedTypesPolicy\n ? (trustedTypesPolicy as TrustedTypePolicy)?.createScriptURL(gtagScriptURL)\n : gtagScriptURL;\n\n script.async = true;\n document.head.appendChild(script);\n}\n\n/**\n * Get reference to, or create, global datalayer.\n * @param dataLayerName Name of datalayer (most often the default, \"_dataLayer\").\n */\nexport function getOrCreateDataLayer(dataLayerName: string): DataLayer {\n // Check for existing dataLayer and create if needed.\n let dataLayer: DataLayer = [];\n if (Array.isArray(window[dataLayerName])) {\n dataLayer = window[dataLayerName] as DataLayer;\n } else {\n window[dataLayerName] = dataLayer;\n }\n return dataLayer;\n}\n\n/**\n * Wrapped gtag logic when gtag is called with 'config' command.\n *\n * @param gtagCore Basic gtag function that just appends to dataLayer.\n * @param initializationPromisesMap Map of appIds to their initialization promises.\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\n * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.\n * @param measurementId GA Measurement ID to set config for.\n * @param gtagParams Gtag config params to set.\n */\nasync function gtagOnConfig(\n gtagCore: Gtag,\n initializationPromisesMap: { [appId: string]: Promise<string> },\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n measurementIdToAppId: { [measurementId: string]: string },\n measurementId: string,\n gtagParams?: ControlParams & EventParams & CustomParams\n): Promise<void> {\n // If config is already fetched, we know the appId and can use it to look up what FID promise we\n /// are waiting for, and wait only on that one.\n const correspondingAppId = measurementIdToAppId[measurementId as string];\n try {\n if (correspondingAppId) {\n await initializationPromisesMap[correspondingAppId];\n } else {\n // If config is not fetched yet, wait for all configs (we don't know which one we need) and\n // find the appId (if any) corresponding to this measurementId. If there is one, wait on\n // that appId's initialization promise. If there is none, promise resolves and gtag\n // call goes through.\n const dynamicConfigResults = await promiseAllSettled(\n dynamicConfigPromisesList\n );\n const foundConfig = dynamicConfigResults.find(\n config => config.measurementId === measurementId\n );\n if (foundConfig) {\n await initializationPromisesMap[foundConfig.appId];\n }\n }\n } catch (e) {\n logger.error(e);\n }\n gtagCore(GtagCommand.CONFIG, measurementId, gtagParams);\n}\n\n/**\n * Wrapped gtag logic when gtag is called with 'event' command.\n *\n * @param gtagCore Basic gtag function that just appends to dataLayer.\n * @param initializationPromisesMap Map of appIds to their initialization promises.\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\n * @param measurementId GA Measurement ID to log event to.\n * @param gtagParams Params to log with this event.\n */\nasync function gtagOnEvent(\n gtagCore: Gtag,\n initializationPromisesMap: { [appId: string]: Promise<string> },\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n measurementId: string,\n gtagParams?: ControlParams & EventParams & CustomParams\n): Promise<void> {\n try {\n let initializationPromisesToWaitFor: Array<Promise<string>> = [];\n\n // If there's a 'send_to' param, check if any ID specified matches\n // an initializeIds() promise we are waiting for.\n if (gtagParams && gtagParams['send_to']) {\n let gaSendToList: string | string[] = gtagParams['send_to'];\n // Make it an array if is isn't, so it can be dealt with the same way.\n if (!Array.isArray(gaSendToList)) {\n gaSendToList = [gaSendToList];\n }\n // Checking 'send_to' fields requires having all measurement ID results back from\n // the dynamic config fetch.\n const dynamicConfigResults = await promiseAllSettled(\n dynamicConfigPromisesList\n );\n for (const sendToId of gaSendToList) {\n // Any fetched dynamic measurement ID that matches this 'send_to' ID\n const foundConfig = dynamicConfigResults.find(\n config => config.measurementId === sendToId\n );\n const initializationPromise =\n foundConfig && initializationPromisesMap[foundConfig.appId];\n if (initializationPromise) {\n initializationPromisesToWaitFor.push(initializationPromise);\n } else {\n // Found an item in 'send_to' that is not associated\n // directly with an FID, possibly a group. Empty this array,\n // exit the loop early, and let it get populated below.\n initializationPromisesToWaitFor = [];\n break;\n }\n }\n }\n\n // This will be unpopulated if there was no 'send_to' field , or\n // if not all entries in the 'send_to' field could be mapped to\n // a FID. In these cases, wait on all pending initialization promises.\n if (initializationPromisesToWaitFor.length === 0) {\n initializationPromisesToWaitFor = Object.values(\n initializationPromisesMap\n );\n }\n\n // Run core gtag function with args after all relevant initialization\n // promises have been resolved.\n await Promise.all(initializationPromisesToWaitFor);\n // Workaround for http://b/141370449 - third argument cannot be undefined.\n gtagCore(GtagCommand.EVENT, measurementId, gtagParams || {});\n } catch (e) {\n logger.error(e);\n }\n}\n\n/**\n * Wraps a standard gtag function with extra code to wait for completion of\n * relevant initialization promises before sending requests.\n *\n * @param gtagCore Basic gtag function that just appends to dataLayer.\n * @param initializationPromisesMap Map of appIds to their initialization promises.\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\n * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.\n */\nfunction wrapGtag(\n gtagCore: Gtag,\n /**\n * Allows wrapped gtag calls to wait on whichever intialization promises are required,\n * depending on the contents of the gtag params' `send_to` field, if any.\n */\n initializationPromisesMap: { [appId: string]: Promise<string> },\n /**\n * Wrapped gtag calls sometimes require all dynamic config fetches to have returned\n * before determining what initialization promises (which include FIDs) to wait for.\n */\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n /**\n * Wrapped gtag config calls can narrow down which initialization promise (with FID)\n * to wait for if the measurementId is already fetched, by getting the corresponding appId,\n * which is the key for the initialization promises map.\n */\n measurementIdToAppId: { [measurementId: string]: string }\n): Gtag {\n /**\n * Wrapper around gtag that ensures FID is sent with gtag calls.\n * @param command Gtag command type.\n * @param idOrNameOrParams Measurement ID if command is EVENT/CONFIG, params if command is SET.\n * @param gtagParams Params if event is EVENT/CONFIG.\n */\n async function gtagWrapper(\n command: 'config' | 'set' | 'event' | 'consent' | 'get' | string,\n ...args: unknown[]\n ): Promise<void> {\n try {\n // If event, check that relevant initialization promises have completed.\n if (command === GtagCommand.EVENT) {\n const [measurementId, gtagParams] = args;\n // If EVENT, second arg must be measurementId.\n await gtagOnEvent(\n gtagCore,\n initializationPromisesMap,\n dynamicConfigPromisesList,\n measurementId as string,\n gtagParams as GtagConfigOrEventParams\n );\n } else if (command === GtagCommand.CONFIG) {\n const [measurementId, gtagParams] = args;\n // If CONFIG, second arg must be measurementId.\n await gtagOnConfig(\n gtagCore,\n initializationPromisesMap,\n dynamicConfigPromisesList,\n measurementIdToAppId,\n measurementId as string,\n gtagParams as GtagConfigOrEventParams\n );\n } else if (command === GtagCommand.CONSENT) {\n const [gtagParams] = args;\n gtagCore(GtagCommand.CONSENT, 'update', gtagParams as ConsentSettings);\n } else if (command === GtagCommand.GET) {\n const [measurementId, fieldName, callback] = args;\n gtagCore(\n GtagCommand.GET,\n measurementId as string,\n fieldName as string,\n callback as (...args: unknown[]) => void\n );\n } else if (command === GtagCommand.SET) {\n const [customParams] = args;\n // If SET, second arg must be params.\n gtagCore(GtagCommand.SET, customParams as CustomParams);\n } else {\n gtagCore(command, ...args);\n }\n } catch (e) {\n logger.error(e);\n }\n }\n return gtagWrapper as Gtag;\n}\n\n/**\n * Creates global gtag function or wraps existing one if found.\n * This wrapped function attaches Firebase instance ID (FID) to gtag 'config' and\n * 'event' calls that belong to the GAID associated with this Firebase instance.\n *\n * @param initializationPromisesMap Map of appIds to their initialization promises.\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\n * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.\n * @param dataLayerName Name of global GA datalayer array.\n * @param gtagFunctionName Name of global gtag function (\"gtag\" if not user-specified).\n */\nexport function wrapOrCreateGtag(\n initializationPromisesMap: { [appId: string]: Promise<string> },\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n measurementIdToAppId: { [measurementId: string]: string },\n dataLayerName: string,\n gtagFunctionName: string\n): {\n gtagCore: Gtag;\n wrappedGtag: Gtag;\n} {\n // Create a basic core gtag function\n let gtagCore: Gtag = function (..._args: unknown[]) {\n // Must push IArguments object, not an array.\n (window[dataLayerName] as DataLayer).push(arguments);\n };\n\n // Replace it with existing one if found\n if (\n window[gtagFunctionName] &&\n typeof window[gtagFunctionName] === 'function'\n ) {\n // @ts-ignore\n gtagCore = window[gtagFunctionName];\n }\n\n window[gtagFunctionName] = wrapGtag(\n gtagCore,\n initializationPromisesMap,\n dynamicConfigPromisesList,\n measurementIdToAppId\n );\n\n return {\n gtagCore,\n wrappedGtag: window[gtagFunctionName] as Gtag\n };\n}\n\n/**\n * Returns the script tag in the DOM matching both the gtag url pattern\n * and the provided data layer name.\n */\nexport function findGtagScriptOnPage(\n dataLayerName: string\n): HTMLScriptElement | null {\n const scriptTags = window.document.getElementsByTagName('script');\n for (const tag of Object.values(scriptTags)) {\n if (\n tag.src &&\n tag.src.includes(GTAG_URL) &&\n tag.src.includes(dataLayerName)\n ) {\n return tag;\n }\n }\n return null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Most logic is copied from packages/remote-config/src/client/retrying_client.ts\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { DynamicConfig, ThrottleMetadata, MinimalDynamicConfig } from './types';\nimport { FirebaseError, calculateBackoffMillis } from '@firebase/util';\nimport { AnalyticsError, ERROR_FACTORY } from './errors';\nimport { DYNAMIC_CONFIG_URL, FETCH_TIMEOUT_MILLIS } from './constants';\nimport { logger } from './logger';\n\n// App config fields needed by analytics.\nexport interface AppFields {\n appId: string;\n apiKey: string;\n measurementId?: string;\n}\n\n/**\n * Backoff factor for 503 errors, which we want to be conservative about\n * to avoid overloading servers. Each retry interval will be\n * BASE_INTERVAL_MILLIS * LONG_RETRY_FACTOR ^ retryCount, so the second one\n * will be ~30 seconds (with fuzzing).\n */\nexport const LONG_RETRY_FACTOR = 30;\n\n/**\n * Base wait interval to multiplied by backoffFactor^backoffCount.\n */\nconst BASE_INTERVAL_MILLIS = 1000;\n\n/**\n * Stubbable retry data storage class.\n */\nclass RetryData {\n constructor(\n public throttleMetadata: { [appId: string]: ThrottleMetadata } = {},\n public intervalMillis: number = BASE_INTERVAL_MILLIS\n ) {}\n\n getThrottleMetadata(appId: string): ThrottleMetadata {\n return this.throttleMetadata[appId];\n }\n\n setThrottleMetadata(appId: string, metadata: ThrottleMetadata): void {\n this.throttleMetadata[appId] = metadata;\n }\n\n deleteThrottleMetadata(appId: string): void {\n delete this.throttleMetadata[appId];\n }\n}\n\nconst defaultRetryData = new RetryData();\n\n/**\n * Set GET request headers.\n * @param apiKey App API key.\n */\nfunction getHeaders(apiKey: string): Headers {\n return new Headers({\n Accept: 'application/json',\n 'x-goog-api-key': apiKey\n });\n}\n\n/**\n * Fetches dynamic config from backend.\n * @param app Firebase app to fetch config for.\n */\nexport async function fetchDynamicConfig(\n appFields: AppFields\n): Promise<DynamicConfig> {\n const { appId, apiKey } = appFields;\n const request: RequestInit = {\n method: 'GET',\n headers: getHeaders(apiKey)\n };\n const appUrl = DYNAMIC_CONFIG_URL.replace('{app-id}', appId);\n const response = await fetch(appUrl, request);\n if (response.status !== 200 && response.status !== 304) {\n let errorMessage = '';\n try {\n // Try to get any error message text from server response.\n const jsonResponse = (await response.json()) as {\n error?: { message?: string };\n };\n if (jsonResponse.error?.message) {\n errorMessage = jsonResponse.error.message;\n }\n } catch (_ignored) {}\n throw ERROR_FACTORY.create(AnalyticsError.CONFIG_FETCH_FAILED, {\n httpStatus: response.status,\n responseMessage: errorMessage\n });\n }\n return response.json();\n}\n\n/**\n * Fetches dynamic config from backend, retrying if failed.\n * @param app Firebase app to fetch config for.\n */\nexport async function fetchDynamicConfigWithRetry(\n app: FirebaseApp,\n // retryData and timeoutMillis are parameterized to allow passing a different value for testing.\n retryData: RetryData = defaultRetryData,\n timeoutMillis?: number\n): Promise<DynamicConfig | MinimalDynamicConfig> {\n const { appId, apiKey, measurementId } = app.options;\n\n if (!appId) {\n throw ERROR_FACTORY.create(AnalyticsError.NO_APP_ID);\n }\n\n if (!apiKey) {\n if (measurementId) {\n return {\n measurementId,\n appId\n };\n }\n throw ERROR_FACTORY.create(AnalyticsError.NO_API_KEY);\n }\n\n const throttleMetadata: ThrottleMetadata = retryData.getThrottleMetadata(\n appId\n ) || {\n backoffCount: 0,\n throttleEndTimeMillis: Date.now()\n };\n\n const signal = new AnalyticsAbortSignal();\n\n setTimeout(\n async () => {\n // Note a very low delay, eg < 10ms, can elapse before listeners are initialized.\n signal.abort();\n },\n timeoutMillis !== undefined ? timeoutMillis : FETCH_TIMEOUT_MILLIS\n );\n\n return attemptFetchDynamicConfigWithRetry(\n { appId, apiKey, measurementId },\n throttleMetadata,\n signal,\n retryData\n );\n}\n\n/**\n * Runs one retry attempt.\n * @param appFields Necessary app config fields.\n * @param throttleMetadata Ongoing metadata to determine throttling times.\n * @param signal Abort signal.\n */\nasync function attemptFetchDynamicConfigWithRetry(\n appFields: AppFields,\n { throttleEndTimeMillis, backoffCount }: ThrottleMetadata,\n signal: AnalyticsAbortSignal,\n retryData: RetryData = defaultRetryData // for testing\n): Promise<DynamicConfig | MinimalDynamicConfig> {\n const { appId, measurementId } = appFields;\n // Starts with a (potentially zero) timeout to support resumption from stored state.\n // Ensures the throttle end time is honored if the last attempt timed out.\n // Note the SDK will never make a request if the fetch timeout expires at this point.\n try {\n await setAbortableTimeout(signal, throttleEndTimeMillis);\n } catch (e) {\n if (measurementId) {\n logger.warn(\n `Timed out fetching this Firebase app's measurement ID from the server.` +\n ` Falling back to the measurement ID ${measurementId}` +\n ` provided in the \"measurementId\" field in the local Firebase config. [${\n (e as Error)?.message\n }]`\n );\n return { appId, measurementId };\n }\n throw e;\n }\n\n try {\n const response = await fetchDynamicConfig(appFields);\n\n // Note the SDK only clears throttle state if response is success or non-retriable.\n retryData.deleteThrottleMetadata(appId);\n\n return response;\n } catch (e) {\n const error = e as Error;\n if (!isRetriableError(error)) {\n retryData.deleteThrottleMetadata(appId);\n if (measurementId) {\n logger.warn(\n `Failed to fetch this Firebase app's measurement ID from the server.` +\n ` Falling back to the measurement ID ${measurementId}` +\n ` provided in the \"measurementId\" field in the local Firebase config. [${error?.message}]`\n );\n return { appId, measurementId };\n } else {\n throw e;\n }\n }\n\n const backoffMillis =\n Number(error?.customData?.httpStatus) === 503\n ? calculateBackoffMillis(\n backoffCount,\n retryData.intervalMillis,\n LONG_RETRY_FACTOR\n )\n : calculateBackoffMillis(backoffCount, retryData.intervalMillis);\n\n // Increments backoff state.\n const throttleMetadata = {\n throttleEndTimeMillis: Date.now() + backoffMillis,\n backoffCount: backoffCount + 1\n };\n\n // Persists state.\n retryData.setThrottleMetadata(appId, throttleMetadata);\n logger.debug(`Calling attemptFetch again in ${backoffMillis} millis`);\n\n return attemptFetchDynamicConfigWithRetry(\n appFields,\n throttleMetadata,\n signal,\n retryData\n );\n }\n}\n\n/**\n * Supports waiting on a backoff by:\n *\n * <ul>\n * <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li>\n * <li>Listening on a signal bus for abort events, just like the Fetch API</li>\n * <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled\n * request appear the same.</li>\n * </ul>\n *\n * <p>Visible for testing.\n */\nfunction setAbortableTimeout(\n signal: AnalyticsAbortSignal,\n throttleEndTimeMillis: number\n): Promise<void> {\n return new Promise((resolve, reject) => {\n // Derives backoff from given end time, normalizing negative numbers to zero.\n const backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0);\n\n const timeout = setTimeout(resolve, backoffMillis);\n\n // Adds listener, rather than sets onabort, because signal is a shared object.\n signal.addEventListener(() => {\n clearTimeout(timeout);\n // If the request completes before this timeout, the rejection has no effect.\n reject(\n ERROR_FACTORY.create(AnalyticsError.FETCH_THROTTLE, {\n throttleEndTimeMillis\n })\n );\n });\n });\n}\n\ntype RetriableError = FirebaseError & { customData: { httpStatus: string } };\n\n/**\n * Returns true if the {@link Error} indicates a fetch request may succeed later.\n */\nfunction isRetriableError(e: Error): e is RetriableError {\n if (!(e instanceof FirebaseError) || !e.customData) {\n return false;\n }\n\n // Uses string index defined by ErrorData, which FirebaseError implements.\n const httpStatus = Number(e.customData['httpStatus']);\n\n return (\n httpStatus === 429 ||\n httpStatus === 500 ||\n httpStatus === 503 ||\n httpStatus === 504\n );\n}\n\n/**\n * Shims a minimal AbortSignal (copied from Remote Config).\n *\n * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects\n * of networking, such as retries. Firebase doesn't use AbortController enough to justify a\n * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be\n * swapped out if/when we do.\n */\nexport class AnalyticsAbortSignal {\n listeners: Array<() => void> = [];\n addEventListener(listener: () => void): void {\n this.listeners.push(listener);\n }\n abort(): void {\n this.listeners.forEach(listener => listener());\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AnalyticsCallOptions,\n CustomParams,\n ControlParams,\n EventParams,\n ConsentSettings\n} from './public-types';\nimport { Gtag } from './types';\nimport { GtagCommand } from './constants';\nimport { AnalyticsError, ERROR_FACTORY } from './errors';\n\n/**\n * Event parameters to set on 'gtag' during initialization.\n */\nexport let defaultEventParametersForInit: CustomParams | undefined;\n\n/**\n * Logs an analytics event through the Firebase SDK.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n * @param eventName Google Analytics event name, choose from standard list or use a custom string.\n * @param eventParams Analytics event parameters.\n */\nexport async function logEvent(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>,\n eventName: string,\n eventParams?: EventParams,\n options?: AnalyticsCallOptions\n): Promise<void> {\n if (options && options.global) {\n gtagFunction(GtagCommand.EVENT, eventName, eventParams);\n return;\n } else {\n const measurementId = await initializationPromise;\n const params: EventParams | ControlParams = {\n ...eventParams,\n 'send_to': measurementId\n };\n gtagFunction(GtagCommand.EVENT, eventName, params);\n }\n}\n\n/**\n * Set screen_name parameter for this Google Analytics ID.\n *\n * @deprecated Use {@link logEvent} with `eventName` as 'screen_view' and add relevant `eventParams`.\n * See {@link https://firebase.google.com/docs/analytics/screenviews | Track Screenviews}.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n * @param screenName Screen name string to set.\n */\nexport async function setCurrentScreen(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>,\n screenName: string | null,\n options?: AnalyticsCallOptions\n): Promise<void> {\n if (options && options.global) {\n gtagFunction(GtagCommand.SET, { 'screen_name': screenName });\n return Promise.resolve();\n } else {\n const measurementId = await initializationPromise;\n gtagFunction(GtagCommand.CONFIG, measurementId, {\n update: true,\n 'screen_name': screenName\n });\n }\n}\n\n/**\n * Set user_id parameter for this Google Analytics ID.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n * @param id User ID string to set\n */\nexport async function setUserId(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>,\n id: string | null,\n options?: AnalyticsCallOptions\n): Promise<void> {\n if (options && options.global) {\n gtagFunction(GtagCommand.SET, { 'user_id': id });\n return Promise.resolve();\n } else {\n const measurementId = await initializationPromise;\n gtagFunction(GtagCommand.CONFIG, measurementId, {\n update: true,\n 'user_id': id\n });\n }\n}\n\n/**\n * Set all other user properties other than user_id and screen_name.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n * @param properties Map of user properties to set\n */\nexport async function setUserProperties(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>,\n properties: CustomParams,\n options?: AnalyticsCallOptions\n): Promise<void> {\n if (options && options.global) {\n const flatProperties: { [key: string]: unknown } = {};\n for (const key of Object.keys(properties)) {\n // use dot notation for merge behavior in gtag.js\n flatProperties[`user_properties.${key}`] = properties[key];\n }\n gtagFunction(GtagCommand.SET, flatProperties);\n return Promise.resolve();\n } else {\n const measurementId = await initializationPromise;\n gtagFunction(GtagCommand.CONFIG, measurementId, {\n update: true,\n 'user_properties': properties\n });\n }\n}\n\n/**\n * Retrieves a unique Google Analytics identifier for the web client.\n * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n */\nexport async function internalGetGoogleAnalyticsClientId(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>\n): Promise<string> {\n const measurementId = await initializationPromise;\n return new Promise((resolve, reject) => {\n gtagFunction(\n GtagCommand.GET,\n measurementId,\n 'client_id',\n (clientId: string) => {\n if (!clientId) {\n reject(ERROR_FACTORY.create(AnalyticsError.NO_CLIENT_ID));\n }\n resolve(clientId);\n }\n );\n });\n}\n\n/**\n * Set whether collection is enabled for this ID.\n *\n * @param enabled If true, collection is enabled for this ID.\n */\nexport async function setAnalyticsCollectionEnabled(\n initializationPromise: Promise<string>,\n enabled: boolean\n): Promise<void> {\n const measurementId = await initializationPromise;\n window[`ga-disable-${measurementId}`] = !enabled;\n}\n\n/**\n * Consent parameters to default to during 'gtag' initialization.\n */\nexport let defaultConsentSettingsForInit: ConsentSettings | undefined;\n\n/**\n * Sets the variable {@link defaultConsentSettingsForInit} for use in the initialization of\n * analytics.\n *\n * @param consentSettings Maps the applicable end user consent state for gtag.js.\n */\nexport function _setConsentDefaultForInit(\n consentSettings?: ConsentSettings\n): void {\n defaultConsentSettingsForInit = consentSettings;\n}\n\n/**\n * Sets the variable `defaultEventParametersForInit` for use in the initialization of\n * analytics.\n *\n * @param customParams Any custom params the user may pass to gtag.js.\n */\nexport function _setDefaultEventParametersForInit(\n customParams?: CustomParams\n): void {\n defaultEventParametersForInit = customParams;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DynamicConfig, Gtag, MinimalDynamicConfig } from './types';\nimport { GtagCommand, GA_FID_KEY, ORIGIN_KEY } from './constants';\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\nimport { fetchDynamicConfigWithRetry } from './get-config';\nimport { logger } from './logger';\nimport { FirebaseApp } from '@firebase/app';\nimport {\n isIndexedDBAvailable,\n validateIndexedDBOpenable\n} from '@firebase/util';\nimport { ERROR_FACTORY, AnalyticsError } from './errors';\nimport { findGtagScriptOnPage, insertScriptTag } from './helpers';\nimport { AnalyticsSettings } from './public-types';\nimport {\n defaultConsentSettingsForInit,\n _setConsentDefaultForInit,\n defaultEventParametersForInit,\n _setDefaultEventParametersForInit\n} from './functions';\n\nasync function validateIndexedDB(): Promise<boolean> {\n if (!isIndexedDBAvailable()) {\n logger.warn(\n ERROR_FACTORY.create(AnalyticsError.INDEXEDDB_UNAVAILABLE, {\n errorInfo: 'IndexedDB is not available in this environment.'\n }).message\n );\n return false;\n } else {\n try {\n await validateIndexedDBOpenable();\n } catch (e) {\n logger.warn(\n ERROR_FACTORY.create(AnalyticsError.INDEXEDDB_UNAVAILABLE, {\n errorInfo: (e as Error)?.toString()\n }).message\n );\n return false;\n }\n }\n return true;\n}\n\n/**\n * Initialize the analytics instance in gtag.js by calling config command with fid.\n *\n * NOTE: We combine analytics initialization and setting fid together because we want fid to be\n * part of the `page_view` event that's sent during the initialization\n * @param app Firebase app\n * @param gtagCore The gtag function that's not wrapped.\n * @param dynamicConfigPromisesList Array of all dynamic config promises.\n * @param measurementIdToAppId Maps measurementID to appID.\n * @param installations _FirebaseInstallationsInternal instance.\n *\n * @returns Measurement ID.\n */\nexport async function _initializeAnalytics(\n app: FirebaseApp,\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n measurementIdToAppId: { [key: string]: string },\n installations: _FirebaseInstallationsInternal,\n gtagCore: Gtag,\n dataLayerName: string,\n options?: AnalyticsSettings\n): Promise<string> {\n const dynamicConfigPromise = fetchDynamicConfigWithRetry(app);\n // Once fetched, map measurementIds to appId, for ease of lookup in wrapped gtag function.\n dynamicConfigPromise\n .then(config => {\n measurementIdToAppId[config.measurementId] = config.appId;\n if (\n app.options.measurementId &&\n config.measurementId !== app.options.measurementId\n ) {\n logger.warn(\n `The measurement ID in the local Firebase config (${app.options.measurementId})` +\n ` does not match the measurement ID fetched from the server (${config.measurementId}).` +\n ` To ensure analytics events are always sent to the correct Analytics property,` +\n ` update the` +\n ` measurement ID field in the local config or remove it from the local config.`\n );\n }\n })\n .catch(e => logger.error(e));\n // Add to list to track state of all dynamic config promises.\n dynamicConfigPromisesList.push(dynamicConfigPromise);\n\n const fidPromise: Promise<string | undefined> = validateIndexedDB().then(\n envIsValid => {\n if (envIsValid) {\n return installations.getId();\n } else {\n return undefined;\n }\n }\n );\n\n const [dynamicConfig, fid] = await Promise.all([\n dynamicConfigPromise,\n fidPromise\n ]);\n\n // Detect if user has already put the gtag <script> tag on this page with the passed in\n // data layer name.\n if (!findGtagScriptOnPage(dataLayerName)) {\n insertScriptTag(dataLayerName, dynamicConfig.measurementId);\n }\n\n // Detects if there are consent settings that need to be configured.\n if (defaultConsentSettingsForInit) {\n gtagCore(GtagCommand.CONSENT, 'default', defaultConsentSettingsForInit);\n _setConsentDefaultForInit(undefined);\n }\n\n // This command initializes gtag.js and only needs to be called once for the entire web app,\n // but since it is idempotent, we can call it multiple times.\n // We keep it together with other initialization logic for better code structure.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (gtagCore as any)('js', new Date());\n // User config added first. We don't want users to accidentally overwrite\n // base Firebase config properties.\n const configProperties: Record<string, unknown> = options?.config ?? {};\n\n // guard against developers accidentally setting properties with prefix `firebase_`\n configProperties[ORIGIN_KEY] = 'firebase';\n configProperties.update = true;\n\n if (fid != null) {\n configProperties[GA_FID_KEY] = fid;\n }\n\n // It should be the first config command called on this GA-ID\n // Initialize this GA-ID and set FID on it using the gtag config API.\n // Note: This will trigger a page_view event unless 'send_page_view' is set to false in\n // `configProperties`.\n gtagCore(GtagCommand.CONFIG, dynamicConfig.measurementId, configProperties);\n\n // Detects if there is data that will be set on every event logged from the SDK.\n if (defaultEventParametersForInit) {\n gtagCore(GtagCommand.SET, defaultEventParametersForInit);\n _setDefaultEventParametersForInit(undefined);\n }\n\n return dynamicConfig.measurementId;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SettingsOptions, Analytics, AnalyticsSettings } from './public-types';\nimport { Gtag, DynamicConfig, MinimalDynamicConfig } from './types';\nimport { getOrCreateDataLayer, wrapOrCreateGtag } from './helpers';\nimport { AnalyticsError, ERROR_FACTORY } from './errors';\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\nimport { areCookiesEnabled, isBrowserExtension } from '@firebase/util';\nimport { _initializeAnalytics } from './initialize-analytics';\nimport { logger } from './logger';\nimport { FirebaseApp, _FirebaseService } from '@firebase/app';\n\n/**\n * Analytics Service class.\n */\nexport class AnalyticsService implements Analytics, _FirebaseService {\n constructor(public app: FirebaseApp) {}\n _delete(): Promise<void> {\n delete initializationPromisesMap[this.app.options.appId!];\n return Promise.resolve();\n }\n}\n\n/**\n * Maps appId to full initialization promise. Wrapped gtag calls must wait on\n * all or some of these, depending on the call's `send_to` param and the status\n * of the dynamic config fetches (see below).\n */\nexport let initializationPromisesMap: {\n [appId: string]: Promise<string>; // Promise contains measurement ID string.\n} = {};\n\n/**\n * List of dynamic config fetch promises. In certain cases, wrapped gtag calls\n * wait on all these to be complete in order to determine if it can selectively\n * wait for only certain initialization (FID) promises or if it must wait for all.\n */\nlet dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n> = [];\n\n/**\n * Maps fetched measurementIds to appId. Populated when the app's dynamic config\n * fetch completes. If already populated, gtag config calls can use this to\n * selectively wait for only this app's initialization promise (FID) instead of all\n * initialization promises.\n */\nconst measurementIdToAppId: { [measurementId: string]: string } = {};\n\n/**\n * Name for window global data layer array used by GA: defaults to 'dataLayer'.\n */\nlet dataLayerName: string = 'dataLayer';\n\n/**\n * Name for window global gtag function used by GA: defaults to 'gtag'.\n */\nlet gtagName: string = 'gtag';\n\n/**\n * Reproduction of standard gtag function or reference to existing\n * gtag function on window object.\n */\nlet gtagCoreFunction: Gtag;\n\n/**\n * Wrapper around gtag function that ensures FID is sent with all\n * relevant event and config calls.\n */\nexport let wrappedGtagFunction: Gtag;\n\n/**\n * Flag to ensure page initialization steps (creation or wrapping of\n * dataLayer and gtag script) are only run once per page load.\n */\nlet globalInitDone: boolean = false;\n\n/**\n * For testing\n * @internal\n */\nexport function resetGlobalVars(\n newGlobalInitDone = false,\n newInitializationPromisesMap = {},\n newDynamicPromises = []\n): void {\n globalInitDone = newGlobalInitDone;\n initializationPromisesMap = newInitializationPromisesMap;\n dynamicConfigPromisesList = newDynamicPromises;\n dataLayerName = 'dataLayer';\n gtagName = 'gtag';\n}\n\n/**\n * For testing\n * @internal\n */\nexport function getGlobalVars(): {\n initializationPromisesMap: { [appId: string]: Promise<string> };\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >;\n} {\n return {\n initializationPromisesMap,\n dynamicConfigPromisesList\n };\n}\n\n/**\n * Configures Firebase Analytics to use custom `gtag` or `dataLayer` names.\n * Intended to be used if `gtag.js` script has been installed on\n * this page independently of Firebase Analytics, and is using non-default\n * names for either the `gtag` function or for `dataLayer`.\n * Must be called before calling `getAnalytics()` or it won't\n * have any effect.\n *\n * @public\n *\n * @param options - Custom gtag and dataLayer names.\n */\nexport function settings(options: SettingsOptions): void {\n if (globalInitDone) {\n throw ERROR_FACTORY.create(AnalyticsError.ALREADY_INITIALIZED);\n }\n if (options.dataLayerName) {\n dataLayerName = options.dataLayerName;\n }\n if (options.gtagName) {\n gtagName = options.gtagName;\n }\n}\n\n/**\n * Returns true if no environment mismatch is found.\n * If environment mismatches are found, throws an INVALID_ANALYTICS_CONTEXT\n * error that also lists details for each mismatch found.\n */\nfunction warnOnBrowserContextMismatch(): void {\n const mismatchedEnvMessages = [];\n if (isBrowserExtension()) {\n mismatchedEnvMessages.push('This is a browser extension environment.');\n }\n if (!areCookiesEnabled()) {\n mismatchedEnvMessages.push('Cookies are not available.');\n }\n if (mismatchedEnvMessages.length > 0) {\n const details = mismatchedEnvMessages\n .map((message, index) => `(${index + 1}) ${message}`)\n .join(' ');\n const err = ERROR_FACTORY.create(AnalyticsError.INVALID_ANALYTICS_CONTEXT, {\n errorInfo: details\n });\n logger.warn(err.message);\n }\n}\n\n/**\n * Analytics instance factory.\n * @internal\n */\nexport function factory(\n app: FirebaseApp,\n installations: _FirebaseInstallationsInternal,\n options?: AnalyticsSettings\n): AnalyticsService {\n warnOnBrowserContextMismatch();\n const appId = app.options.appId;\n if (!appId) {\n throw ERROR_FACTORY.create(AnalyticsError.NO_APP_ID);\n }\n if (!app.options.apiKey) {\n if (app.options.measurementId) {\n logger.warn(\n `The \"apiKey\" field is empty in the local Firebase config. This is needed to fetch the latest` +\n ` measurement ID for this Firebase app. Falling back to the measurement ID ${app.options.measurementId}` +\n ` provided in the \"measurementId\" field in the local Firebase config.`\n );\n } else {\n throw ERROR_FACTORY.create(AnalyticsError.NO_API_KEY);\n }\n }\n if (initializationPromisesMap[appId] != null) {\n throw ERROR_FACTORY.create(AnalyticsError.ALREADY_EXISTS, {\n id: appId\n });\n }\n\n if (!globalInitDone) {\n // Steps here should only be done once per page: creation or wrapping\n // of dataLayer and global gtag function.\n\n getOrCreateDataLayer(dataLayerName);\n\n const { wrappedGtag, gtagCore } = wrapOrCreateGtag(\n initializationPromisesMap,\n dynamicConfigPromisesList,\n measurementIdToAppId,\n dataLayerName,\n gtagName\n );\n wrappedGtagFunction = wrappedGtag;\n gtagCoreFunction = gtagCore;\n\n globalInitDone = true;\n }\n // Async but non-blocking.\n // This map reflects the completion state of all promises for each appId.\n initializationPromisesMap[appId] = _initializeAnalytics(\n app,\n dynamicConfigPromisesList,\n measurementIdToAppId,\n installations,\n gtagCoreFunction,\n dataLayerName,\n options\n );\n\n const analyticsInstance: AnalyticsService = new AnalyticsService(app);\n\n return analyticsInstance;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable camelcase */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProvider, FirebaseApp, getApp } from '@firebase/app';\nimport {\n Analytics,\n AnalyticsCallOptions,\n AnalyticsSettings,\n ConsentSettings,\n CustomParams,\n EventNameString,\n EventParams\n} from './public-types';\nimport { Provider } from '@firebase/component';\nimport {\n isIndexedDBAvailable,\n validateIndexedDBOpenable,\n areCookiesEnabled,\n isBrowserExtension,\n getModularInstance,\n deepEqual\n} from '@firebase/util';\nimport { ANALYTICS_TYPE, GtagCommand } from './constants';\nimport {\n AnalyticsService,\n initializationPromisesMap,\n wrappedGtagFunction\n} from './factory';\nimport { logger } from './logger';\nimport {\n logEvent as internalLogEvent,\n setCurrentScreen as internalSetCurrentScreen,\n setUserId as internalSetUserId,\n setUserProperties as internalSetUserProperties,\n setAnalyticsCollectionEnabled as internalSetAnalyticsCollectionEnabled,\n _setConsentDefaultForInit,\n _setDefaultEventParametersForInit,\n internalGetGoogleAnalyticsClientId\n} from './functions';\nimport { ERROR_FACTORY, AnalyticsError } from './errors';\n\nexport { settings } from './factory';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n [ANALYTICS_TYPE]: AnalyticsService;\n }\n}\n\n/**\n * Returns an {@link Analytics} instance for the given app.\n *\n * @public\n *\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n */\nexport function getAnalytics(app: FirebaseApp = getApp()): Analytics {\n app = getModularInstance(app);\n // Dependencies\n const analyticsProvider: Provider<'analytics'> = _getProvider(\n app,\n ANALYTICS_TYPE\n );\n\n if (analyticsProvider.isInitialized()) {\n return analyticsProvider.getImmediate();\n }\n\n return initializeAnalytics(app);\n}\n\n/**\n * Returns an {@link Analytics} instance for the given app.\n *\n * @public\n *\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n */\nexport function initializeAnalytics(\n app: FirebaseApp,\n options: AnalyticsSettings = {}\n): Analytics {\n // Dependencies\n const analyticsProvider: Provider<'analytics'> = _getProvider(\n app,\n ANALYTICS_TYPE\n );\n if (analyticsProvider.isInitialized()) {\n const existingInstance = analyticsProvider.getImmediate();\n if (deepEqual(options, analyticsProvider.getOptions())) {\n return existingInstance;\n } else {\n throw ERROR_FACTORY.create(AnalyticsError.ALREADY_INITIALIZED);\n }\n }\n const analyticsInstance = analyticsProvider.initialize({ options });\n return analyticsInstance;\n}\n\n/**\n * This is a public static method provided to users that wraps four different checks:\n *\n * 1. Check if it's not a browser extension environment.\n * 2. Check if cookies are enabled in current browser.\n * 3. Check if IndexedDB is supported by the browser environment.\n * 4. Check if the current browser context is valid for using `IndexedDB.open()`.\n *\n * @public\n *\n */\nexport async function isSupported(): Promise<boolean> {\n if (isBrowserExtension()) {\n return false;\n }\n if (!areCookiesEnabled()) {\n return false;\n }\n if (!isIndexedDBAvailable()) {\n return false;\n }\n\n try {\n const isDBOpenable: boolean = await validateIndexedDBOpenable();\n return isDBOpenable;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Use gtag `config` command to set `screen_name`.\n *\n * @public\n *\n * @deprecated Use {@link logEvent} with `eventName` as 'screen_view' and add relevant `eventParams`.\n * See {@link https://firebase.google.com/docs/analytics/screenviews | Track Screenviews}.\n *\n * @param analyticsInstance - The {@link Analytics} instance.\n * @param screenName - Screen name to set.\n */\nexport function setCurrentScreen(\n analyticsInstance: Analytics,\n screenName: string,\n options?: AnalyticsCallOptions\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalSetCurrentScreen(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n screenName,\n options\n ).catch(e => logger.error(e));\n}\n\n/**\n * Retrieves a unique Google Analytics identifier for the web client.\n * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.\n *\n * @public\n *\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n */\nexport async function getGoogleAnalyticsClientId(\n analyticsInstance: Analytics\n): Promise<string> {\n analyticsInstance = getModularInstance(analyticsInstance);\n return internalGetGoogleAnalyticsClientId(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!]\n );\n}\n\n/**\n * Use gtag `config` command to set `user_id`.\n *\n * @public\n *\n * @param analyticsInstance - The {@link Analytics} instance.\n * @param id - User ID to set.\n */\nexport function setUserId(\n analyticsInstance: Analytics,\n id: string | null,\n options?: AnalyticsCallOptions\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalSetUserId(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n id,\n options\n ).catch(e => logger.error(e));\n}\n\n/**\n * Use gtag `config` command to set all params specified.\n *\n * @public\n */\nexport function setUserProperties(\n analyticsInstance: Analytics,\n properties: CustomParams,\n options?: AnalyticsCallOptions\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalSetUserProperties(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n properties,\n options\n ).catch(e => logger.error(e));\n}\n\n/**\n * Sets whether Google Analytics collection is enabled for this app on this device.\n * Sets global `window['ga-disable-analyticsId'] = true;`\n *\n * @public\n *\n * @param analyticsInstance - The {@link Analytics} instance.\n * @param enabled - If true, enables collection, if false, disables it.\n */\nexport function setAnalyticsCollectionEnabled(\n analyticsInstance: Analytics,\n enabled: boolean\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalSetAnalyticsCollectionEnabled(\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n enabled\n ).catch(e => logger.error(e));\n}\n\n/**\n * Adds data that will be set on every event logged from the SDK, including automatic ones.\n * With gtag's \"set\" command, the values passed persist on the current page and are passed with\n * all subsequent events.\n * @public\n * @param customParams - Any custom params the user may pass to gtag.js.\n */\nexport function setDefaultEventParameters(customParams: CustomParams): void {\n // Check if reference to existing gtag function on window object exists\n if (wrappedGtagFunction) {\n wrappedGtagFunction(GtagCommand.SET, customParams);\n } else {\n _setDefaultEventParametersForInit(customParams);\n }\n}\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'add_payment_info',\n eventParams?: {\n coupon?: EventParams['coupon'];\n currency?: EventParams['currency'];\n items?: EventParams['items'];\n payment_type?: EventParams['payment_type'];\n value?: EventParams['value'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'add_shipping_info',\n eventParams?: {\n coupon?: EventParams['coupon'];\n currency?: EventParams['currency'];\n items?: EventParams['items'];\n shipping_tier?: EventParams['shipping_tier'];\n value?: EventParams['value'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'add_to_cart' | 'add_to_wishlist' | 'remove_from_cart',\n eventParams?: {\n currency?: EventParams['currency'];\n value?: EventParams['value'];\n items?: EventParams['items'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'begin_checkout',\n eventParams?: {\n currency?: EventParams['currency'];\n coupon?: EventParams['coupon'];\n value?: EventParams['value'];\n items?: EventParams['items'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'checkout_progress',\n eventParams?: {\n currency?: EventParams['currency'];\n coupon?: EventParams['coupon'];\n value?: EventParams['value'];\n items?: EventParams['items'];\n checkout_step?: EventParams['checkout_step'];\n checkout_option?: EventParams['checkout_option'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * See\n * {@link https://developers.google.com/analytics/devguides/collection/ga4/exceptions\n * | Measure exceptions}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'exception',\n eventParams?: {\n description?: EventParams['description'];\n fatal?: EventParams['fatal'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'generate_lead',\n eventParams?: {\n value?: EventParams['value'];\n currency?: EventParams['currency'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'login',\n eventParams?: {\n method?: EventParams['method'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * See\n * {@link https://developers.google.com/analytics/devguides/collection/ga4/page-view\n * | Page views}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'page_view',\n eventParams?: {\n page_title?: string;\n page_location?: string;\n page_path?: string;\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'purchase' | 'refund',\n eventParams?: {\n value?: EventParams['value'];\n currency?: EventParams['currency'];\n transaction_id: EventParams['transaction_id'];\n tax?: EventParams['tax'];\n shipping?: EventParams['shipping'];\n items?: EventParams['items'];\n coupon?: EventParams['coupon'];\n affiliation?: EventParams['affiliation'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * See {@link https://firebase.google.com/docs/analytics/screenviews\n * | Track Screenviews}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'screen_view',\n eventParams?: {\n firebase_screen: EventParams['firebase_screen'];\n firebase_screen_class: EventParams['firebase_screen_class'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'search' | 'view_search_results',\n eventParams?: {\n search_term?: EventParams['search_term'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'select_content',\n eventParams?: {\n content_type?: EventParams['content_type'];\n item_id?: EventParams['item_id'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'select_item',\n eventParams?: {\n items?: EventParams['items'];\n item_list_name?: EventParams['item_list_name'];\n item_list_id?: EventParams['item_list_id'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'select_promotion' | 'view_promotion',\n eventParams?: {\n items?: EventParams['items'];\n promotion_id?: EventParams['promotion_id'];\n promotion_name?: EventParams['promotion_name'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'set_checkout_option',\n eventParams?: {\n checkout_step?: EventParams['checkout_step'];\n checkout_option?: EventParams['checkout_option'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'share',\n eventParams?: {\n method?: EventParams['method'];\n content_type?: EventParams['content_type'];\n item_id?: EventParams['item_id'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'sign_up',\n eventParams?: {\n method?: EventParams['method'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'timing_complete',\n eventParams?: {\n name: string;\n value: number;\n event_category?: string;\n event_label?: string;\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'view_cart' | 'view_item',\n eventParams?: {\n currency?: EventParams['currency'];\n items?: EventParams['items'];\n value?: EventParams['value'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'view_item_list',\n eventParams?: {\n items?: EventParams['items'];\n item_list_name?: EventParams['item_list_name'];\n item_list_id?: EventParams['item_list_id'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent<T extends string>(\n analyticsInstance: Analytics,\n eventName: CustomEventName<T>,\n eventParams?: { [key: string]: any },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * List of official event parameters can be found in the gtag.js\n * reference documentation:\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n *\n * @public\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: string,\n eventParams?: EventParams,\n options?: AnalyticsCallOptions\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalLogEvent(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n eventName,\n eventParams,\n options\n ).catch(e => logger.error(e));\n}\n\n/**\n * Any custom event name string not in the standard list of recommended\n * event names.\n * @public\n */\nexport type CustomEventName<T> = T extends EventNameString ? never : T;\n\n/**\n * Sets the applicable end user consent state for this web app across all gtag references once\n * Firebase Analytics is initialized.\n *\n * Use the {@link ConsentSettings} to specify individual consent type values. By default consent\n * types are set to \"granted\".\n * @public\n * @param consentSettings - Maps the applicable end user consent state for gtag.js.\n */\nexport function setConsent(consentSettings: ConsentSettings): void {\n // Check if reference to existing gtag function on window object exists\n if (wrappedGtagFunction) {\n wrappedGtagFunction(GtagCommand.CONSENT, 'update', consentSettings);\n } else {\n _setConsentDefaultForInit(consentSettings);\n }\n}\n","/**\n * Firebase Analytics\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerVersion, _registerComponent } from '@firebase/app';\nimport { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types';\nimport { factory } from './factory';\nimport { ANALYTICS_TYPE } from './constants';\nimport {\n Component,\n ComponentType,\n ComponentContainer,\n InstanceFactoryOptions\n} from '@firebase/component';\nimport { ERROR_FACTORY, AnalyticsError } from './errors';\nimport { logEvent } from './api';\nimport { name, version } from '../package.json';\nimport { AnalyticsCallOptions } from './public-types';\nimport '@firebase/installations';\n\ndeclare global {\n interface Window {\n [key: string]: unknown;\n }\n}\n\nfunction registerAnalytics(): void {\n _registerComponent(\n new Component(\n ANALYTICS_TYPE,\n (container, { options: analyticsOptions }: InstanceFactoryOptions) => {\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app').getImmediate();\n const installations = container\n .getProvider('installations-internal')\n .getImmediate();\n\n return factory(app, installations, analyticsOptions);\n },\n ComponentType.PUBLIC\n )\n );\n\n _registerComponent(\n new Component('analytics-internal', internalFactory, ComponentType.PRIVATE)\n );\n\n registerVersion(name, version);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n\n function internalFactory(\n container: ComponentContainer\n ): FirebaseAnalyticsInternal {\n try {\n const analytics = container.getProvider(ANALYTICS_TYPE).getImmediate();\n return {\n logEvent: (\n eventName: string,\n eventParams?: { [key: string]: unknown },\n options?: AnalyticsCallOptions\n ) => logEvent(analytics, eventName, eventParams, options)\n };\n } catch (e) {\n throw ERROR_FACTORY.create(AnalyticsError.INTEROP_COMPONENT_REG_FAILED, {\n reason: e as Error\n });\n }\n }\n}\n\nregisterAnalytics();\n\nexport * from './api';\nexport * from './public-types';\n","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n function next() {\n while (env.stack.length) {\n var rec = env.stack.pop();\n try {\n var result = rec.dispose && rec.dispose.call(rec.value);\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n catch (e) {\n fail(e);\n }\n }\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorMap, User } from '../model/public_types';\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nimport { IdTokenMfaResponse } from '../api/authentication/mfa';\nimport { AppName } from '../model/auth';\nimport { AuthCredential } from './credentials';\n\n/**\n * Enumeration of Firebase Auth error codes.\n *\n * @internal\n */\nexport const enum AuthErrorCode {\n ADMIN_ONLY_OPERATION = 'admin-restricted-operation',\n ARGUMENT_ERROR = 'argument-error',\n APP_NOT_AUTHORIZED = 'app-not-authorized',\n APP_NOT_INSTALLED = 'app-not-installed',\n CAPTCHA_CHECK_FAILED = 'captcha-check-failed',\n CODE_EXPIRED = 'code-expired',\n CORDOVA_NOT_READY = 'cordova-not-ready',\n CORS_UNSUPPORTED = 'cors-unsupported',\n CREDENTIAL_ALREADY_IN_USE = 'credential-already-in-use',\n CREDENTIAL_MISMATCH = 'custom-token-mismatch',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN = 'requires-recent-login',\n DEPENDENT_SDK_INIT_BEFORE_AUTH = 'dependent-sdk-initialized-before-auth',\n DYNAMIC_LINK_NOT_ACTIVATED = 'dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION = 'email-change-needs-verification',\n EMAIL_EXISTS = 'email-already-in-use',\n EMULATOR_CONFIG_FAILED = 'emulator-config-failed',\n EXPIRED_OOB_CODE = 'expired-action-code',\n EXPIRED_POPUP_REQUEST = 'cancelled-popup-request',\n INTERNAL_ERROR = 'internal-error',\n INVALID_API_KEY = 'invalid-api-key',\n INVALID_APP_CREDENTIAL = 'invalid-app-credential',\n INVALID_APP_ID = 'invalid-app-id',\n INVALID_AUTH = 'invalid-user-token',\n INVALID_AUTH_EVENT = 'invalid-auth-event',\n INVALID_CERT_HASH = 'invalid-cert-hash',\n INVALID_CODE = 'invalid-verification-code',\n INVALID_CONTINUE_URI = 'invalid-continue-uri',\n INVALID_CORDOVA_CONFIGURATION = 'invalid-cordova-configuration',\n INVALID_CUSTOM_TOKEN = 'invalid-custom-token',\n INVALID_DYNAMIC_LINK_DOMAIN = 'invalid-dynamic-link-domain',\n INVALID_EMAIL = 'invalid-email',\n INVALID_EMULATOR_SCHEME = 'invalid-emulator-scheme',\n INVALID_IDP_RESPONSE = 'invalid-credential',\n INVALID_MESSAGE_PAYLOAD = 'invalid-message-payload',\n INVALID_MFA_SESSION = 'invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID = 'invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER = 'invalid-oauth-provider',\n INVALID_OOB_CODE = 'invalid-action-code',\n INVALID_ORIGIN = 'unauthorized-domain',\n INVALID_PASSWORD = 'wrong-password',\n INVALID_PERSISTENCE = 'invalid-persistence-type',\n INVALID_PHONE_NUMBER = 'invalid-phone-number',\n INVALID_PROVIDER_ID = 'invalid-provider-id',\n INVALID_RECIPIENT_EMAIL = 'invalid-recipient-email',\n INVALID_SENDER = 'invalid-sender',\n INVALID_SESSION_INFO = 'invalid-verification-id',\n INVALID_TENANT_ID = 'invalid-tenant-id',\n LOGIN_BLOCKED = 'login-blocked',\n MFA_INFO_NOT_FOUND = 'multi-factor-info-not-found',\n MFA_REQUIRED = 'multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME = 'missing-android-pkg-name',\n MISSING_APP_CREDENTIAL = 'missing-app-credential',\n MISSING_AUTH_DOMAIN = 'auth-domain-config-required',\n MISSING_CODE = 'missing-verification-code',\n MISSING_CONTINUE_URI = 'missing-continue-uri',\n MISSING_IFRAME_START = 'missing-iframe-start',\n MISSING_IOS_BUNDLE_ID = 'missing-ios-bundle-id',\n MISSING_OR_INVALID_NONCE = 'missing-or-invalid-nonce',\n MISSING_MFA_INFO = 'missing-multi-factor-info',\n MISSING_MFA_SESSION = 'missing-multi-factor-session',\n MISSING_PHONE_NUMBER = 'missing-phone-number',\n MISSING_PASSWORD = 'missing-password',\n MISSING_SESSION_INFO = 'missing-verification-id',\n MODULE_DESTROYED = 'app-deleted',\n NEED_CONFIRMATION = 'account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED = 'network-request-failed',\n NULL_USER = 'null-user',\n NO_AUTH_EVENT = 'no-auth-event',\n NO_SUCH_PROVIDER = 'no-such-provider',\n OPERATION_NOT_ALLOWED = 'operation-not-allowed',\n OPERATION_NOT_SUPPORTED = 'operation-not-supported-in-this-environment',\n POPUP_BLOCKED = 'popup-blocked',\n POPUP_CLOSED_BY_USER = 'popup-closed-by-user',\n PROVIDER_ALREADY_LINKED = 'provider-already-linked',\n QUOTA_EXCEEDED = 'quota-exceeded',\n REDIRECT_CANCELLED_BY_USER = 'redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING = 'redirect-operation-pending',\n REJECTED_CREDENTIAL = 'rejected-credential',\n SECOND_FACTOR_ALREADY_ENROLLED = 'second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED = 'maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH = 'tenant-id-mismatch',\n TIMEOUT = 'timeout',\n TOKEN_EXPIRED = 'user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER = 'too-many-requests',\n UNAUTHORIZED_DOMAIN = 'unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR = 'unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE = 'unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION = 'unsupported-tenant-operation',\n UNVERIFIED_EMAIL = 'unverified-email',\n USER_CANCELLED = 'user-cancelled',\n USER_DELETED = 'user-not-found',\n USER_DISABLED = 'user-disabled',\n USER_MISMATCH = 'user-mismatch',\n USER_SIGNED_OUT = 'user-signed-out',\n WEAK_PASSWORD = 'weak-password',\n WEB_STORAGE_UNSUPPORTED = 'web-storage-unsupported',\n ALREADY_INITIALIZED = 'already-initialized',\n RECAPTCHA_NOT_ENABLED = 'recaptcha-not-enabled',\n MISSING_RECAPTCHA_TOKEN = 'missing-recaptcha-token',\n INVALID_RECAPTCHA_TOKEN = 'invalid-recaptcha-token',\n INVALID_RECAPTCHA_ACTION = 'invalid-recaptcha-action',\n MISSING_CLIENT_TYPE = 'missing-client-type',\n MISSING_RECAPTCHA_VERSION = 'missing-recaptcha-version',\n INVALID_RECAPTCHA_VERSION = 'invalid-recaptcha-version',\n INVALID_REQ_TYPE = 'invalid-req-type',\n UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION = 'unsupported-password-policy-schema-version',\n PASSWORD_DOES_NOT_MEET_REQUIREMENTS = 'password-does-not-meet-requirements'\n}\n\nfunction _debugErrorMap(): ErrorMap<AuthErrorCode> {\n return {\n [AuthErrorCode.ADMIN_ONLY_OPERATION]:\n 'This operation is restricted to administrators only.',\n [AuthErrorCode.ARGUMENT_ERROR]: '',\n [AuthErrorCode.APP_NOT_AUTHORIZED]:\n \"This app, identified by the domain where it's hosted, is not \" +\n 'authorized to use Firebase Authentication with the provided API key. ' +\n 'Review your key configuration in the Google API console.',\n [AuthErrorCode.APP_NOT_INSTALLED]:\n 'The requested mobile application corresponding to the identifier (' +\n 'Android package name or iOS bundle ID) provided is not installed on ' +\n 'this device.',\n [AuthErrorCode.CAPTCHA_CHECK_FAILED]:\n 'The reCAPTCHA response token provided is either invalid, expired, ' +\n 'already used or the domain associated with it does not match the list ' +\n 'of whitelisted domains.',\n [AuthErrorCode.CODE_EXPIRED]:\n 'The SMS code has expired. Please re-send the verification code to try ' +\n 'again.',\n [AuthErrorCode.CORDOVA_NOT_READY]: 'Cordova framework is not ready.',\n [AuthErrorCode.CORS_UNSUPPORTED]: 'This browser is not supported.',\n [AuthErrorCode.CREDENTIAL_ALREADY_IN_USE]:\n 'This credential is already associated with a different user account.',\n [AuthErrorCode.CREDENTIAL_MISMATCH]:\n 'The custom token corresponds to a different audience.',\n [AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN]:\n 'This operation is sensitive and requires recent authentication. Log in ' +\n 'again before retrying this request.',\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]:\n 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.',\n [AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED]:\n 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +\n 'conditions.',\n [AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION]:\n 'Multi-factor users must always have a verified email.',\n [AuthErrorCode.EMAIL_EXISTS]:\n 'The email address is already in use by another account.',\n [AuthErrorCode.EMULATOR_CONFIG_FAILED]:\n 'Auth instance has already been used to make a network call. Auth can ' +\n 'no longer be configured to use the emulator. Try calling ' +\n '\"connectAuthEmulator()\" sooner.',\n [AuthErrorCode.EXPIRED_OOB_CODE]: 'The action code has expired.',\n [AuthErrorCode.EXPIRED_POPUP_REQUEST]:\n 'This operation has been cancelled due to another conflicting popup being opened.',\n [AuthErrorCode.INTERNAL_ERROR]: 'An internal AuthError has occurred.',\n [AuthErrorCode.INVALID_APP_CREDENTIAL]:\n 'The phone verification request contains an invalid application verifier.' +\n ' The reCAPTCHA token response is either invalid or expired.',\n [AuthErrorCode.INVALID_APP_ID]:\n 'The mobile app identifier is not registed for the current project.',\n [AuthErrorCode.INVALID_AUTH]:\n \"This user's credential isn't valid for this project. This can happen \" +\n \"if the user's token has been tampered with, or if the user isn't for \" +\n 'the project associated with this API key.',\n [AuthErrorCode.INVALID_AUTH_EVENT]: 'An internal AuthError has occurred.',\n [AuthErrorCode.INVALID_CODE]:\n 'The SMS verification code used to create the phone auth credential is ' +\n 'invalid. Please resend the verification code sms and be sure to use the ' +\n 'verification code provided by the user.',\n [AuthErrorCode.INVALID_CONTINUE_URI]:\n 'The continue URL provided in the request is invalid.',\n [AuthErrorCode.INVALID_CORDOVA_CONFIGURATION]:\n 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +\n 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +\n 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +\n 'cordova-plugin-customurlscheme.',\n [AuthErrorCode.INVALID_CUSTOM_TOKEN]:\n 'The custom token format is incorrect. Please check the documentation.',\n [AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN]:\n 'The provided dynamic link domain is not configured or authorized for the current project.',\n [AuthErrorCode.INVALID_EMAIL]: 'The email address is badly formatted.',\n [AuthErrorCode.INVALID_EMULATOR_SCHEME]:\n 'Emulator URL must start with a valid scheme (http:// or https://).',\n [AuthErrorCode.INVALID_API_KEY]:\n 'Your API key is invalid, please check you have copied it correctly.',\n [AuthErrorCode.INVALID_CERT_HASH]:\n 'The SHA-1 certificate hash provided is invalid.',\n [AuthErrorCode.INVALID_IDP_RESPONSE]:\n 'The supplied auth credential is malformed or has expired.',\n [AuthErrorCode.INVALID_MESSAGE_PAYLOAD]:\n 'The email template corresponding to this action contains invalid characters in its message. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [AuthErrorCode.INVALID_MFA_SESSION]:\n 'The request does not contain a valid proof of first factor successful sign-in.',\n [AuthErrorCode.INVALID_OAUTH_PROVIDER]:\n 'EmailAuthProvider is not supported for this operation. This operation ' +\n 'only supports OAuth providers.',\n [AuthErrorCode.INVALID_OAUTH_CLIENT_ID]:\n 'The OAuth client ID provided is either invalid or does not match the ' +\n 'specified API key.',\n [AuthErrorCode.INVALID_ORIGIN]:\n 'This domain is not authorized for OAuth operations for your Firebase ' +\n 'project. Edit the list of authorized domains from the Firebase console.',\n [AuthErrorCode.INVALID_OOB_CODE]:\n 'The action code is invalid. This can happen if the code is malformed, ' +\n 'expired, or has already been used.',\n [AuthErrorCode.INVALID_PASSWORD]:\n 'The password is invalid or the user does not have a password.',\n [AuthErrorCode.INVALID_PERSISTENCE]:\n 'The specified persistence type is invalid. It can only be local, session or none.',\n [AuthErrorCode.INVALID_PHONE_NUMBER]:\n 'The format of the phone number provided is incorrect. Please enter the ' +\n 'phone number in a format that can be parsed into E.164 format. E.164 ' +\n 'phone numbers are written in the format [+][country code][subscriber ' +\n 'number including area code].',\n [AuthErrorCode.INVALID_PROVIDER_ID]:\n 'The specified provider ID is invalid.',\n [AuthErrorCode.INVALID_RECIPIENT_EMAIL]:\n 'The email corresponding to this action failed to send as the provided ' +\n 'recipient email address is invalid.',\n [AuthErrorCode.INVALID_SENDER]:\n 'The email template corresponding to this action contains an invalid sender email or name. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [AuthErrorCode.INVALID_SESSION_INFO]:\n 'The verification ID used to create the phone auth credential is invalid.',\n [AuthErrorCode.INVALID_TENANT_ID]:\n \"The Auth instance's tenant ID is invalid.\",\n [AuthErrorCode.LOGIN_BLOCKED]:\n 'Login blocked by user-provided method: {$originalMessage}',\n [AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME]:\n 'An Android Package Name must be provided if the Android App is required to be installed.',\n [AuthErrorCode.MISSING_AUTH_DOMAIN]:\n 'Be sure to include authDomain when calling firebase.initializeApp(), ' +\n 'by following the instructions in the Firebase console.',\n [AuthErrorCode.MISSING_APP_CREDENTIAL]:\n 'The phone verification request is missing an application verifier ' +\n 'assertion. A reCAPTCHA response token needs to be provided.',\n [AuthErrorCode.MISSING_CODE]:\n 'The phone auth credential was created with an empty SMS verification code.',\n [AuthErrorCode.MISSING_CONTINUE_URI]:\n 'A continue URL must be provided in the request.',\n [AuthErrorCode.MISSING_IFRAME_START]: 'An internal AuthError has occurred.',\n [AuthErrorCode.MISSING_IOS_BUNDLE_ID]:\n 'An iOS Bundle ID must be provided if an App Store ID is provided.',\n [AuthErrorCode.MISSING_OR_INVALID_NONCE]:\n 'The request does not contain a valid nonce. This can occur if the ' +\n 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +\n 'in the ID token payload.',\n [AuthErrorCode.MISSING_PASSWORD]: 'A non-empty password must be provided',\n [AuthErrorCode.MISSING_MFA_INFO]:\n 'No second factor identifier is provided.',\n [AuthErrorCode.MISSING_MFA_SESSION]:\n 'The request is missing proof of first factor successful sign-in.',\n [AuthErrorCode.MISSING_PHONE_NUMBER]:\n 'To send verification codes, provide a phone number for the recipient.',\n [AuthErrorCode.MISSING_SESSION_INFO]:\n 'The phone auth credential was created with an empty verification ID.',\n [AuthErrorCode.MODULE_DESTROYED]:\n 'This instance of FirebaseApp has been deleted.',\n [AuthErrorCode.MFA_INFO_NOT_FOUND]:\n 'The user does not have a second factor matching the identifier provided.',\n [AuthErrorCode.MFA_REQUIRED]:\n 'Proof of ownership of a second factor is required to complete sign-in.',\n [AuthErrorCode.NEED_CONFIRMATION]:\n 'An account already exists with the same email address but different ' +\n 'sign-in credentials. Sign in using a provider associated with this ' +\n 'email address.',\n [AuthErrorCode.NETWORK_REQUEST_FAILED]:\n 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',\n [AuthErrorCode.NO_AUTH_EVENT]: 'An internal AuthError has occurred.',\n [AuthErrorCode.NO_SUCH_PROVIDER]:\n 'User was not linked to an account with the given provider.',\n [AuthErrorCode.NULL_USER]:\n 'A null user object was provided as the argument for an operation which ' +\n 'requires a non-null user object.',\n [AuthErrorCode.OPERATION_NOT_ALLOWED]:\n 'The given sign-in provider is disabled for this Firebase project. ' +\n 'Enable it in the Firebase console, under the sign-in method tab of the ' +\n 'Auth section.',\n [AuthErrorCode.OPERATION_NOT_SUPPORTED]:\n 'This operation is not supported in the environment this application is ' +\n 'running on. \"location.protocol\" must be http, https or chrome-extension' +\n ' and web storage must be enabled.',\n [AuthErrorCode.POPUP_BLOCKED]:\n 'Unable to establish a connection with the popup. It may have been blocked by the browser.',\n [AuthErrorCode.POPUP_CLOSED_BY_USER]:\n 'The popup has been closed by the user before finalizing the operation.',\n [AuthErrorCode.PROVIDER_ALREADY_LINKED]:\n 'User can only be linked to one identity for the given provider.',\n [AuthErrorCode.QUOTA_EXCEEDED]:\n \"The project's quota for this operation has been exceeded.\",\n [AuthErrorCode.REDIRECT_CANCELLED_BY_USER]:\n 'The redirect operation has been cancelled by the user before finalizing.',\n [AuthErrorCode.REDIRECT_OPERATION_PENDING]:\n 'A redirect sign-in operation is already pending.',\n [AuthErrorCode.REJECTED_CREDENTIAL]:\n 'The request contains malformed or mismatching credentials.',\n [AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED]:\n 'The second factor is already enrolled on this account.',\n [AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED]:\n 'The maximum allowed number of second factors on a user has been exceeded.',\n [AuthErrorCode.TENANT_ID_MISMATCH]:\n \"The provided tenant ID does not match the Auth instance's tenant ID\",\n [AuthErrorCode.TIMEOUT]: 'The operation has timed out.',\n [AuthErrorCode.TOKEN_EXPIRED]:\n \"The user's credential is no longer valid. The user must sign in again.\",\n [AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER]:\n 'We have blocked all requests from this device due to unusual activity. ' +\n 'Try again later.',\n [AuthErrorCode.UNAUTHORIZED_DOMAIN]:\n 'The domain of the continue URL is not whitelisted. Please whitelist ' +\n 'the domain in the Firebase console.',\n [AuthErrorCode.UNSUPPORTED_FIRST_FACTOR]:\n 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',\n [AuthErrorCode.UNSUPPORTED_PERSISTENCE]:\n 'The current environment does not support the specified persistence type.',\n [AuthErrorCode.UNSUPPORTED_TENANT_OPERATION]:\n 'This operation is not supported in a multi-tenant context.',\n [AuthErrorCode.UNVERIFIED_EMAIL]:\n 'The operation requires a verified email.',\n [AuthErrorCode.USER_CANCELLED]:\n 'The user did not grant your application the permissions it requested.',\n [AuthErrorCode.USER_DELETED]:\n 'There is no user record corresponding to this identifier. The user may ' +\n 'have been deleted.',\n [AuthErrorCode.USER_DISABLED]:\n 'The user account has been disabled by an administrator.',\n [AuthErrorCode.USER_MISMATCH]:\n 'The supplied credentials do not correspond to the previously signed in user.',\n [AuthErrorCode.USER_SIGNED_OUT]: '',\n [AuthErrorCode.WEAK_PASSWORD]:\n 'The password must be 6 characters long or more.',\n [AuthErrorCode.WEB_STORAGE_UNSUPPORTED]:\n 'This browser is not supported or 3rd party cookies and data may be disabled.',\n [AuthErrorCode.ALREADY_INITIALIZED]:\n 'initializeAuth() has already been called with ' +\n 'different options. To avoid this error, call initializeAuth() with the ' +\n 'same options as when it was originally called, or call getAuth() to return the' +\n ' already initialized instance.',\n [AuthErrorCode.MISSING_RECAPTCHA_TOKEN]:\n 'The reCAPTCHA token is missing when sending request to the backend.',\n [AuthErrorCode.INVALID_RECAPTCHA_TOKEN]:\n 'The reCAPTCHA token is invalid when sending request to the backend.',\n [AuthErrorCode.INVALID_RECAPTCHA_ACTION]:\n 'The reCAPTCHA action is invalid when sending request to the backend.',\n [AuthErrorCode.RECAPTCHA_NOT_ENABLED]:\n 'reCAPTCHA Enterprise integration is not enabled for this project.',\n [AuthErrorCode.MISSING_CLIENT_TYPE]:\n 'The reCAPTCHA client type is missing when sending request to the backend.',\n [AuthErrorCode.MISSING_RECAPTCHA_VERSION]:\n 'The reCAPTCHA version is missing when sending request to the backend.',\n [AuthErrorCode.INVALID_REQ_TYPE]: 'Invalid request parameters.',\n [AuthErrorCode.INVALID_RECAPTCHA_VERSION]:\n 'The reCAPTCHA version is invalid when sending request to the backend.',\n [AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION]:\n 'The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.',\n [AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS]:\n 'The password does not meet the requirements.'\n };\n}\n\nexport interface ErrorMapRetriever extends AuthErrorMap {\n (): ErrorMap<AuthErrorCode>;\n}\n\nfunction _prodErrorMap(): ErrorMap<AuthErrorCode> {\n // We will include this one message in the prod error map since by the very\n // nature of this error, developers will never be able to see the message\n // using the debugErrorMap (which is installed during auth initialization).\n return {\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]:\n 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.'\n } as ErrorMap<AuthErrorCode>;\n}\n\n/**\n * A verbose error map with detailed descriptions for most error codes.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nexport const debugErrorMap: AuthErrorMap = _debugErrorMap;\n\n/**\n * A minimal error map with all verbose error messages stripped.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nexport const prodErrorMap: AuthErrorMap = _prodErrorMap;\n\nexport interface NamedErrorParams {\n appName: AppName;\n credential?: AuthCredential;\n email?: string;\n phoneNumber?: string;\n tenantId?: string;\n user?: User;\n _serverResponse?: object;\n}\n\n/**\n * @internal\n */\ntype GenericAuthErrorParams = {\n [key in Exclude<\n AuthErrorCode,\n | AuthErrorCode.ARGUMENT_ERROR\n | AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH\n | AuthErrorCode.INTERNAL_ERROR\n | AuthErrorCode.MFA_REQUIRED\n | AuthErrorCode.NO_AUTH_EVENT\n | AuthErrorCode.OPERATION_NOT_SUPPORTED\n >]: {\n appName?: AppName;\n email?: string;\n phoneNumber?: string;\n message?: string;\n };\n};\n\n/**\n * @internal\n */\nexport interface AuthErrorParams extends GenericAuthErrorParams {\n [AuthErrorCode.ARGUMENT_ERROR]: { appName?: AppName };\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]: { appName?: AppName };\n [AuthErrorCode.INTERNAL_ERROR]: { appName?: AppName };\n [AuthErrorCode.LOGIN_BLOCKED]: {\n appName?: AppName;\n originalMessage?: string;\n };\n [AuthErrorCode.OPERATION_NOT_SUPPORTED]: { appName?: AppName };\n [AuthErrorCode.NO_AUTH_EVENT]: { appName?: AppName };\n [AuthErrorCode.MFA_REQUIRED]: {\n appName: AppName;\n _serverResponse: IdTokenMfaResponse;\n };\n [AuthErrorCode.INVALID_CORDOVA_CONFIGURATION]: {\n appName: AppName;\n missingPlugin?: string;\n };\n}\n\nexport const _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory<\n AuthErrorCode,\n AuthErrorParams\n>('auth', 'Firebase', _prodErrorMap());\n\n/**\n * A map of potential `Auth` error codes, for easier comparison with errors\n * thrown by the SDK.\n *\n * @remarks\n * Note that you can't tree-shake individual keys\n * in the map, so by using the map you might substantially increase your\n * bundle size.\n *\n * @public\n */\nexport const AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {\n ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',\n ARGUMENT_ERROR: 'auth/argument-error',\n APP_NOT_AUTHORIZED: 'auth/app-not-authorized',\n APP_NOT_INSTALLED: 'auth/app-not-installed',\n CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',\n CODE_EXPIRED: 'auth/code-expired',\n CORDOVA_NOT_READY: 'auth/cordova-not-ready',\n CORS_UNSUPPORTED: 'auth/cors-unsupported',\n CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',\n CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',\n DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',\n DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',\n EMAIL_EXISTS: 'auth/email-already-in-use',\n EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',\n EXPIRED_OOB_CODE: 'auth/expired-action-code',\n EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',\n INTERNAL_ERROR: 'auth/internal-error',\n INVALID_API_KEY: 'auth/invalid-api-key',\n INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',\n INVALID_APP_ID: 'auth/invalid-app-id',\n INVALID_AUTH: 'auth/invalid-user-token',\n INVALID_AUTH_EVENT: 'auth/invalid-auth-event',\n INVALID_CERT_HASH: 'auth/invalid-cert-hash',\n INVALID_CODE: 'auth/invalid-verification-code',\n INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',\n INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',\n INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',\n INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',\n INVALID_EMAIL: 'auth/invalid-email',\n INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',\n INVALID_IDP_RESPONSE: 'auth/invalid-credential',\n INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',\n INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',\n INVALID_OOB_CODE: 'auth/invalid-action-code',\n INVALID_ORIGIN: 'auth/unauthorized-domain',\n INVALID_PASSWORD: 'auth/wrong-password',\n INVALID_PERSISTENCE: 'auth/invalid-persistence-type',\n INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',\n INVALID_PROVIDER_ID: 'auth/invalid-provider-id',\n INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',\n INVALID_SENDER: 'auth/invalid-sender',\n INVALID_SESSION_INFO: 'auth/invalid-verification-id',\n INVALID_TENANT_ID: 'auth/invalid-tenant-id',\n MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',\n MFA_REQUIRED: 'auth/multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',\n MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',\n MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',\n MISSING_CODE: 'auth/missing-verification-code',\n MISSING_CONTINUE_URI: 'auth/missing-continue-uri',\n MISSING_IFRAME_START: 'auth/missing-iframe-start',\n MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',\n MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',\n MISSING_MFA_INFO: 'auth/missing-multi-factor-info',\n MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',\n MISSING_PHONE_NUMBER: 'auth/missing-phone-number',\n MISSING_SESSION_INFO: 'auth/missing-verification-id',\n MODULE_DESTROYED: 'auth/app-deleted',\n NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED: 'auth/network-request-failed',\n NULL_USER: 'auth/null-user',\n NO_AUTH_EVENT: 'auth/no-auth-event',\n NO_SUCH_PROVIDER: 'auth/no-such-provider',\n OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',\n OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',\n POPUP_BLOCKED: 'auth/popup-blocked',\n POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',\n PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',\n QUOTA_EXCEEDED: 'auth/quota-exceeded',\n REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',\n REJECTED_CREDENTIAL: 'auth/rejected-credential',\n SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',\n TIMEOUT: 'auth/timeout',\n TOKEN_EXPIRED: 'auth/user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',\n UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',\n UNVERIFIED_EMAIL: 'auth/unverified-email',\n USER_CANCELLED: 'auth/user-cancelled',\n USER_DELETED: 'auth/user-not-found',\n USER_DISABLED: 'auth/user-disabled',\n USER_MISMATCH: 'auth/user-mismatch',\n USER_SIGNED_OUT: 'auth/user-signed-out',\n WEAK_PASSWORD: 'auth/weak-password',\n WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',\n ALREADY_INITIALIZED: 'auth/already-initialized',\n RECAPTCHA_NOT_ENABLED: 'auth/recaptcha-not-enabled',\n MISSING_RECAPTCHA_TOKEN: 'auth/missing-recaptcha-token',\n INVALID_RECAPTCHA_TOKEN: 'auth/invalid-recaptcha-token',\n INVALID_RECAPTCHA_ACTION: 'auth/invalid-recaptcha-action',\n MISSING_CLIENT_TYPE: 'auth/missing-client-type',\n MISSING_RECAPTCHA_VERSION: 'auth/missing-recaptcha-version',\n INVALID_RECAPTCHA_VERSION: 'auth/invalid-recaptcha-version',\n INVALID_REQ_TYPE: 'auth/invalid-req-type'\n} as const;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { SDK_VERSION } from '@firebase/app';\n\nexport { LogLevel };\n\nconst logClient = new Logger('@firebase/auth');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function _getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\nexport function _setLogLevel(newLevel: LogLevel): void {\n logClient.logLevel = newLevel;\n}\n\nexport function _logDebug(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n logClient.debug(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function _logWarn(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n logClient.warn(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function _logError(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth } from '../../model/public_types';\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { AuthInternal } from '../../model/auth';\nimport {\n _DEFAULT_AUTH_ERROR_FACTORY,\n AuthErrorCode,\n AuthErrorParams,\n prodErrorMap,\n ErrorMapRetriever\n} from '../errors';\nimport { _logError } from './log';\n\ntype AuthErrorListParams<K> = K extends keyof AuthErrorParams\n ? [AuthErrorParams[K]]\n : [];\ntype LessAppName<K extends AuthErrorCode> = Omit<AuthErrorParams[K], 'appName'>;\n\n/**\n * Unconditionally fails, throwing a developer facing INTERNAL_ERROR\n *\n * @example\n * ```javascript\n * fail(auth, AuthErrorCode.MFA_REQUIRED); // Error: the MFA_REQUIRED error needs more params than appName\n * fail(auth, AuthErrorCode.MFA_REQUIRED, {serverResponse}); // Compiles\n * fail(AuthErrorCode.INTERNAL_ERROR); // Compiles; internal error does not need appName\n * fail(AuthErrorCode.USER_DELETED); // Error: USER_DELETED requires app name\n * fail(auth, AuthErrorCode.USER_DELETED); // Compiles; USER_DELETED _only_ needs app name\n * ```\n *\n * @param appName App name for tagging the error\n * @throws FirebaseError\n */\nexport function _fail<K extends AuthErrorCode>(\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): never;\nexport function _fail<K extends AuthErrorCode>(\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName<K> ? [LessAppName<K>?] : [LessAppName<K>]\n): never;\nexport function _fail<K extends AuthErrorCode>(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): never {\n throw createErrorInternal(authOrCode, ...rest);\n}\n\nexport function _createError<K extends AuthErrorCode>(\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): FirebaseError;\nexport function _createError<K extends AuthErrorCode>(\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName<K> ? [LessAppName<K>?] : [LessAppName<K>]\n): FirebaseError;\nexport function _createError<K extends AuthErrorCode>(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): FirebaseError {\n return createErrorInternal(authOrCode, ...rest);\n}\n\nexport function _errorWithCustomMessage(\n auth: Auth,\n code: AuthErrorCode,\n message: string\n): FirebaseError {\n const errorMap = {\n ...(prodErrorMap as ErrorMapRetriever)(),\n [code]: message\n };\n const factory = new ErrorFactory<AuthErrorCode, AuthErrorParams>(\n 'auth',\n 'Firebase',\n errorMap\n );\n return factory.create(code, {\n appName: auth.name\n });\n}\n\nexport function _assertInstanceOf(\n auth: Auth,\n object: object,\n instance: unknown\n): void {\n const constructorInstance = instance as { new (...args: unknown[]): unknown };\n if (!(object instanceof constructorInstance)) {\n if (constructorInstance.name !== object.constructor.name) {\n _fail(auth, AuthErrorCode.ARGUMENT_ERROR);\n }\n\n throw _errorWithCustomMessage(\n auth,\n AuthErrorCode.ARGUMENT_ERROR,\n `Type of ${object.constructor.name} does not match expected instance.` +\n `Did you pass a reference from a different Auth SDK?`\n );\n }\n}\n\nfunction createErrorInternal<K extends AuthErrorCode>(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): FirebaseError {\n if (typeof authOrCode !== 'string') {\n const code = rest[0] as K;\n const fullParams = [...rest.slice(1)] as AuthErrorListParams<K>;\n if (fullParams[0]) {\n fullParams[0].appName = authOrCode.name;\n }\n\n return (authOrCode as AuthInternal)._errorFactory.create(\n code,\n ...fullParams\n );\n }\n\n return _DEFAULT_AUTH_ERROR_FACTORY.create(\n authOrCode,\n ...(rest as AuthErrorListParams<K>)\n );\n}\n\nexport function _assert<K extends AuthErrorCode>(\n assertion: unknown,\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): asserts assertion;\nexport function _assert<K extends AuthErrorCode>(\n assertion: unknown,\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName<K> ? [LessAppName<K>?] : [LessAppName<K>]\n): asserts assertion;\nexport function _assert<K extends AuthErrorCode>(\n assertion: unknown,\n authOrCode: Auth | K,\n ...rest: unknown[]\n): asserts assertion {\n if (!assertion) {\n throw createErrorInternal(authOrCode, ...rest);\n }\n}\n\n// We really do want to accept literally any function type here\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype TypeExpectation = Function | string | MapType;\n\ninterface MapType extends Record<string, TypeExpectation | Optional> {}\n\nclass Optional {\n constructor(readonly type: TypeExpectation) {}\n}\n\nexport function opt(type: TypeExpectation): Optional {\n return new Optional(type);\n}\n\n/**\n * Asserts the runtime types of arguments. The 'expected' field can be one of\n * a class, a string (representing a \"typeof\" call), or a record map of name\n * to type. Furthermore, the opt() function can be used to mark a field as\n * optional. For example:\n *\n * function foo(auth: Auth, profile: {displayName?: string}, update = false) {\n * assertTypes(arguments, [AuthImpl, {displayName: opt('string')}, opt('boolean')]);\n * }\n *\n * opt() can be used for any type:\n * function foo(auth?: Auth) {\n * assertTypes(arguments, [opt(AuthImpl)]);\n * }\n *\n * The string types can be or'd together, and you can use \"null\" as well (note\n * that typeof null === 'object'; this is an edge case). For example:\n *\n * function foo(profile: {displayName?: string | null}) {\n * assertTypes(arguments, [{displayName: opt('string|null')}]);\n * }\n *\n * @param args\n * @param expected\n */\nexport function assertTypes(\n args: Omit<IArguments, 'callee'>,\n ...expected: Array<TypeExpectation | Optional>\n): void {\n if (args.length > expected.length) {\n _fail(AuthErrorCode.ARGUMENT_ERROR, {});\n }\n\n for (let i = 0; i < expected.length; i++) {\n let expect = expected[i];\n const arg = args[i];\n\n if (expect instanceof Optional) {\n // If the arg is undefined, then it matches \"optional\" and we can move to\n // the next arg\n if (typeof arg === 'undefined') {\n continue;\n }\n expect = expect.type;\n }\n\n if (typeof expect === 'string') {\n // Handle the edge case for null because typeof null === 'object'\n if (expect.includes('null') && arg === null) {\n continue;\n }\n\n const required = expect.split('|');\n _assert(required.includes(typeof arg), AuthErrorCode.ARGUMENT_ERROR, {});\n } else if (typeof expect === 'object') {\n // Recursively check record arguments\n const record = arg as Record<string, unknown>;\n const map = expect as MapType;\n const keys = Object.keys(expect);\n\n assertTypes(\n keys.map(k => record[k]),\n ...keys.map(k => map[k])\n );\n } else {\n _assert(arg instanceof expect, AuthErrorCode.ARGUMENT_ERROR, {});\n }\n }\n}\n\n/**\n * Unconditionally fails, throwing an internal error with the given message.\n *\n * @param failure type of failure encountered\n * @throws Error\n */\nexport function debugFail(failure: string): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const message = `INTERNAL ASSERTION FAILED: ` + failure;\n _logError(message);\n\n // NOTE: We don't use FirebaseError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * @param assertion\n * @param message\n */\nexport function debugAssert(\n assertion: unknown,\n message: string\n): asserts assertion {\n if (!assertion) {\n debugFail(message);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function _getCurrentUrl(): string {\n return (typeof self !== 'undefined' && self.location?.href) || '';\n}\n\nexport function _isHttpOrHttps(): boolean {\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\n}\n\nexport function _getCurrentScheme(): string | null {\n return (typeof self !== 'undefined' && self.location?.protocol) || null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isMobileCordova, isReactNative } from '@firebase/util';\nimport { _isOnline } from './navigator';\nimport { debugAssert } from './assert';\n\nexport const enum DelayMin {\n OFFLINE = 5000\n}\n\n/**\n * A structure to help pick between a range of long and short delay durations\n * depending on the current environment. In general, the long delay is used for\n * mobile environments whereas short delays are used for desktop environments.\n */\nexport class Delay {\n // The default value for the offline delay timeout in ms.\n\n private readonly isMobile: boolean;\n constructor(\n private readonly shortDelay: number,\n private readonly longDelay: number\n ) {\n // Internal error when improperly initialized.\n debugAssert(\n longDelay > shortDelay,\n 'Short delay should be less than long delay!'\n );\n this.isMobile = isMobileCordova() || isReactNative();\n }\n\n get(): number {\n if (!_isOnline()) {\n // Pick the shorter timeout.\n return Math.min(DelayMin.OFFLINE, this.shortDelay);\n }\n // If running in a mobile environment, return the long delay, otherwise\n // return the short delay.\n // This could be improved in the future to dynamically change based on other\n // variables instead of just reading the current environment.\n return this.isMobile ? this.longDelay : this.shortDelay;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isBrowserExtension } from '@firebase/util';\nimport { _isHttpOrHttps } from './location';\n\n/**\n * Determine whether the browser is working online\n */\nexport function _isOnline(): boolean {\n if (\n typeof navigator !== 'undefined' &&\n navigator &&\n 'onLine' in navigator &&\n typeof navigator.onLine === 'boolean' &&\n // Apply only for traditional web apps and Chrome extensions.\n // This is especially true for Cordova apps which have unreliable\n // navigator.onLine behavior unless cordova-plugin-network-information is\n // installed which overwrites the native navigator.onLine value and\n // defines navigator.connection.\n (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)\n ) {\n return navigator.onLine;\n }\n // If we can't determine the state, assume it is online.\n return true;\n}\n\nexport function _getUserLanguage(): string | null {\n if (typeof navigator === 'undefined') {\n return null;\n }\n const navigatorLanguage: NavigatorLanguage = navigator;\n return (\n // Most reliable, but only supported in Chrome/Firefox.\n (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\n // Supported in most browsers, but returns the language of the browser\n // UI, not the language set in browser settings.\n navigatorLanguage.language ||\n // Couldn't determine language.\n null\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ConfigInternal } from '../../model/auth';\nimport { debugAssert } from './assert';\n\nexport function _emulatorUrl(config: ConfigInternal, path?: string): string {\n debugAssert(config.emulator, 'Emulator should always be set here');\n const { url } = config.emulator;\n\n if (!path) {\n return url;\n }\n\n return `${url}${path.startsWith('/') ? path.slice(1) : path}`;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugFail } from './assert';\n\nexport class FetchProvider {\n private static fetchImpl: typeof fetch | null;\n private static headersImpl: typeof Headers | null;\n private static responseImpl: typeof Response | null;\n\n static initialize(\n fetchImpl: typeof fetch,\n headersImpl?: typeof Headers,\n responseImpl?: typeof Response\n ): void {\n this.fetchImpl = fetchImpl;\n if (headersImpl) {\n this.headersImpl = headersImpl;\n }\n if (responseImpl) {\n this.responseImpl = responseImpl;\n }\n }\n\n static fetch(): typeof fetch {\n if (this.fetchImpl) {\n return this.fetchImpl;\n }\n if (typeof self !== 'undefined' && 'fetch' in self) {\n return self.fetch;\n }\n if (typeof globalThis !== 'undefined' && globalThis.fetch) {\n return globalThis.fetch;\n }\n if (typeof fetch !== 'undefined') {\n return fetch;\n }\n debugFail(\n 'Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n\n static headers(): typeof Headers {\n if (this.headersImpl) {\n return this.headersImpl;\n }\n if (typeof self !== 'undefined' && 'Headers' in self) {\n return self.Headers;\n }\n if (typeof globalThis !== 'undefined' && globalThis.Headers) {\n return globalThis.Headers;\n }\n if (typeof Headers !== 'undefined') {\n return Headers;\n }\n debugFail(\n 'Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n\n static response(): typeof Response {\n if (this.responseImpl) {\n return this.responseImpl;\n }\n if (typeof self !== 'undefined' && 'Response' in self) {\n return self.Response;\n }\n if (typeof globalThis !== 'undefined' && globalThis.Response) {\n return globalThis.Response;\n }\n if (typeof Response !== 'undefined') {\n return Response;\n }\n debugFail(\n 'Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../core/errors';\n\n/**\n * Errors that can be returned by the backend\n */\nexport const enum ServerError {\n ADMIN_ONLY_OPERATION = 'ADMIN_ONLY_OPERATION',\n BLOCKING_FUNCTION_ERROR_RESPONSE = 'BLOCKING_FUNCTION_ERROR_RESPONSE',\n CAPTCHA_CHECK_FAILED = 'CAPTCHA_CHECK_FAILED',\n CORS_UNSUPPORTED = 'CORS_UNSUPPORTED',\n CREDENTIAL_MISMATCH = 'CREDENTIAL_MISMATCH',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN = 'CREDENTIAL_TOO_OLD_LOGIN_AGAIN',\n DYNAMIC_LINK_NOT_ACTIVATED = 'DYNAMIC_LINK_NOT_ACTIVATED',\n EMAIL_CHANGE_NEEDS_VERIFICATION = 'EMAIL_CHANGE_NEEDS_VERIFICATION',\n EMAIL_EXISTS = 'EMAIL_EXISTS',\n EMAIL_NOT_FOUND = 'EMAIL_NOT_FOUND',\n EXPIRED_OOB_CODE = 'EXPIRED_OOB_CODE',\n FEDERATED_USER_ID_ALREADY_LINKED = 'FEDERATED_USER_ID_ALREADY_LINKED',\n INVALID_APP_CREDENTIAL = 'INVALID_APP_CREDENTIAL',\n INVALID_APP_ID = 'INVALID_APP_ID',\n INVALID_CERT_HASH = 'INVALID_CERT_HASH',\n INVALID_CODE = 'INVALID_CODE',\n INVALID_CONTINUE_URI = 'INVALID_CONTINUE_URI',\n INVALID_CUSTOM_TOKEN = 'INVALID_CUSTOM_TOKEN',\n INVALID_DYNAMIC_LINK_DOMAIN = 'INVALID_DYNAMIC_LINK_DOMAIN',\n INVALID_EMAIL = 'INVALID_EMAIL',\n INVALID_ID_TOKEN = 'INVALID_ID_TOKEN',\n INVALID_IDP_RESPONSE = 'INVALID_IDP_RESPONSE',\n INVALID_IDENTIFIER = 'INVALID_IDENTIFIER',\n INVALID_MESSAGE_PAYLOAD = 'INVALID_MESSAGE_PAYLOAD',\n INVALID_MFA_PENDING_CREDENTIAL = 'INVALID_MFA_PENDING_CREDENTIAL',\n INVALID_OAUTH_CLIENT_ID = 'INVALID_OAUTH_CLIENT_ID',\n INVALID_OOB_CODE = 'INVALID_OOB_CODE',\n INVALID_PASSWORD = 'INVALID_PASSWORD',\n INVALID_PENDING_TOKEN = 'INVALID_PENDING_TOKEN',\n INVALID_PHONE_NUMBER = 'INVALID_PHONE_NUMBER',\n INVALID_PROVIDER_ID = 'INVALID_PROVIDER_ID',\n INVALID_RECIPIENT_EMAIL = 'INVALID_RECIPIENT_EMAIL',\n INVALID_SENDER = 'INVALID_SENDER',\n INVALID_SESSION_INFO = 'INVALID_SESSION_INFO',\n INVALID_TEMPORARY_PROOF = 'INVALID_TEMPORARY_PROOF',\n INVALID_TENANT_ID = 'INVALID_TENANT_ID',\n MFA_ENROLLMENT_NOT_FOUND = 'MFA_ENROLLMENT_NOT_FOUND',\n MISSING_ANDROID_PACKAGE_NAME = 'MISSING_ANDROID_PACKAGE_NAME',\n MISSING_APP_CREDENTIAL = 'MISSING_APP_CREDENTIAL',\n MISSING_CODE = 'MISSING_CODE',\n MISSING_CONTINUE_URI = 'MISSING_CONTINUE_URI',\n MISSING_CUSTOM_TOKEN = 'MISSING_CUSTOM_TOKEN',\n MISSING_IOS_BUNDLE_ID = 'MISSING_IOS_BUNDLE_ID',\n MISSING_MFA_ENROLLMENT_ID = 'MISSING_MFA_ENROLLMENT_ID',\n MISSING_MFA_PENDING_CREDENTIAL = 'MISSING_MFA_PENDING_CREDENTIAL',\n MISSING_OOB_CODE = 'MISSING_OOB_CODE',\n MISSING_OR_INVALID_NONCE = 'MISSING_OR_INVALID_NONCE',\n MISSING_PASSWORD = 'MISSING_PASSWORD',\n MISSING_REQ_TYPE = 'MISSING_REQ_TYPE',\n MISSING_PHONE_NUMBER = 'MISSING_PHONE_NUMBER',\n MISSING_SESSION_INFO = 'MISSING_SESSION_INFO',\n OPERATION_NOT_ALLOWED = 'OPERATION_NOT_ALLOWED',\n PASSWORD_LOGIN_DISABLED = 'PASSWORD_LOGIN_DISABLED',\n QUOTA_EXCEEDED = 'QUOTA_EXCEEDED',\n RESET_PASSWORD_EXCEED_LIMIT = 'RESET_PASSWORD_EXCEED_LIMIT',\n REJECTED_CREDENTIAL = 'REJECTED_CREDENTIAL',\n SECOND_FACTOR_EXISTS = 'SECOND_FACTOR_EXISTS',\n SECOND_FACTOR_LIMIT_EXCEEDED = 'SECOND_FACTOR_LIMIT_EXCEEDED',\n SESSION_EXPIRED = 'SESSION_EXPIRED',\n TENANT_ID_MISMATCH = 'TENANT_ID_MISMATCH',\n TOKEN_EXPIRED = 'TOKEN_EXPIRED',\n TOO_MANY_ATTEMPTS_TRY_LATER = 'TOO_MANY_ATTEMPTS_TRY_LATER',\n UNSUPPORTED_FIRST_FACTOR = 'UNSUPPORTED_FIRST_FACTOR',\n UNSUPPORTED_TENANT_OPERATION = 'UNSUPPORTED_TENANT_OPERATION',\n UNAUTHORIZED_DOMAIN = 'UNAUTHORIZED_DOMAIN',\n UNVERIFIED_EMAIL = 'UNVERIFIED_EMAIL',\n USER_CANCELLED = 'USER_CANCELLED',\n USER_DISABLED = 'USER_DISABLED',\n USER_NOT_FOUND = 'USER_NOT_FOUND',\n WEAK_PASSWORD = 'WEAK_PASSWORD',\n RECAPTCHA_NOT_ENABLED = 'RECAPTCHA_NOT_ENABLED',\n MISSING_RECAPTCHA_TOKEN = 'MISSING_RECAPTCHA_TOKEN',\n INVALID_RECAPTCHA_TOKEN = 'INVALID_RECAPTCHA_TOKEN',\n INVALID_RECAPTCHA_ACTION = 'INVALID_RECAPTCHA_ACTION',\n MISSING_CLIENT_TYPE = 'MISSING_CLIENT_TYPE',\n MISSING_RECAPTCHA_VERSION = 'MISSING_RECAPTCHA_VERSION',\n INVALID_RECAPTCHA_VERSION = 'INVALID_RECAPTCHA_VERSION',\n INVALID_REQ_TYPE = 'INVALID_REQ_TYPE',\n PASSWORD_DOES_NOT_MEET_REQUIREMENTS = 'PASSWORD_DOES_NOT_MEET_REQUIREMENTS'\n}\n\n/**\n * API Response in the event of an error\n */\nexport interface JsonError {\n error: {\n code: number;\n message: string;\n errors?: [\n {\n message: ServerError;\n domain: string;\n reason: string;\n }\n ];\n };\n}\n\n/**\n * Type definition for a map from server errors to developer visible errors\n */\nexport declare type ServerErrorMap<ApiError extends string> = {\n readonly [K in ApiError]: AuthErrorCode;\n};\n\n/**\n * Map from errors returned by the server to errors to developer visible errors\n */\nexport const SERVER_ERROR_MAP: Partial<ServerErrorMap<ServerError>> = {\n // Custom token errors.\n [ServerError.CREDENTIAL_MISMATCH]: AuthErrorCode.CREDENTIAL_MISMATCH,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_CUSTOM_TOKEN]: AuthErrorCode.INTERNAL_ERROR,\n\n // Create Auth URI errors.\n [ServerError.INVALID_IDENTIFIER]: AuthErrorCode.INVALID_EMAIL,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_CONTINUE_URI]: AuthErrorCode.INTERNAL_ERROR,\n\n // Sign in with email and password errors (some apply to sign up too).\n [ServerError.INVALID_PASSWORD]: AuthErrorCode.INVALID_PASSWORD,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_PASSWORD]: AuthErrorCode.MISSING_PASSWORD,\n\n // Sign up with email and password errors.\n [ServerError.EMAIL_EXISTS]: AuthErrorCode.EMAIL_EXISTS,\n [ServerError.PASSWORD_LOGIN_DISABLED]: AuthErrorCode.OPERATION_NOT_ALLOWED,\n\n // Verify assertion for sign in with credential errors:\n [ServerError.INVALID_IDP_RESPONSE]: AuthErrorCode.INVALID_IDP_RESPONSE,\n [ServerError.INVALID_PENDING_TOKEN]: AuthErrorCode.INVALID_IDP_RESPONSE,\n [ServerError.FEDERATED_USER_ID_ALREADY_LINKED]:\n AuthErrorCode.CREDENTIAL_ALREADY_IN_USE,\n\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_REQ_TYPE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Send Password reset email errors:\n [ServerError.EMAIL_NOT_FOUND]: AuthErrorCode.USER_DELETED,\n [ServerError.RESET_PASSWORD_EXCEED_LIMIT]:\n AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER,\n\n [ServerError.EXPIRED_OOB_CODE]: AuthErrorCode.EXPIRED_OOB_CODE,\n [ServerError.INVALID_OOB_CODE]: AuthErrorCode.INVALID_OOB_CODE,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_OOB_CODE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Operations that require ID token in request:\n [ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN]:\n AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN,\n [ServerError.INVALID_ID_TOKEN]: AuthErrorCode.INVALID_AUTH,\n [ServerError.TOKEN_EXPIRED]: AuthErrorCode.TOKEN_EXPIRED,\n [ServerError.USER_NOT_FOUND]: AuthErrorCode.TOKEN_EXPIRED,\n\n // Other errors.\n [ServerError.TOO_MANY_ATTEMPTS_TRY_LATER]:\n AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER,\n [ServerError.PASSWORD_DOES_NOT_MEET_REQUIREMENTS]:\n AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS,\n\n // Phone Auth related errors.\n [ServerError.INVALID_CODE]: AuthErrorCode.INVALID_CODE,\n [ServerError.INVALID_SESSION_INFO]: AuthErrorCode.INVALID_SESSION_INFO,\n [ServerError.INVALID_TEMPORARY_PROOF]: AuthErrorCode.INVALID_IDP_RESPONSE,\n [ServerError.MISSING_SESSION_INFO]: AuthErrorCode.MISSING_SESSION_INFO,\n [ServerError.SESSION_EXPIRED]: AuthErrorCode.CODE_EXPIRED,\n\n // Other action code errors when additional settings passed.\n // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.\n // This is OK as this error will be caught by client side validation.\n [ServerError.MISSING_ANDROID_PACKAGE_NAME]:\n AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME,\n [ServerError.UNAUTHORIZED_DOMAIN]: AuthErrorCode.UNAUTHORIZED_DOMAIN,\n\n // getProjectConfig errors when clientId is passed.\n [ServerError.INVALID_OAUTH_CLIENT_ID]: AuthErrorCode.INVALID_OAUTH_CLIENT_ID,\n\n // User actions (sign-up or deletion) disabled errors.\n [ServerError.ADMIN_ONLY_OPERATION]: AuthErrorCode.ADMIN_ONLY_OPERATION,\n\n // Multi factor related errors.\n [ServerError.INVALID_MFA_PENDING_CREDENTIAL]:\n AuthErrorCode.INVALID_MFA_SESSION,\n [ServerError.MFA_ENROLLMENT_NOT_FOUND]: AuthErrorCode.MFA_INFO_NOT_FOUND,\n [ServerError.MISSING_MFA_ENROLLMENT_ID]: AuthErrorCode.MISSING_MFA_INFO,\n [ServerError.MISSING_MFA_PENDING_CREDENTIAL]:\n AuthErrorCode.MISSING_MFA_SESSION,\n [ServerError.SECOND_FACTOR_EXISTS]:\n AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED,\n [ServerError.SECOND_FACTOR_LIMIT_EXCEEDED]:\n AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED,\n\n // Blocking functions related errors.\n [ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Recaptcha related errors.\n [ServerError.RECAPTCHA_NOT_ENABLED]: AuthErrorCode.RECAPTCHA_NOT_ENABLED,\n [ServerError.MISSING_RECAPTCHA_TOKEN]: AuthErrorCode.MISSING_RECAPTCHA_TOKEN,\n [ServerError.INVALID_RECAPTCHA_TOKEN]: AuthErrorCode.INVALID_RECAPTCHA_TOKEN,\n [ServerError.INVALID_RECAPTCHA_ACTION]:\n AuthErrorCode.INVALID_RECAPTCHA_ACTION,\n [ServerError.MISSING_CLIENT_TYPE]: AuthErrorCode.MISSING_CLIENT_TYPE,\n [ServerError.MISSING_RECAPTCHA_VERSION]:\n AuthErrorCode.MISSING_RECAPTCHA_VERSION,\n [ServerError.INVALID_RECAPTCHA_VERSION]:\n AuthErrorCode.INVALID_RECAPTCHA_VERSION,\n [ServerError.INVALID_REQ_TYPE]: AuthErrorCode.INVALID_REQ_TYPE\n};\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError, querystring } from '@firebase/util';\n\nimport { AuthErrorCode, NamedErrorParams } from '../core/errors';\nimport {\n _createError,\n _errorWithCustomMessage,\n _fail\n} from '../core/util/assert';\nimport { Delay } from '../core/util/delay';\nimport { _emulatorUrl } from '../core/util/emulator';\nimport { FetchProvider } from '../core/util/fetch_provider';\nimport { Auth } from '../model/public_types';\nimport { AuthInternal, ConfigInternal } from '../model/auth';\nimport { IdTokenResponse, TaggedWithTokenResponse } from '../model/id_token';\nimport { IdTokenMfaResponse } from './authentication/mfa';\nimport { SERVER_ERROR_MAP, ServerError, ServerErrorMap } from './errors';\n\nexport const enum HttpMethod {\n POST = 'POST',\n GET = 'GET'\n}\n\nexport const enum HttpHeader {\n CONTENT_TYPE = 'Content-Type',\n X_FIREBASE_LOCALE = 'X-Firebase-Locale',\n X_CLIENT_VERSION = 'X-Client-Version',\n X_FIREBASE_GMPID = 'X-Firebase-gmpid',\n X_FIREBASE_CLIENT = 'X-Firebase-Client',\n X_FIREBASE_APP_CHECK = 'X-Firebase-AppCheck'\n}\n\nexport const enum Endpoint {\n CREATE_AUTH_URI = '/v1/accounts:createAuthUri',\n DELETE_ACCOUNT = '/v1/accounts:delete',\n RESET_PASSWORD = '/v1/accounts:resetPassword',\n SIGN_UP = '/v1/accounts:signUp',\n SIGN_IN_WITH_CUSTOM_TOKEN = '/v1/accounts:signInWithCustomToken',\n SIGN_IN_WITH_EMAIL_LINK = '/v1/accounts:signInWithEmailLink',\n SIGN_IN_WITH_IDP = '/v1/accounts:signInWithIdp',\n SIGN_IN_WITH_PASSWORD = '/v1/accounts:signInWithPassword',\n SIGN_IN_WITH_PHONE_NUMBER = '/v1/accounts:signInWithPhoneNumber',\n SEND_VERIFICATION_CODE = '/v1/accounts:sendVerificationCode',\n SEND_OOB_CODE = '/v1/accounts:sendOobCode',\n SET_ACCOUNT_INFO = '/v1/accounts:update',\n GET_ACCOUNT_INFO = '/v1/accounts:lookup',\n GET_RECAPTCHA_PARAM = '/v1/recaptchaParams',\n START_MFA_ENROLLMENT = '/v2/accounts/mfaEnrollment:start',\n FINALIZE_MFA_ENROLLMENT = '/v2/accounts/mfaEnrollment:finalize',\n START_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:start',\n FINALIZE_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:finalize',\n WITHDRAW_MFA = '/v2/accounts/mfaEnrollment:withdraw',\n GET_PROJECT_CONFIG = '/v1/projects',\n GET_RECAPTCHA_CONFIG = '/v2/recaptchaConfig',\n GET_PASSWORD_POLICY = '/v2/passwordPolicy',\n TOKEN = '/v1/token',\n REVOKE_TOKEN = '/v2/accounts:revokeToken'\n}\n\nexport const enum RecaptchaClientType {\n WEB = 'CLIENT_TYPE_WEB',\n ANDROID = 'CLIENT_TYPE_ANDROID',\n IOS = 'CLIENT_TYPE_IOS'\n}\n\nexport const enum RecaptchaVersion {\n ENTERPRISE = 'RECAPTCHA_ENTERPRISE'\n}\n\nexport const enum RecaptchaActionName {\n SIGN_IN_WITH_PASSWORD = 'signInWithPassword',\n GET_OOB_CODE = 'getOobCode',\n SIGN_UP_PASSWORD = 'signUpPassword'\n}\n\nexport const enum EnforcementState {\n ENFORCE = 'ENFORCE',\n AUDIT = 'AUDIT',\n OFF = 'OFF',\n ENFORCEMENT_STATE_UNSPECIFIED = 'ENFORCEMENT_STATE_UNSPECIFIED'\n}\n\n// Providers that have reCAPTCHA Enterprise support.\nexport const enum RecaptchaProvider {\n EMAIL_PASSWORD_PROVIDER = 'EMAIL_PASSWORD_PROVIDER'\n}\n\nexport const DEFAULT_API_TIMEOUT_MS = new Delay(30_000, 60_000);\n\nexport function _addTidIfNecessary<T extends { tenantId?: string }>(\n auth: Auth,\n request: T\n): T {\n if (auth.tenantId && !request.tenantId) {\n return {\n ...request,\n tenantId: auth.tenantId\n };\n }\n return request;\n}\n\nexport async function _performApiRequest<T, V>(\n auth: Auth,\n method: HttpMethod,\n path: Endpoint,\n request?: T,\n customErrorMap: Partial<ServerErrorMap<ServerError>> = {}\n): Promise<V> {\n return _performFetchWithErrorHandling(auth, customErrorMap, async () => {\n let body = {};\n let params = {};\n if (request) {\n if (method === HttpMethod.GET) {\n params = request;\n } else {\n body = {\n body: JSON.stringify(request)\n };\n }\n }\n\n const query = querystring({\n key: auth.config.apiKey,\n ...params\n }).slice(1);\n\n const headers = await (auth as AuthInternal)._getAdditionalHeaders();\n headers[HttpHeader.CONTENT_TYPE] = 'application/json';\n\n if (auth.languageCode) {\n headers[HttpHeader.X_FIREBASE_LOCALE] = auth.languageCode;\n }\n\n return FetchProvider.fetch()(\n _getFinalTarget(auth, auth.config.apiHost, path, query),\n {\n method,\n headers,\n referrerPolicy: 'no-referrer',\n ...body\n }\n );\n });\n}\n\nexport async function _performFetchWithErrorHandling<V>(\n auth: Auth,\n customErrorMap: Partial<ServerErrorMap<ServerError>>,\n fetchFn: () => Promise<Response>\n): Promise<V> {\n (auth as AuthInternal)._canInitEmulator = false;\n const errorMap = { ...SERVER_ERROR_MAP, ...customErrorMap };\n try {\n const networkTimeout = new NetworkTimeout<Response>(auth);\n const response: Response = await Promise.race<Promise<Response>>([\n fetchFn(),\n networkTimeout.promise\n ]);\n\n // If we've reached this point, the fetch succeeded and the networkTimeout\n // didn't throw; clear the network timeout delay so that Node won't hang\n networkTimeout.clearNetworkTimeout();\n\n const json = await response.json();\n if ('needConfirmation' in json) {\n throw _makeTaggedError(auth, AuthErrorCode.NEED_CONFIRMATION, json);\n }\n\n if (response.ok && !('errorMessage' in json)) {\n return json;\n } else {\n const errorMessage = response.ok ? json.errorMessage : json.error.message;\n const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');\n if (serverErrorCode === ServerError.FEDERATED_USER_ID_ALREADY_LINKED) {\n throw _makeTaggedError(\n auth,\n AuthErrorCode.CREDENTIAL_ALREADY_IN_USE,\n json\n );\n } else if (serverErrorCode === ServerError.EMAIL_EXISTS) {\n throw _makeTaggedError(auth, AuthErrorCode.EMAIL_EXISTS, json);\n } else if (serverErrorCode === ServerError.USER_DISABLED) {\n throw _makeTaggedError(auth, AuthErrorCode.USER_DISABLED, json);\n }\n const authError =\n errorMap[serverErrorCode as ServerError] ||\n (serverErrorCode\n .toLowerCase()\n .replace(/[_\\s]+/g, '-') as unknown as AuthErrorCode);\n if (serverErrorMessage) {\n throw _errorWithCustomMessage(auth, authError, serverErrorMessage);\n } else {\n _fail(auth, authError);\n }\n }\n } catch (e) {\n if (e instanceof FirebaseError) {\n throw e;\n }\n // Changing this to a different error code will log user out when there is a network error\n // because we treat any error other than NETWORK_REQUEST_FAILED as token is invalid.\n // https://github.com/firebase/firebase-js-sdk/blob/4fbc73610d70be4e0852e7de63a39cb7897e8546/packages/auth/src/core/auth/auth_impl.ts#L309-L316\n _fail(auth, AuthErrorCode.NETWORK_REQUEST_FAILED, { 'message': String(e) });\n }\n}\n\nexport async function _performSignInRequest<T, V extends IdTokenResponse>(\n auth: Auth,\n method: HttpMethod,\n path: Endpoint,\n request?: T,\n customErrorMap: Partial<ServerErrorMap<ServerError>> = {}\n): Promise<V> {\n const serverResponse = (await _performApiRequest<T, V | IdTokenMfaResponse>(\n auth,\n method,\n path,\n request,\n customErrorMap\n )) as V;\n if ('mfaPendingCredential' in serverResponse) {\n _fail(auth, AuthErrorCode.MFA_REQUIRED, {\n _serverResponse: serverResponse\n });\n }\n\n return serverResponse;\n}\n\nexport function _getFinalTarget(\n auth: Auth,\n host: string,\n path: string,\n query: string\n): string {\n const base = `${host}${path}?${query}`;\n\n if (!(auth as AuthInternal).config.emulator) {\n return `${auth.config.apiScheme}://${base}`;\n }\n\n return _emulatorUrl(auth.config as ConfigInternal, base);\n}\n\nexport function _parseEnforcementState(\n enforcementStateStr: string\n): EnforcementState {\n switch (enforcementStateStr) {\n case 'ENFORCE':\n return EnforcementState.ENFORCE;\n case 'AUDIT':\n return EnforcementState.AUDIT;\n case 'OFF':\n return EnforcementState.OFF;\n default:\n return EnforcementState.ENFORCEMENT_STATE_UNSPECIFIED;\n }\n}\n\nclass NetworkTimeout<T> {\n // Node timers and browser timers are fundamentally incompatible, but we\n // don't care about the value here\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private timer: any | null = null;\n readonly promise = new Promise<T>((_, reject) => {\n this.timer = setTimeout(() => {\n return reject(\n _createError(this.auth, AuthErrorCode.NETWORK_REQUEST_FAILED)\n );\n }, DEFAULT_API_TIMEOUT_MS.get());\n });\n\n clearNetworkTimeout(): void {\n clearTimeout(this.timer);\n }\n\n constructor(private readonly auth: Auth) {}\n}\n\ninterface PotentialResponse extends IdTokenResponse {\n email?: string;\n phoneNumber?: string;\n}\n\nexport function _makeTaggedError(\n auth: Auth,\n code: AuthErrorCode,\n response: PotentialResponse\n): FirebaseError {\n const errorParams: NamedErrorParams = {\n appName: auth.name\n };\n\n if (response.email) {\n errorParams.email = response.email;\n }\n if (response.phoneNumber) {\n errorParams.phoneNumber = response.phoneNumber;\n }\n\n const error = _createError(auth, code, errorParams);\n\n // We know customData is defined on error because errorParams is defined\n (error.customData! as TaggedWithTokenResponse)._tokenResponse = response;\n return error;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RecaptchaParameters } from '../../model/public_types';\nimport {\n GetRecaptchaConfigResponse,\n RecaptchaEnforcementProviderState\n} from '../../api/authentication/recaptcha';\nimport { EnforcementState, _parseEnforcementState } from '../../api/index';\n\n// reCAPTCHA v2 interface\nexport interface Recaptcha {\n render: (container: HTMLElement, parameters: RecaptchaParameters) => number;\n getResponse: (id: number) => string;\n execute: (id: number) => unknown;\n reset: (id: number) => unknown;\n}\n\nexport function isV2(\n grecaptcha: Recaptcha | GreCAPTCHA | undefined\n): grecaptcha is Recaptcha {\n return (\n grecaptcha !== undefined &&\n (grecaptcha as Recaptcha).getResponse !== undefined\n );\n}\n\n// reCAPTCHA Enterprise & v3 shared interface\nexport interface GreCAPTCHATopLevel extends GreCAPTCHA {\n enterprise: GreCAPTCHA;\n}\n\n// reCAPTCHA Enterprise interface\nexport interface GreCAPTCHA {\n ready: (callback: () => void) => void;\n execute: (siteKey: string, options: { action: string }) => Promise<string>;\n render: (\n container: string | HTMLElement,\n parameters: GreCAPTCHARenderOption\n ) => string;\n}\n\nexport interface GreCAPTCHARenderOption {\n sitekey: string;\n size: 'invisible';\n}\n\nexport function isEnterprise(\n grecaptcha: Recaptcha | GreCAPTCHA | undefined\n): grecaptcha is GreCAPTCHATopLevel {\n return (\n grecaptcha !== undefined &&\n (grecaptcha as GreCAPTCHATopLevel).enterprise !== undefined\n );\n}\n\n// TODO(chuanr): Replace this with the AuthWindow after resolving the dependency issue in Node.js env.\ndeclare global {\n interface Window {\n grecaptcha?: Recaptcha | GreCAPTCHATopLevel;\n }\n}\n\nexport class RecaptchaConfig {\n /**\n * The reCAPTCHA site key.\n */\n siteKey: string = '';\n\n /**\n * The list of providers and their enablement status for reCAPTCHA Enterprise.\n */\n recaptchaEnforcementState: RecaptchaEnforcementProviderState[] = [];\n\n constructor(response: GetRecaptchaConfigResponse) {\n if (response.recaptchaKey === undefined) {\n throw new Error('recaptchaKey undefined');\n }\n // Example response.recaptchaKey: \"projects/proj123/keys/sitekey123\"\n this.siteKey = response.recaptchaKey.split('/')[3];\n this.recaptchaEnforcementState = response.recaptchaEnforcementState;\n }\n\n /**\n * Returns the reCAPTCHA Enterprise enforcement state for the given provider.\n *\n * @param providerStr - The provider whose enforcement state is to be returned.\n * @returns The reCAPTCHA Enterprise enforcement state for the given provider.\n */\n getProviderEnforcementState(providerStr: string): EnforcementState | null {\n if (\n !this.recaptchaEnforcementState ||\n this.recaptchaEnforcementState.length === 0\n ) {\n return null;\n }\n\n for (const recaptchaEnforcementState of this.recaptchaEnforcementState) {\n if (\n recaptchaEnforcementState.provider &&\n recaptchaEnforcementState.provider === providerStr\n ) {\n return _parseEnforcementState(\n recaptchaEnforcementState.enforcementState\n );\n }\n }\n return null;\n }\n\n /**\n * Returns true if the reCAPTCHA Enterprise enforcement state for the provider is set to ENFORCE or AUDIT.\n *\n * @param providerStr - The provider whose enablement state is to be returned.\n * @returns Whether or not reCAPTCHA Enterprise protection is enabled for the given provider.\n */\n isProviderEnabled(providerStr: string): boolean {\n return (\n this.getProviderEnforcementState(providerStr) ===\n EnforcementState.ENFORCE ||\n this.getProviderEnforcementState(providerStr) === EnforcementState.AUDIT\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _performApiRequest,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\ninterface GetRecaptchaParamResponse {\n recaptchaSiteKey?: string;\n}\n\nexport async function getRecaptchaParams(auth: Auth): Promise<string> {\n return (\n (\n await _performApiRequest<void, GetRecaptchaParamResponse>(\n auth,\n HttpMethod.GET,\n Endpoint.GET_RECAPTCHA_PARAM\n )\n ).recaptchaSiteKey || ''\n );\n}\n\n// The following functions are for reCAPTCHA enterprise integration.\ninterface GetRecaptchaConfigRequest {\n tenantId?: string;\n clientType?: RecaptchaClientType;\n version?: RecaptchaVersion;\n}\n\nexport interface RecaptchaEnforcementProviderState {\n provider: string;\n enforcementState: string;\n}\n\nexport interface GetRecaptchaConfigResponse {\n recaptchaKey: string;\n recaptchaEnforcementState: RecaptchaEnforcementProviderState[];\n}\n\nexport async function getRecaptchaConfig(\n auth: Auth,\n request: GetRecaptchaConfigRequest\n): Promise<GetRecaptchaConfigResponse> {\n return _performApiRequest<\n GetRecaptchaConfigRequest,\n GetRecaptchaConfigResponse\n >(\n auth,\n HttpMethod.GET,\n Endpoint.GET_RECAPTCHA_CONFIG,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function utcTimestampToDateString(\n utcTimestamp?: string | number\n): string | undefined {\n if (!utcTimestamp) {\n return undefined;\n }\n try {\n // Convert to date object.\n const date = new Date(Number(utcTimestamp));\n // Test date is valid.\n if (!isNaN(date.getTime())) {\n // Convert to UTC date string.\n return date.toUTCString();\n }\n } catch (e) {\n // Do nothing. undefined will be returned.\n }\n return undefined;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdTokenResult, ParsedToken, User } from '../../model/public_types';\nimport { base64Decode, getModularInstance } from '@firebase/util';\n\nimport { UserInternal } from '../../model/user';\nimport { _assert } from '../util/assert';\nimport { _logError } from '../util/log';\nimport { utcTimestampToDateString } from '../util/time';\nimport { AuthErrorCode } from '../errors';\n\n/**\n * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport function getIdToken(user: User, forceRefresh = false): Promise<string> {\n return getModularInstance(user).getIdToken(forceRefresh);\n}\n\n/**\n * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport async function getIdTokenResult(\n user: User,\n forceRefresh = false\n): Promise<IdTokenResult> {\n const userInternal = getModularInstance(user) as UserInternal;\n const token = await userInternal.getIdToken(forceRefresh);\n const claims = _parseToken(token);\n\n _assert(\n claims && claims.exp && claims.auth_time && claims.iat,\n userInternal.auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const firebase =\n typeof claims.firebase === 'object' ? claims.firebase : undefined;\n\n const signInProvider: string | undefined = firebase?.['sign_in_provider'];\n\n return {\n claims,\n token,\n authTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.auth_time)\n )!,\n issuedAtTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.iat)\n )!,\n expirationTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.exp)\n )!,\n signInProvider: signInProvider || null,\n signInSecondFactor: firebase?.['sign_in_second_factor'] || null\n };\n}\n\nfunction secondsStringToMilliseconds(seconds: string): number {\n return Number(seconds) * 1000;\n}\n\nexport function _parseToken(token: string): ParsedToken | null {\n const [algorithm, payload, signature] = token.split('.');\n if (\n algorithm === undefined ||\n payload === undefined ||\n signature === undefined\n ) {\n _logError('JWT malformed, contained fewer than 3 sections');\n return null;\n }\n\n try {\n const decoded = base64Decode(payload);\n if (!decoded) {\n _logError('Failed to decode base64 JWT payload');\n return null;\n }\n return JSON.parse(decoded);\n } catch (e) {\n _logError(\n 'Caught error parsing JWT payload as JSON',\n (e as Error)?.toString()\n );\n return null;\n }\n}\n\n/**\n * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.\n */\nexport function _tokenExpiresIn(token: string): number {\n const parsedToken = _parseToken(token);\n _assert(parsedToken, AuthErrorCode.INTERNAL_ERROR);\n _assert(typeof parsedToken.exp !== 'undefined', AuthErrorCode.INTERNAL_ERROR);\n _assert(typeof parsedToken.iat !== 'undefined', AuthErrorCode.INTERNAL_ERROR);\n return Number(parsedToken.exp) - Number(parsedToken.iat);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\n\nexport async function _logoutIfInvalidated<T>(\n user: UserInternal,\n promise: Promise<T>,\n bypassAuthState = false\n): Promise<T> {\n if (bypassAuthState) {\n return promise;\n }\n try {\n return await promise;\n } catch (e) {\n if (e instanceof FirebaseError && isUserInvalidated(e)) {\n if (user.auth.currentUser === user) {\n await user.auth.signOut();\n }\n }\n\n throw e;\n }\n}\n\nfunction isUserInvalidated({ code }: FirebaseError): boolean {\n return (\n code === `auth/${AuthErrorCode.USER_DISABLED}` ||\n code === `auth/${AuthErrorCode.TOKEN_EXPIRED}`\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\n\n// Refresh the token five minutes before expiration\nexport const enum Duration {\n OFFSET = 5 * 1000 * 60,\n RETRY_BACKOFF_MIN = 30 * 1000,\n RETRY_BACKOFF_MAX = 16 * 60 * 1000\n}\n\nexport class ProactiveRefresh {\n private isRunning = false;\n\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private timerId: any | null = null;\n private errorBackoff = Duration.RETRY_BACKOFF_MIN;\n\n constructor(private readonly user: UserInternal) {}\n\n _start(): void {\n if (this.isRunning) {\n return;\n }\n\n this.isRunning = true;\n this.schedule();\n }\n\n _stop(): void {\n if (!this.isRunning) {\n return;\n }\n\n this.isRunning = false;\n if (this.timerId !== null) {\n clearTimeout(this.timerId);\n }\n }\n\n private getInterval(wasError: boolean): number {\n if (wasError) {\n const interval = this.errorBackoff;\n this.errorBackoff = Math.min(\n this.errorBackoff * 2,\n Duration.RETRY_BACKOFF_MAX\n );\n return interval;\n } else {\n // Reset the error backoff\n this.errorBackoff = Duration.RETRY_BACKOFF_MIN;\n const expTime = this.user.stsTokenManager.expirationTime ?? 0;\n const interval = expTime - Date.now() - Duration.OFFSET;\n\n return Math.max(0, interval);\n }\n }\n\n private schedule(wasError = false): void {\n if (!this.isRunning) {\n // Just in case...\n return;\n }\n\n const interval = this.getInterval(wasError);\n this.timerId = setTimeout(async () => {\n await this.iteration();\n }, interval);\n }\n\n private async iteration(): Promise<void> {\n try {\n await this.user.getIdToken(true);\n } catch (e) {\n // Only retry on network errors\n if (\n (e as FirebaseError)?.code ===\n `auth/${AuthErrorCode.NETWORK_REQUEST_FAILED}`\n ) {\n this.schedule(/* wasError */ true);\n }\n\n return;\n }\n this.schedule();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserMetadata as UserMetadataType } from '../../model/public_types';\n\nimport { utcTimestampToDateString } from '../util/time';\n\nexport class UserMetadata implements UserMetadataType {\n creationTime?: string;\n lastSignInTime?: string;\n\n constructor(\n private createdAt?: string | number,\n private lastLoginAt?: string | number\n ) {\n this._initializeTime();\n }\n\n private _initializeTime(): void {\n this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);\n this.creationTime = utcTimestampToDateString(this.createdAt);\n }\n\n _copy(metadata: UserMetadata): void {\n this.createdAt = metadata.createdAt;\n this.lastLoginAt = metadata.lastLoginAt;\n this._initializeTime();\n }\n\n toJSON(): object {\n return {\n createdAt: this.createdAt,\n lastLoginAt: this.lastLoginAt\n };\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User, UserInfo } from '../../model/public_types';\n\nimport {\n getAccountInfo,\n ProviderUserInfo\n} from '../../api/account_management/account';\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { UserMetadata } from './user_metadata';\nimport { getModularInstance } from '@firebase/util';\n\nexport async function _reloadWithoutSaving(user: UserInternal): Promise<void> {\n const auth = user.auth;\n const idToken = await user.getIdToken();\n const response = await _logoutIfInvalidated(\n user,\n getAccountInfo(auth, { idToken })\n );\n\n _assert(response?.users.length, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const coreAccount = response.users[0];\n\n user._notifyReloadListener(coreAccount);\n\n const newProviderData = coreAccount.providerUserInfo?.length\n ? extractProviderData(coreAccount.providerUserInfo)\n : [];\n\n const providerData = mergeProviderData(user.providerData, newProviderData);\n\n // Preserves the non-nonymous status of the stored user, even if no more\n // credentials (federated or email/password) are linked to the user. If\n // the user was previously anonymous, then use provider data to update.\n // On the other hand, if it was not anonymous before, it should never be\n // considered anonymous now.\n const oldIsAnonymous = user.isAnonymous;\n const newIsAnonymous =\n !(user.email && coreAccount.passwordHash) && !providerData?.length;\n const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;\n\n const updates: Partial<UserInternal> = {\n uid: coreAccount.localId,\n displayName: coreAccount.displayName || null,\n photoURL: coreAccount.photoUrl || null,\n email: coreAccount.email || null,\n emailVerified: coreAccount.emailVerified || false,\n phoneNumber: coreAccount.phoneNumber || null,\n tenantId: coreAccount.tenantId || null,\n providerData,\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\n isAnonymous\n };\n\n Object.assign(user, updates);\n}\n\n/**\n * Reloads user account data, if signed in.\n *\n * @param user - The user.\n *\n * @public\n */\nexport async function reload(user: User): Promise<void> {\n const userInternal: UserInternal = getModularInstance(user) as UserInternal;\n await _reloadWithoutSaving(userInternal);\n\n // Even though the current user hasn't changed, update\n // current user will trigger a persistence update w/ the\n // new info.\n await userInternal.auth._persistUserIfCurrent(userInternal);\n userInternal.auth._notifyListenersIfCurrent(userInternal);\n}\n\nfunction mergeProviderData(\n original: UserInfo[],\n newData: UserInfo[]\n): UserInfo[] {\n const deduped = original.filter(\n o => !newData.some(n => n.providerId === o.providerId)\n );\n return [...deduped, ...newData];\n}\n\nfunction extractProviderData(providers: ProviderUserInfo[]): UserInfo[] {\n return providers.map(({ providerId, ...provider }) => {\n return {\n providerId,\n uid: provider.rawId || '',\n displayName: provider.displayName || null,\n email: provider.email || null,\n phoneNumber: provider.phoneNumber || null,\n photoURL: provider.photoUrl || null\n };\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Endpoint, HttpMethod, _performApiRequest } from '../index';\nimport { MfaEnrollment } from './mfa';\nimport { Auth } from '../../model/public_types';\n\nexport interface DeleteAccountRequest {\n idToken: string;\n}\n\nexport async function deleteAccount(\n auth: Auth,\n request: DeleteAccountRequest\n): Promise<void> {\n return _performApiRequest<DeleteAccountRequest, void>(\n auth,\n HttpMethod.POST,\n Endpoint.DELETE_ACCOUNT,\n request\n );\n}\n\nexport interface ProviderUserInfo {\n providerId: string;\n rawId?: string;\n email?: string;\n displayName?: string;\n photoUrl?: string;\n phoneNumber?: string;\n}\n\nexport interface DeleteLinkedAccountsRequest {\n idToken: string;\n deleteProvider: string[];\n}\n\nexport interface DeleteLinkedAccountsResponse {\n providerUserInfo: ProviderUserInfo[];\n}\n\nexport async function deleteLinkedAccounts(\n auth: Auth,\n request: DeleteLinkedAccountsRequest\n): Promise<DeleteLinkedAccountsResponse> {\n return _performApiRequest<\n DeleteLinkedAccountsRequest,\n DeleteLinkedAccountsResponse\n >(auth, HttpMethod.POST, Endpoint.SET_ACCOUNT_INFO, request);\n}\n\nexport interface APIUserInfo {\n localId?: string;\n displayName?: string;\n photoUrl?: string;\n email?: string;\n emailVerified?: boolean;\n phoneNumber?: string;\n lastLoginAt?: number;\n createdAt?: number;\n tenantId?: string;\n passwordHash?: string;\n providerUserInfo?: ProviderUserInfo[];\n mfaInfo?: MfaEnrollment[];\n}\n\nexport interface GetAccountInfoRequest {\n idToken: string;\n}\n\nexport interface GetAccountInfoResponse {\n users: APIUserInfo[];\n}\n\nexport async function getAccountInfo(\n auth: Auth,\n request: GetAccountInfoRequest\n): Promise<GetAccountInfoResponse> {\n return _performApiRequest<GetAccountInfoRequest, GetAccountInfoResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.GET_ACCOUNT_INFO,\n request\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FinalizeMfaResponse } from '../../api/authentication/mfa';\nimport { requestStsToken } from '../../api/authentication/token';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { PersistedBlob } from '../persistence';\nimport { _assert, debugFail } from '../util/assert';\nimport { _tokenExpiresIn } from './id_token_result';\n\n/**\n * The number of milliseconds before the official expiration time of a token\n * to refresh that token, to provide a buffer for RPCs to complete.\n */\nexport const enum Buffer {\n TOKEN_REFRESH = 30_000\n}\n\n/**\n * We need to mark this class as internal explicitly to exclude it in the public typings, because\n * it references AuthInternal which has a circular dependency with UserInternal.\n *\n * @internal\n */\nexport class StsTokenManager {\n refreshToken: string | null = null;\n accessToken: string | null = null;\n expirationTime: number | null = null;\n\n get isExpired(): boolean {\n return (\n !this.expirationTime ||\n Date.now() > this.expirationTime - Buffer.TOKEN_REFRESH\n );\n }\n\n updateFromServerResponse(\n response: IdTokenResponse | FinalizeMfaResponse\n ): void {\n _assert(response.idToken, AuthErrorCode.INTERNAL_ERROR);\n _assert(\n typeof response.idToken !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n _assert(\n typeof response.refreshToken !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n const expiresIn =\n 'expiresIn' in response && typeof response.expiresIn !== 'undefined'\n ? Number(response.expiresIn)\n : _tokenExpiresIn(response.idToken);\n this.updateTokensAndExpiration(\n response.idToken,\n response.refreshToken,\n expiresIn\n );\n }\n\n async getToken(\n auth: AuthInternal,\n forceRefresh = false\n ): Promise<string | null> {\n _assert(\n !this.accessToken || this.refreshToken,\n auth,\n AuthErrorCode.TOKEN_EXPIRED\n );\n\n if (!forceRefresh && this.accessToken && !this.isExpired) {\n return this.accessToken;\n }\n\n if (this.refreshToken) {\n await this.refresh(auth, this.refreshToken!);\n return this.accessToken;\n }\n\n return null;\n }\n\n clearRefreshToken(): void {\n this.refreshToken = null;\n }\n\n private async refresh(auth: AuthInternal, oldToken: string): Promise<void> {\n const { accessToken, refreshToken, expiresIn } = await requestStsToken(\n auth,\n oldToken\n );\n this.updateTokensAndExpiration(\n accessToken,\n refreshToken,\n Number(expiresIn)\n );\n }\n\n private updateTokensAndExpiration(\n accessToken: string,\n refreshToken: string,\n expiresInSec: number\n ): void {\n this.refreshToken = refreshToken || null;\n this.accessToken = accessToken || null;\n this.expirationTime = Date.now() + expiresInSec * 1000;\n }\n\n static fromJSON(appName: string, object: PersistedBlob): StsTokenManager {\n const { refreshToken, accessToken, expirationTime } = object;\n\n const manager = new StsTokenManager();\n if (refreshToken) {\n _assert(typeof refreshToken === 'string', AuthErrorCode.INTERNAL_ERROR, {\n appName\n });\n manager.refreshToken = refreshToken;\n }\n if (accessToken) {\n _assert(typeof accessToken === 'string', AuthErrorCode.INTERNAL_ERROR, {\n appName\n });\n manager.accessToken = accessToken;\n }\n if (expirationTime) {\n _assert(\n typeof expirationTime === 'number',\n AuthErrorCode.INTERNAL_ERROR,\n {\n appName\n }\n );\n manager.expirationTime = expirationTime;\n }\n return manager;\n }\n\n toJSON(): object {\n return {\n refreshToken: this.refreshToken,\n accessToken: this.accessToken,\n expirationTime: this.expirationTime\n };\n }\n\n _assign(stsTokenManager: StsTokenManager): void {\n this.accessToken = stsTokenManager.accessToken;\n this.refreshToken = stsTokenManager.refreshToken;\n this.expirationTime = stsTokenManager.expirationTime;\n }\n\n _clone(): StsTokenManager {\n return Object.assign(new StsTokenManager(), this.toJSON());\n }\n\n _performRefresh(): never {\n return debugFail('not implemented');\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable camelcase */\n\nimport { querystring } from '@firebase/util';\n\nimport {\n _getFinalTarget,\n _performFetchWithErrorHandling,\n _performApiRequest,\n _addTidIfNecessary,\n HttpMethod,\n HttpHeader,\n Endpoint\n} from '../index';\nimport { FetchProvider } from '../../core/util/fetch_provider';\nimport { Auth } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\n\nexport const enum TokenType {\n REFRESH_TOKEN = 'REFRESH_TOKEN',\n ACCESS_TOKEN = 'ACCESS_TOKEN'\n}\n\n/** The server responses with snake_case; we convert to camelCase */\ninterface RequestStsTokenServerResponse {\n access_token: string;\n expires_in: string;\n refresh_token: string;\n}\n\nexport interface RequestStsTokenResponse {\n accessToken: string;\n expiresIn: string;\n refreshToken: string;\n}\n\nexport interface RevokeTokenRequest {\n providerId: string;\n tokenType: TokenType;\n token: string;\n idToken: string;\n tenantId?: string;\n}\n\nexport interface RevokeTokenResponse {}\n\nexport async function requestStsToken(\n auth: Auth,\n refreshToken: string\n): Promise<RequestStsTokenResponse> {\n const response =\n await _performFetchWithErrorHandling<RequestStsTokenServerResponse>(\n auth,\n {},\n async () => {\n const body = querystring({\n 'grant_type': 'refresh_token',\n 'refresh_token': refreshToken\n }).slice(1);\n const { tokenApiHost, apiKey } = auth.config;\n const url = _getFinalTarget(\n auth,\n tokenApiHost,\n Endpoint.TOKEN,\n `key=${apiKey}`\n );\n\n const headers = await (auth as AuthInternal)._getAdditionalHeaders();\n headers[HttpHeader.CONTENT_TYPE] = 'application/x-www-form-urlencoded';\n\n return FetchProvider.fetch()(url, {\n method: HttpMethod.POST,\n headers,\n body\n });\n }\n );\n\n // The response comes back in snake_case. Convert to camel:\n return {\n accessToken: response.access_token,\n expiresIn: response.expires_in,\n refreshToken: response.refresh_token\n };\n}\n\nexport async function revokeToken(\n auth: Auth,\n request: RevokeTokenRequest\n): Promise<RevokeTokenResponse> {\n return _performApiRequest<RevokeTokenRequest, RevokeTokenResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.REVOKE_TOKEN,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdTokenResult } from '../../model/public_types';\nimport { NextFn } from '@firebase/util';\n\nimport {\n APIUserInfo,\n deleteAccount\n} from '../../api/account_management/account';\nimport { FinalizeMfaResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport {\n MutableUserInfo,\n UserInternal,\n UserParameters\n} from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { PersistedBlob } from '../persistence';\nimport { _assert } from '../util/assert';\nimport { getIdTokenResult } from './id_token_result';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { ProactiveRefresh } from './proactive_refresh';\nimport { _reloadWithoutSaving, reload } from './reload';\nimport { StsTokenManager } from './token_manager';\nimport { UserMetadata } from './user_metadata';\nimport { ProviderId } from '../../model/enums';\n\nfunction assertStringOrUndefined(\n assertion: unknown,\n appName: string\n): asserts assertion is string | undefined {\n _assert(\n typeof assertion === 'string' || typeof assertion === 'undefined',\n AuthErrorCode.INTERNAL_ERROR,\n { appName }\n );\n}\n\nexport class UserImpl implements UserInternal {\n // For the user object, provider is always Firebase.\n readonly providerId = ProviderId.FIREBASE;\n stsTokenManager: StsTokenManager;\n // Last known accessToken so we know when it changes\n private accessToken: string | null;\n\n uid: string;\n auth: AuthInternal;\n emailVerified: boolean;\n isAnonymous: boolean;\n tenantId: string | null;\n readonly metadata: UserMetadata;\n providerData: MutableUserInfo[];\n\n // Optional fields from UserInfo\n displayName: string | null;\n email: string | null;\n phoneNumber: string | null;\n photoURL: string | null;\n\n _redirectEventId?: string;\n private readonly proactiveRefresh = new ProactiveRefresh(this);\n\n constructor({ uid, auth, stsTokenManager, ...opt }: UserParameters) {\n this.uid = uid;\n this.auth = auth;\n this.stsTokenManager = stsTokenManager;\n this.accessToken = stsTokenManager.accessToken;\n this.displayName = opt.displayName || null;\n this.email = opt.email || null;\n this.emailVerified = opt.emailVerified || false;\n this.phoneNumber = opt.phoneNumber || null;\n this.photoURL = opt.photoURL || null;\n this.isAnonymous = opt.isAnonymous || false;\n this.tenantId = opt.tenantId || null;\n this.providerData = opt.providerData ? [...opt.providerData] : [];\n this.metadata = new UserMetadata(\n opt.createdAt || undefined,\n opt.lastLoginAt || undefined\n );\n }\n\n async getIdToken(forceRefresh?: boolean): Promise<string> {\n const accessToken = await _logoutIfInvalidated(\n this,\n this.stsTokenManager.getToken(this.auth, forceRefresh)\n );\n _assert(accessToken, this.auth, AuthErrorCode.INTERNAL_ERROR);\n\n if (this.accessToken !== accessToken) {\n this.accessToken = accessToken;\n await this.auth._persistUserIfCurrent(this);\n this.auth._notifyListenersIfCurrent(this);\n }\n\n return accessToken;\n }\n\n getIdTokenResult(forceRefresh?: boolean): Promise<IdTokenResult> {\n return getIdTokenResult(this, forceRefresh);\n }\n\n reload(): Promise<void> {\n return reload(this);\n }\n\n private reloadUserInfo: APIUserInfo | null = null;\n private reloadListener: NextFn<APIUserInfo> | null = null;\n\n _assign(user: UserInternal): void {\n if (this === user) {\n return;\n }\n _assert(this.uid === user.uid, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.displayName = user.displayName;\n this.photoURL = user.photoURL;\n this.email = user.email;\n this.emailVerified = user.emailVerified;\n this.phoneNumber = user.phoneNumber;\n this.isAnonymous = user.isAnonymous;\n this.tenantId = user.tenantId;\n this.providerData = user.providerData.map(userInfo => ({ ...userInfo }));\n this.metadata._copy(user.metadata);\n this.stsTokenManager._assign(user.stsTokenManager);\n }\n\n _clone(auth: AuthInternal): UserInternal {\n const newUser = new UserImpl({\n ...this,\n auth,\n stsTokenManager: this.stsTokenManager._clone()\n });\n newUser.metadata._copy(this.metadata);\n return newUser;\n }\n\n _onReload(callback: NextFn<APIUserInfo>): void {\n // There should only ever be one listener, and that is a single instance of MultiFactorUser\n _assert(!this.reloadListener, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.reloadListener = callback;\n if (this.reloadUserInfo) {\n this._notifyReloadListener(this.reloadUserInfo);\n this.reloadUserInfo = null;\n }\n }\n\n _notifyReloadListener(userInfo: APIUserInfo): void {\n if (this.reloadListener) {\n this.reloadListener(userInfo);\n } else {\n // If no listener is subscribed yet, save the result so it's available when they do subscribe\n this.reloadUserInfo = userInfo;\n }\n }\n\n _startProactiveRefresh(): void {\n this.proactiveRefresh._start();\n }\n\n _stopProactiveRefresh(): void {\n this.proactiveRefresh._stop();\n }\n\n async _updateTokensIfNecessary(\n response: IdTokenResponse | FinalizeMfaResponse,\n reload = false\n ): Promise<void> {\n let tokensRefreshed = false;\n if (\n response.idToken &&\n response.idToken !== this.stsTokenManager.accessToken\n ) {\n this.stsTokenManager.updateFromServerResponse(response);\n tokensRefreshed = true;\n }\n\n if (reload) {\n await _reloadWithoutSaving(this);\n }\n\n await this.auth._persistUserIfCurrent(this);\n if (tokensRefreshed) {\n this.auth._notifyListenersIfCurrent(this);\n }\n }\n\n async delete(): Promise<void> {\n const idToken = await this.getIdToken();\n await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));\n this.stsTokenManager.clearRefreshToken();\n\n // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()\n // cancels pending actions...\n\n return this.auth.signOut();\n }\n\n toJSON(): PersistedBlob {\n return {\n uid: this.uid,\n email: this.email || undefined,\n emailVerified: this.emailVerified,\n displayName: this.displayName || undefined,\n isAnonymous: this.isAnonymous,\n photoURL: this.photoURL || undefined,\n phoneNumber: this.phoneNumber || undefined,\n tenantId: this.tenantId || undefined,\n providerData: this.providerData.map(userInfo => ({ ...userInfo })),\n stsTokenManager: this.stsTokenManager.toJSON(),\n // Redirect event ID must be maintained in case there is a pending\n // redirect event.\n _redirectEventId: this._redirectEventId,\n ...this.metadata.toJSON(),\n\n // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):\n apiKey: this.auth.config.apiKey,\n appName: this.auth.name\n // Missing authDomain will be tolerated by the legacy SDK.\n // stsTokenManager.apiKey isn't actually required (despite the legacy SDK persisting it).\n };\n }\n\n get refreshToken(): string {\n return this.stsTokenManager.refreshToken || '';\n }\n\n static _fromJSON(auth: AuthInternal, object: PersistedBlob): UserInternal {\n const displayName = object.displayName ?? undefined;\n const email = object.email ?? undefined;\n const phoneNumber = object.phoneNumber ?? undefined;\n const photoURL = object.photoURL ?? undefined;\n const tenantId = object.tenantId ?? undefined;\n const _redirectEventId = object._redirectEventId ?? undefined;\n const createdAt = object.createdAt ?? undefined;\n const lastLoginAt = object.lastLoginAt ?? undefined;\n const {\n uid,\n emailVerified,\n isAnonymous,\n providerData,\n stsTokenManager: plainObjectTokenManager\n } = object;\n\n _assert(uid && plainObjectTokenManager, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const stsTokenManager = StsTokenManager.fromJSON(\n this.name,\n plainObjectTokenManager as PersistedBlob\n );\n\n _assert(typeof uid === 'string', auth, AuthErrorCode.INTERNAL_ERROR);\n assertStringOrUndefined(displayName, auth.name);\n assertStringOrUndefined(email, auth.name);\n _assert(\n typeof emailVerified === 'boolean',\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n _assert(\n typeof isAnonymous === 'boolean',\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n assertStringOrUndefined(phoneNumber, auth.name);\n assertStringOrUndefined(photoURL, auth.name);\n assertStringOrUndefined(tenantId, auth.name);\n assertStringOrUndefined(_redirectEventId, auth.name);\n assertStringOrUndefined(createdAt, auth.name);\n assertStringOrUndefined(lastLoginAt, auth.name);\n const user = new UserImpl({\n uid,\n auth,\n email,\n emailVerified,\n displayName,\n isAnonymous,\n photoURL,\n phoneNumber,\n tenantId,\n stsTokenManager,\n createdAt,\n lastLoginAt\n });\n\n if (providerData && Array.isArray(providerData)) {\n user.providerData = providerData.map(userInfo => ({ ...userInfo }));\n }\n\n if (_redirectEventId) {\n user._redirectEventId = _redirectEventId;\n }\n\n return user;\n }\n\n /**\n * Initialize a User from an idToken server response\n * @param auth\n * @param idTokenResponse\n */\n static async _fromIdTokenResponse(\n auth: AuthInternal,\n idTokenResponse: IdTokenResponse,\n isAnonymous: boolean = false\n ): Promise<UserInternal> {\n const stsTokenManager = new StsTokenManager();\n stsTokenManager.updateFromServerResponse(idTokenResponse);\n\n // Initialize the Firebase Auth user.\n const user = new UserImpl({\n uid: idTokenResponse.localId,\n auth,\n stsTokenManager,\n isAnonymous\n });\n\n // Updates the user info and data and resolves with a user instance.\n await _reloadWithoutSaving(user);\n return user;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\n/**\n * Our API has a lot of one-off constants that are used to do things.\n * Unfortunately we can't export these as classes instantiated directly since\n * the constructor may side effect and therefore can't be proven to be safely\n * culled. Instead, we export these classes themselves as a lowerCamelCase\n * constant, and instantiate them under the hood.\n */\nexport interface SingletonInstantiator<T> {\n new (): T;\n}\n\nconst instanceCache: Map<unknown, unknown> = new Map();\n\nexport function _getInstance<T>(cls: unknown): T {\n debugAssert(cls instanceof Function, 'Expected a class definition');\n let instance = instanceCache.get(cls) as T | undefined;\n\n if (instance) {\n debugAssert(\n instance instanceof cls,\n 'Instance stored in cache mismatched with class'\n );\n return instance;\n }\n\n instance = new (cls as SingletonInstantiator<T>)();\n instanceCache.set(cls, instance);\n return instance;\n}\n\nexport function _clearInstanceMap(): void {\n instanceCache.clear();\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport {\n PersistenceInternal,\n PersistenceType,\n PersistenceValue,\n StorageEventListener\n} from '../persistence';\n\nexport class InMemoryPersistence implements PersistenceInternal {\n static type: 'NONE' = 'NONE';\n readonly type = PersistenceType.NONE;\n storage: Record<string, PersistenceValue> = {};\n\n async _isAvailable(): Promise<boolean> {\n return true;\n }\n\n async _set(key: string, value: PersistenceValue): Promise<void> {\n this.storage[key] = value;\n }\n\n async _get<T extends PersistenceValue>(key: string): Promise<T | null> {\n const value = this.storage[key];\n return value === undefined ? null : (value as T);\n }\n\n async _remove(key: string): Promise<void> {\n delete this.storage[key];\n }\n\n _addListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n\n _removeListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type 'NONE'.\n *\n * @public\n */\nexport const inMemoryPersistence: Persistence = InMemoryPersistence;\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ApiKey, AppName, AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { PersistedBlob, PersistenceInternal } from '../persistence';\nimport { UserImpl } from '../user/user_impl';\nimport { _getInstance } from '../util/instantiator';\nimport { inMemoryPersistence } from './in_memory';\n\nexport const enum KeyName {\n AUTH_USER = 'authUser',\n AUTH_EVENT = 'authEvent',\n REDIRECT_USER = 'redirectUser',\n PERSISTENCE_USER = 'persistence'\n}\nexport const enum Namespace {\n PERSISTENCE = 'firebase'\n}\n\nexport function _persistenceKeyName(\n key: string,\n apiKey: ApiKey,\n appName: AppName\n): string {\n return `${Namespace.PERSISTENCE}:${key}:${apiKey}:${appName}`;\n}\n\nexport class PersistenceUserManager {\n private readonly fullUserKey: string;\n private readonly fullPersistenceKey: string;\n private readonly boundEventHandler: () => void;\n\n private constructor(\n public persistence: PersistenceInternal,\n private readonly auth: AuthInternal,\n private readonly userKey: string\n ) {\n const { config, name } = this.auth;\n this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);\n this.fullPersistenceKey = _persistenceKeyName(\n KeyName.PERSISTENCE_USER,\n config.apiKey,\n name\n );\n this.boundEventHandler = auth._onStorageEvent.bind(auth);\n this.persistence._addListener(this.fullUserKey, this.boundEventHandler);\n }\n\n setCurrentUser(user: UserInternal): Promise<void> {\n return this.persistence._set(this.fullUserKey, user.toJSON());\n }\n\n async getCurrentUser(): Promise<UserInternal | null> {\n const blob = await this.persistence._get<PersistedBlob>(this.fullUserKey);\n return blob ? UserImpl._fromJSON(this.auth, blob) : null;\n }\n\n removeCurrentUser(): Promise<void> {\n return this.persistence._remove(this.fullUserKey);\n }\n\n savePersistenceForRedirect(): Promise<void> {\n return this.persistence._set(\n this.fullPersistenceKey,\n this.persistence.type\n );\n }\n\n async setPersistence(newPersistence: PersistenceInternal): Promise<void> {\n if (this.persistence === newPersistence) {\n return;\n }\n\n const currentUser = await this.getCurrentUser();\n await this.removeCurrentUser();\n\n this.persistence = newPersistence;\n\n if (currentUser) {\n return this.setCurrentUser(currentUser);\n }\n }\n\n delete(): void {\n this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);\n }\n\n static async create(\n auth: AuthInternal,\n persistenceHierarchy: PersistenceInternal[],\n userKey = KeyName.AUTH_USER\n ): Promise<PersistenceUserManager> {\n if (!persistenceHierarchy.length) {\n return new PersistenceUserManager(\n _getInstance(inMemoryPersistence),\n auth,\n userKey\n );\n }\n\n // Eliminate any persistences that are not available\n const availablePersistences = (\n await Promise.all(\n persistenceHierarchy.map(async persistence => {\n if (await persistence._isAvailable()) {\n return persistence;\n }\n return undefined;\n })\n )\n ).filter(persistence => persistence) as PersistenceInternal[];\n\n // Fall back to the first persistence listed, or in memory if none available\n let selectedPersistence =\n availablePersistences[0] ||\n _getInstance<PersistenceInternal>(inMemoryPersistence);\n\n const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);\n\n // Pull out the existing user, setting the chosen persistence to that\n // persistence if the user exists.\n let userToMigrate: UserInternal | null = null;\n // Note, here we check for a user in _all_ persistences, not just the\n // ones deemed available. If we can migrate a user out of a broken\n // persistence, we will (but only if that persistence supports migration).\n for (const persistence of persistenceHierarchy) {\n try {\n const blob = await persistence._get<PersistedBlob>(key);\n if (blob) {\n const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)\n if (persistence !== selectedPersistence) {\n userToMigrate = user;\n }\n selectedPersistence = persistence;\n break;\n }\n } catch {}\n }\n\n // If we find the user in a persistence that does support migration, use\n // that migration path (of only persistences that support migration)\n const migrationHierarchy = availablePersistences.filter(\n p => p._shouldAllowMigration\n );\n\n // If the persistence does _not_ allow migration, just finish off here\n if (\n !selectedPersistence._shouldAllowMigration ||\n !migrationHierarchy.length\n ) {\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\n }\n\n selectedPersistence = migrationHierarchy[0];\n if (userToMigrate) {\n // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does\n // we'll just let it bubble to surface the error.\n await selectedPersistence._set(key, userToMigrate.toJSON());\n }\n\n // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues\n // such as users getting stuck with a previous account after signing out and refreshing the tab.\n await Promise.all(\n persistenceHierarchy.map(async persistence => {\n if (persistence !== selectedPersistence) {\n try {\n await persistence._remove(key);\n } catch {}\n }\n })\n );\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIE, getUA } from '@firebase/util';\n\ninterface NavigatorStandalone extends Navigator {\n standalone?: unknown;\n}\n\ninterface Document {\n documentMode?: number;\n}\n\n/**\n * Enums for Browser name.\n */\nexport const enum BrowserName {\n ANDROID = 'Android',\n BLACKBERRY = 'Blackberry',\n EDGE = 'Edge',\n FIREFOX = 'Firefox',\n IE = 'IE',\n IEMOBILE = 'IEMobile',\n OPERA = 'Opera',\n OTHER = 'Other',\n CHROME = 'Chrome',\n SAFARI = 'Safari',\n SILK = 'Silk',\n WEBOS = 'Webos'\n}\n\n/**\n * Determine the browser for the purposes of reporting usage to the API\n */\nexport function _getBrowserName(userAgent: string): BrowserName | string {\n const ua = userAgent.toLowerCase();\n if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {\n return BrowserName.OPERA;\n } else if (_isIEMobile(ua)) {\n // Windows phone IEMobile browser.\n return BrowserName.IEMOBILE;\n } else if (ua.includes('msie') || ua.includes('trident/')) {\n return BrowserName.IE;\n } else if (ua.includes('edge/')) {\n return BrowserName.EDGE;\n } else if (_isFirefox(ua)) {\n return BrowserName.FIREFOX;\n } else if (ua.includes('silk/')) {\n return BrowserName.SILK;\n } else if (_isBlackBerry(ua)) {\n // Blackberry browser.\n return BrowserName.BLACKBERRY;\n } else if (_isWebOS(ua)) {\n // WebOS default browser.\n return BrowserName.WEBOS;\n } else if (_isSafari(ua)) {\n return BrowserName.SAFARI;\n } else if (\n (ua.includes('chrome/') || _isChromeIOS(ua)) &&\n !ua.includes('edge/')\n ) {\n return BrowserName.CHROME;\n } else if (_isAndroid(ua)) {\n // Android stock browser.\n return BrowserName.ANDROID;\n } else {\n // Most modern browsers have name/version at end of user agent string.\n const re = /([a-zA-Z\\d\\.]+)\\/[a-zA-Z\\d\\.]*$/;\n const matches = userAgent.match(re);\n if (matches?.length === 2) {\n return matches[1];\n }\n }\n return BrowserName.OTHER;\n}\n\nexport function _isFirefox(ua = getUA()): boolean {\n return /firefox\\//i.test(ua);\n}\n\nexport function _isSafari(userAgent = getUA()): boolean {\n const ua = userAgent.toLowerCase();\n return (\n ua.includes('safari/') &&\n !ua.includes('chrome/') &&\n !ua.includes('crios/') &&\n !ua.includes('android')\n );\n}\n\nexport function _isChromeIOS(ua = getUA()): boolean {\n return /crios\\//i.test(ua);\n}\n\nexport function _isIEMobile(ua = getUA()): boolean {\n return /iemobile/i.test(ua);\n}\n\nexport function _isAndroid(ua = getUA()): boolean {\n return /android/i.test(ua);\n}\n\nexport function _isBlackBerry(ua = getUA()): boolean {\n return /blackberry/i.test(ua);\n}\n\nexport function _isWebOS(ua = getUA()): boolean {\n return /webos/i.test(ua);\n}\n\nexport function _isIOS(ua = getUA()): boolean {\n return (\n /iphone|ipad|ipod/i.test(ua) ||\n (/macintosh/i.test(ua) && /mobile/i.test(ua))\n );\n}\n\nexport function _isIOS7Or8(ua = getUA()): boolean {\n return (\n /(iPad|iPhone|iPod).*OS 7_\\d/i.test(ua) ||\n /(iPad|iPhone|iPod).*OS 8_\\d/i.test(ua)\n );\n}\n\nexport function _isIOSStandalone(ua = getUA()): boolean {\n return _isIOS(ua) && !!(window.navigator as NavigatorStandalone)?.standalone;\n}\n\nexport function _isIE10(): boolean {\n return isIE() && (document as Document).documentMode === 10;\n}\n\nexport function _isMobileBrowser(ua: string = getUA()): boolean {\n // TODO: implement getBrowserName equivalent for OS.\n return (\n _isIOS(ua) ||\n _isAndroid(ua) ||\n _isWebOS(ua) ||\n _isBlackBerry(ua) ||\n /windows phone/i.test(ua) ||\n _isIEMobile(ua)\n );\n}\n\nexport function _isIframe(): boolean {\n try {\n // Check that the current window is not the top window.\n // If so, return true.\n return !!(window && window !== window.top);\n } catch (e) {\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { _getBrowserName } from './browser';\nimport { getUA } from '@firebase/util';\n\nexport const enum ClientImplementation {\n CORE = 'JsCore'\n}\n\n/**\n * @internal\n */\nexport const enum ClientPlatform {\n BROWSER = 'Browser',\n NODE = 'Node',\n REACT_NATIVE = 'ReactNative',\n CORDOVA = 'Cordova',\n WORKER = 'Worker'\n}\n\n/*\n * Determine the SDK version string\n */\nexport function _getClientVersion(\n clientPlatform: ClientPlatform,\n frameworks: readonly string[] = []\n): string {\n let reportedPlatform: string;\n switch (clientPlatform) {\n case ClientPlatform.BROWSER:\n // In a browser environment, report the browser name.\n reportedPlatform = _getBrowserName(getUA());\n break;\n case ClientPlatform.WORKER:\n // Technically a worker runs from a browser but we need to differentiate a\n // worker from a browser.\n // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.\n reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;\n break;\n default:\n reportedPlatform = clientPlatform;\n }\n const reportedFrameworks = frameworks.length\n ? frameworks.join(',')\n : 'FirebaseCore-web'; /* default value if no other framework is used */\n return `${reportedPlatform}/${ClientImplementation.CORE}/${SDK_VERSION}/${reportedFrameworks}`;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthInternal } from '../../model/auth';\nimport { Unsubscribe, User } from '../../model/public_types';\nimport { AuthErrorCode } from '../errors';\n\ninterface MiddlewareEntry {\n (user: User | null): Promise<void>;\n onAbort?: () => void;\n}\n\nexport class AuthMiddlewareQueue {\n private readonly queue: MiddlewareEntry[] = [];\n\n constructor(private readonly auth: AuthInternal) {}\n\n pushCallback(\n callback: (user: User | null) => void | Promise<void>,\n onAbort?: () => void\n ): Unsubscribe {\n // The callback could be sync or async. Wrap it into a\n // function that is always async.\n const wrappedCallback: MiddlewareEntry = (\n user: User | null\n ): Promise<void> =>\n new Promise((resolve, reject) => {\n try {\n const result = callback(user);\n // Either resolve with existing promise or wrap a non-promise\n // return value into a promise.\n resolve(result);\n } catch (e) {\n // Sync callback throws.\n reject(e);\n }\n });\n // Attach the onAbort if present\n wrappedCallback.onAbort = onAbort;\n this.queue.push(wrappedCallback);\n\n const index = this.queue.length - 1;\n return () => {\n // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb\n // indexing of other elements.\n this.queue[index] = () => Promise.resolve();\n };\n }\n\n async runMiddleware(nextUser: User | null): Promise<void> {\n if (this.auth.currentUser === nextUser) {\n return;\n }\n\n // While running the middleware, build a temporary stack of onAbort\n // callbacks to call if one middleware callback rejects.\n\n const onAbortStack: Array<() => void> = [];\n try {\n for (const beforeStateCallback of this.queue) {\n await beforeStateCallback(nextUser);\n\n // Only push the onAbort if the callback succeeds\n if (beforeStateCallback.onAbort) {\n onAbortStack.push(beforeStateCallback.onAbort);\n }\n }\n } catch (e) {\n // Run all onAbort, with separate try/catch to ignore any errors and\n // continue\n onAbortStack.reverse();\n for (const onAbort of onAbortStack) {\n try {\n onAbort();\n } catch (_) {\n /* swallow error */\n }\n }\n\n throw this.auth._errorFactory.create(AuthErrorCode.LOGIN_BLOCKED, {\n originalMessage: (e as Error)?.message\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GetPasswordPolicyResponse } from '../../api/password_policy/get_password_policy';\nimport {\n PasswordPolicyCustomStrengthOptions,\n PasswordPolicyInternal,\n PasswordValidationStatusInternal\n} from '../../model/password_policy';\nimport { PasswordValidationStatus } from '../../model/public_types';\n\n// Minimum min password length enforced by the backend, even if no minimum length is set.\nconst MINIMUM_MIN_PASSWORD_LENGTH = 6;\n\n/**\n * Stores password policy requirements and provides password validation against the policy.\n *\n * @internal\n */\nexport class PasswordPolicyImpl implements PasswordPolicyInternal {\n readonly customStrengthOptions: PasswordPolicyCustomStrengthOptions;\n readonly allowedNonAlphanumericCharacters: string;\n readonly enforcementState: string;\n readonly forceUpgradeOnSignin: boolean;\n readonly schemaVersion: number;\n\n constructor(response: GetPasswordPolicyResponse) {\n // Only include custom strength options defined in the response.\n const responseOptions = response.customStrengthOptions;\n this.customStrengthOptions = {};\n // TODO: Remove once the backend is updated to include the minimum min password length instead of undefined when there is no minimum length set.\n this.customStrengthOptions.minPasswordLength =\n responseOptions.minPasswordLength ?? MINIMUM_MIN_PASSWORD_LENGTH;\n if (responseOptions.maxPasswordLength) {\n this.customStrengthOptions.maxPasswordLength =\n responseOptions.maxPasswordLength;\n }\n if (responseOptions.containsLowercaseCharacter !== undefined) {\n this.customStrengthOptions.containsLowercaseLetter =\n responseOptions.containsLowercaseCharacter;\n }\n if (responseOptions.containsUppercaseCharacter !== undefined) {\n this.customStrengthOptions.containsUppercaseLetter =\n responseOptions.containsUppercaseCharacter;\n }\n if (responseOptions.containsNumericCharacter !== undefined) {\n this.customStrengthOptions.containsNumericCharacter =\n responseOptions.containsNumericCharacter;\n }\n if (responseOptions.containsNonAlphanumericCharacter !== undefined) {\n this.customStrengthOptions.containsNonAlphanumericCharacter =\n responseOptions.containsNonAlphanumericCharacter;\n }\n\n this.enforcementState = response.enforcementState;\n if (this.enforcementState === 'ENFORCEMENT_STATE_UNSPECIFIED') {\n this.enforcementState = 'OFF';\n }\n\n // Use an empty string if no non-alphanumeric characters are specified in the response.\n this.allowedNonAlphanumericCharacters =\n response.allowedNonAlphanumericCharacters?.join('') ?? '';\n\n this.forceUpgradeOnSignin = response.forceUpgradeOnSignin ?? false;\n this.schemaVersion = response.schemaVersion;\n }\n\n validatePassword(password: string): PasswordValidationStatus {\n const status: PasswordValidationStatusInternal = {\n isValid: true,\n passwordPolicy: this\n };\n\n // Check the password length and character options.\n this.validatePasswordLengthOptions(password, status);\n this.validatePasswordCharacterOptions(password, status);\n\n // Combine the status into single isValid property.\n status.isValid &&= status.meetsMinPasswordLength ?? true;\n status.isValid &&= status.meetsMaxPasswordLength ?? true;\n status.isValid &&= status.containsLowercaseLetter ?? true;\n status.isValid &&= status.containsUppercaseLetter ?? true;\n status.isValid &&= status.containsNumericCharacter ?? true;\n status.isValid &&= status.containsNonAlphanumericCharacter ?? true;\n\n return status;\n }\n\n /**\n * Validates that the password meets the length options for the policy.\n *\n * @param password Password to validate.\n * @param status Validation status.\n */\n private validatePasswordLengthOptions(\n password: string,\n status: PasswordValidationStatusInternal\n ): void {\n const minPasswordLength = this.customStrengthOptions.minPasswordLength;\n const maxPasswordLength = this.customStrengthOptions.maxPasswordLength;\n if (minPasswordLength) {\n status.meetsMinPasswordLength = password.length >= minPasswordLength;\n }\n if (maxPasswordLength) {\n status.meetsMaxPasswordLength = password.length <= maxPasswordLength;\n }\n }\n\n /**\n * Validates that the password meets the character options for the policy.\n *\n * @param password Password to validate.\n * @param status Validation status.\n */\n private validatePasswordCharacterOptions(\n password: string,\n status: PasswordValidationStatusInternal\n ): void {\n // Assign statuses for requirements even if the password is an empty string.\n this.updatePasswordCharacterOptionsStatuses(\n status,\n /* containsLowercaseCharacter= */ false,\n /* containsUppercaseCharacter= */ false,\n /* containsNumericCharacter= */ false,\n /* containsNonAlphanumericCharacter= */ false\n );\n\n let passwordChar;\n for (let i = 0; i < password.length; i++) {\n passwordChar = password.charAt(i);\n this.updatePasswordCharacterOptionsStatuses(\n status,\n /* containsLowercaseCharacter= */ passwordChar >= 'a' &&\n passwordChar <= 'z',\n /* containsUppercaseCharacter= */ passwordChar >= 'A' &&\n passwordChar <= 'Z',\n /* containsNumericCharacter= */ passwordChar >= '0' &&\n passwordChar <= '9',\n /* containsNonAlphanumericCharacter= */ this.allowedNonAlphanumericCharacters.includes(\n passwordChar\n )\n );\n }\n }\n\n /**\n * Updates the running validation status with the statuses for the character options.\n * Expected to be called each time a character is processed to update each option status\n * based on the current character.\n *\n * @param status Validation status.\n * @param containsLowercaseCharacter Whether the character is a lowercase letter.\n * @param containsUppercaseCharacter Whether the character is an uppercase letter.\n * @param containsNumericCharacter Whether the character is a numeric character.\n * @param containsNonAlphanumericCharacter Whether the character is a non-alphanumeric character.\n */\n private updatePasswordCharacterOptionsStatuses(\n status: PasswordValidationStatusInternal,\n containsLowercaseCharacter: boolean,\n containsUppercaseCharacter: boolean,\n containsNumericCharacter: boolean,\n containsNonAlphanumericCharacter: boolean\n ): void {\n if (this.customStrengthOptions.containsLowercaseLetter) {\n status.containsLowercaseLetter ||= containsLowercaseCharacter;\n }\n if (this.customStrengthOptions.containsUppercaseLetter) {\n status.containsUppercaseLetter ||= containsUppercaseCharacter;\n }\n if (this.customStrengthOptions.containsNumericCharacter) {\n status.containsNumericCharacter ||= containsNumericCharacter;\n }\n if (this.customStrengthOptions.containsNonAlphanumericCharacter) {\n status.containsNonAlphanumericCharacter ||=\n containsNonAlphanumericCharacter;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _FirebaseService, FirebaseApp } from '@firebase/app';\nimport { Provider } from '@firebase/component';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\nimport {\n Auth,\n AuthErrorMap,\n AuthSettings,\n EmulatorConfig,\n NextOrObserver,\n Persistence,\n PopupRedirectResolver,\n User,\n UserCredential,\n CompleteFn,\n ErrorFn,\n NextFn,\n Unsubscribe,\n PasswordValidationStatus\n} from '../../model/public_types';\nimport {\n createSubscribe,\n ErrorFactory,\n FirebaseError,\n getModularInstance,\n Observer,\n Subscribe\n} from '@firebase/util';\n\nimport { AuthInternal, ConfigInternal } from '../../model/auth';\nimport { PopupRedirectResolverInternal } from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport {\n AuthErrorCode,\n AuthErrorParams,\n ErrorMapRetriever,\n _DEFAULT_AUTH_ERROR_FACTORY\n} from '../errors';\nimport { PersistenceInternal } from '../persistence';\nimport {\n KeyName,\n PersistenceUserManager\n} from '../persistence/persistence_user_manager';\nimport { _reloadWithoutSaving } from '../user/reload';\nimport { _assert } from '../util/assert';\nimport { _getInstance } from '../util/instantiator';\nimport { _getUserLanguage } from '../util/navigator';\nimport { _getClientVersion } from '../util/version';\nimport { HttpHeader } from '../../api';\nimport {\n RevokeTokenRequest,\n TokenType,\n revokeToken\n} from '../../api/authentication/token';\nimport { AuthMiddlewareQueue } from './middleware';\nimport { RecaptchaConfig } from '../../platform_browser/recaptcha/recaptcha';\nimport { _logWarn } from '../util/log';\nimport { _getPasswordPolicy } from '../../api/password_policy/get_password_policy';\nimport { PasswordPolicyInternal } from '../../model/password_policy';\nimport { PasswordPolicyImpl } from './password_policy_impl';\n\ninterface AsyncAction {\n (): Promise<void>;\n}\n\nexport const enum DefaultConfig {\n TOKEN_API_HOST = 'securetoken.googleapis.com',\n API_HOST = 'identitytoolkit.googleapis.com',\n API_SCHEME = 'https'\n}\n\nexport class AuthImpl implements AuthInternal, _FirebaseService {\n currentUser: User | null = null;\n emulatorConfig: EmulatorConfig | null = null;\n private operations = Promise.resolve();\n private persistenceManager?: PersistenceUserManager;\n private redirectPersistenceManager?: PersistenceUserManager;\n private authStateSubscription = new Subscription<User>(this);\n private idTokenSubscription = new Subscription<User>(this);\n private readonly beforeStateQueue = new AuthMiddlewareQueue(this);\n private redirectUser: UserInternal | null = null;\n private isProactiveRefreshEnabled = false;\n private readonly EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION: number = 1;\n\n // Any network calls will set this to true and prevent subsequent emulator\n // initialization\n _canInitEmulator = true;\n _isInitialized = false;\n _deleted = false;\n _initializationPromise: Promise<void> | null = null;\n _popupRedirectResolver: PopupRedirectResolverInternal | null = null;\n _errorFactory: ErrorFactory<AuthErrorCode, AuthErrorParams> =\n _DEFAULT_AUTH_ERROR_FACTORY;\n _agentRecaptchaConfig: RecaptchaConfig | null = null;\n _tenantRecaptchaConfigs: Record<string, RecaptchaConfig> = {};\n _projectPasswordPolicy: PasswordPolicyInternal | null = null;\n _tenantPasswordPolicies: Record<string, PasswordPolicyInternal> = {};\n readonly name: string;\n\n // Tracks the last notified UID for state change listeners to prevent\n // repeated calls to the callbacks. Undefined means it's never been\n // called, whereas null means it's been called with a signed out user\n private lastNotifiedUid: string | null | undefined = undefined;\n\n languageCode: string | null = null;\n tenantId: string | null = null;\n settings: AuthSettings = { appVerificationDisabledForTesting: false };\n\n constructor(\n public readonly app: FirebaseApp,\n private readonly heartbeatServiceProvider: Provider<'heartbeat'>,\n private readonly appCheckServiceProvider: Provider<AppCheckInternalComponentName>,\n public readonly config: ConfigInternal\n ) {\n this.name = app.name;\n this.clientVersion = config.sdkClientVersion;\n }\n\n _initializeWithPersistence(\n persistenceHierarchy: PersistenceInternal[],\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise<void> {\n if (popupRedirectResolver) {\n this._popupRedirectResolver = _getInstance(popupRedirectResolver);\n }\n\n // Have to check for app deletion throughout initialization (after each\n // promise resolution)\n this._initializationPromise = this.queue(async () => {\n if (this._deleted) {\n return;\n }\n\n this.persistenceManager = await PersistenceUserManager.create(\n this,\n persistenceHierarchy\n );\n\n if (this._deleted) {\n return;\n }\n\n // Initialize the resolver early if necessary (only applicable to web:\n // this will cause the iframe to load immediately in certain cases)\n if (this._popupRedirectResolver?._shouldInitProactively) {\n // If this fails, don't halt auth loading\n try {\n await this._popupRedirectResolver._initialize(this);\n } catch (e) {\n /* Ignore the error */\n }\n }\n\n await this.initializeCurrentUser(popupRedirectResolver);\n this.lastNotifiedUid = this.currentUser?.uid || null;\n\n if (this._deleted) {\n return;\n }\n\n this._isInitialized = true;\n });\n\n return this._initializationPromise;\n }\n\n /**\n * If the persistence is changed in another window, the user manager will let us know\n */\n async _onStorageEvent(): Promise<void> {\n if (this._deleted) {\n return;\n }\n\n const user = await this.assertedPersistence.getCurrentUser();\n\n if (!this.currentUser && !user) {\n // No change, do nothing (was signed out and remained signed out).\n return;\n }\n\n // If the same user is to be synchronized.\n if (this.currentUser && user && this.currentUser.uid === user.uid) {\n // Data update, simply copy data changes.\n this._currentUser._assign(user);\n // If tokens changed from previous user tokens, this will trigger\n // notifyAuthListeners_.\n await this.currentUser.getIdToken();\n return;\n }\n\n // Update current Auth state. Either a new login or logout.\n // Skip blocking callbacks, they should not apply to a change in another tab.\n await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);\n }\n\n private async initializeCurrentUser(\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise<void> {\n // First check to see if we have a pending redirect event.\n const previouslyStoredUser =\n (await this.assertedPersistence.getCurrentUser()) as UserInternal | null;\n let futureCurrentUser = previouslyStoredUser;\n let needsTocheckMiddleware = false;\n if (popupRedirectResolver && this.config.authDomain) {\n await this.getOrInitRedirectPersistenceManager();\n const redirectUserEventId = this.redirectUser?._redirectEventId;\n const storedUserEventId = futureCurrentUser?._redirectEventId;\n const result = await this.tryRedirectSignIn(popupRedirectResolver);\n\n // If the stored user (i.e. the old \"currentUser\") has a redirectId that\n // matches the redirect user, then we want to initially sign in with the\n // new user object from result.\n // TODO(samgho): More thoroughly test all of this\n if (\n (!redirectUserEventId || redirectUserEventId === storedUserEventId) &&\n result?.user\n ) {\n futureCurrentUser = result.user as UserInternal;\n needsTocheckMiddleware = true;\n }\n }\n\n // If no user in persistence, there is no current user. Set to null.\n if (!futureCurrentUser) {\n return this.directlySetCurrentUser(null);\n }\n\n if (!futureCurrentUser._redirectEventId) {\n // This isn't a redirect link operation, we can reload and bail.\n // First though, ensure that we check the middleware is happy.\n if (needsTocheckMiddleware) {\n try {\n await this.beforeStateQueue.runMiddleware(futureCurrentUser);\n } catch (e) {\n futureCurrentUser = previouslyStoredUser;\n // We know this is available since the bit is only set when the\n // resolver is available\n this._popupRedirectResolver!._overrideRedirectResult(this, () =>\n Promise.reject(e)\n );\n }\n }\n\n if (futureCurrentUser) {\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n } else {\n return this.directlySetCurrentUser(null);\n }\n }\n\n _assert(this._popupRedirectResolver, this, AuthErrorCode.ARGUMENT_ERROR);\n await this.getOrInitRedirectPersistenceManager();\n\n // If the redirect user's event ID matches the current user's event ID,\n // DO NOT reload the current user, otherwise they'll be cleared from storage.\n // This is important for the reauthenticateWithRedirect() flow.\n if (\n this.redirectUser &&\n this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId\n ) {\n return this.directlySetCurrentUser(futureCurrentUser);\n }\n\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n }\n\n private async tryRedirectSignIn(\n redirectResolver: PopupRedirectResolver\n ): Promise<UserCredential | null> {\n // The redirect user needs to be checked (and signed in if available)\n // during auth initialization. All of the normal sign in and link/reauth\n // flows call back into auth and push things onto the promise queue. We\n // need to await the result of the redirect sign in *inside the promise\n // queue*. This presents a problem: we run into deadlock. See:\n // ┌> [Initialization] ─────┐\n // ┌> [<other queue tasks>] │\n // └─ [getRedirectResult] <─┘\n // where [] are tasks on the queue and arrows denote awaits\n // Initialization will never complete because it's waiting on something\n // that's waiting for initialization to complete!\n //\n // Instead, this method calls getRedirectResult() (stored in\n // _completeRedirectFn) with an optional parameter that instructs all of\n // the underlying auth operations to skip anything that mutates auth state.\n\n let result: UserCredential | null = null;\n try {\n // We know this._popupRedirectResolver is set since redirectResolver\n // is passed in. The _completeRedirectFn expects the unwrapped extern.\n result = await this._popupRedirectResolver!._completeRedirectFn(\n this,\n redirectResolver,\n true\n );\n } catch (e) {\n // Swallow any errors here; the code can retrieve them in\n // getRedirectResult().\n await this._setRedirectUser(null);\n }\n\n return result;\n }\n\n private async reloadAndSetCurrentUserOrClear(\n user: UserInternal\n ): Promise<void> {\n try {\n await _reloadWithoutSaving(user);\n } catch (e) {\n if (\n (e as FirebaseError)?.code !==\n `auth/${AuthErrorCode.NETWORK_REQUEST_FAILED}`\n ) {\n // Something's wrong with the user's token. Log them out and remove\n // them from storage\n return this.directlySetCurrentUser(null);\n }\n }\n\n return this.directlySetCurrentUser(user);\n }\n\n useDeviceLanguage(): void {\n this.languageCode = _getUserLanguage();\n }\n\n async _delete(): Promise<void> {\n this._deleted = true;\n }\n\n async updateCurrentUser(userExtern: User | null): Promise<void> {\n // The public updateCurrentUser method needs to make a copy of the user,\n // and also check that the project matches\n const user = userExtern\n ? (getModularInstance(userExtern) as UserInternal)\n : null;\n if (user) {\n _assert(\n user.auth.config.apiKey === this.config.apiKey,\n this,\n AuthErrorCode.INVALID_AUTH\n );\n }\n return this._updateCurrentUser(user && user._clone(this));\n }\n\n async _updateCurrentUser(\n user: User | null,\n skipBeforeStateCallbacks: boolean = false\n ): Promise<void> {\n if (this._deleted) {\n return;\n }\n if (user) {\n _assert(\n this.tenantId === user.tenantId,\n this,\n AuthErrorCode.TENANT_ID_MISMATCH\n );\n }\n\n if (!skipBeforeStateCallbacks) {\n await this.beforeStateQueue.runMiddleware(user);\n }\n\n return this.queue(async () => {\n await this.directlySetCurrentUser(user as UserInternal | null);\n this.notifyAuthListeners();\n });\n }\n\n async signOut(): Promise<void> {\n // Run first, to block _setRedirectUser() if any callbacks fail.\n await this.beforeStateQueue.runMiddleware(null);\n // Clear the redirect user when signOut is called\n if (this.redirectPersistenceManager || this._popupRedirectResolver) {\n await this._setRedirectUser(null);\n }\n\n // Prevent callbacks from being called again in _updateCurrentUser, as\n // they were already called in the first line.\n return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);\n }\n\n setPersistence(persistence: Persistence): Promise<void> {\n return this.queue(async () => {\n await this.assertedPersistence.setPersistence(_getInstance(persistence));\n });\n }\n\n _getRecaptchaConfig(): RecaptchaConfig | null {\n if (this.tenantId == null) {\n return this._agentRecaptchaConfig;\n } else {\n return this._tenantRecaptchaConfigs[this.tenantId];\n }\n }\n\n async validatePassword(password: string): Promise<PasswordValidationStatus> {\n if (!this._getPasswordPolicyInternal()) {\n await this._updatePasswordPolicy();\n }\n\n // Password policy will be defined after fetching.\n const passwordPolicy: PasswordPolicyInternal =\n this._getPasswordPolicyInternal()!;\n\n // Check that the policy schema version is supported by the SDK.\n // TODO: Update this logic to use a max supported policy schema version once we have multiple schema versions.\n if (\n passwordPolicy.schemaVersion !==\n this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION\n ) {\n return Promise.reject(\n this._errorFactory.create(\n AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION,\n {}\n )\n );\n }\n\n return passwordPolicy.validatePassword(password);\n }\n\n _getPasswordPolicyInternal(): PasswordPolicyInternal | null {\n if (this.tenantId === null) {\n return this._projectPasswordPolicy;\n } else {\n return this._tenantPasswordPolicies[this.tenantId];\n }\n }\n\n async _updatePasswordPolicy(): Promise<void> {\n const response = await _getPasswordPolicy(this);\n\n const passwordPolicy: PasswordPolicyInternal = new PasswordPolicyImpl(\n response\n );\n\n if (this.tenantId === null) {\n this._projectPasswordPolicy = passwordPolicy;\n } else {\n this._tenantPasswordPolicies[this.tenantId] = passwordPolicy;\n }\n }\n\n _getPersistence(): string {\n return this.assertedPersistence.persistence.type;\n }\n\n _updateErrorMap(errorMap: AuthErrorMap): void {\n this._errorFactory = new ErrorFactory<AuthErrorCode, AuthErrorParams>(\n 'auth',\n 'Firebase',\n (errorMap as ErrorMapRetriever)()\n );\n }\n\n onAuthStateChanged(\n nextOrObserver: NextOrObserver<User>,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n return this.registerStateListener(\n this.authStateSubscription,\n nextOrObserver,\n error,\n completed\n );\n }\n\n beforeAuthStateChanged(\n callback: (user: User | null) => void | Promise<void>,\n onAbort?: () => void\n ): Unsubscribe {\n return this.beforeStateQueue.pushCallback(callback, onAbort);\n }\n\n onIdTokenChanged(\n nextOrObserver: NextOrObserver<User>,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n return this.registerStateListener(\n this.idTokenSubscription,\n nextOrObserver,\n error,\n completed\n );\n }\n\n authStateReady(): Promise<void> {\n return new Promise((resolve, reject) => {\n if (this.currentUser) {\n resolve();\n } else {\n const unsubscribe = this.onAuthStateChanged(() => {\n unsubscribe();\n resolve();\n }, reject);\n }\n });\n }\n\n /**\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\n */\n async revokeAccessToken(token: string): Promise<void> {\n if (this.currentUser) {\n const idToken = await this.currentUser.getIdToken();\n // Generalize this to accept other providers once supported.\n const request: RevokeTokenRequest = {\n providerId: 'apple.com',\n tokenType: TokenType.ACCESS_TOKEN,\n token,\n idToken\n };\n if (this.tenantId != null) {\n request.tenantId = this.tenantId;\n }\n await revokeToken(this, request);\n }\n }\n\n toJSON(): object {\n return {\n apiKey: this.config.apiKey,\n authDomain: this.config.authDomain,\n appName: this.name,\n currentUser: this._currentUser?.toJSON()\n };\n }\n\n async _setRedirectUser(\n user: UserInternal | null,\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise<void> {\n const redirectManager = await this.getOrInitRedirectPersistenceManager(\n popupRedirectResolver\n );\n return user === null\n ? redirectManager.removeCurrentUser()\n : redirectManager.setCurrentUser(user);\n }\n\n private async getOrInitRedirectPersistenceManager(\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise<PersistenceUserManager> {\n if (!this.redirectPersistenceManager) {\n const resolver: PopupRedirectResolverInternal | null =\n (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||\n this._popupRedirectResolver;\n _assert(resolver, this, AuthErrorCode.ARGUMENT_ERROR);\n this.redirectPersistenceManager = await PersistenceUserManager.create(\n this,\n [_getInstance(resolver._redirectPersistence)],\n KeyName.REDIRECT_USER\n );\n this.redirectUser =\n await this.redirectPersistenceManager.getCurrentUser();\n }\n\n return this.redirectPersistenceManager;\n }\n\n async _redirectUserForId(id: string): Promise<UserInternal | null> {\n // Make sure we've cleared any pending persistence actions if we're not in\n // the initializer\n if (this._isInitialized) {\n await this.queue(async () => {});\n }\n\n if (this._currentUser?._redirectEventId === id) {\n return this._currentUser;\n }\n\n if (this.redirectUser?._redirectEventId === id) {\n return this.redirectUser;\n }\n\n return null;\n }\n\n async _persistUserIfCurrent(user: UserInternal): Promise<void> {\n if (user === this.currentUser) {\n return this.queue(async () => this.directlySetCurrentUser(user));\n }\n }\n\n /** Notifies listeners only if the user is current */\n _notifyListenersIfCurrent(user: UserInternal): void {\n if (user === this.currentUser) {\n this.notifyAuthListeners();\n }\n }\n\n _key(): string {\n return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;\n }\n\n _startProactiveRefresh(): void {\n this.isProactiveRefreshEnabled = true;\n if (this.currentUser) {\n this._currentUser._startProactiveRefresh();\n }\n }\n\n _stopProactiveRefresh(): void {\n this.isProactiveRefreshEnabled = false;\n if (this.currentUser) {\n this._currentUser._stopProactiveRefresh();\n }\n }\n\n /** Returns the current user cast as the internal type */\n get _currentUser(): UserInternal {\n return this.currentUser as UserInternal;\n }\n\n private notifyAuthListeners(): void {\n if (!this._isInitialized) {\n return;\n }\n\n this.idTokenSubscription.next(this.currentUser);\n\n const currentUid = this.currentUser?.uid ?? null;\n if (this.lastNotifiedUid !== currentUid) {\n this.lastNotifiedUid = currentUid;\n this.authStateSubscription.next(this.currentUser);\n }\n }\n\n private registerStateListener(\n subscription: Subscription<User>,\n nextOrObserver: NextOrObserver<User>,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n if (this._deleted) {\n return () => {};\n }\n\n const cb =\n typeof nextOrObserver === 'function'\n ? nextOrObserver\n : nextOrObserver.next.bind(nextOrObserver);\n\n let isUnsubscribed = false;\n\n const promise = this._isInitialized\n ? Promise.resolve()\n : this._initializationPromise;\n _assert(promise, this, AuthErrorCode.INTERNAL_ERROR);\n // The callback needs to be called asynchronously per the spec.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n promise.then(() => {\n if (isUnsubscribed) {\n return;\n }\n cb(this.currentUser);\n });\n\n if (typeof nextOrObserver === 'function') {\n const unsubscribe = subscription.addObserver(\n nextOrObserver,\n error,\n completed\n );\n return () => {\n isUnsubscribed = true;\n unsubscribe();\n };\n } else {\n const unsubscribe = subscription.addObserver(nextOrObserver);\n return () => {\n isUnsubscribed = true;\n unsubscribe();\n };\n }\n }\n\n /**\n * Unprotected (from race conditions) method to set the current user. This\n * should only be called from within a queued callback. This is necessary\n * because the queue shouldn't rely on another queued callback.\n */\n private async directlySetCurrentUser(\n user: UserInternal | null\n ): Promise<void> {\n if (this.currentUser && this.currentUser !== user) {\n this._currentUser._stopProactiveRefresh();\n }\n if (user && this.isProactiveRefreshEnabled) {\n user._startProactiveRefresh();\n }\n\n this.currentUser = user;\n\n if (user) {\n await this.assertedPersistence.setCurrentUser(user);\n } else {\n await this.assertedPersistence.removeCurrentUser();\n }\n }\n\n private queue(action: AsyncAction): Promise<void> {\n // In case something errors, the callback still should be called in order\n // to keep the promise chain alive\n this.operations = this.operations.then(action, action);\n return this.operations;\n }\n\n private get assertedPersistence(): PersistenceUserManager {\n _assert(this.persistenceManager, this, AuthErrorCode.INTERNAL_ERROR);\n return this.persistenceManager;\n }\n\n private frameworks: string[] = [];\n private clientVersion: string;\n _logFramework(framework: string): void {\n if (!framework || this.frameworks.includes(framework)) {\n return;\n }\n this.frameworks.push(framework);\n\n // Sort alphabetically so that \"FirebaseCore-web,FirebaseUI-web\" and\n // \"FirebaseUI-web,FirebaseCore-web\" aren't viewed as different.\n this.frameworks.sort();\n this.clientVersion = _getClientVersion(\n this.config.clientPlatform,\n this._getFrameworks()\n );\n }\n _getFrameworks(): readonly string[] {\n return this.frameworks;\n }\n async _getAdditionalHeaders(): Promise<Record<string, string>> {\n // Additional headers on every request\n const headers: Record<string, string> = {\n [HttpHeader.X_CLIENT_VERSION]: this.clientVersion\n };\n\n if (this.app.options.appId) {\n headers[HttpHeader.X_FIREBASE_GMPID] = this.app.options.appId;\n }\n\n // If the heartbeat service exists, add the heartbeat string\n const heartbeatsHeader = await this.heartbeatServiceProvider\n .getImmediate({\n optional: true\n })\n ?.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers[HttpHeader.X_FIREBASE_CLIENT] = heartbeatsHeader;\n }\n\n // If the App Check service exists, add the App Check token in the headers\n const appCheckToken = await this._getAppCheckToken();\n if (appCheckToken) {\n headers[HttpHeader.X_FIREBASE_APP_CHECK] = appCheckToken;\n }\n\n return headers;\n }\n\n async _getAppCheckToken(): Promise<string | undefined> {\n const appCheckTokenResult = await this.appCheckServiceProvider\n .getImmediate({ optional: true })\n ?.getToken();\n if (appCheckTokenResult?.error) {\n // Context: appCheck.getToken() will never throw even if an error happened.\n // In the error case, a dummy token will be returned along with an error field describing\n // the error. In general, we shouldn't care about the error condition and just use\n // the token (actual or dummy) to send requests.\n _logWarn(\n `Error while retrieving App Check token: ${appCheckTokenResult.error}`\n );\n }\n return appCheckTokenResult?.token;\n }\n}\n\n/**\n * Method to be used to cast down to our private implmentation of Auth.\n * It will also handle unwrapping from the compat type if necessary\n *\n * @param auth Auth object passed in from developer\n */\nexport function _castAuth(auth: Auth): AuthInternal {\n return getModularInstance(auth) as AuthInternal;\n}\n\n/** Helper class to wrap subscriber logic */\nclass Subscription<T> {\n private observer: Observer<T | null> | null = null;\n readonly addObserver: Subscribe<T | null> = createSubscribe(\n observer => (this.observer = observer)\n );\n\n constructor(readonly auth: AuthInternal) {}\n\n get next(): NextFn<T | null> {\n _assert(this.observer, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return this.observer.next.bind(this.observer);\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _performApiRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\n/**\n * Request object for fetching the password policy.\n */\nexport interface GetPasswordPolicyRequest {\n tenantId?: string;\n}\n\n/**\n * Response object for fetching the password policy.\n */\nexport interface GetPasswordPolicyResponse {\n customStrengthOptions: {\n minPasswordLength?: number;\n maxPasswordLength?: number;\n containsLowercaseCharacter?: boolean;\n containsUppercaseCharacter?: boolean;\n containsNumericCharacter?: boolean;\n containsNonAlphanumericCharacter?: boolean;\n };\n allowedNonAlphanumericCharacters?: string[];\n enforcementState: string;\n forceUpgradeOnSignin?: boolean;\n schemaVersion: number;\n}\n\n/**\n * Fetches the password policy for the currently set tenant or the project if no tenant is set.\n *\n * @param auth Auth object.\n * @param request Password policy request.\n * @returns Password policy response.\n */\nexport async function _getPasswordPolicy(\n auth: Auth,\n request: GetPasswordPolicyRequest = {}\n): Promise<GetPasswordPolicyResponse> {\n return _performApiRequest<\n GetPasswordPolicyRequest,\n GetPasswordPolicyResponse\n >(\n auth,\n HttpMethod.GET,\n Endpoint.GET_PASSWORD_POLICY,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../core/errors';\nimport { _createError } from '../core/util/assert';\n\nfunction getScriptParentElement(): HTMLDocument | HTMLHeadElement {\n return document.getElementsByTagName('head')?.[0] ?? document;\n}\n\nexport function _loadJS(url: string): Promise<Event> {\n // TODO: consider adding timeout support & cancellation\n return new Promise((resolve, reject) => {\n const el = document.createElement('script');\n el.setAttribute('src', url);\n el.onload = resolve;\n el.onerror = e => {\n const error = _createError(AuthErrorCode.INTERNAL_ERROR);\n error.customData = e as unknown as Record<string, unknown>;\n reject(error);\n };\n el.type = 'text/javascript';\n el.charset = 'UTF-8';\n getScriptParentElement().appendChild(el);\n });\n}\n\nexport function _generateCallbackName(prefix: string): string {\n return `__${prefix}${Math.floor(Math.random() * 1000000)}`;\n}\n","/* eslint-disable @typescript-eslint/no-require-imports */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isEnterprise, RecaptchaConfig } from './recaptcha';\nimport { getRecaptchaConfig } from '../../api/authentication/recaptcha';\nimport {\n RecaptchaClientType,\n RecaptchaVersion,\n RecaptchaActionName,\n RecaptchaProvider\n} from '../../api';\n\nimport { Auth } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport * as jsHelpers from '../load_js';\nimport { AuthErrorCode } from '../../core/errors';\n\nconst RECAPTCHA_ENTERPRISE_URL =\n 'https://www.google.com/recaptcha/enterprise.js?render=';\n\nexport const RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = 'recaptcha-enterprise';\nexport const FAKE_TOKEN = 'NO_RECAPTCHA';\n\nexport class RecaptchaEnterpriseVerifier {\n /**\n * Identifies the type of application verifier (e.g. \"recaptcha-enterprise\").\n */\n readonly type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;\n\n private readonly auth: AuthInternal;\n\n /**\n *\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\n *\n */\n constructor(authExtern: Auth) {\n this.auth = _castAuth(authExtern);\n }\n\n /**\n * Executes the verification process.\n *\n * @returns A Promise for a token that can be used to assert the validity of a request.\n */\n async verify(\n action: string = 'verify',\n forceRefresh = false\n ): Promise<string> {\n async function retrieveSiteKey(auth: AuthInternal): Promise<string> {\n if (!forceRefresh) {\n if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {\n return auth._agentRecaptchaConfig.siteKey;\n }\n if (\n auth.tenantId != null &&\n auth._tenantRecaptchaConfigs[auth.tenantId] !== undefined\n ) {\n return auth._tenantRecaptchaConfigs[auth.tenantId].siteKey;\n }\n }\n\n return new Promise<string>(async (resolve, reject) => {\n getRecaptchaConfig(auth, {\n clientType: RecaptchaClientType.WEB,\n version: RecaptchaVersion.ENTERPRISE\n })\n .then(response => {\n if (response.recaptchaKey === undefined) {\n reject(new Error('recaptcha Enterprise site key undefined'));\n } else {\n const config = new RecaptchaConfig(response);\n if (auth.tenantId == null) {\n auth._agentRecaptchaConfig = config;\n } else {\n auth._tenantRecaptchaConfigs[auth.tenantId] = config;\n }\n return resolve(config.siteKey);\n }\n })\n .catch(error => {\n reject(error);\n });\n });\n }\n\n function retrieveRecaptchaToken(\n siteKey: string,\n resolve: (value: string | PromiseLike<string>) => void,\n reject: (reason?: unknown) => void\n ): void {\n const grecaptcha = window.grecaptcha;\n if (isEnterprise(grecaptcha)) {\n grecaptcha.enterprise.ready(() => {\n grecaptcha.enterprise\n .execute(siteKey, { action })\n .then(token => {\n resolve(token);\n })\n .catch(() => {\n resolve(FAKE_TOKEN);\n });\n });\n } else {\n reject(Error('No reCAPTCHA enterprise script loaded.'));\n }\n }\n\n return new Promise<string>((resolve, reject) => {\n retrieveSiteKey(this.auth)\n .then(siteKey => {\n if (!forceRefresh && isEnterprise(window.grecaptcha)) {\n retrieveRecaptchaToken(siteKey, resolve, reject);\n } else {\n if (typeof window === 'undefined') {\n reject(\n new Error('RecaptchaVerifier is only supported in browser')\n );\n return;\n }\n jsHelpers\n ._loadJS(RECAPTCHA_ENTERPRISE_URL + siteKey)\n .then(() => {\n retrieveRecaptchaToken(siteKey, resolve, reject);\n })\n .catch(error => {\n reject(error);\n });\n }\n })\n .catch(error => {\n reject(error);\n });\n });\n }\n}\n\nexport async function injectRecaptchaFields<T>(\n auth: AuthInternal,\n request: T,\n action: RecaptchaActionName,\n captchaResp = false\n): Promise<T> {\n const verifier = new RecaptchaEnterpriseVerifier(auth);\n let captchaResponse;\n try {\n captchaResponse = await verifier.verify(action);\n } catch (error) {\n captchaResponse = await verifier.verify(action, true);\n }\n const newRequest = { ...request };\n if (!captchaResp) {\n Object.assign(newRequest, { captchaResponse });\n } else {\n Object.assign(newRequest, { 'captchaResp': captchaResponse });\n }\n Object.assign(newRequest, { 'clientType': RecaptchaClientType.WEB });\n Object.assign(newRequest, {\n 'recaptchaVersion': RecaptchaVersion.ENTERPRISE\n });\n return newRequest;\n}\n\ntype ActionMethod<TRequest, TResponse> = (\n auth: Auth,\n request: TRequest\n) => Promise<TResponse>;\n\nexport async function handleRecaptchaFlow<TRequest, TResponse>(\n authInstance: AuthInternal,\n request: TRequest,\n actionName: RecaptchaActionName,\n actionMethod: ActionMethod<TRequest, TResponse>\n): Promise<TResponse> {\n if (\n authInstance\n ._getRecaptchaConfig()\n ?.isProviderEnabled(RecaptchaProvider.EMAIL_PASSWORD_PROVIDER)\n ) {\n const requestWithRecaptcha = await injectRecaptchaFields(\n authInstance,\n request,\n actionName,\n actionName === RecaptchaActionName.GET_OOB_CODE\n );\n return actionMethod(authInstance, requestWithRecaptcha);\n } else {\n return actionMethod(authInstance, request).catch(async error => {\n if (error.code === `auth/${AuthErrorCode.MISSING_RECAPTCHA_TOKEN}`) {\n console.log(\n `${actionName} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`\n );\n const requestWithRecaptcha = await injectRecaptchaFields(\n authInstance,\n request,\n actionName,\n actionName === RecaptchaActionName.GET_OOB_CODE\n );\n return actionMethod(authInstance, requestWithRecaptcha);\n } else {\n return Promise.reject(error);\n }\n });\n }\n}\n\nexport async function _initializeRecaptchaConfig(auth: Auth): Promise<void> {\n const authInternal = _castAuth(auth);\n\n const response = await getRecaptchaConfig(authInternal, {\n clientType: RecaptchaClientType.WEB,\n version: RecaptchaVersion.ENTERPRISE\n });\n\n const config = new RecaptchaConfig(response);\n if (authInternal.tenantId == null) {\n authInternal._agentRecaptchaConfig = config;\n } else {\n authInternal._tenantRecaptchaConfigs[authInternal.tenantId] = config;\n }\n\n if (config.isProviderEnabled(RecaptchaProvider.EMAIL_PASSWORD_PROVIDER)) {\n const verifier = new RecaptchaEnterpriseVerifier(authInternal);\n void verifier.verify();\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Auth } from '../../model/public_types';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _castAuth } from './auth_impl';\n\n/**\n * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production\n * Firebase Auth services.\n *\n * @remarks\n * This must be called synchronously immediately following the first call to\n * {@link initializeAuth}. Do not use with production credentials as emulator\n * traffic is not encrypted.\n *\n *\n * @example\n * ```javascript\n * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').\n * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to\n * `true` to disable the warning banner attached to the DOM.\n *\n * @public\n */\nexport function connectAuthEmulator(\n auth: Auth,\n url: string,\n options?: { disableWarnings: boolean }\n): void {\n const authInternal = _castAuth(auth);\n _assert(\n authInternal._canInitEmulator,\n authInternal,\n AuthErrorCode.EMULATOR_CONFIG_FAILED\n );\n\n _assert(\n /^https?:\\/\\//.test(url),\n authInternal,\n AuthErrorCode.INVALID_EMULATOR_SCHEME\n );\n\n const disableWarnings = !!options?.disableWarnings;\n\n const protocol = extractProtocol(url);\n const { host, port } = extractHostAndPort(url);\n const portStr = port === null ? '' : `:${port}`;\n\n // Always replace path with \"/\" (even if input url had no path at all, or had a different one).\n authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };\n authInternal.settings.appVerificationDisabledForTesting = true;\n authInternal.emulatorConfig = Object.freeze({\n host,\n port,\n protocol: protocol.replace(':', ''),\n options: Object.freeze({ disableWarnings })\n });\n\n if (!disableWarnings) {\n emitEmulatorWarning();\n }\n}\n\nfunction extractProtocol(url: string): string {\n const protocolEnd = url.indexOf(':');\n return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);\n}\n\nfunction extractHostAndPort(url: string): {\n host: string;\n port: number | null;\n} {\n const protocol = extractProtocol(url);\n const authority = /(\\/\\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.\n if (!authority) {\n return { host: '', port: null };\n }\n const hostAndPort = authority[2].split('@').pop() || ''; // Strip out \"username:password@\".\n const bracketedIPv6 = /^(\\[[^\\]]+\\])(:|$)/.exec(hostAndPort);\n if (bracketedIPv6) {\n const host = bracketedIPv6[1];\n return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };\n } else {\n const [host, port] = hostAndPort.split(':');\n return { host, port: parsePort(port) };\n }\n}\n\nfunction parsePort(portStr: string): number | null {\n if (!portStr) {\n return null;\n }\n const port = Number(portStr);\n if (isNaN(port)) {\n return null;\n }\n return port;\n}\n\nfunction emitEmulatorWarning(): void {\n function attachBanner(): void {\n const el = document.createElement('p');\n const sty = el.style;\n el.innerText =\n 'Running in emulator mode. Do not use with production credentials.';\n sty.position = 'fixed';\n sty.width = '100%';\n sty.backgroundColor = '#ffffff';\n sty.border = '.1em solid #000000';\n sty.color = '#b50000';\n sty.bottom = '0px';\n sty.left = '0px';\n sty.margin = '0px';\n sty.zIndex = '10000';\n sty.textAlign = 'center';\n el.classList.add('firebase-emulator-warning');\n document.body.appendChild(el);\n }\n\n if (typeof console !== 'undefined' && typeof console.info === 'function') {\n console.info(\n 'WARNING: You are using the Auth Emulator,' +\n ' which is intended for local testing only. Do not use with' +\n ' production credentials.'\n );\n }\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n if (document.readyState === 'loading') {\n window.addEventListener('DOMContentLoaded', attachBanner);\n } else {\n attachBanner();\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { debugFail } from '../util/assert';\n\n/**\n * Interface that represents the credentials returned by an {@link AuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nexport class AuthCredential {\n /** @internal */\n protected constructor(\n /**\n * The authentication provider ID for the credential.\n *\n * @remarks\n * For example, 'facebook.com', or 'google.com'.\n */\n readonly providerId: string,\n /**\n * The authentication sign in method for the credential.\n *\n * @remarks\n * For example, {@link SignInMethod}.EMAIL_PASSWORD, or\n * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method\n * identifier as returned in {@link fetchSignInMethodsForEmail}.\n */\n readonly signInMethod: string\n ) {}\n\n /**\n * Returns a JSON-serializable representation of this object.\n *\n * @returns a JSON-serializable representation of this object.\n */\n toJSON(): object {\n return debugFail('not implemented');\n }\n\n /** @internal */\n _getIdTokenResponse(_auth: AuthInternal): Promise<PhoneOrOauthTokenResponse> {\n return debugFail('not implemented');\n }\n /** @internal */\n _linkToIdToken(\n _auth: AuthInternal,\n _idToken: string\n ): Promise<IdTokenResponse> {\n return debugFail('not implemented');\n }\n /** @internal */\n _getReauthenticationResolver(_auth: AuthInternal): Promise<IdTokenResponse> {\n return debugFail('not implemented');\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActionCodeOperation, Auth } from '../../model/public_types';\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { MfaEnrollment } from './mfa';\nimport { SignUpRequest, SignUpResponse } from '../authentication/sign_up';\n\nexport interface ResetPasswordRequest {\n oobCode: string;\n newPassword?: string;\n tenantId?: string;\n}\n\nexport interface ResetPasswordResponse {\n email: string;\n newEmail?: string;\n requestType?: ActionCodeOperation;\n mfaInfo?: MfaEnrollment;\n}\n\nexport async function resetPassword(\n auth: Auth,\n request: ResetPasswordRequest\n): Promise<ResetPasswordResponse> {\n return _performApiRequest<ResetPasswordRequest, ResetPasswordResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.RESET_PASSWORD,\n _addTidIfNecessary(auth, request)\n );\n}\nexport interface UpdateEmailPasswordRequest {\n idToken: string;\n returnSecureToken?: boolean;\n email?: string;\n password?: string;\n}\n\nexport interface UpdateEmailPasswordResponse extends IdTokenResponse {}\n\nexport async function updateEmailPassword(\n auth: Auth,\n request: UpdateEmailPasswordRequest\n): Promise<UpdateEmailPasswordResponse> {\n return _performApiRequest<\n UpdateEmailPasswordRequest,\n UpdateEmailPasswordResponse\n >(auth, HttpMethod.POST, Endpoint.SET_ACCOUNT_INFO, request);\n}\n\n// Used for linking an email/password account to an existing idToken. Uses the same request/response\n// format as updateEmailPassword.\nexport async function linkEmailPassword(\n auth: Auth,\n request: SignUpRequest\n): Promise<SignUpResponse> {\n return _performApiRequest<SignUpRequest, SignUpResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_UP,\n request\n );\n}\n\nexport interface ApplyActionCodeRequest {\n oobCode: string;\n tenantId?: string;\n}\n\nexport interface ApplyActionCodeResponse {}\n\nexport async function applyActionCode(\n auth: Auth,\n request: ApplyActionCodeRequest\n): Promise<ApplyActionCodeResponse> {\n return _performApiRequest<ApplyActionCodeRequest, ApplyActionCodeResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SET_ACCOUNT_INFO,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActionCodeOperation, Auth } from '../../model/public_types';\n\nimport {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _addTidIfNecessary,\n _performApiRequest,\n _performSignInRequest\n} from '../index';\nimport { IdToken, IdTokenResponse } from '../../model/id_token';\n\nexport interface SignInWithPasswordRequest {\n returnSecureToken?: boolean;\n email: string;\n password: string;\n tenantId?: string;\n captchaResponse?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface SignInWithPasswordResponse extends IdTokenResponse {\n email: string;\n displayName: string;\n}\n\nexport async function signInWithPassword(\n auth: Auth,\n request: SignInWithPasswordRequest\n): Promise<SignInWithPasswordResponse> {\n return _performSignInRequest<\n SignInWithPasswordRequest,\n SignInWithPasswordResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PASSWORD,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface GetOobCodeRequest {\n email?: string; // Everything except VERIFY_AND_CHANGE_EMAIL\n continueUrl?: string;\n iOSBundleId?: string;\n iosAppStoreId?: string;\n androidPackageName?: string;\n androidInstallApp?: boolean;\n androidMinimumVersionCode?: string;\n canHandleCodeInApp?: boolean;\n dynamicLinkDomain?: string;\n tenantId?: string;\n targetProjectid?: string;\n}\n\nexport interface VerifyEmailRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.VERIFY_EMAIL;\n idToken: IdToken;\n}\n\nexport interface PasswordResetRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.PASSWORD_RESET;\n email: string;\n captchaResp?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface EmailSignInRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.EMAIL_SIGNIN;\n email: string;\n captchaResp?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface VerifyAndChangeEmailRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL;\n idToken: IdToken;\n newEmail: string;\n}\n\ninterface GetOobCodeResponse {\n email: string;\n}\n\nexport interface VerifyEmailResponse extends GetOobCodeResponse {}\nexport interface PasswordResetResponse extends GetOobCodeResponse {}\nexport interface EmailSignInResponse extends GetOobCodeResponse {}\nexport interface VerifyAndChangeEmailResponse extends GetOobCodeRequest {}\n\nasync function sendOobCode(\n auth: Auth,\n request: GetOobCodeRequest\n): Promise<GetOobCodeResponse> {\n return _performApiRequest<GetOobCodeRequest, GetOobCodeResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SEND_OOB_CODE,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport async function sendEmailVerification(\n auth: Auth,\n request: VerifyEmailRequest\n): Promise<VerifyEmailResponse> {\n return sendOobCode(auth, request);\n}\n\nexport async function sendPasswordResetEmail(\n auth: Auth,\n request: PasswordResetRequest\n): Promise<PasswordResetResponse> {\n return sendOobCode(auth, request);\n}\n\nexport async function sendSignInLinkToEmail(\n auth: Auth,\n request: EmailSignInRequest\n): Promise<EmailSignInResponse> {\n return sendOobCode(auth, request);\n}\n\nexport async function verifyAndChangeEmail(\n auth: Auth,\n request: VerifyAndChangeEmailRequest\n): Promise<VerifyAndChangeEmailResponse> {\n return sendOobCode(auth, request);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\nimport { linkEmailPassword } from '../../api/account_management/email_and_password';\nimport {\n signInWithPassword,\n SignInWithPasswordRequest\n} from '../../api/authentication/email_and_password';\nimport {\n signInWithEmailLink,\n signInWithEmailLinkForLinking\n} from '../../api/authentication/email_link';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from '../util/assert';\nimport { AuthCredential } from './auth_credential';\nimport { handleRecaptchaFlow } from '../../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { RecaptchaActionName, RecaptchaClientType } from '../../api';\nimport { SignUpRequest } from '../../api/authentication/sign_up';\n/**\n * Interface that represents the credentials returned by {@link EmailAuthProvider} for\n * {@link ProviderId}.PASSWORD\n *\n * @remarks\n * Covers both {@link SignInMethod}.EMAIL_PASSWORD and\n * {@link SignInMethod}.EMAIL_LINK.\n *\n * @public\n */\nexport class EmailAuthCredential extends AuthCredential {\n /** @internal */\n private constructor(\n /** @internal */\n readonly _email: string,\n /** @internal */\n readonly _password: string,\n signInMethod: SignInMethod,\n /** @internal */\n readonly _tenantId: string | null = null\n ) {\n super(ProviderId.PASSWORD, signInMethod);\n }\n\n /** @internal */\n static _fromEmailAndPassword(\n email: string,\n password: string\n ): EmailAuthCredential {\n return new EmailAuthCredential(\n email,\n password,\n SignInMethod.EMAIL_PASSWORD\n );\n }\n\n /** @internal */\n static _fromEmailAndCode(\n email: string,\n oobCode: string,\n tenantId: string | null = null\n ): EmailAuthCredential {\n return new EmailAuthCredential(\n email,\n oobCode,\n SignInMethod.EMAIL_LINK,\n tenantId\n );\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n email: this._email,\n password: this._password,\n signInMethod: this.signInMethod,\n tenantId: this._tenantId\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.\n *\n * @param json - Either `object` or the stringified representation of the object. When string is\n * provided, `JSON.parse` would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: object | string): EmailAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n if (obj?.email && obj?.password) {\n if (obj.signInMethod === SignInMethod.EMAIL_PASSWORD) {\n return this._fromEmailAndPassword(obj.email, obj.password);\n } else if (obj.signInMethod === SignInMethod.EMAIL_LINK) {\n return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);\n }\n }\n return null;\n }\n\n /** @internal */\n async _getIdTokenResponse(auth: AuthInternal): Promise<IdTokenResponse> {\n switch (this.signInMethod) {\n case SignInMethod.EMAIL_PASSWORD:\n const request: SignInWithPasswordRequest = {\n returnSecureToken: true,\n email: this._email,\n password: this._password,\n clientType: RecaptchaClientType.WEB\n };\n return handleRecaptchaFlow(\n auth,\n request,\n RecaptchaActionName.SIGN_IN_WITH_PASSWORD,\n signInWithPassword\n );\n case SignInMethod.EMAIL_LINK:\n return signInWithEmailLink(auth, {\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n /** @internal */\n async _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n switch (this.signInMethod) {\n case SignInMethod.EMAIL_PASSWORD:\n const request: SignUpRequest = {\n idToken,\n returnSecureToken: true,\n email: this._email,\n password: this._password,\n clientType: RecaptchaClientType.WEB\n };\n return handleRecaptchaFlow(\n auth,\n request,\n RecaptchaActionName.SIGN_UP_PASSWORD,\n linkEmailPassword\n );\n case SignInMethod.EMAIL_LINK:\n return signInWithEmailLinkForLinking(auth, {\n idToken,\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n return this._getIdTokenResponse(auth);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _performSignInRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithEmailLinkRequest {\n email: string;\n oobCode: string;\n tenantId?: string;\n}\n\nexport interface SignInWithEmailLinkResponse extends IdTokenResponse {\n email: string;\n isNewUser: boolean;\n}\n\nexport async function signInWithEmailLink(\n auth: Auth,\n request: SignInWithEmailLinkRequest\n): Promise<SignInWithEmailLinkResponse> {\n return _performSignInRequest<\n SignInWithEmailLinkRequest,\n SignInWithEmailLinkResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_EMAIL_LINK,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface SignInWithEmailLinkForLinkingRequest\n extends SignInWithEmailLinkRequest {\n idToken: string;\n}\n\nexport async function signInWithEmailLinkForLinking(\n auth: Auth,\n request: SignInWithEmailLinkForLinkingRequest\n): Promise<SignInWithEmailLinkResponse> {\n return _performSignInRequest<\n SignInWithEmailLinkForLinkingRequest,\n SignInWithEmailLinkResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_EMAIL_LINK,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdToken, IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithIdpRequest {\n requestUri: string;\n postBody?: string;\n sessionId?: string;\n tenantId?: string;\n returnSecureToken: boolean;\n returnIdpCredential?: boolean;\n idToken?: IdToken;\n autoCreate?: boolean;\n pendingToken?: string;\n}\n\n/**\n * @internal\n */\nexport interface SignInWithIdpResponse extends IdTokenResponse {\n oauthAccessToken?: string;\n oauthTokenSecret?: string;\n nonce?: string;\n oauthIdToken?: string;\n pendingToken?: string;\n}\n\nexport async function signInWithIdp(\n auth: Auth,\n request: SignInWithIdpRequest\n): Promise<SignInWithIdpResponse> {\n return _performSignInRequest<SignInWithIdpRequest, SignInWithIdpResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_IDP,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { querystring } from '@firebase/util';\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from '../util/assert';\nimport { AuthCredential } from './auth_credential';\n\nconst IDP_REQUEST_URI = 'http://localhost';\n\nexport interface OAuthCredentialParams {\n // OAuth 2 uses either id token or access token\n idToken?: string | null;\n accessToken?: string | null;\n\n // These fields are used with OAuth 1\n oauthToken?: string;\n secret?: string;\n oauthTokenSecret?: string;\n\n // Nonce is only set if pendingToken is not present\n nonce?: string;\n pendingToken?: string;\n\n // Utilities\n providerId: string;\n signInMethod: string;\n}\n\n/**\n * Represents the OAuth credentials returned by an {@link OAuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nexport class OAuthCredential extends AuthCredential {\n /**\n * The OAuth ID token associated with the credential if it belongs to an OIDC provider,\n * such as `google.com`.\n * @readonly\n */\n idToken?: string;\n /**\n * The OAuth access token associated with the credential if it belongs to an\n * {@link OAuthProvider}, such as `facebook.com`, `twitter.com`, etc.\n * @readonly\n */\n accessToken?: string;\n /**\n * The OAuth access token secret associated with the credential if it belongs to an OAuth 1.0\n * provider, such as `twitter.com`.\n * @readonly\n */\n secret?: string;\n\n private nonce?: string;\n private pendingToken: string | null = null;\n\n /** @internal */\n static _fromParams(params: OAuthCredentialParams): OAuthCredential {\n const cred = new OAuthCredential(params.providerId, params.signInMethod);\n\n if (params.idToken || params.accessToken) {\n // OAuth 2 and either ID token or access token.\n if (params.idToken) {\n cred.idToken = params.idToken;\n }\n\n if (params.accessToken) {\n cred.accessToken = params.accessToken;\n }\n\n // Add nonce if available and no pendingToken is present.\n if (params.nonce && !params.pendingToken) {\n cred.nonce = params.nonce;\n }\n\n if (params.pendingToken) {\n cred.pendingToken = params.pendingToken;\n }\n } else if (params.oauthToken && params.oauthTokenSecret) {\n // OAuth 1 and OAuth token with token secret\n cred.accessToken = params.oauthToken;\n cred.secret = params.oauthTokenSecret;\n } else {\n _fail(AuthErrorCode.ARGUMENT_ERROR);\n }\n\n return cred;\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n idToken: this.idToken,\n accessToken: this.accessToken,\n secret: this.secret,\n nonce: this.nonce,\n pendingToken: this.pendingToken,\n providerId: this.providerId,\n signInMethod: this.signInMethod\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an\n * {@link AuthCredential}.\n *\n * @param json - Input can be either Object or the stringified representation of the object.\n * When string is provided, JSON.parse would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: string | object): OAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n const { providerId, signInMethod, ...rest }: OAuthCredentialParams = obj;\n if (!providerId || !signInMethod) {\n return null;\n }\n\n const cred = new OAuthCredential(providerId, signInMethod);\n cred.idToken = rest.idToken || undefined;\n cred.accessToken = rest.accessToken || undefined;\n cred.secret = rest.secret;\n cred.nonce = rest.nonce;\n cred.pendingToken = rest.pendingToken || null;\n return cred;\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n request.idToken = idToken;\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n request.autoCreate = false;\n return signInWithIdp(auth, request);\n }\n\n private buildRequest(): SignInWithIdpRequest {\n const request: SignInWithIdpRequest = {\n requestUri: IDP_REQUEST_URI,\n returnSecureToken: true\n };\n\n if (this.pendingToken) {\n request.pendingToken = this.pendingToken;\n } else {\n const postBody: Record<string, string> = {};\n if (this.idToken) {\n postBody['id_token'] = this.idToken;\n }\n if (this.accessToken) {\n postBody['access_token'] = this.accessToken;\n }\n if (this.secret) {\n postBody['oauth_token_secret'] = this.secret;\n }\n\n postBody['providerId'] = this.providerId;\n if (this.nonce && !this.pendingToken) {\n postBody['nonce'] = this.nonce;\n }\n\n request.postBody = querystring(postBody);\n }\n\n return request;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _makeTaggedError,\n _performApiRequest,\n _performSignInRequest\n} from '../index';\nimport { AuthErrorCode } from '../../core/errors';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { ServerError, ServerErrorMap } from '../errors';\nimport { Auth } from '../../model/public_types';\n\nexport interface SendPhoneVerificationCodeRequest {\n phoneNumber: string;\n recaptchaToken: string;\n tenantId?: string;\n}\n\nexport interface SendPhoneVerificationCodeResponse {\n sessionInfo: string;\n}\n\nexport async function sendPhoneVerificationCode(\n auth: Auth,\n request: SendPhoneVerificationCodeRequest\n): Promise<SendPhoneVerificationCodeResponse> {\n return _performApiRequest<\n SendPhoneVerificationCodeRequest,\n SendPhoneVerificationCodeResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SEND_VERIFICATION_CODE,\n _addTidIfNecessary(auth, request)\n );\n}\n\n/**\n * @internal\n */\nexport interface SignInWithPhoneNumberRequest {\n temporaryProof?: string;\n phoneNumber?: string;\n sessionInfo?: string;\n code?: string;\n tenantId?: string;\n}\n\nexport interface LinkWithPhoneNumberRequest\n extends SignInWithPhoneNumberRequest {\n idToken: string;\n}\n\n/**\n * @internal\n */\nexport interface SignInWithPhoneNumberResponse extends IdTokenResponse {\n temporaryProof?: string;\n phoneNumber?: string;\n}\n\nexport async function signInWithPhoneNumber(\n auth: Auth,\n request: SignInWithPhoneNumberRequest\n): Promise<SignInWithPhoneNumberResponse> {\n return _performSignInRequest<\n SignInWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport async function linkWithPhoneNumber(\n auth: Auth,\n request: LinkWithPhoneNumberRequest\n): Promise<SignInWithPhoneNumberResponse> {\n const response = await _performSignInRequest<\n LinkWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, request)\n );\n if (response.temporaryProof) {\n throw _makeTaggedError(auth, AuthErrorCode.NEED_CONFIRMATION, response);\n }\n return response;\n}\n\ninterface VerifyPhoneNumberForExistingRequest\n extends SignInWithPhoneNumberRequest {\n operation: 'REAUTH';\n}\n\nconst VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_: Partial<\n ServerErrorMap<ServerError>\n> = {\n [ServerError.USER_NOT_FOUND]: AuthErrorCode.USER_DELETED\n};\n\nexport async function verifyPhoneNumberForExisting(\n auth: Auth,\n request: SignInWithPhoneNumberRequest\n): Promise<SignInWithPhoneNumberResponse> {\n const apiRequest: VerifyPhoneNumberForExistingRequest = {\n ...request,\n operation: 'REAUTH'\n };\n return _performSignInRequest<\n VerifyPhoneNumberForExistingRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, apiRequest),\n VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport {\n linkWithPhoneNumber,\n signInWithPhoneNumber,\n SignInWithPhoneNumberRequest,\n verifyPhoneNumberForExisting\n} from '../../api/authentication/sms';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthCredential } from './auth_credential';\n\nexport interface PhoneAuthCredentialParameters {\n verificationId?: string;\n verificationCode?: string;\n phoneNumber?: string;\n temporaryProof?: string;\n}\n\n/**\n * Represents the credentials returned by {@link PhoneAuthProvider}.\n *\n * @public\n */\nexport class PhoneAuthCredential extends AuthCredential {\n private constructor(private readonly params: PhoneAuthCredentialParameters) {\n super(ProviderId.PHONE, SignInMethod.PHONE);\n }\n\n /** @internal */\n static _fromVerification(\n verificationId: string,\n verificationCode: string\n ): PhoneAuthCredential {\n return new PhoneAuthCredential({ verificationId, verificationCode });\n }\n\n /** @internal */\n static _fromTokenResponse(\n phoneNumber: string,\n temporaryProof: string\n ): PhoneAuthCredential {\n return new PhoneAuthCredential({ phoneNumber, temporaryProof });\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise<PhoneOrOauthTokenResponse> {\n return signInWithPhoneNumber(auth, this._makeVerificationRequest());\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n return linkWithPhoneNumber(auth, {\n idToken,\n ...this._makeVerificationRequest()\n });\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());\n }\n\n /** @internal */\n _makeVerificationRequest(): SignInWithPhoneNumberRequest {\n const { temporaryProof, phoneNumber, verificationId, verificationCode } =\n this.params;\n if (temporaryProof && phoneNumber) {\n return { temporaryProof, phoneNumber };\n }\n\n return {\n sessionInfo: verificationId,\n code: verificationCode\n };\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n const obj: Record<string, string> = {\n providerId: this.providerId\n };\n if (this.params.phoneNumber) {\n obj.phoneNumber = this.params.phoneNumber;\n }\n if (this.params.temporaryProof) {\n obj.temporaryProof = this.params.temporaryProof;\n }\n if (this.params.verificationCode) {\n obj.verificationCode = this.params.verificationCode;\n }\n if (this.params.verificationId) {\n obj.verificationId = this.params.verificationId;\n }\n\n return obj;\n }\n\n /** Generates a phone credential based on a plain object or a JSON string. */\n static fromJSON(json: object | string): PhoneAuthCredential | null {\n if (typeof json === 'string') {\n json = JSON.parse(json);\n }\n\n const { verificationId, verificationCode, phoneNumber, temporaryProof } =\n json as { [key: string]: string };\n if (\n !verificationCode &&\n !verificationId &&\n !phoneNumber &&\n !temporaryProof\n ) {\n return null;\n }\n\n return new PhoneAuthCredential({\n verificationId,\n verificationCode,\n phoneNumber,\n temporaryProof\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { extractQuerystring, querystringDecode } from '@firebase/util';\nimport { ActionCodeOperation } from '../model/public_types';\nimport { AuthErrorCode } from './errors';\nimport { _assert } from './util/assert';\n\n/**\n * Enums for fields in URL query string.\n *\n * @enum {string}\n */\nconst enum QueryField {\n API_KEY = 'apiKey',\n CODE = 'oobCode',\n CONTINUE_URL = 'continueUrl',\n LANGUAGE_CODE = 'languageCode',\n MODE = 'mode',\n TENANT_ID = 'tenantId'\n}\n\n/**\n * Maps the mode string in action code URL to Action Code Info operation.\n *\n * @param mode\n */\nfunction parseMode(mode: string | null): ActionCodeOperation | null {\n switch (mode) {\n case 'recoverEmail':\n return ActionCodeOperation.RECOVER_EMAIL;\n case 'resetPassword':\n return ActionCodeOperation.PASSWORD_RESET;\n case 'signIn':\n return ActionCodeOperation.EMAIL_SIGNIN;\n case 'verifyEmail':\n return ActionCodeOperation.VERIFY_EMAIL;\n case 'verifyAndChangeEmail':\n return ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL;\n case 'revertSecondFactorAddition':\n return ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION;\n default:\n return null;\n }\n}\n\n/**\n * Helper to parse FDL links\n *\n * @param url\n */\nfunction parseDeepLink(url: string): string {\n const link = querystringDecode(extractQuerystring(url))['link'];\n\n // Double link case (automatic redirect).\n const doubleDeepLink = link\n ? querystringDecode(extractQuerystring(link))['deep_link_id']\n : null;\n // iOS custom scheme links.\n const iOSDeepLink = querystringDecode(extractQuerystring(url))[\n 'deep_link_id'\n ];\n const iOSDoubleDeepLink = iOSDeepLink\n ? querystringDecode(extractQuerystring(iOSDeepLink))['link']\n : null;\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\n}\n\n/**\n * A utility class to parse email action URLs such as password reset, email verification,\n * email link sign in, etc.\n *\n * @public\n */\nexport class ActionCodeURL {\n /**\n * The API key of the email action link.\n */\n readonly apiKey: string;\n /**\n * The action code of the email action link.\n */\n readonly code: string;\n /**\n * The continue URL of the email action link. Null if not provided.\n */\n readonly continueUrl: string | null;\n /**\n * The language code of the email action link. Null if not provided.\n */\n readonly languageCode: string | null;\n /**\n * The action performed by the email action link. It returns from one of the types from\n * {@link ActionCodeInfo}\n */\n readonly operation: string;\n /**\n * The tenant ID of the email action link. Null if the email action is from the parent project.\n */\n readonly tenantId: string | null;\n\n /**\n * @param actionLink - The link from which to extract the URL.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @internal\n */\n constructor(actionLink: string) {\n const searchParams = querystringDecode(extractQuerystring(actionLink));\n const apiKey = searchParams[QueryField.API_KEY] ?? null;\n const code = searchParams[QueryField.CODE] ?? null;\n const operation = parseMode(searchParams[QueryField.MODE] ?? null);\n // Validate API key, code and mode.\n _assert(apiKey && code && operation, AuthErrorCode.ARGUMENT_ERROR);\n this.apiKey = apiKey;\n this.operation = operation;\n this.code = code;\n this.continueUrl = searchParams[QueryField.CONTINUE_URL] ?? null;\n this.languageCode = searchParams[QueryField.LANGUAGE_CODE] ?? null;\n this.tenantId = searchParams[QueryField.TENANT_ID] ?? null;\n }\n\n /**\n * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,\n * otherwise returns null.\n *\n * @param link - The email action link string.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @public\n */\n static parseLink(link: string): ActionCodeURL | null {\n const actionLink = parseDeepLink(link);\n try {\n return new ActionCodeURL(actionLink);\n } catch {\n return null;\n }\n }\n}\n\n/**\n * Parses the email action link string and returns an {@link ActionCodeURL} if\n * the link is valid, otherwise returns null.\n *\n * @public\n */\nexport function parseActionCodeURL(link: string): ActionCodeURL | null {\n return ActionCodeURL.parseLink(link);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\nimport { AuthProvider } from '../../model/public_types';\n\nimport { ActionCodeURL } from '../action_code_url';\nimport { EmailAuthCredential } from '../credentials/email';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\n\n/**\n * Provider for generating {@link EmailAuthCredential}.\n *\n * @public\n */\nexport class EmailAuthProvider implements AuthProvider {\n /**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\n static readonly PROVIDER_ID: 'password' = ProviderId.PASSWORD;\n /**\n * Always set to {@link SignInMethod}.EMAIL_PASSWORD.\n */\n static readonly EMAIL_PASSWORD_SIGN_IN_METHOD: 'password' =\n SignInMethod.EMAIL_PASSWORD;\n /**\n * Always set to {@link SignInMethod}.EMAIL_LINK.\n */\n static readonly EMAIL_LINK_SIGN_IN_METHOD: 'emailLink' =\n SignInMethod.EMAIL_LINK;\n /**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\n readonly providerId = EmailAuthProvider.PROVIDER_ID;\n\n /**\n * Initialize an {@link AuthCredential} using an email and password.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credential(email, password);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * const userCredential = await signInWithEmailAndPassword(auth, email, password);\n * ```\n *\n * @param email - Email address.\n * @param password - User account password.\n * @returns The auth provider credential.\n */\n static credential(email: string, password: string): EmailAuthCredential {\n return EmailAuthCredential._fromEmailAndPassword(email, password);\n }\n\n /**\n * Initialize an {@link AuthCredential} using an email and an email link after a sign in with\n * email link operation.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * await sendSignInLinkToEmail(auth, email);\n * // Obtain emailLink from user.\n * const userCredential = await signInWithEmailLink(auth, email, emailLink);\n * ```\n *\n * @param auth - The {@link Auth} instance used to verify the link.\n * @param email - Email address.\n * @param emailLink - Sign-in email link.\n * @returns - The auth provider credential.\n */\n static credentialWithLink(\n email: string,\n emailLink: string\n ): EmailAuthCredential {\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\n _assert(actionCodeUrl, AuthErrorCode.ARGUMENT_ERROR);\n\n return EmailAuthCredential._fromEmailAndCode(\n email,\n actionCodeUrl.code,\n actionCodeUrl.tenantId\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider } from '../../model/public_types';\n\n/**\n * Map of OAuth Custom Parameters.\n *\n * @public\n */\nexport type CustomParameters = Record<string, string>;\n\n/**\n * The base class for all Federated providers (OAuth (including OIDC), SAML).\n *\n * This class is not meant to be instantiated directly.\n *\n * @public\n */\nexport abstract class FederatedAuthProvider implements AuthProvider {\n /** @internal */\n defaultLanguageCode: string | null = null;\n /** @internal */\n private customParameters: CustomParameters = {};\n\n /**\n * Constructor for generic OAuth providers.\n *\n * @param providerId - Provider for which credentials should be generated.\n */\n constructor(readonly providerId: string) {}\n\n /**\n * Set the language gode.\n *\n * @param languageCode - language code\n */\n setDefaultLanguage(languageCode: string | null): void {\n this.defaultLanguageCode = languageCode;\n }\n\n /**\n * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in\n * operations.\n *\n * @remarks\n * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,\n * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.\n *\n * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.\n */\n setCustomParameters(customOAuthParameters: CustomParameters): AuthProvider {\n this.customParameters = customOAuthParameters;\n return this;\n }\n\n /**\n * Retrieve the current list of {@link CustomParameters}.\n */\n getCustomParameters(): CustomParameters {\n return this.customParameters;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider, UserCredential } from '../../model/public_types';\n\nimport { _assert } from '../util/assert';\nimport { AuthErrorCode } from '../errors';\n\nimport { OAuthCredential, OAuthCredentialParams } from '../credentials/oauth';\nimport { UserCredentialInternal } from '../../model/user';\nimport { FirebaseError } from '@firebase/util';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { SignInWithIdpResponse } from '../../../internal';\nimport { FederatedAuthProvider } from './federated';\n\n/**\n * Defines the options for initializing an {@link OAuthCredential}.\n *\n * @remarks\n * For ID tokens with nonce claim, the raw nonce has to also be provided.\n *\n * @public\n */\nexport interface OAuthCredentialOptions {\n /**\n * The OAuth ID token used to initialize the {@link OAuthCredential}.\n */\n idToken?: string;\n /**\n * The OAuth access token used to initialize the {@link OAuthCredential}.\n */\n accessToken?: string;\n /**\n * The raw nonce associated with the ID token.\n *\n * @remarks\n * It is required when an ID token with a nonce field is provided. The SHA-256 hash of the\n * raw nonce must match the nonce field in the ID token.\n */\n rawNonce?: string;\n}\n\n/**\n * Common code to all OAuth providers. This is separate from the\n * {@link OAuthProvider} so that child providers (like\n * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.\n * Instead, they rely on a static `credential` method.\n */\nexport abstract class BaseOAuthProvider\n extends FederatedAuthProvider\n implements AuthProvider\n{\n /** @internal */\n private scopes: string[] = [];\n\n /**\n * Add an OAuth scope to the credential.\n *\n * @param scope - Provider OAuth scope to add.\n */\n addScope(scope: string): AuthProvider {\n // If not already added, add scope to list.\n if (!this.scopes.includes(scope)) {\n this.scopes.push(scope);\n }\n return this;\n }\n\n /**\n * Retrieve the current list of OAuth scopes.\n */\n getScopes(): string[] {\n return [...this.scopes];\n }\n}\n\n/**\n * Provider for generating generic {@link OAuthCredential}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new OAuthProvider('google.com');\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new OAuthProvider('google.com');\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nexport class OAuthProvider extends BaseOAuthProvider {\n /**\n * Creates an {@link OAuthCredential} from a JSON string or a plain object.\n * @param json - A plain object or a JSON string\n */\n static credentialFromJSON(json: object | string): OAuthCredential {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n _assert(\n 'providerId' in obj && 'signInMethod' in obj,\n AuthErrorCode.ARGUMENT_ERROR\n );\n return OAuthCredential._fromParams(obj);\n }\n\n /**\n * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.\n *\n * @remarks\n * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of\n * the raw nonce must match the nonce field in the ID token.\n *\n * @example\n * ```javascript\n * // `googleUser` from the onsuccess Google Sign In callback.\n * // Initialize a generate OAuth provider with a `google.com` providerId.\n * const provider = new OAuthProvider('google.com');\n * const credential = provider.credential({\n * idToken: googleUser.getAuthResponse().id_token,\n * });\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param params - Either the options object containing the ID token, access token and raw nonce\n * or the ID token string.\n */\n credential(params: OAuthCredentialOptions): OAuthCredential {\n return this._credential({ ...params, nonce: params.rawNonce });\n }\n\n /** An internal credential method that accepts more permissive options */\n private _credential(\n params: Omit<OAuthCredentialParams, 'signInMethod' | 'providerId'>\n ): OAuthCredential {\n _assert(params.idToken || params.accessToken, AuthErrorCode.ARGUMENT_ERROR);\n // For OAuthCredential, sign in method is same as providerId.\n return OAuthCredential._fromParams({\n ...params,\n providerId: this.providerId,\n signInMethod: this.providerId\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return OAuthProvider.oauthCredentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return OAuthProvider.oauthCredentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static oauthCredentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const {\n oauthIdToken,\n oauthAccessToken,\n oauthTokenSecret,\n pendingToken,\n nonce,\n providerId\n } = tokenResponse as SignInWithIdpResponse;\n if (\n !oauthAccessToken &&\n !oauthTokenSecret &&\n !oauthIdToken &&\n !pendingToken\n ) {\n return null;\n }\n\n if (!providerId) {\n return null;\n }\n\n try {\n return new OAuthProvider(providerId)._credential({\n idToken: oauthIdToken,\n accessToken: oauthAccessToken,\n nonce,\n pendingToken\n });\n } catch (e) {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('user_birthday');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * provider.addScope('user_birthday');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nexport class FacebookAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.FACEBOOK. */\n static readonly FACEBOOK_SIGN_IN_METHOD: 'facebook.com' =\n SignInMethod.FACEBOOK;\n /** Always set to {@link ProviderId}.FACEBOOK. */\n static readonly PROVIDER_ID: 'facebook.com' = ProviderId.FACEBOOK;\n\n constructor() {\n super(ProviderId.FACEBOOK);\n }\n\n /**\n * Creates a credential for Facebook.\n *\n * @example\n * ```javascript\n * // `event` from the Facebook auth.authResponseChange callback.\n * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param accessToken - Facebook access token.\n */\n static credential(accessToken: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: FacebookAuthProvider.PROVIDER_ID,\n signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return FacebookAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return FacebookAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n\n try {\n return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GoogleAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GoogleAuthProvider();\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nexport class GoogleAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.GOOGLE. */\n static readonly GOOGLE_SIGN_IN_METHOD: 'google.com' = SignInMethod.GOOGLE;\n /** Always set to {@link ProviderId}.GOOGLE. */\n static readonly PROVIDER_ID: 'google.com' = ProviderId.GOOGLE;\n\n constructor() {\n super(ProviderId.GOOGLE);\n this.addScope('profile');\n }\n\n /**\n * Creates a credential for Google. At least one of ID token and access token is required.\n *\n * @example\n * ```javascript\n * // \\`googleUser\\` from the onsuccess Google Sign In callback.\n * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param idToken - Google ID token.\n * @param accessToken - Google access token.\n */\n static credential(\n idToken?: string | null,\n accessToken?: string | null\n ): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: GoogleAuthProvider.PROVIDER_ID,\n signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,\n idToken,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return GoogleAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return GoogleAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const { oauthIdToken, oauthAccessToken } =\n tokenResponse as SignInWithIdpResponse;\n if (!oauthIdToken && !oauthAccessToken) {\n // This could be an oauth 1 credential or a phone credential\n return null;\n }\n\n try {\n return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.\n *\n * @remarks\n * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use\n * the {@link signInWithPopup} handler:\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GithubAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('repo');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Github Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GithubAuthProvider();\n * provider.addScope('repo');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Github Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nexport class GithubAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.GITHUB. */\n static readonly GITHUB_SIGN_IN_METHOD: 'github.com' = SignInMethod.GITHUB;\n /** Always set to {@link ProviderId}.GITHUB. */\n static readonly PROVIDER_ID: 'github.com' = ProviderId.GITHUB;\n\n constructor() {\n super(ProviderId.GITHUB);\n }\n\n /**\n * Creates a credential for Github.\n *\n * @param accessToken - Github access token.\n */\n static credential(accessToken: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: GithubAuthProvider.PROVIDER_ID,\n signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return GithubAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return GithubAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n\n try {\n return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @license\n * Copyright 2020 Twitter LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new TwitterAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new TwitterAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * ```\n *\n * @public\n */\nexport class TwitterAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.TWITTER. */\n static readonly TWITTER_SIGN_IN_METHOD: 'twitter.com' = SignInMethod.TWITTER;\n /** Always set to {@link ProviderId}.TWITTER. */\n static readonly PROVIDER_ID: 'twitter.com' = ProviderId.TWITTER;\n\n constructor() {\n super(ProviderId.TWITTER);\n }\n\n /**\n * Creates a credential for Twitter.\n *\n * @param token - Twitter access token.\n * @param secret - Twitter secret.\n */\n static credential(token: string, secret: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: TwitterAuthProvider.PROVIDER_ID,\n signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,\n oauthToken: token,\n oauthTokenSecret: secret\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return TwitterAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return TwitterAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n const { oauthAccessToken, oauthTokenSecret } =\n tokenResponse as SignInWithIdpResponse;\n if (!oauthAccessToken || !oauthTokenSecret) {\n return null;\n }\n\n try {\n return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignUpRequest {\n idToken?: string;\n returnSecureToken?: boolean;\n email?: string;\n password?: string;\n tenantId?: string;\n captchaResponse?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface SignUpResponse extends IdTokenResponse {\n displayName?: string;\n email?: string;\n}\n\nexport async function signUp(\n auth: Auth,\n request: SignUpRequest\n): Promise<SignUpResponse> {\n return _performSignInRequest<SignUpRequest, SignUpResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_UP,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { UserImpl } from './user_impl';\nimport { AuthInternal } from '../../model/auth';\nimport { OperationType, ProviderId } from '../../model/enums';\n\ninterface UserCredentialParams {\n readonly user: UserInternal;\n readonly providerId: ProviderId | string | null;\n readonly _tokenResponse?: PhoneOrOauthTokenResponse;\n readonly operationType: OperationType;\n}\n\nexport class UserCredentialImpl\n implements UserCredentialInternal, UserCredentialParams\n{\n readonly user: UserInternal;\n readonly providerId: ProviderId | string | null;\n readonly _tokenResponse: PhoneOrOauthTokenResponse | undefined;\n readonly operationType: OperationType;\n\n constructor(params: UserCredentialParams) {\n this.user = params.user;\n this.providerId = params.providerId;\n this._tokenResponse = params._tokenResponse;\n this.operationType = params.operationType;\n }\n\n static async _fromIdTokenResponse(\n auth: AuthInternal,\n operationType: OperationType,\n idTokenResponse: IdTokenResponse,\n isAnonymous: boolean = false\n ): Promise<UserCredentialInternal> {\n const user = await UserImpl._fromIdTokenResponse(\n auth,\n idTokenResponse,\n isAnonymous\n );\n const providerId = providerIdForResponse(idTokenResponse);\n const userCred = new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: idTokenResponse,\n operationType\n });\n return userCred;\n }\n\n static async _forOperation(\n user: UserInternal,\n operationType: OperationType,\n response: PhoneOrOauthTokenResponse\n ): Promise<UserCredentialImpl> {\n await user._updateTokensIfNecessary(response, /* reload */ true);\n const providerId = providerIdForResponse(response);\n return new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: response,\n operationType\n });\n }\n}\n\nfunction providerIdForResponse(\n response: IdTokenResponse\n): ProviderId | string | null {\n if (response.providerId) {\n return response.providerId;\n }\n\n if ('phoneNumber' in response) {\n return ProviderId.PHONE;\n }\n\n return null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MultiFactorError as MultiFactorErrorPublic } from '../model/public_types';\nimport { FirebaseError } from '@firebase/util';\nimport { AuthInternal } from '../model/auth';\nimport { IdTokenResponse } from '../model/id_token';\nimport { AuthErrorCode } from '../core/errors';\nimport { UserInternal } from '../model/user';\nimport { AuthCredential } from '../core/credentials';\nimport { IdTokenMfaResponse } from '../api/authentication/mfa';\nimport { OperationType } from '../model/enums';\n\nexport type MultiFactorErrorData = MultiFactorErrorPublic['customData'] & {\n _serverResponse: IdTokenMfaResponse;\n};\n\nexport class MultiFactorError\n extends FirebaseError\n implements MultiFactorErrorPublic\n{\n readonly customData: MultiFactorErrorData;\n\n private constructor(\n auth: AuthInternal,\n error: FirebaseError,\n readonly operationType: OperationType,\n readonly user?: UserInternal\n ) {\n super(error.code, error.message);\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MultiFactorError.prototype);\n this.customData = {\n appName: auth.name,\n tenantId: auth.tenantId ?? undefined,\n _serverResponse: error.customData!._serverResponse as IdTokenMfaResponse,\n operationType\n };\n }\n\n static _fromErrorAndOperation(\n auth: AuthInternal,\n error: FirebaseError,\n operationType: OperationType,\n user?: UserInternal\n ): MultiFactorError {\n return new MultiFactorError(auth, error, operationType, user);\n }\n}\n\nexport function _processCredentialSavingMfaContextIfNecessary(\n auth: AuthInternal,\n operationType: OperationType,\n credential: AuthCredential,\n user?: UserInternal\n): Promise<IdTokenResponse> {\n const idTokenProvider =\n operationType === OperationType.REAUTHENTICATE\n ? credential._getReauthenticationResolver(auth)\n : credential._getIdTokenResponse(auth);\n\n return idTokenProvider.catch(error => {\n if (error.code === `auth/${AuthErrorCode.MFA_REQUIRED}`) {\n throw MultiFactorError._fromErrorAndOperation(\n auth,\n error,\n operationType,\n user\n );\n }\n\n throw error;\n });\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../../model/public_types';\n\nimport { deleteLinkedAccounts } from '../../api/account_management/account';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { providerDataAsNames } from '../util/providers';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { _reloadWithoutSaving } from './reload';\nimport { UserCredentialImpl } from './user_credential_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType, ProviderId } from '../../model/enums';\n\n/**\n * Unlinks a provider from a user account.\n *\n * @param user - The user.\n * @param providerId - The provider to unlink.\n *\n * @public\n */\nexport async function unlink(user: User, providerId: string): Promise<User> {\n const userInternal = getModularInstance(user) as UserInternal;\n await _assertLinkedStatus(true, userInternal, providerId);\n const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {\n idToken: await userInternal.getIdToken(),\n deleteProvider: [providerId]\n });\n\n const providersLeft = providerDataAsNames(providerUserInfo || []);\n\n userInternal.providerData = userInternal.providerData.filter(pd =>\n providersLeft.has(pd.providerId)\n );\n if (!providersLeft.has(ProviderId.PHONE)) {\n userInternal.phoneNumber = null;\n }\n\n await userInternal.auth._persistUserIfCurrent(userInternal);\n return userInternal;\n}\n\nexport async function _link(\n user: UserInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise<UserCredentialInternal> {\n const response = await _logoutIfInvalidated(\n user,\n credential._linkToIdToken(user.auth, await user.getIdToken()),\n bypassAuthState\n );\n return UserCredentialImpl._forOperation(user, OperationType.LINK, response);\n}\n\nexport async function _assertLinkedStatus(\n expected: boolean,\n user: UserInternal,\n provider: string\n): Promise<void> {\n await _reloadWithoutSaving(user);\n const providerIds = providerDataAsNames(user.providerData);\n\n const code =\n expected === false\n ? AuthErrorCode.PROVIDER_ALREADY_LINKED\n : AuthErrorCode.NO_SUCH_PROVIDER;\n _assert(providerIds.has(provider) === expected, user.auth, code);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { _processCredentialSavingMfaContextIfNecessary } from '../../mfa/mfa_error';\nimport { OperationType } from '../../model/enums';\nimport { UserInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { AuthErrorCode } from '../errors';\nimport { _assert, _fail } from '../util/assert';\nimport { _parseToken } from './id_token_result';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { UserCredentialImpl } from './user_credential_impl';\n\nexport async function _reauthenticate(\n user: UserInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise<UserCredentialImpl> {\n const { auth } = user;\n const operationType = OperationType.REAUTHENTICATE;\n\n try {\n const response = await _logoutIfInvalidated(\n user,\n _processCredentialSavingMfaContextIfNecessary(\n auth,\n operationType,\n credential,\n user\n ),\n bypassAuthState\n );\n _assert(response.idToken, auth, AuthErrorCode.INTERNAL_ERROR);\n const parsed = _parseToken(response.idToken);\n _assert(parsed, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const { sub: localId } = parsed;\n _assert(user.uid === localId, auth, AuthErrorCode.USER_MISMATCH);\n\n return UserCredentialImpl._forOperation(user, operationType, response);\n } catch (e) {\n // Convert user deleted error into user mismatch\n if ((e as FirebaseError)?.code === `auth/${AuthErrorCode.USER_DELETED}`) {\n _fail(auth, AuthErrorCode.USER_MISMATCH);\n }\n throw e;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential, Auth, User } from '../../model/public_types';\n\nimport { _processCredentialSavingMfaContextIfNecessary } from '../../mfa/mfa_error';\nimport { AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { _assertLinkedStatus, _link } from '../user/link_unlink';\nimport { _reauthenticate } from '../user/reauthenticate';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../../model/enums';\n\nexport async function _signInWithCredential(\n auth: AuthInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise<UserCredential> {\n const operationType = OperationType.SIGN_IN;\n const response = await _processCredentialSavingMfaContextIfNecessary(\n auth,\n operationType,\n credential\n );\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n auth,\n operationType,\n response\n );\n\n if (!bypassAuthState) {\n await auth._updateCurrentUser(userCredential.user);\n }\n return userCredential;\n}\n\n/**\n * Asynchronously signs in with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * @param auth - The {@link Auth} instance.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function signInWithCredential(\n auth: Auth,\n credential: AuthCredential\n): Promise<UserCredential> {\n return _signInWithCredential(_castAuth(auth), credential);\n}\n\n/**\n * Links the user account with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function linkWithCredential(\n user: User,\n credential: AuthCredential\n): Promise<UserCredential> {\n const userInternal = getModularInstance(user) as UserInternal;\n\n await _assertLinkedStatus(false, userInternal, credential.providerId);\n\n return _link(userInternal, credential);\n}\n\n/**\n * Re-authenticates a user using a fresh credential.\n *\n * @remarks\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in\n * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error\n * or a `TOKEN_EXPIRED` error.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function reauthenticateWithCredential(\n user: User,\n credential: AuthCredential\n): Promise<UserCredential> {\n return _reauthenticate(getModularInstance(user) as UserInternal, credential);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ActionCodeInfo,\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n UserCredential\n} from '../../model/public_types';\n\nimport * as account from '../../api/account_management/email_and_password';\nimport * as authentication from '../../api/authentication/email_and_password';\nimport { signUp, SignUpRequest } from '../../api/authentication/sign_up';\nimport { MultiFactorInfoImpl } from '../../mfa/mfa_info';\nimport { EmailAuthProvider } from '../providers/email';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _assert } from '../util/assert';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { signInWithCredential } from './credential';\nimport { _castAuth } from '../auth/auth_impl';\nimport { AuthErrorCode } from '../errors';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../../model/enums';\nimport { handleRecaptchaFlow } from '../../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { RecaptchaActionName, RecaptchaClientType } from '../../api';\n\n/**\n * Updates the password policy cached in the {@link Auth} instance if a policy is already\n * cached for the project or tenant.\n *\n * @remarks\n * We only fetch the password policy if the password did not meet policy requirements and\n * there is an existing policy cached. A developer must call validatePassword at least\n * once for the cache to be automatically updated.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @private\n */\nasync function recachePasswordPolicy(auth: Auth): Promise<void> {\n const authInternal = _castAuth(auth);\n if (authInternal._getPasswordPolicyInternal()) {\n await authInternal._updatePasswordPolicy();\n }\n}\n\n/**\n * Sends a password reset email to the given email address.\n *\n * @remarks\n * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in\n * the email sent to the user, along with the new password specified by the user.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain code from user.\n * await confirmPasswordReset('user@example.com', code);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendPasswordResetEmail(\n auth: Auth,\n email: string,\n actionCodeSettings?: ActionCodeSettings\n): Promise<void> {\n const authInternal = _castAuth(auth);\n const request: authentication.PasswordResetRequest = {\n requestType: ActionCodeOperation.PASSWORD_RESET,\n email,\n clientType: RecaptchaClientType.WEB\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\n }\n await handleRecaptchaFlow(\n authInternal,\n request,\n RecaptchaActionName.GET_OOB_CODE,\n authentication.sendPasswordResetEmail\n );\n}\n\n/**\n * Completes the password reset process, given a confirmation code and new password.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A confirmation code sent to the user.\n * @param newPassword - The new password.\n *\n * @public\n */\nexport async function confirmPasswordReset(\n auth: Auth,\n oobCode: string,\n newPassword: string\n): Promise<void> {\n await account\n .resetPassword(getModularInstance(auth), {\n oobCode,\n newPassword\n })\n .catch(async error => {\n if (\n error.code ===\n `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\n });\n // Do not return the email.\n}\n\n/**\n * Applies a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nexport async function applyActionCode(\n auth: Auth,\n oobCode: string\n): Promise<void> {\n await account.applyActionCode(getModularInstance(auth), { oobCode });\n}\n\n/**\n * Checks a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @returns metadata about the code.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nexport async function checkActionCode(\n auth: Auth,\n oobCode: string\n): Promise<ActionCodeInfo> {\n const authModular = getModularInstance(auth);\n const response = await account.resetPassword(authModular, { oobCode });\n\n // Email could be empty only if the request type is EMAIL_SIGNIN or\n // VERIFY_AND_CHANGE_EMAIL.\n // New email should not be empty if the request type is\n // VERIFY_AND_CHANGE_EMAIL.\n // Multi-factor info could not be empty if the request type is\n // REVERT_SECOND_FACTOR_ADDITION.\n const operation = response.requestType;\n _assert(operation, authModular, AuthErrorCode.INTERNAL_ERROR);\n switch (operation) {\n case ActionCodeOperation.EMAIL_SIGNIN:\n break;\n case ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL:\n _assert(response.newEmail, authModular, AuthErrorCode.INTERNAL_ERROR);\n break;\n case ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION:\n _assert(response.mfaInfo, authModular, AuthErrorCode.INTERNAL_ERROR);\n // fall through\n default:\n _assert(response.email, authModular, AuthErrorCode.INTERNAL_ERROR);\n }\n\n // The multi-factor info for revert second factor addition\n let multiFactorInfo: MultiFactorInfoImpl | null = null;\n if (response.mfaInfo) {\n multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(\n _castAuth(authModular),\n response.mfaInfo\n );\n }\n\n return {\n data: {\n email:\n (response.requestType === ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL\n ? response.newEmail\n : response.email) || null,\n previousEmail:\n (response.requestType === ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL\n ? response.email\n : response.newEmail) || null,\n multiFactorInfo\n },\n operation\n };\n}\n\n/**\n * Checks a password reset code sent to the user by email or other out-of-band mechanism.\n *\n * @returns the user's email address if valid.\n *\n * @param auth - The {@link Auth} instance.\n * @param code - A verification code sent to the user.\n *\n * @public\n */\nexport async function verifyPasswordResetCode(\n auth: Auth,\n code: string\n): Promise<string> {\n const { data } = await checkActionCode(getModularInstance(auth), code);\n // Email should always be present since a code was sent to it\n return data.email!;\n}\n\n/**\n * Creates a new user account associated with the specified email address and password.\n *\n * @remarks\n * On successful creation of the user account, this user will also be signed in to your application.\n *\n * User account creation can fail if the account already exists or the password is invalid.\n *\n * Note: The email address acts as a unique identifier for the user and enables an email-based\n * password reset. This function will create a new user account and set the initial user password.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param password - The user's chosen password.\n *\n * @public\n */\nexport async function createUserWithEmailAndPassword(\n auth: Auth,\n email: string,\n password: string\n): Promise<UserCredential> {\n const authInternal = _castAuth(auth);\n const request: SignUpRequest = {\n returnSecureToken: true,\n email,\n password,\n clientType: RecaptchaClientType.WEB\n };\n const signUpResponse: Promise<IdTokenResponse> = handleRecaptchaFlow(\n authInternal,\n request,\n RecaptchaActionName.SIGN_UP_PASSWORD,\n signUp\n );\n const response = await signUpResponse.catch(error => {\n if (\n error.code === `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\n });\n\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response\n );\n await authInternal._updateCurrentUser(userCredential.user);\n\n return userCredential;\n}\n\n/**\n * Asynchronously signs in using an email and password.\n *\n * @remarks\n * Fails with an error if the email address and password do not match.\n *\n * Note: The user's password is NOT the password used to access the user's email account. The\n * email address serves as a unique identifier for the user, and the password is used to access\n * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The users email address.\n * @param password - The users password.\n *\n * @public\n */\nexport function signInWithEmailAndPassword(\n auth: Auth,\n email: string,\n password: string\n): Promise<UserCredential> {\n return signInWithCredential(\n getModularInstance(auth),\n EmailAuthProvider.credential(email, password)\n ).catch(async error => {\n if (\n error.code === `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n MultiFactorAssertion,\n MultiFactorInfo,\n MultiFactorSession,\n MultiFactorUser,\n User\n} from '../model/public_types';\n\nimport { withdrawMfa } from '../api/account_management/mfa';\nimport { _logoutIfInvalidated } from '../core/user/invalidation';\nimport { UserInternal } from '../model/user';\nimport { MultiFactorAssertionImpl } from './mfa_assertion';\nimport { MultiFactorInfoImpl } from './mfa_info';\nimport { MultiFactorSessionImpl } from './mfa_session';\nimport { getModularInstance } from '@firebase/util';\n\nexport class MultiFactorUserImpl implements MultiFactorUser {\n enrolledFactors: MultiFactorInfo[] = [];\n\n private constructor(readonly user: UserInternal) {\n user._onReload(userInfo => {\n if (userInfo.mfaInfo) {\n this.enrolledFactors = userInfo.mfaInfo.map(enrollment =>\n MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment)\n );\n }\n });\n }\n\n static _fromUser(user: UserInternal): MultiFactorUserImpl {\n return new MultiFactorUserImpl(user);\n }\n\n async getSession(): Promise<MultiFactorSession> {\n return MultiFactorSessionImpl._fromIdtoken(\n await this.user.getIdToken(),\n this.user\n );\n }\n\n async enroll(\n assertionExtern: MultiFactorAssertion,\n displayName?: string | null\n ): Promise<void> {\n const assertion = assertionExtern as MultiFactorAssertionImpl;\n const session = (await this.getSession()) as MultiFactorSessionImpl;\n const finalizeMfaResponse = await _logoutIfInvalidated(\n this.user,\n assertion._process(this.user.auth, session, displayName)\n );\n // New tokens will be issued after enrollment of the new second factors.\n // They need to be updated on the user.\n await this.user._updateTokensIfNecessary(finalizeMfaResponse);\n // The user needs to be reloaded to get the new multi-factor information\n // from server. USER_RELOADED event will be triggered and `enrolledFactors`\n // will be updated.\n return this.user.reload();\n }\n\n async unenroll(infoOrUid: MultiFactorInfo | string): Promise<void> {\n const mfaEnrollmentId =\n typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;\n const idToken = await this.user.getIdToken();\n try {\n const idTokenResponse = await _logoutIfInvalidated(\n this.user,\n withdrawMfa(this.user.auth, {\n idToken,\n mfaEnrollmentId\n })\n );\n // Remove the second factor from the user's list.\n this.enrolledFactors = this.enrolledFactors.filter(\n ({ uid }) => uid !== mfaEnrollmentId\n );\n // Depending on whether the backend decided to revoke the user's session,\n // the tokenResponse may be empty. If the tokens were not updated (and they\n // are now invalid), reloading the user will discover this and invalidate\n // the user's state accordingly.\n await this.user._updateTokensIfNecessary(idTokenResponse);\n await this.user.reload();\n } catch (e) {\n throw e;\n }\n }\n}\n\nconst multiFactorUserCache = new WeakMap<User, MultiFactorUser>();\n\n/**\n * The {@link MultiFactorUser} corresponding to the user.\n *\n * @remarks\n * This is used to access all multi-factor properties and operations related to the user.\n *\n * @param user - The user.\n *\n * @public\n */\nexport function multiFactor(user: User): MultiFactorUser {\n const userModular = getModularInstance(user);\n if (!multiFactorUserCache.has(userModular)) {\n multiFactorUserCache.set(\n userModular,\n MultiFactorUserImpl._fromUser(userModular as UserInternal)\n );\n }\n return multiFactorUserCache.get(userModular)!;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Persistence } from '../../model/public_types';\n\nexport const enum PersistenceType {\n SESSION = 'SESSION',\n LOCAL = 'LOCAL',\n NONE = 'NONE'\n}\n\nexport type PersistedBlob = Record<string, unknown>;\n\nexport interface Instantiator<T> {\n (blob: PersistedBlob): T;\n}\n\nexport type PersistenceValue = PersistedBlob | string;\n\nexport const STORAGE_AVAILABLE_KEY = '__sak';\n\nexport interface StorageEventListener {\n (value: PersistenceValue | null): void;\n}\n\nexport interface PersistenceInternal extends Persistence {\n type: PersistenceType;\n _isAvailable(): Promise<boolean>;\n _set(key: string, value: PersistenceValue): Promise<void>;\n _get<T extends PersistenceValue>(key: string): Promise<T | null>;\n _remove(key: string): Promise<void>;\n _addListener(key: string, listener: StorageEventListener): void;\n _removeListener(key: string, listener: StorageEventListener): void;\n // Should this persistence allow migration up the chosen hierarchy?\n _shouldAllowMigration?: boolean;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n PersistenceValue,\n STORAGE_AVAILABLE_KEY,\n PersistenceType\n} from '../../core/persistence';\n\n// There are two different browser persistence types: local and session.\n// Both have the same implementation but use a different underlying storage\n// object.\n\nexport abstract class BrowserPersistenceClass {\n protected constructor(\n protected readonly storageRetriever: () => Storage,\n readonly type: PersistenceType\n ) {}\n\n _isAvailable(): Promise<boolean> {\n try {\n if (!this.storage) {\n return Promise.resolve(false);\n }\n this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');\n this.storage.removeItem(STORAGE_AVAILABLE_KEY);\n return Promise.resolve(true);\n } catch {\n return Promise.resolve(false);\n }\n }\n\n _set(key: string, value: PersistenceValue): Promise<void> {\n this.storage.setItem(key, JSON.stringify(value));\n return Promise.resolve();\n }\n\n _get<T extends PersistenceValue>(key: string): Promise<T | null> {\n const json = this.storage.getItem(key);\n return Promise.resolve(json ? JSON.parse(json) : null);\n }\n\n _remove(key: string): Promise<void> {\n this.storage.removeItem(key);\n return Promise.resolve();\n }\n\n protected get storage(): Storage {\n return this.storageRetriever();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport { getUA } from '@firebase/util';\nimport {\n _isSafari,\n _isIOS,\n _isIframe,\n _isMobileBrowser,\n _isIE10\n} from '../../core/util/browser';\nimport {\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n PersistenceValue,\n StorageEventListener\n} from '../../core/persistence';\nimport { BrowserPersistenceClass } from './browser';\n\nfunction _iframeCannotSyncWebStorage(): boolean {\n const ua = getUA();\n return _isSafari(ua) || _isIOS(ua);\n}\n\n// The polling period in case events are not supported\nexport const _POLLING_INTERVAL_MS = 1000;\n\n// The IE 10 localStorage cross tab synchronization delay in milliseconds\nconst IE10_LOCAL_STORAGE_SYNC_DELAY = 10;\n\nclass BrowserLocalPersistence\n extends BrowserPersistenceClass\n implements InternalPersistence\n{\n static type: 'LOCAL' = 'LOCAL';\n\n constructor() {\n super(() => window.localStorage, PersistenceType.LOCAL);\n }\n\n private readonly boundEventHandler = (\n event: StorageEvent,\n poll?: boolean\n ): void => this.onStorageEvent(event, poll);\n private readonly listeners: Record<string, Set<StorageEventListener>> = {};\n private readonly localCache: Record<string, string | null> = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private pollTimer: any | null = null;\n\n // Safari or iOS browser and embedded in an iframe.\n private readonly safariLocalStorageNotSynced =\n _iframeCannotSyncWebStorage() && _isIframe();\n // Whether to use polling instead of depending on window events\n private readonly fallbackToPolling = _isMobileBrowser();\n readonly _shouldAllowMigration = true;\n\n private forAllChangedKeys(\n cb: (key: string, oldValue: string | null, newValue: string | null) => void\n ): void {\n // Check all keys with listeners on them.\n for (const key of Object.keys(this.listeners)) {\n // Get value from localStorage.\n const newValue = this.storage.getItem(key);\n const oldValue = this.localCache[key];\n // If local map value does not match, trigger listener with storage event.\n // Differentiate this simulated event from the real storage event.\n if (newValue !== oldValue) {\n cb(key, oldValue, newValue);\n }\n }\n }\n\n private onStorageEvent(event: StorageEvent, poll = false): void {\n // Key would be null in some situations, like when localStorage is cleared\n if (!event.key) {\n this.forAllChangedKeys(\n (key: string, _oldValue: string | null, newValue: string | null) => {\n this.notifyListeners(key, newValue);\n }\n );\n return;\n }\n\n const key = event.key;\n\n // Check the mechanism how this event was detected.\n // The first event will dictate the mechanism to be used.\n if (poll) {\n // Environment detects storage changes via polling.\n // Remove storage event listener to prevent possible event duplication.\n this.detachListener();\n } else {\n // Environment detects storage changes via storage event listener.\n // Remove polling listener to prevent possible event duplication.\n this.stopPolling();\n }\n\n // Safari embedded iframe. Storage event will trigger with the delta\n // changes but no changes will be applied to the iframe localStorage.\n if (this.safariLocalStorageNotSynced) {\n // Get current iframe page value.\n const storedValue = this.storage.getItem(key);\n // Value not synchronized, synchronize manually.\n if (event.newValue !== storedValue) {\n if (event.newValue !== null) {\n // Value changed from current value.\n this.storage.setItem(key, event.newValue);\n } else {\n // Current value deleted.\n this.storage.removeItem(key);\n }\n } else if (this.localCache[key] === event.newValue && !poll) {\n // Already detected and processed, do not trigger listeners again.\n return;\n }\n }\n\n const triggerListeners = (): void => {\n // Keep local map up to date in case storage event is triggered before\n // poll.\n const storedValue = this.storage.getItem(key);\n if (!poll && this.localCache[key] === storedValue) {\n // Real storage event which has already been detected, do nothing.\n // This seems to trigger in some IE browsers for some reason.\n return;\n }\n this.notifyListeners(key, storedValue);\n };\n\n const storedValue = this.storage.getItem(key);\n if (\n _isIE10() &&\n storedValue !== event.newValue &&\n event.newValue !== event.oldValue\n ) {\n // IE 10 has this weird bug where a storage event would trigger with the\n // correct key, oldValue and newValue but localStorage.getItem(key) does\n // not yield the updated value until a few milliseconds. This ensures\n // this recovers from that situation.\n setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);\n } else {\n triggerListeners();\n }\n }\n\n private notifyListeners(key: string, value: string | null): void {\n this.localCache[key] = value;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(value ? JSON.parse(value) : value);\n }\n }\n }\n\n private startPolling(): void {\n this.stopPolling();\n\n this.pollTimer = setInterval(() => {\n this.forAllChangedKeys(\n (key: string, oldValue: string | null, newValue: string | null) => {\n this.onStorageEvent(\n new StorageEvent('storage', {\n key,\n oldValue,\n newValue\n }),\n /* poll */ true\n );\n }\n );\n }, _POLLING_INTERVAL_MS);\n }\n\n private stopPolling(): void {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n private attachListener(): void {\n window.addEventListener('storage', this.boundEventHandler);\n }\n\n private detachListener(): void {\n window.removeEventListener('storage', this.boundEventHandler);\n }\n\n _addListener(key: string, listener: StorageEventListener): void {\n if (Object.keys(this.listeners).length === 0) {\n // Whether browser can detect storage event when it had already been pushed to the background.\n // This may happen in some mobile browsers. A localStorage change in the foreground window\n // will not be detected in the background window via the storage event.\n // This was detected in iOS 7.x mobile browsers\n if (this.fallbackToPolling) {\n this.startPolling();\n } else {\n this.attachListener();\n }\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n this.localCache[key] = this.storage.getItem(key);\n }\n this.listeners[key].add(listener);\n }\n\n _removeListener(key: string, listener: StorageEventListener): void {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n\n if (Object.keys(this.listeners).length === 0) {\n this.detachListener();\n this.stopPolling();\n }\n }\n\n // Update local cache on base operations:\n\n async _set(key: string, value: PersistenceValue): Promise<void> {\n await super._set(key, value);\n this.localCache[key] = JSON.stringify(value);\n }\n\n async _get<T extends PersistenceValue>(key: string): Promise<T | null> {\n const value = await super._get<T>(key);\n this.localCache[key] = JSON.stringify(value);\n return value;\n }\n\n async _remove(key: string): Promise<void> {\n await super._remove(key);\n delete this.localCache[key];\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`\n * for the underlying storage.\n *\n * @public\n */\nexport const browserLocalPersistence: Persistence = BrowserLocalPersistence;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport {\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n StorageEventListener\n} from '../../core/persistence';\nimport { BrowserPersistenceClass } from './browser';\n\nclass BrowserSessionPersistence\n extends BrowserPersistenceClass\n implements InternalPersistence\n{\n static type: 'SESSION' = 'SESSION';\n\n constructor() {\n super(() => window.sessionStorage, PersistenceType.SESSION);\n }\n\n _addListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n\n _removeListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n}\n\n/**\n * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`\n * for the underlying storage.\n *\n * @public\n */\nexport const browserSessionPersistence: Persistence = BrowserSessionPersistence;\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ReceiverHandler,\n _EventType,\n _ReceiverResponse,\n SenderMessageEvent,\n _Status,\n _SenderRequest\n} from './index';\nimport { _allSettled } from './promise';\n\n/**\n * Interface class for receiving messages.\n *\n */\nexport class Receiver {\n private static readonly receivers: Receiver[] = [];\n private readonly boundEventHandler: EventListener;\n\n private readonly handlersMap: {\n // Typescript doesn't have existential types :(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [eventType: string]: Set<ReceiverHandler<any, any>>;\n } = {};\n\n constructor(private readonly eventTarget: EventTarget) {\n this.boundEventHandler = this.handleEvent.bind(this);\n }\n\n /**\n * Obtain an instance of a Receiver for a given event target, if none exists it will be created.\n *\n * @param eventTarget - An event target (such as window or self) through which the underlying\n * messages will be received.\n */\n static _getInstance(eventTarget: EventTarget): Receiver {\n // The results are stored in an array since objects can't be keys for other\n // objects. In addition, setting a unique property on an event target as a\n // hash map key may not be allowed due to CORS restrictions.\n const existingInstance = this.receivers.find(receiver =>\n receiver.isListeningto(eventTarget)\n );\n if (existingInstance) {\n return existingInstance;\n }\n const newInstance = new Receiver(eventTarget);\n this.receivers.push(newInstance);\n return newInstance;\n }\n\n private isListeningto(eventTarget: EventTarget): boolean {\n return this.eventTarget === eventTarget;\n }\n\n /**\n * Fans out a MessageEvent to the appropriate listeners.\n *\n * @remarks\n * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have\n * finished processing.\n *\n * @param event - The MessageEvent.\n *\n */\n private async handleEvent<\n T extends _ReceiverResponse,\n S extends _SenderRequest\n >(event: Event): Promise<void> {\n const messageEvent = event as MessageEvent<SenderMessageEvent<S>>;\n const { eventId, eventType, data } = messageEvent.data;\n\n const handlers: Set<ReceiverHandler<T, S>> | undefined =\n this.handlersMap[eventType];\n if (!handlers?.size) {\n return;\n }\n\n messageEvent.ports[0].postMessage({\n status: _Status.ACK,\n eventId,\n eventType\n });\n\n const promises = Array.from(handlers).map(async handler =>\n handler(messageEvent.origin, data)\n );\n const response = await _allSettled(promises);\n messageEvent.ports[0].postMessage({\n status: _Status.DONE,\n eventId,\n eventType,\n response\n });\n }\n\n /**\n * Subscribe an event handler for a particular event.\n *\n * @param eventType - Event name to subscribe to.\n * @param eventHandler - The event handler which should receive the events.\n *\n */\n _subscribe<T extends _ReceiverResponse, S extends _SenderRequest>(\n eventType: _EventType,\n eventHandler: ReceiverHandler<T, S>\n ): void {\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.addEventListener('message', this.boundEventHandler);\n }\n\n if (!this.handlersMap[eventType]) {\n this.handlersMap[eventType] = new Set();\n }\n\n this.handlersMap[eventType].add(eventHandler);\n }\n\n /**\n * Unsubscribe an event handler from a particular event.\n *\n * @param eventType - Event name to unsubscribe from.\n * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.\n *\n */\n _unsubscribe<T extends _ReceiverResponse, S extends _SenderRequest>(\n eventType: _EventType,\n eventHandler?: ReceiverHandler<T, S>\n ): void {\n if (this.handlersMap[eventType] && eventHandler) {\n this.handlersMap[eventType].delete(eventHandler);\n }\n if (!eventHandler || this.handlersMap[eventType].size === 0) {\n delete this.handlersMap[eventType];\n }\n\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.removeEventListener('message', this.boundEventHandler);\n }\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** TODO: remove this once tslib has a polyfill for Promise.allSettled */\ninterface PromiseFulfilledResult<T> {\n fulfilled: true;\n value: T;\n}\n\ninterface PromiseRejectedResult {\n fulfilled: false;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n reason: any;\n}\n\nexport type PromiseSettledResult<T> =\n | PromiseFulfilledResult<T>\n | PromiseRejectedResult;\n\n/**\n * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.\n *\n * @param promises - Array of promises to wait on.\n */\nexport function _allSettled<T>(\n promises: Array<Promise<T>>\n): Promise<Array<PromiseSettledResult<T>>> {\n return Promise.all(\n promises.map(async promise => {\n try {\n const value = await promise;\n return {\n fulfilled: true,\n value\n } as PromiseFulfilledResult<T>;\n } catch (reason) {\n return {\n fulfilled: false,\n reason\n } as PromiseRejectedResult;\n }\n })\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function _generateEventId(prefix = '', digits = 10): string {\n let random = '';\n for (let i = 0; i < digits; i++) {\n random += Math.floor(Math.random() * 10);\n }\n return prefix + random;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _generateEventId } from '../../core/util/event_id';\nimport {\n _SenderRequest,\n _EventType,\n ReceiverMessageEvent,\n _MessageError,\n SenderMessageEvent,\n _Status,\n _ReceiverMessageResponse,\n _ReceiverResponse,\n _TimeoutDuration\n} from './index';\n\ninterface MessageHandler {\n messageChannel: MessageChannel;\n onMessage: EventListenerOrEventListenerObject;\n}\n\n/**\n * Interface for sending messages and waiting for a completion response.\n *\n */\nexport class Sender {\n private readonly handlers = new Set<MessageHandler>();\n\n constructor(private readonly target: ServiceWorker) {}\n\n /**\n * Unsubscribe the handler and remove it from our tracking Set.\n *\n * @param handler - The handler to unsubscribe.\n */\n private removeMessageHandler(handler: MessageHandler): void {\n if (handler.messageChannel) {\n handler.messageChannel.port1.removeEventListener(\n 'message',\n handler.onMessage\n );\n handler.messageChannel.port1.close();\n }\n this.handlers.delete(handler);\n }\n\n /**\n * Send a message to the Receiver located at {@link target}.\n *\n * @remarks\n * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the\n * receiver has had a chance to fully process the event.\n *\n * @param eventType - Type of event to send.\n * @param data - The payload of the event.\n * @param timeout - Timeout for waiting on an ACK from the receiver.\n *\n * @returns An array of settled promises from all the handlers that were listening on the receiver.\n */\n async _send<T extends _ReceiverResponse, S extends _SenderRequest>(\n eventType: _EventType,\n data: S,\n timeout = _TimeoutDuration.ACK\n ): Promise<_ReceiverMessageResponse<T>> {\n const messageChannel =\n typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;\n if (!messageChannel) {\n throw new Error(_MessageError.CONNECTION_UNAVAILABLE);\n }\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let completionTimer: any;\n let handler: MessageHandler;\n return new Promise<_ReceiverMessageResponse<T>>((resolve, reject) => {\n const eventId = _generateEventId('', 20);\n messageChannel.port1.start();\n const ackTimer = setTimeout(() => {\n reject(new Error(_MessageError.UNSUPPORTED_EVENT));\n }, timeout);\n handler = {\n messageChannel,\n onMessage(event: Event): void {\n const messageEvent = event as MessageEvent<ReceiverMessageEvent<T>>;\n if (messageEvent.data.eventId !== eventId) {\n return;\n }\n switch (messageEvent.data.status) {\n case _Status.ACK:\n // The receiver should ACK first.\n clearTimeout(ackTimer);\n completionTimer = setTimeout(() => {\n reject(new Error(_MessageError.TIMEOUT));\n }, _TimeoutDuration.COMPLETION);\n break;\n case _Status.DONE:\n // Once the receiver's handlers are finished we will get the results.\n clearTimeout(completionTimer);\n resolve(messageEvent.data.response);\n break;\n default:\n clearTimeout(ackTimer);\n clearTimeout(completionTimer);\n reject(new Error(_MessageError.INVALID_RESPONSE));\n break;\n }\n }\n };\n this.handlers.add(handler);\n messageChannel.port1.addEventListener('message', handler.onMessage);\n this.target.postMessage(\n {\n eventType,\n eventId,\n data\n } as SenderMessageEvent<S>,\n [messageChannel.port2]\n );\n }).finally(() => {\n if (handler) {\n this.removeMessageHandler(handler);\n }\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Recaptcha, GreCAPTCHATopLevel } from './recaptcha/recaptcha';\n\n/**\n * A specialized window type that melds the normal window type plus the\n * various bits we need. The three different blocks that are &'d together\n * cant be defined in the same block together.\n */\nexport type AuthWindow = {\n // Standard window types\n [T in keyof Window]: Window[T];\n} & {\n // Any known / named properties we want to add\n grecaptcha?: Recaptcha | GreCAPTCHATopLevel;\n /* eslint-disable-next-line @typescript-eslint/no-explicit-any */\n ___jsl?: Record<string, any>;\n gapi?: typeof gapi;\n} & {\n // A final catch-all for callbacks (which will have random names) that\n // we will stick on the window.\n [callback: string]: (...args: unknown[]) => void;\n};\n\n/**\n * Lazy accessor for window, since the compat layer won't tree shake this out,\n * we need to make sure not to mess with window unless we have to\n */\nexport function _window(): AuthWindow {\n return window as unknown as AuthWindow;\n}\n\nexport function _setWindowLocation(url: string): void {\n _window().location.href = url;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _window } from '../auth_window';\n\nexport function _isWorker(): boolean {\n return (\n typeof _window()['WorkerGlobalScope'] !== 'undefined' &&\n typeof _window()['importScripts'] === 'function'\n );\n}\n\nexport async function _getActiveServiceWorker(): Promise<ServiceWorker | null> {\n if (!navigator?.serviceWorker) {\n return null;\n }\n try {\n const registration = await navigator.serviceWorker.ready;\n return registration.active;\n } catch {\n return null;\n }\n}\n\nexport function _getServiceWorkerController(): ServiceWorker | null {\n return navigator?.serviceWorker?.controller || null;\n}\n\nexport function _getWorkerGlobalScope(): ServiceWorker | null {\n return _isWorker() ? (self as unknown as ServiceWorker) : null;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\nimport {\n PersistedBlob,\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n PersistenceValue,\n StorageEventListener,\n STORAGE_AVAILABLE_KEY\n} from '../../core/persistence/';\nimport {\n _EventType,\n _PingResponse,\n KeyChangedResponse,\n KeyChangedRequest,\n PingRequest,\n _TimeoutDuration\n} from '../messagechannel/index';\nimport { Receiver } from '../messagechannel/receiver';\nimport { Sender } from '../messagechannel/sender';\nimport {\n _isWorker,\n _getActiveServiceWorker,\n _getServiceWorkerController,\n _getWorkerGlobalScope\n} from '../util/worker';\n\nexport const DB_NAME = 'firebaseLocalStorageDb';\nconst DB_VERSION = 1;\nconst DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';\nconst DB_DATA_KEYPATH = 'fbase_key';\n\ninterface DBObject {\n [DB_DATA_KEYPATH]: string;\n value: PersistedBlob;\n}\n\n/**\n * Promise wrapper for IDBRequest\n *\n * Unfortunately we can't cleanly extend Promise<T> since promises are not callable in ES6\n *\n */\nclass DBPromise<T> {\n constructor(private readonly request: IDBRequest) {}\n\n toPromise(): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n this.request.addEventListener('success', () => {\n resolve(this.request.result);\n });\n this.request.addEventListener('error', () => {\n reject(this.request.error);\n });\n });\n }\n}\n\nfunction getObjectStore(db: IDBDatabase, isReadWrite: boolean): IDBObjectStore {\n return db\n .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')\n .objectStore(DB_OBJECTSTORE_NAME);\n}\n\nexport async function _clearDatabase(db: IDBDatabase): Promise<void> {\n const objectStore = getObjectStore(db, true);\n return new DBPromise<void>(objectStore.clear()).toPromise();\n}\n\nexport function _deleteDatabase(): Promise<void> {\n const request = indexedDB.deleteDatabase(DB_NAME);\n return new DBPromise<void>(request).toPromise();\n}\n\nexport function _openDatabase(): Promise<IDBDatabase> {\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n return new Promise((resolve, reject) => {\n request.addEventListener('error', () => {\n reject(request.error);\n });\n\n request.addEventListener('upgradeneeded', () => {\n const db = request.result;\n\n try {\n db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });\n } catch (e) {\n reject(e);\n }\n });\n\n request.addEventListener('success', async () => {\n const db: IDBDatabase = request.result;\n // Strange bug that occurs in Firefox when multiple tabs are opened at the\n // same time. The only way to recover seems to be deleting the database\n // and re-initializing it.\n // https://github.com/firebase/firebase-js-sdk/issues/634\n\n if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {\n // Need to close the database or else you get a `blocked` event\n db.close();\n await _deleteDatabase();\n resolve(await _openDatabase());\n } else {\n resolve(db);\n }\n });\n });\n}\n\nexport async function _putObject(\n db: IDBDatabase,\n key: string,\n value: PersistenceValue | string\n): Promise<void> {\n const request = getObjectStore(db, true).put({\n [DB_DATA_KEYPATH]: key,\n value\n });\n return new DBPromise<void>(request).toPromise();\n}\n\nasync function getObject(\n db: IDBDatabase,\n key: string\n): Promise<PersistedBlob | null> {\n const request = getObjectStore(db, false).get(key);\n const data = await new DBPromise<DBObject | undefined>(request).toPromise();\n return data === undefined ? null : data.value;\n}\n\nexport function _deleteObject(db: IDBDatabase, key: string): Promise<void> {\n const request = getObjectStore(db, true).delete(key);\n return new DBPromise<void>(request).toPromise();\n}\n\nexport const _POLLING_INTERVAL_MS = 800;\nexport const _TRANSACTION_RETRY_COUNT = 3;\n\nclass IndexedDBLocalPersistence implements InternalPersistence {\n static type: 'LOCAL' = 'LOCAL';\n\n type = PersistenceType.LOCAL;\n db?: IDBDatabase;\n readonly _shouldAllowMigration = true;\n\n private readonly listeners: Record<string, Set<StorageEventListener>> = {};\n private readonly localCache: Record<string, PersistenceValue | null> = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private pollTimer: any | null = null;\n private pendingWrites = 0;\n\n private receiver: Receiver | null = null;\n private sender: Sender | null = null;\n private serviceWorkerReceiverAvailable = false;\n private activeServiceWorker: ServiceWorker | null = null;\n // Visible for testing only\n readonly _workerInitializationPromise: Promise<void>;\n\n constructor() {\n // Fire & forget the service worker registration as it may never resolve\n this._workerInitializationPromise =\n this.initializeServiceWorkerMessaging().then(\n () => {},\n () => {}\n );\n }\n\n async _openDb(): Promise<IDBDatabase> {\n if (this.db) {\n return this.db;\n }\n this.db = await _openDatabase();\n return this.db;\n }\n\n async _withRetries<T>(op: (db: IDBDatabase) => Promise<T>): Promise<T> {\n let numAttempts = 0;\n\n while (true) {\n try {\n const db = await this._openDb();\n return await op(db);\n } catch (e) {\n if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {\n throw e;\n }\n if (this.db) {\n this.db.close();\n this.db = undefined;\n }\n // TODO: consider adding exponential backoff\n }\n }\n }\n\n /**\n * IndexedDB events do not propagate from the main window to the worker context. We rely on a\n * postMessage interface to send these events to the worker ourselves.\n */\n private async initializeServiceWorkerMessaging(): Promise<void> {\n return _isWorker() ? this.initializeReceiver() : this.initializeSender();\n }\n\n /**\n * As the worker we should listen to events from the main window.\n */\n private async initializeReceiver(): Promise<void> {\n this.receiver = Receiver._getInstance(_getWorkerGlobalScope()!);\n // Refresh from persistence if we receive a KeyChanged message.\n this.receiver._subscribe(\n _EventType.KEY_CHANGED,\n async (_origin: string, data: KeyChangedRequest) => {\n const keys = await this._poll();\n return {\n keyProcessed: keys.includes(data.key)\n };\n }\n );\n // Let the sender know that we are listening so they give us more timeout.\n this.receiver._subscribe(\n _EventType.PING,\n async (_origin: string, _data: PingRequest) => {\n return [_EventType.KEY_CHANGED];\n }\n );\n }\n\n /**\n * As the main window, we should let the worker know when keys change (set and remove).\n *\n * @remarks\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}\n * may not resolve.\n */\n private async initializeSender(): Promise<void> {\n // Check to see if there's an active service worker.\n this.activeServiceWorker = await _getActiveServiceWorker();\n if (!this.activeServiceWorker) {\n return;\n }\n this.sender = new Sender(this.activeServiceWorker);\n // Ping the service worker to check what events they can handle.\n const results = await this.sender._send<_PingResponse, PingRequest>(\n _EventType.PING,\n {},\n _TimeoutDuration.LONG_ACK\n );\n if (!results) {\n return;\n }\n if (\n results[0]?.fulfilled &&\n results[0]?.value.includes(_EventType.KEY_CHANGED)\n ) {\n this.serviceWorkerReceiverAvailable = true;\n }\n }\n\n /**\n * Let the worker know about a changed key, the exact key doesn't technically matter since the\n * worker will just trigger a full sync anyway.\n *\n * @remarks\n * For now, we only support one service worker per page.\n *\n * @param key - Storage key which changed.\n */\n private async notifyServiceWorker(key: string): Promise<void> {\n if (\n !this.sender ||\n !this.activeServiceWorker ||\n _getServiceWorkerController() !== this.activeServiceWorker\n ) {\n return;\n }\n try {\n await this.sender._send<KeyChangedResponse, KeyChangedRequest>(\n _EventType.KEY_CHANGED,\n { key },\n // Use long timeout if receiver has previously responded to a ping from us.\n this.serviceWorkerReceiverAvailable\n ? _TimeoutDuration.LONG_ACK\n : _TimeoutDuration.ACK\n );\n } catch {\n // This is a best effort approach. Ignore errors.\n }\n }\n\n async _isAvailable(): Promise<boolean> {\n try {\n if (!indexedDB) {\n return false;\n }\n const db = await _openDatabase();\n await _putObject(db, STORAGE_AVAILABLE_KEY, '1');\n await _deleteObject(db, STORAGE_AVAILABLE_KEY);\n return true;\n } catch {}\n return false;\n }\n\n private async _withPendingWrite(write: () => Promise<void>): Promise<void> {\n this.pendingWrites++;\n try {\n await write();\n } finally {\n this.pendingWrites--;\n }\n }\n\n async _set(key: string, value: PersistenceValue): Promise<void> {\n return this._withPendingWrite(async () => {\n await this._withRetries((db: IDBDatabase) => _putObject(db, key, value));\n this.localCache[key] = value;\n return this.notifyServiceWorker(key);\n });\n }\n\n async _get<T extends PersistenceValue>(key: string): Promise<T | null> {\n const obj = (await this._withRetries((db: IDBDatabase) =>\n getObject(db, key)\n )) as T;\n this.localCache[key] = obj;\n return obj;\n }\n\n async _remove(key: string): Promise<void> {\n return this._withPendingWrite(async () => {\n await this._withRetries((db: IDBDatabase) => _deleteObject(db, key));\n delete this.localCache[key];\n return this.notifyServiceWorker(key);\n });\n }\n\n private async _poll(): Promise<string[]> {\n // TODO: check if we need to fallback if getAll is not supported\n const result = await this._withRetries((db: IDBDatabase) => {\n const getAllRequest = getObjectStore(db, false).getAll();\n return new DBPromise<DBObject[] | null>(getAllRequest).toPromise();\n });\n\n if (!result) {\n return [];\n }\n\n // If we have pending writes in progress abort, we'll get picked up on the next poll\n if (this.pendingWrites !== 0) {\n return [];\n }\n\n const keys = [];\n const keysInResult = new Set();\n for (const { fbase_key: key, value } of result) {\n keysInResult.add(key);\n if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {\n this.notifyListeners(key, value as PersistenceValue);\n keys.push(key);\n }\n }\n for (const localKey of Object.keys(this.localCache)) {\n if (this.localCache[localKey] && !keysInResult.has(localKey)) {\n // Deleted\n this.notifyListeners(localKey, null);\n keys.push(localKey);\n }\n }\n return keys;\n }\n\n private notifyListeners(\n key: string,\n newValue: PersistenceValue | null\n ): void {\n this.localCache[key] = newValue;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(newValue);\n }\n }\n }\n\n private startPolling(): void {\n this.stopPolling();\n\n this.pollTimer = setInterval(\n async () => this._poll(),\n _POLLING_INTERVAL_MS\n );\n }\n\n private stopPolling(): void {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n _addListener(key: string, listener: StorageEventListener): void {\n if (Object.keys(this.listeners).length === 0) {\n this.startPolling();\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n void this._get(key); // This can happen in the background async and we can return immediately.\n }\n this.listeners[key].add(listener);\n }\n\n _removeListener(key: string, listener: StorageEventListener): void {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n\n if (Object.keys(this.listeners).length === 0) {\n this.stopPolling();\n }\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`\n * for the underlying storage.\n *\n * @public\n */\nexport const indexedDBLocalPersistence: Persistence = IndexedDBLocalPersistence;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { querystring } from '@firebase/util';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert, _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as jsHelpers from '../load_js';\nimport { Recaptcha, isV2 } from './recaptcha';\nimport { MockReCaptcha } from './recaptcha_mock';\n\n// ReCaptcha will load using the same callback, so the callback function needs\n// to be kept around\nexport const _JSLOAD_CALLBACK = jsHelpers._generateCallbackName('rcb');\nconst NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);\nconst RECAPTCHA_BASE = 'https://www.google.com/recaptcha/api.js?';\n\n/**\n * We need to mark this interface as internal explicitly to exclude it in the public typings, because\n * it references AuthInternal which has a circular dependency with UserInternal.\n *\n * @internal\n */\nexport interface ReCaptchaLoader {\n load(auth: AuthInternal, hl?: string): Promise<Recaptcha>;\n clearedOneInstance(): void;\n}\n\n/**\n * Loader for the GReCaptcha library. There should only ever be one of this.\n */\nexport class ReCaptchaLoaderImpl implements ReCaptchaLoader {\n private hostLanguage = '';\n private counter = 0;\n /**\n * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise\n * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but\n * `window.grecaptcha.render()` will not. Another load will add it.\n */\n private readonly librarySeparatelyLoaded = !!_window().grecaptcha?.render;\n\n load(auth: AuthInternal, hl = ''): Promise<Recaptcha> {\n _assert(isHostLanguageValid(hl), auth, AuthErrorCode.ARGUMENT_ERROR);\n\n if (this.shouldResolveImmediately(hl) && isV2(_window().grecaptcha)) {\n return Promise.resolve(_window().grecaptcha! as Recaptcha);\n }\n return new Promise<Recaptcha>((resolve, reject) => {\n const networkTimeout = _window().setTimeout(() => {\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n }, NETWORK_TIMEOUT_DELAY.get());\n\n _window()[_JSLOAD_CALLBACK] = () => {\n _window().clearTimeout(networkTimeout);\n delete _window()[_JSLOAD_CALLBACK];\n\n const recaptcha = _window().grecaptcha as Recaptcha;\n\n if (!recaptcha || !isV2(recaptcha)) {\n reject(_createError(auth, AuthErrorCode.INTERNAL_ERROR));\n return;\n }\n\n // Wrap the greptcha render function so that we know if the developer has\n // called it separately\n const render = recaptcha.render;\n recaptcha.render = (container, params) => {\n const widgetId = render(container, params);\n this.counter++;\n return widgetId;\n };\n\n this.hostLanguage = hl;\n resolve(recaptcha);\n };\n\n const url = `${RECAPTCHA_BASE}?${querystring({\n onload: _JSLOAD_CALLBACK,\n render: 'explicit',\n hl\n })}`;\n\n jsHelpers._loadJS(url).catch(() => {\n clearTimeout(networkTimeout);\n reject(_createError(auth, AuthErrorCode.INTERNAL_ERROR));\n });\n });\n }\n\n clearedOneInstance(): void {\n this.counter--;\n }\n\n private shouldResolveImmediately(hl: string): boolean {\n // We can resolve immediately if:\n // • grecaptcha is already defined AND (\n // 1. the requested language codes are the same OR\n // 2. there exists already a ReCaptcha on the page\n // 3. the library was already loaded by the app\n // In cases (2) and (3), we _can't_ reload as it would break the recaptchas\n // that are already in the page\n return (\n !!_window().grecaptcha?.render &&\n (hl === this.hostLanguage ||\n this.counter > 0 ||\n this.librarySeparatelyLoaded)\n );\n }\n}\n\nfunction isHostLanguageValid(hl: string): boolean {\n return hl.length <= 6 && /^\\s*[a-zA-Z0-9\\-]*\\s*$/.test(hl);\n}\n\nexport class MockReCaptchaLoaderImpl implements ReCaptchaLoader {\n async load(auth: AuthInternal): Promise<Recaptcha> {\n return new MockReCaptcha(auth);\n }\n\n clearedOneInstance(): void {}\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth, RecaptchaParameters } from '../../model/public_types';\nimport { getRecaptchaParams } from '../../api/authentication/recaptcha';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport { _isHttpOrHttps } from '../../core/util/location';\nimport { ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport { _isWorker } from '../util/worker';\nimport { Recaptcha } from './recaptcha';\nimport {\n MockReCaptchaLoaderImpl,\n ReCaptchaLoader,\n ReCaptchaLoaderImpl\n} from './recaptcha_loader';\n\nexport const RECAPTCHA_VERIFIER_TYPE = 'recaptcha';\n\nconst DEFAULT_PARAMS: RecaptchaParameters = {\n theme: 'light',\n type: 'image'\n};\n\ntype TokenCallback = (token: string) => void;\n\n/**\n * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.\n *\n * @remarks\n * `RecaptchaVerifier` does not work in a Node.js environment.\n *\n * @public\n */\nexport class RecaptchaVerifier implements ApplicationVerifierInternal {\n /**\n * The application verifier type.\n *\n * @remarks\n * For a reCAPTCHA verifier, this is 'recaptcha'.\n */\n readonly type = RECAPTCHA_VERIFIER_TYPE;\n private destroyed = false;\n private widgetId: number | null = null;\n private readonly container: HTMLElement;\n private readonly isInvisible: boolean;\n private readonly tokenChangeListeners = new Set<TokenCallback>();\n private renderPromise: Promise<number> | null = null;\n private readonly auth: AuthInternal;\n\n /** @internal */\n readonly _recaptchaLoader: ReCaptchaLoader;\n private recaptcha: Recaptcha | null = null;\n\n /**\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\n *\n * @param containerOrId - The reCAPTCHA container parameter.\n *\n * @remarks\n * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a\n * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to\n * an element ID. The corresponding element must also must be in the DOM at the time of\n * initialization.\n *\n * @param parameters - The optional reCAPTCHA parameters.\n *\n * @remarks\n * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for\n * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will\n * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value\n * 'invisible'.\n */\n constructor(\n authExtern: Auth,\n containerOrId: HTMLElement | string,\n private readonly parameters: RecaptchaParameters = {\n ...DEFAULT_PARAMS\n }\n ) {\n this.auth = _castAuth(authExtern);\n this.isInvisible = this.parameters.size === 'invisible';\n _assert(\n typeof document !== 'undefined',\n this.auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n const container =\n typeof containerOrId === 'string'\n ? document.getElementById(containerOrId)\n : containerOrId;\n _assert(container, this.auth, AuthErrorCode.ARGUMENT_ERROR);\n\n this.container = container;\n this.parameters.callback = this.makeTokenCallback(this.parameters.callback);\n\n this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting\n ? new MockReCaptchaLoaderImpl()\n : new ReCaptchaLoaderImpl();\n\n this.validateStartingState();\n // TODO: Figure out if sdk version is needed\n }\n\n /**\n * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.\n *\n * @returns A Promise for the reCAPTCHA token.\n */\n async verify(): Promise<string> {\n this.assertNotDestroyed();\n const id = await this.render();\n const recaptcha = this.getAssertedRecaptcha();\n\n const response = recaptcha.getResponse(id);\n if (response) {\n return response;\n }\n\n return new Promise<string>(resolve => {\n const tokenChange = (token: string): void => {\n if (!token) {\n return; // Ignore token expirations.\n }\n this.tokenChangeListeners.delete(tokenChange);\n resolve(token);\n };\n\n this.tokenChangeListeners.add(tokenChange);\n if (this.isInvisible) {\n recaptcha.execute(id);\n }\n });\n }\n\n /**\n * Renders the reCAPTCHA widget on the page.\n *\n * @returns A Promise that resolves with the reCAPTCHA widget ID.\n */\n render(): Promise<number> {\n try {\n this.assertNotDestroyed();\n } catch (e) {\n // This method returns a promise. Since it's not async (we want to return the\n // _same_ promise if rendering is still occurring), the API surface should\n // reject with the error rather than just throw\n return Promise.reject(e);\n }\n\n if (this.renderPromise) {\n return this.renderPromise;\n }\n\n this.renderPromise = this.makeRenderPromise().catch(e => {\n this.renderPromise = null;\n throw e;\n });\n\n return this.renderPromise;\n }\n\n /** @internal */\n _reset(): void {\n this.assertNotDestroyed();\n if (this.widgetId !== null) {\n this.getAssertedRecaptcha().reset(this.widgetId);\n }\n }\n\n /**\n * Clears the reCAPTCHA widget from the page and destroys the instance.\n */\n clear(): void {\n this.assertNotDestroyed();\n this.destroyed = true;\n this._recaptchaLoader.clearedOneInstance();\n if (!this.isInvisible) {\n this.container.childNodes.forEach(node => {\n this.container.removeChild(node);\n });\n }\n }\n\n private validateStartingState(): void {\n _assert(!this.parameters.sitekey, this.auth, AuthErrorCode.ARGUMENT_ERROR);\n _assert(\n this.isInvisible || !this.container.hasChildNodes(),\n this.auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n typeof document !== 'undefined',\n this.auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n }\n\n private makeTokenCallback(\n existing: TokenCallback | string | undefined\n ): TokenCallback {\n return token => {\n this.tokenChangeListeners.forEach(listener => listener(token));\n if (typeof existing === 'function') {\n existing(token);\n } else if (typeof existing === 'string') {\n const globalFunc = _window()[existing];\n if (typeof globalFunc === 'function') {\n globalFunc(token);\n }\n }\n };\n }\n\n private assertNotDestroyed(): void {\n _assert(!this.destroyed, this.auth, AuthErrorCode.INTERNAL_ERROR);\n }\n\n private async makeRenderPromise(): Promise<number> {\n await this.init();\n if (!this.widgetId) {\n let container = this.container;\n if (!this.isInvisible) {\n const guaranteedEmpty = document.createElement('div');\n container.appendChild(guaranteedEmpty);\n container = guaranteedEmpty;\n }\n\n this.widgetId = this.getAssertedRecaptcha().render(\n container,\n this.parameters\n );\n }\n\n return this.widgetId;\n }\n\n private async init(): Promise<void> {\n _assert(\n _isHttpOrHttps() && !_isWorker(),\n this.auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n\n await domReady();\n this.recaptcha = await this._recaptchaLoader.load(\n this.auth,\n this.auth.languageCode || undefined\n );\n\n const siteKey = await getRecaptchaParams(this.auth);\n _assert(siteKey, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.parameters.sitekey = siteKey;\n }\n\n private getAssertedRecaptcha(): Recaptcha {\n _assert(this.recaptcha, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return this.recaptcha;\n }\n}\n\nfunction domReady(): Promise<void> {\n let resolver: (() => void) | null = null;\n return new Promise<void>(resolve => {\n if (document.readyState === 'complete') {\n resolve();\n return;\n }\n\n // Document not ready, wait for load before resolving.\n // Save resolver, so we can remove listener in case it was externally\n // cancelled.\n resolver = () => resolve();\n window.addEventListener('load', resolver);\n }).catch(e => {\n if (resolver) {\n window.removeEventListener('load', resolver);\n }\n\n throw e;\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ApplicationVerifier,\n Auth,\n ConfirmationResult,\n PhoneInfoOptions,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { startEnrollPhoneMfa } from '../../api/account_management/mfa';\nimport { startSignInPhoneMfa } from '../../api/authentication/mfa';\nimport { sendPhoneVerificationCode } from '../../api/authentication/sms';\nimport { ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { PhoneAuthCredential } from '../../core/credentials/phone';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assertLinkedStatus, _link } from '../../core/user/link_unlink';\nimport { _assert } from '../../core/util/assert';\nimport { AuthInternal } from '../../model/auth';\nimport {\n linkWithCredential,\n reauthenticateWithCredential,\n signInWithCredential\n} from '../../core/strategies/credential';\nimport {\n MultiFactorSessionImpl,\n MultiFactorSessionType\n} from '../../mfa/mfa_session';\nimport { UserInternal } from '../../model/user';\nimport { RECAPTCHA_VERIFIER_TYPE } from '../recaptcha/recaptcha_verifier';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { ProviderId } from '../../model/enums';\n\ninterface OnConfirmationCallback {\n (credential: PhoneAuthCredential): Promise<UserCredential>;\n}\n\nclass ConfirmationResultImpl implements ConfirmationResult {\n constructor(\n readonly verificationId: string,\n private readonly onConfirmation: OnConfirmationCallback\n ) {}\n\n confirm(verificationCode: string): Promise<UserCredential> {\n const authCredential = PhoneAuthCredential._fromVerification(\n this.verificationId,\n verificationCode\n );\n return this.onConfirmation(authCredential);\n }\n}\n\n/**\n * Asynchronously signs in using a phone number.\n *\n * @remarks\n * This method sends a code via SMS to the given\n * phone number, and returns a {@link ConfirmationResult}. After the user\n * provides the code sent to their phone, call {@link ConfirmationResult.confirm}\n * with the code to sign the user in.\n *\n * For abuse prevention, this method also requires a {@link ApplicationVerifier}.\n * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.\n * This function can work on other platforms that do not support the\n * {@link RecaptchaVerifier} (like React Native), but you need to use a\n * third-party {@link ApplicationVerifier} implementation.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain a verificationCode from the user.\n * const credential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function signInWithPhoneNumber(\n auth: Auth,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise<ConfirmationResult> {\n const authInternal = _castAuth(auth);\n const verificationId = await _verifyPhoneNumber(\n authInternal,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n signInWithCredential(authInternal, cred)\n );\n}\n\n/**\n * Links the user account with the given phone number.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function linkWithPhoneNumber(\n user: User,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise<ConfirmationResult> {\n const userInternal = getModularInstance(user) as UserInternal;\n await _assertLinkedStatus(false, userInternal, ProviderId.PHONE);\n const verificationId = await _verifyPhoneNumber(\n userInternal.auth,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n linkWithCredential(userInternal, cred)\n );\n}\n\n/**\n * Re-authenticates a user using a fresh phone credential.\n *\n * @remarks\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.\n *\n * This method does not work in a Node.js environment.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function reauthenticateWithPhoneNumber(\n user: User,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise<ConfirmationResult> {\n const userInternal = getModularInstance(user) as UserInternal;\n const verificationId = await _verifyPhoneNumber(\n userInternal.auth,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n reauthenticateWithCredential(userInternal, cred)\n );\n}\n\n/**\n * Returns a verification ID to be used in conjunction with the SMS code that is sent.\n *\n */\nexport async function _verifyPhoneNumber(\n auth: AuthInternal,\n options: PhoneInfoOptions | string,\n verifier: ApplicationVerifierInternal\n): Promise<string> {\n const recaptchaToken = await verifier.verify();\n\n try {\n _assert(\n typeof recaptchaToken === 'string',\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n verifier.type === RECAPTCHA_VERIFIER_TYPE,\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n\n let phoneInfoOptions: PhoneInfoOptions;\n\n if (typeof options === 'string') {\n phoneInfoOptions = {\n phoneNumber: options\n };\n } else {\n phoneInfoOptions = options;\n }\n\n if ('session' in phoneInfoOptions) {\n const session = phoneInfoOptions.session as MultiFactorSessionImpl;\n\n if ('phoneNumber' in phoneInfoOptions) {\n _assert(\n session.type === MultiFactorSessionType.ENROLL,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const response = await startEnrollPhoneMfa(auth, {\n idToken: session.credential,\n phoneEnrollmentInfo: {\n phoneNumber: phoneInfoOptions.phoneNumber,\n recaptchaToken\n }\n });\n return response.phoneSessionInfo.sessionInfo;\n } else {\n _assert(\n session.type === MultiFactorSessionType.SIGN_IN,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const mfaEnrollmentId =\n phoneInfoOptions.multiFactorHint?.uid ||\n phoneInfoOptions.multiFactorUid;\n _assert(mfaEnrollmentId, auth, AuthErrorCode.MISSING_MFA_INFO);\n const response = await startSignInPhoneMfa(auth, {\n mfaPendingCredential: session.credential,\n mfaEnrollmentId,\n phoneSignInInfo: {\n recaptchaToken\n }\n });\n return response.phoneResponseInfo.sessionInfo;\n }\n } else {\n const { sessionInfo } = await sendPhoneVerificationCode(auth, {\n phoneNumber: phoneInfoOptions.phoneNumber,\n recaptchaToken\n });\n return sessionInfo;\n }\n } finally {\n verifier._reset();\n }\n}\n\n/**\n * Updates the user's phone number.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * await updatePhoneNumber(user, phoneCredential);\n * ```\n *\n * @param user - The user.\n * @param credential - A credential authenticating the new phone number.\n *\n * @public\n */\nexport async function updatePhoneNumber(\n user: User,\n credential: PhoneAuthCredential\n): Promise<void> {\n await _link(getModularInstance(user) as UserInternal, credential);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { SignInWithPhoneNumberRequest } from '../authentication/sms';\nimport { FinalizeMfaResponse } from '../authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\n\n/**\n * MFA Info as returned by the API.\n */\ninterface BaseMfaEnrollment {\n mfaEnrollmentId: string;\n enrolledAt: number;\n displayName?: string;\n}\n\n/**\n * An MFA provided by SMS verification.\n */\nexport interface PhoneMfaEnrollment extends BaseMfaEnrollment {\n phoneInfo: string;\n}\n\n/**\n * An MFA provided by TOTP (Time-based One Time Password).\n */\nexport interface TotpMfaEnrollment extends BaseMfaEnrollment {}\n\n/**\n * MfaEnrollment can be any subtype of BaseMfaEnrollment, currently only PhoneMfaEnrollment and TotpMfaEnrollment are supported.\n */\nexport type MfaEnrollment = PhoneMfaEnrollment | TotpMfaEnrollment;\n\nexport interface StartPhoneMfaEnrollmentRequest {\n idToken: string;\n phoneEnrollmentInfo: {\n phoneNumber: string;\n recaptchaToken: string;\n };\n tenantId?: string;\n}\n\nexport interface StartPhoneMfaEnrollmentResponse {\n phoneSessionInfo: {\n sessionInfo: string;\n };\n}\n\nexport function startEnrollPhoneMfa(\n auth: AuthInternal,\n request: StartPhoneMfaEnrollmentRequest\n): Promise<StartPhoneMfaEnrollmentResponse> {\n return _performApiRequest<\n StartPhoneMfaEnrollmentRequest,\n StartPhoneMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface FinalizePhoneMfaEnrollmentRequest {\n idToken: string;\n phoneVerificationInfo: SignInWithPhoneNumberRequest;\n displayName?: string | null;\n tenantId?: string;\n}\n\nexport interface FinalizePhoneMfaEnrollmentResponse\n extends FinalizeMfaResponse {}\n\nexport function finalizeEnrollPhoneMfa(\n auth: AuthInternal,\n request: FinalizePhoneMfaEnrollmentRequest\n): Promise<FinalizePhoneMfaEnrollmentResponse> {\n return _performApiRequest<\n FinalizePhoneMfaEnrollmentRequest,\n FinalizePhoneMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\nexport interface StartTotpMfaEnrollmentRequest {\n idToken: string;\n totpEnrollmentInfo: {};\n tenantId?: string;\n}\n\nexport interface StartTotpMfaEnrollmentResponse {\n totpSessionInfo: {\n sharedSecretKey: string;\n verificationCodeLength: number;\n hashingAlgorithm: string;\n periodSec: number;\n sessionInfo: string;\n finalizeEnrollmentTime: number;\n };\n}\n\nexport function startEnrollTotpMfa(\n auth: AuthInternal,\n request: StartTotpMfaEnrollmentRequest\n): Promise<StartTotpMfaEnrollmentResponse> {\n return _performApiRequest<\n StartTotpMfaEnrollmentRequest,\n StartTotpMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface TotpVerificationInfo {\n sessionInfo: string;\n verificationCode: string;\n}\nexport interface FinalizeTotpMfaEnrollmentRequest {\n idToken: string;\n totpVerificationInfo: TotpVerificationInfo;\n displayName?: string | null;\n tenantId?: string;\n}\n\nexport interface FinalizeTotpMfaEnrollmentResponse\n extends FinalizeMfaResponse {}\n\nexport function finalizeEnrollTotpMfa(\n auth: AuthInternal,\n request: FinalizeTotpMfaEnrollmentRequest\n): Promise<FinalizeTotpMfaEnrollmentResponse> {\n return _performApiRequest<\n FinalizeTotpMfaEnrollmentRequest,\n FinalizeTotpMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface WithdrawMfaRequest {\n idToken: string;\n mfaEnrollmentId: string;\n tenantId?: string;\n}\n\nexport interface WithdrawMfaResponse extends FinalizeMfaResponse {}\n\nexport function withdrawMfa(\n auth: AuthInternal,\n request: WithdrawMfaRequest\n): Promise<WithdrawMfaResponse> {\n return _performApiRequest<WithdrawMfaRequest, WithdrawMfaResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.WITHDRAW_MFA,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _performApiRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { MfaEnrollment } from '../account_management/mfa';\nimport { SignInWithIdpResponse } from './idp';\nimport {\n SignInWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n} from './sms';\n\nexport interface FinalizeMfaResponse {\n idToken: string;\n refreshToken: string;\n}\n\n/**\n * @internal\n */\nexport interface IdTokenMfaResponse extends IdTokenResponse {\n mfaPendingCredential?: string;\n mfaInfo?: MfaEnrollment[];\n}\n\nexport interface StartPhoneMfaSignInRequest {\n mfaPendingCredential: string;\n mfaEnrollmentId: string;\n phoneSignInInfo: {\n recaptchaToken: string;\n };\n tenantId?: string;\n}\n\nexport interface StartPhoneMfaSignInResponse {\n phoneResponseInfo: {\n sessionInfo: string;\n };\n}\n\nexport function startSignInPhoneMfa(\n auth: Auth,\n request: StartPhoneMfaSignInRequest\n): Promise<StartPhoneMfaSignInResponse> {\n return _performApiRequest<\n StartPhoneMfaSignInRequest,\n StartPhoneMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface FinalizePhoneMfaSignInRequest {\n mfaPendingCredential: string;\n phoneVerificationInfo: SignInWithPhoneNumberRequest;\n tenantId?: string;\n}\n\n// TOTP MFA Sign in only has a finalize phase. Phone MFA has a start phase to initiate sending an\n// SMS and a finalize phase to complete sign in. With TOTP, the user already has the OTP in the\n// TOTP/Authenticator app.\nexport interface FinalizeTotpMfaSignInRequest {\n mfaPendingCredential: string;\n totpVerificationInfo: { verificationCode: string };\n tenantId?: string;\n mfaEnrollmentId: string;\n}\n\nexport interface FinalizePhoneMfaSignInResponse extends FinalizeMfaResponse {}\n\nexport interface FinalizeTotpMfaSignInResponse extends FinalizeMfaResponse {}\n\nexport function finalizeSignInPhoneMfa(\n auth: Auth,\n request: FinalizePhoneMfaSignInRequest\n): Promise<FinalizePhoneMfaSignInResponse> {\n return _performApiRequest<\n FinalizePhoneMfaSignInRequest,\n FinalizePhoneMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport function finalizeSignInTotpMfa(\n auth: Auth,\n request: FinalizeTotpMfaSignInRequest\n): Promise<FinalizeTotpMfaSignInResponse> {\n return _performApiRequest<\n FinalizeTotpMfaSignInRequest,\n FinalizeTotpMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\n/**\n * @internal\n */\nexport type PhoneOrOauthTokenResponse =\n | SignInWithPhoneNumberResponse\n | SignInWithIdpResponse\n | IdTokenResponse;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n PhoneInfoOptions,\n ApplicationVerifier,\n UserCredential\n} from '../../model/public_types';\n\nimport { SignInWithPhoneNumberResponse } from '../../api/authentication/sms';\nimport { ApplicationVerifierInternal as ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { AuthInternal as AuthInternal } from '../../model/auth';\nimport { UserCredentialInternal as UserCredentialInternal } from '../../model/user';\nimport { PhoneAuthCredential } from '../../core/credentials/phone';\nimport { _verifyPhoneNumber } from '../strategies/phone';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthCredential } from '../../core';\nimport { FirebaseError, getModularInstance } from '@firebase/util';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link PhoneAuthCredential}.\n *\n * @remarks\n * `PhoneAuthProvider` does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, phoneCredential);\n * ```\n *\n * @public\n */\nexport class PhoneAuthProvider {\n /** Always set to {@link ProviderId}.PHONE. */\n static readonly PROVIDER_ID: 'phone' = ProviderId.PHONE;\n /** Always set to {@link SignInMethod}.PHONE. */\n static readonly PHONE_SIGN_IN_METHOD: 'phone' = SignInMethod.PHONE;\n\n /** Always set to {@link ProviderId}.PHONE. */\n readonly providerId = PhoneAuthProvider.PROVIDER_ID;\n private readonly auth: AuthInternal;\n\n /**\n * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.\n *\n */\n constructor(auth: Auth) {\n this.auth = _castAuth(auth);\n }\n\n /**\n *\n * Starts a phone number authentication flow by sending a verification code to the given phone\n * number.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in\n * E.164 format (e.g. +16505550101).\n * @param applicationVerifier - For abuse prevention, this method also requires a\n * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,\n * {@link RecaptchaVerifier}.\n *\n * @returns A Promise for a verification ID that can be passed to\n * {@link PhoneAuthProvider.credential} to identify this flow..\n */\n verifyPhoneNumber(\n phoneOptions: PhoneInfoOptions | string,\n applicationVerifier: ApplicationVerifier\n ): Promise<string> {\n return _verifyPhoneNumber(\n this.auth,\n phoneOptions,\n getModularInstance(applicationVerifier as ApplicationVerifierInternal)\n );\n }\n\n /**\n * Creates a phone auth credential, given the verification ID from\n * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's\n * mobile device.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.\n * @param verificationCode - The verification code sent to the user's mobile device.\n *\n * @returns The auth provider credential.\n */\n static credential(\n verificationId: string,\n verificationCode: string\n ): PhoneAuthCredential {\n return PhoneAuthCredential._fromVerification(\n verificationId,\n verificationCode\n );\n }\n\n /**\n * Generates an {@link AuthCredential} from a {@link UserCredential}.\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): AuthCredential | null {\n const credential = userCredential as UserCredentialInternal;\n return PhoneAuthProvider.credentialFromTaggedObject(credential);\n }\n\n /**\n * Returns an {@link AuthCredential} when passed an error.\n *\n * @remarks\n *\n * This method works for errors like\n * `auth/account-exists-with-different-credentials`. This is useful for\n * recovering when attempting to set a user's phone number but the number\n * in question is already tied to another account. For example, the following\n * code tries to update the current user's phone number, and if that\n * fails, links the user with the account associated with that number:\n *\n * ```js\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(number, verifier);\n * try {\n * const code = ''; // Prompt the user for the verification code\n * await updatePhoneNumber(\n * auth.currentUser,\n * PhoneAuthProvider.credential(verificationId, code));\n * } catch (e) {\n * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {\n * const cred = PhoneAuthProvider.credentialFromError(e);\n * await linkWithCredential(auth.currentUser, cred);\n * }\n * }\n *\n * // At this point, auth.currentUser.phoneNumber === number.\n * ```\n *\n * @param error - The error to generate a credential from.\n */\n static credentialFromError(error: FirebaseError): AuthCredential | null {\n return PhoneAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): AuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n const { phoneNumber, temporaryProof } =\n tokenResponse as SignInWithPhoneNumberResponse;\n if (phoneNumber && temporaryProof) {\n return PhoneAuthCredential._fromTokenResponse(\n phoneNumber,\n temporaryProof\n );\n }\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PopupRedirectResolver } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\nimport { PopupRedirectResolverInternal } from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from './assert';\nimport { _getInstance } from './instantiator';\n\n/**\n * Chooses a popup/redirect resolver to use. This prefers the override (which\n * is directly passed in), and falls back to the property set on the auth\n * object. If neither are available, this function errors w/ an argument error.\n */\nexport function _withDefaultResolver(\n auth: AuthInternal,\n resolverOverride: PopupRedirectResolver | undefined\n): PopupRedirectResolverInternal {\n if (resolverOverride) {\n return _getInstance(resolverOverride);\n }\n\n _assert(auth._popupRedirectResolver, auth, AuthErrorCode.ARGUMENT_ERROR);\n\n return auth._popupRedirectResolver;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { _link as _linkUser } from '../user/link_unlink';\nimport { _reauthenticate } from '../user/reauthenticate';\nimport { _assert } from '../util/assert';\nimport { _signInWithCredential } from './credential';\nimport { AuthErrorCode } from '../errors';\nimport { ProviderId } from '../../model/enums';\n\nexport interface IdpTaskParams {\n auth: AuthInternal;\n requestUri: string;\n sessionId?: string;\n tenantId?: string;\n postBody?: string;\n pendingToken?: string;\n user?: UserInternal;\n bypassAuthState?: boolean;\n}\n\nexport type IdpTask = (\n params: IdpTaskParams\n) => Promise<UserCredentialInternal>;\n\nclass IdpCredential extends AuthCredential {\n constructor(readonly params: IdpTaskParams) {\n super(ProviderId.CUSTOM, ProviderId.CUSTOM);\n }\n\n _getIdTokenResponse(auth: AuthInternal): Promise<PhoneOrOauthTokenResponse> {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n return signInWithIdp(auth, this._buildIdpRequest(idToken));\n }\n\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n\n private _buildIdpRequest(idToken?: string): SignInWithIdpRequest {\n const request: SignInWithIdpRequest = {\n requestUri: this.params.requestUri,\n sessionId: this.params.sessionId,\n postBody: this.params.postBody,\n tenantId: this.params.tenantId,\n pendingToken: this.params.pendingToken,\n returnSecureToken: true,\n returnIdpCredential: true\n };\n\n if (idToken) {\n request.idToken = idToken;\n }\n\n return request;\n }\n}\n\nexport function _signIn(\n params: IdpTaskParams\n): Promise<UserCredentialInternal> {\n return _signInWithCredential(\n params.auth,\n new IdpCredential(params),\n params.bypassAuthState\n ) as Promise<UserCredentialInternal>;\n}\n\nexport function _reauth(\n params: IdpTaskParams\n): Promise<UserCredentialInternal> {\n const { auth, user } = params;\n _assert(user, auth, AuthErrorCode.INTERNAL_ERROR);\n return _reauthenticate(\n user,\n new IdpCredential(params),\n params.bypassAuthState\n );\n}\n\nexport async function _link(\n params: IdpTaskParams\n): Promise<UserCredentialInternal> {\n const { auth, user } = params;\n _assert(user, auth, AuthErrorCode.INTERNAL_ERROR);\n return _linkUser(user, new IdpCredential(params), params.bypassAuthState);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\nimport {\n AuthEvent,\n AuthEventConsumer,\n AuthEventType,\n EventManager,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { debugAssert, _fail } from '../util/assert';\nimport {\n _link,\n _reauth,\n _signIn,\n IdpTask,\n IdpTaskParams\n} from '../strategies/idp';\nimport { AuthInternal } from '../../model/auth';\n\ninterface PendingPromise {\n resolve: (cred: UserCredentialInternal | null) => void;\n reject: (error: Error) => void;\n}\n\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n */\nexport abstract class AbstractPopupRedirectOperation\n implements AuthEventConsumer\n{\n private pendingPromise: PendingPromise | null = null;\n private eventManager: EventManager | null = null;\n readonly filter: AuthEventType[];\n\n abstract eventId: string | null;\n\n constructor(\n protected readonly auth: AuthInternal,\n filter: AuthEventType | AuthEventType[],\n protected readonly resolver: PopupRedirectResolverInternal,\n protected user?: UserInternal,\n protected readonly bypassAuthState = false\n ) {\n this.filter = Array.isArray(filter) ? filter : [filter];\n }\n\n abstract onExecution(): Promise<void>;\n\n execute(): Promise<UserCredentialInternal | null> {\n return new Promise<UserCredentialInternal | null>(\n async (resolve, reject) => {\n this.pendingPromise = { resolve, reject };\n\n try {\n this.eventManager = await this.resolver._initialize(this.auth);\n await this.onExecution();\n this.eventManager.registerConsumer(this);\n } catch (e) {\n this.reject(e as Error);\n }\n }\n );\n }\n\n async onAuthEvent(event: AuthEvent): Promise<void> {\n const { urlResponse, sessionId, postBody, tenantId, error, type } = event;\n if (error) {\n this.reject(error);\n return;\n }\n\n const params: IdpTaskParams = {\n auth: this.auth,\n requestUri: urlResponse!,\n sessionId: sessionId!,\n tenantId: tenantId || undefined,\n postBody: postBody || undefined,\n user: this.user,\n bypassAuthState: this.bypassAuthState\n };\n\n try {\n this.resolve(await this.getIdpTask(type)(params));\n } catch (e) {\n this.reject(e as Error);\n }\n }\n\n onError(error: FirebaseError): void {\n this.reject(error);\n }\n\n private getIdpTask(type: AuthEventType): IdpTask {\n switch (type) {\n case AuthEventType.SIGN_IN_VIA_POPUP:\n case AuthEventType.SIGN_IN_VIA_REDIRECT:\n return _signIn;\n case AuthEventType.LINK_VIA_POPUP:\n case AuthEventType.LINK_VIA_REDIRECT:\n return _link;\n case AuthEventType.REAUTH_VIA_POPUP:\n case AuthEventType.REAUTH_VIA_REDIRECT:\n return _reauth;\n default:\n _fail(this.auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n protected resolve(cred: UserCredentialInternal | null): void {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.resolve(cred);\n this.unregisterAndCleanUp();\n }\n\n protected reject(error: Error): void {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.reject(error);\n this.unregisterAndCleanUp();\n }\n\n private unregisterAndCleanUp(): void {\n if (this.eventManager) {\n this.eventManager.unregisterConsumer(this);\n }\n\n this.pendingPromise = null;\n this.cleanUp();\n }\n\n abstract cleanUp(): void;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n AuthProvider,\n PopupRedirectResolver,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthErrorCode } from '../../core/errors';\nimport {\n _assert,\n debugAssert,\n _createError,\n _assertInstanceOf\n} from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { _generateEventId } from '../../core/util/event_id';\nimport { AuthInternal } from '../../model/auth';\nimport {\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport { _withDefaultResolver } from '../../core/util/resolver';\nimport { AuthPopup } from '../util/popup';\nimport { AbstractPopupRedirectOperation } from '../../core/strategies/abstract_popup_redirect_operation';\nimport { FederatedAuthProvider } from '../../core/providers/federated';\nimport { getModularInstance } from '@firebase/util';\n\n/*\n * The event timeout is the same on mobile and desktop, no need for Delay. Set this to 8s since\n * blocking functions can take upto 7s to complete sign in, as documented in:\n * https://cloud.google.com/identity-platform/docs/blocking-functions#understanding_blocking_functions\n * https://firebase.google.com/docs/auth/extend-with-blocking-functions#understanding_blocking_functions\n */\nexport const enum _Timeout {\n AUTH_EVENT = 8000\n}\nexport const _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);\n\n/**\n * Authenticates a Firebase client using a popup-based OAuth authentication flow.\n *\n * @remarks\n * If succeeds, returns the signed in user along with the provider's credential. If sign in was\n * unsuccessful, returns an error object containing additional information about the error.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function signInWithPopup(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<UserCredential> {\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n const action = new PopupOperation(\n authInternal,\n AuthEventType.SIGN_IN_VIA_POPUP,\n provider,\n resolverInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based\n * OAuth flow.\n *\n * @remarks\n * If the reauthentication is successful, the returned result will contain the user and the\n * provider's credential.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n * // Reauthenticate using a popup.\n * await reauthenticateWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function reauthenticateWithPopup(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<UserCredential> {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n const action = new PopupOperation(\n userInternal.auth,\n AuthEventType.REAUTH_VIA_POPUP,\n provider,\n resolverInternal,\n userInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Links the authenticated provider to the user account using a pop-up based OAuth flow.\n *\n * @remarks\n * If the linking is successful, the returned result will contain the user and the provider's credential.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a popup.\n * const provider = new FacebookAuthProvider();\n * await linkWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function linkWithPopup(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<UserCredential> {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n\n const action = new PopupOperation(\n userInternal.auth,\n AuthEventType.LINK_VIA_POPUP,\n provider,\n resolverInternal,\n userInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n *\n */\nclass PopupOperation extends AbstractPopupRedirectOperation {\n // Only one popup is ever shown at once. The lifecycle of the current popup\n // can be managed / cancelled by the constructor.\n private static currentPopupAction: PopupOperation | null = null;\n private authWindow: AuthPopup | null = null;\n private pollId: number | null = null;\n\n constructor(\n auth: AuthInternal,\n filter: AuthEventType,\n private readonly provider: AuthProvider,\n resolver: PopupRedirectResolverInternal,\n user?: UserInternal\n ) {\n super(auth, filter, resolver, user);\n if (PopupOperation.currentPopupAction) {\n PopupOperation.currentPopupAction.cancel();\n }\n\n PopupOperation.currentPopupAction = this;\n }\n\n async executeNotNull(): Promise<UserCredential> {\n const result = await this.execute();\n _assert(result, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return result;\n }\n\n async onExecution(): Promise<void> {\n debugAssert(\n this.filter.length === 1,\n 'Popup operations only handle one event'\n );\n const eventId = _generateEventId();\n this.authWindow = await this.resolver._openPopup(\n this.auth,\n this.provider,\n this.filter[0], // There's always one, see constructor\n eventId\n );\n this.authWindow.associatedEvent = eventId;\n\n // Check for web storage support and origin validation _after_ the popup is\n // loaded. These operations are slow (~1 second or so) Rather than\n // waiting on them before opening the window, optimistically open the popup\n // and check for storage support at the same time. If storage support is\n // not available, this will cause the whole thing to reject properly. It\n // will also close the popup, but since the promise has already rejected,\n // the popup closed by user poll will reject into the void.\n this.resolver._originValidation(this.auth).catch(e => {\n this.reject(e);\n });\n\n this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {\n if (!isSupported) {\n this.reject(\n _createError(this.auth, AuthErrorCode.WEB_STORAGE_UNSUPPORTED)\n );\n }\n });\n\n // Handle user closure. Notice this does *not* use await\n this.pollUserCancellation();\n }\n\n get eventId(): string | null {\n return this.authWindow?.associatedEvent || null;\n }\n\n cancel(): void {\n this.reject(_createError(this.auth, AuthErrorCode.EXPIRED_POPUP_REQUEST));\n }\n\n cleanUp(): void {\n if (this.authWindow) {\n this.authWindow.close();\n }\n\n if (this.pollId) {\n window.clearTimeout(this.pollId);\n }\n\n this.authWindow = null;\n this.pollId = null;\n PopupOperation.currentPopupAction = null;\n }\n\n private pollUserCancellation(): void {\n const poll = (): void => {\n if (this.authWindow?.window?.closed) {\n // Make sure that there is sufficient time for whatever action to\n // complete. The window could have closed but the sign in network\n // call could still be in flight. This is specifically true for\n // Firefox or if the opener is in an iframe, in which case the oauth\n // helper closes the popup.\n this.pollId = window.setTimeout(() => {\n this.pollId = null;\n this.reject(\n _createError(this.auth, AuthErrorCode.POPUP_CLOSED_BY_USER)\n );\n }, _Timeout.AUTH_EVENT);\n return;\n }\n\n this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());\n };\n\n poll();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthInternal } from '../../model/auth';\nimport {\n AuthEvent,\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserCredentialInternal } from '../../model/user';\nimport { PersistenceInternal } from '../persistence';\nimport { _persistenceKeyName } from '../persistence/persistence_user_manager';\nimport { _getInstance } from '../util/instantiator';\nimport { AbstractPopupRedirectOperation } from './abstract_popup_redirect_operation';\n\nconst PENDING_REDIRECT_KEY = 'pendingRedirect';\n\n// We only get one redirect outcome for any one auth, so just store it\n// in here.\nconst redirectOutcomeMap: Map<\n string,\n () => Promise<UserCredentialInternal | null>\n> = new Map();\n\nexport class RedirectAction extends AbstractPopupRedirectOperation {\n eventId = null;\n\n constructor(\n auth: AuthInternal,\n resolver: PopupRedirectResolverInternal,\n bypassAuthState = false\n ) {\n super(\n auth,\n [\n AuthEventType.SIGN_IN_VIA_REDIRECT,\n AuthEventType.LINK_VIA_REDIRECT,\n AuthEventType.REAUTH_VIA_REDIRECT,\n AuthEventType.UNKNOWN\n ],\n resolver,\n undefined,\n bypassAuthState\n );\n }\n\n /**\n * Override the execute function; if we already have a redirect result, then\n * just return it.\n */\n async execute(): Promise<UserCredentialInternal | null> {\n let readyOutcome = redirectOutcomeMap.get(this.auth._key());\n if (!readyOutcome) {\n try {\n const hasPendingRedirect = await _getAndClearPendingRedirectStatus(\n this.resolver,\n this.auth\n );\n const result = hasPendingRedirect ? await super.execute() : null;\n readyOutcome = () => Promise.resolve(result);\n } catch (e) {\n readyOutcome = () => Promise.reject(e);\n }\n\n redirectOutcomeMap.set(this.auth._key(), readyOutcome);\n }\n\n // If we're not bypassing auth state, the ready outcome should be set to\n // null.\n if (!this.bypassAuthState) {\n redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));\n }\n\n return readyOutcome();\n }\n\n async onAuthEvent(event: AuthEvent): Promise<void> {\n if (event.type === AuthEventType.SIGN_IN_VIA_REDIRECT) {\n return super.onAuthEvent(event);\n } else if (event.type === AuthEventType.UNKNOWN) {\n // This is a sentinel value indicating there's no pending redirect\n this.resolve(null);\n return;\n }\n\n if (event.eventId) {\n const user = await this.auth._redirectUserForId(event.eventId);\n if (user) {\n this.user = user;\n return super.onAuthEvent(event);\n } else {\n this.resolve(null);\n }\n }\n }\n\n async onExecution(): Promise<void> {}\n\n cleanUp(): void {}\n}\n\nexport async function _getAndClearPendingRedirectStatus(\n resolver: PopupRedirectResolverInternal,\n auth: AuthInternal\n): Promise<boolean> {\n const key = pendingRedirectKey(auth);\n const persistence = resolverPersistence(resolver);\n if (!(await persistence._isAvailable())) {\n return false;\n }\n const hasPendingRedirect = (await persistence._get(key)) === 'true';\n await persistence._remove(key);\n return hasPendingRedirect;\n}\n\nexport async function _setPendingRedirectStatus(\n resolver: PopupRedirectResolverInternal,\n auth: AuthInternal\n): Promise<void> {\n return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');\n}\n\nexport function _clearRedirectOutcomes(): void {\n redirectOutcomeMap.clear();\n}\n\nexport function _overrideRedirectResult(\n auth: AuthInternal,\n result: () => Promise<UserCredentialInternal | null>\n): void {\n redirectOutcomeMap.set(auth._key(), result);\n}\n\nfunction resolverPersistence(\n resolver: PopupRedirectResolverInternal\n): PersistenceInternal {\n return _getInstance(resolver._redirectPersistence);\n}\n\nfunction pendingRedirectKey(auth: AuthInternal): string {\n return _persistenceKeyName(\n PENDING_REDIRECT_KEY,\n auth.config.apiKey,\n auth.name\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n AuthProvider,\n PopupRedirectResolver,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { _assertLinkedStatus } from '../../core/user/link_unlink';\nimport { _assertInstanceOf } from '../../core/util/assert';\nimport { _generateEventId } from '../../core/util/event_id';\nimport { AuthEventType } from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport { _withDefaultResolver } from '../../core/util/resolver';\nimport {\n RedirectAction,\n _setPendingRedirectStatus\n} from '../../core/strategies/redirect';\nimport { FederatedAuthProvider } from '../../core/providers/federated';\nimport { getModularInstance } from '@firebase/util';\n\n/**\n * Authenticates a Firebase client using a full-page redirect flow.\n *\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link signInWithRedirect}.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function signInWithRedirect(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<never> {\n return _signInWithRedirect(auth, provider, resolver) as Promise<never>;\n}\n\nexport async function _signInWithRedirect(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<void | never> {\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await authInternal._initializationPromise;\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n await _setPendingRedirectStatus(resolverInternal, authInternal);\n\n return resolverInternal._openRedirect(\n authInternal,\n provider,\n AuthEventType.SIGN_IN_VIA_REDIRECT\n );\n}\n\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link reauthenticateWithRedirect}.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * // Reauthenticate using a redirect.\n * await reauthenticateWithRedirect(result.user, provider);\n * // This will again trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function reauthenticateWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<never> {\n return _reauthenticateWithRedirect(\n user,\n provider,\n resolver\n ) as Promise<never>;\n}\nexport async function _reauthenticateWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<void | never> {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await userInternal.auth._initializationPromise;\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(\n userInternal.auth,\n provider,\n AuthEventType.REAUTH_VIA_REDIRECT,\n eventId\n );\n}\n\n/**\n * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link linkWithRedirect}.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a redirect.\n * const provider = new FacebookAuthProvider();\n * await linkWithRedirect(result.user, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function linkWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<never> {\n return _linkWithRedirect(user, provider, resolver) as Promise<never>;\n}\nexport async function _linkWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<void | never> {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await userInternal.auth._initializationPromise;\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _assertLinkedStatus(false, userInternal, provider.providerId);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(\n userInternal.auth,\n provider,\n AuthEventType.LINK_VIA_REDIRECT,\n eventId\n );\n}\n\n/**\n * Returns a {@link UserCredential} from the redirect-based sign-in flow.\n *\n * @remarks\n * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an\n * error. If no redirect operation was called, returns `null`.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function getRedirectResult(\n auth: Auth,\n resolver?: PopupRedirectResolver\n): Promise<UserCredential | null> {\n await _castAuth(auth)._initializationPromise;\n return _getRedirectResult(auth, resolver, false);\n}\n\nexport async function _getRedirectResult(\n auth: Auth,\n resolverExtern?: PopupRedirectResolver,\n bypassAuthState = false\n): Promise<UserCredential | null> {\n const authInternal = _castAuth(auth);\n const resolver = _withDefaultResolver(authInternal, resolverExtern);\n const action = new RedirectAction(authInternal, resolver, bypassAuthState);\n const result = await action.execute();\n\n if (result && !bypassAuthState) {\n delete result.user._redirectEventId;\n await authInternal._persistUserIfCurrent(result.user as UserInternal);\n await authInternal._setRedirectUser(null, resolverExtern);\n }\n\n return result;\n}\n\nasync function prepareUserForRedirect(user: UserInternal): Promise<string> {\n const eventId = _generateEventId(`${user.uid}:::`);\n user._redirectEventId = eventId;\n await user.auth._setRedirectUser(user);\n await user.auth._persistUserIfCurrent(user);\n return eventId;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AuthEvent,\n AuthEventConsumer,\n AuthEventType,\n EventManager\n} from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { AuthInternal } from '../../model/auth';\nimport { _createError } from '../util/assert';\n\n// The amount of time to store the UIDs of seen events; this is\n// set to 10 min by default\nconst EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;\n\nexport class AuthEventManager implements EventManager {\n private readonly cachedEventUids: Set<string> = new Set();\n private readonly consumers: Set<AuthEventConsumer> = new Set();\n protected queuedRedirectEvent: AuthEvent | null = null;\n protected hasHandledPotentialRedirect = false;\n private lastProcessedEventTime = Date.now();\n\n constructor(private readonly auth: AuthInternal) {}\n\n registerConsumer(authEventConsumer: AuthEventConsumer): void {\n this.consumers.add(authEventConsumer);\n\n if (\n this.queuedRedirectEvent &&\n this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)\n ) {\n this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);\n this.saveEventToCache(this.queuedRedirectEvent);\n this.queuedRedirectEvent = null;\n }\n }\n\n unregisterConsumer(authEventConsumer: AuthEventConsumer): void {\n this.consumers.delete(authEventConsumer);\n }\n\n onEvent(event: AuthEvent): boolean {\n // Check if the event has already been handled\n if (this.hasEventBeenHandled(event)) {\n return false;\n }\n\n let handled = false;\n this.consumers.forEach(consumer => {\n if (this.isEventForConsumer(event, consumer)) {\n handled = true;\n this.sendToConsumer(event, consumer);\n this.saveEventToCache(event);\n }\n });\n\n if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {\n // If we've already seen a redirect before, or this is a popup event,\n // bail now\n return handled;\n }\n\n this.hasHandledPotentialRedirect = true;\n\n // If the redirect wasn't handled, hang on to it\n if (!handled) {\n this.queuedRedirectEvent = event;\n handled = true;\n }\n\n return handled;\n }\n\n private sendToConsumer(event: AuthEvent, consumer: AuthEventConsumer): void {\n if (event.error && !isNullRedirectEvent(event)) {\n const code =\n (event.error.code?.split('auth/')[1] as AuthErrorCode) ||\n AuthErrorCode.INTERNAL_ERROR;\n consumer.onError(_createError(this.auth, code));\n } else {\n consumer.onAuthEvent(event);\n }\n }\n\n private isEventForConsumer(\n event: AuthEvent,\n consumer: AuthEventConsumer\n ): boolean {\n const eventIdMatches =\n consumer.eventId === null ||\n (!!event.eventId && event.eventId === consumer.eventId);\n return consumer.filter.includes(event.type) && eventIdMatches;\n }\n\n private hasEventBeenHandled(event: AuthEvent): boolean {\n if (\n Date.now() - this.lastProcessedEventTime >=\n EVENT_DUPLICATION_CACHE_DURATION_MS\n ) {\n this.cachedEventUids.clear();\n }\n\n return this.cachedEventUids.has(eventUid(event));\n }\n\n private saveEventToCache(event: AuthEvent): void {\n this.cachedEventUids.add(eventUid(event));\n this.lastProcessedEventTime = Date.now();\n }\n}\n\nfunction eventUid(e: AuthEvent): string {\n return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');\n}\n\nfunction isNullRedirectEvent({ type, error }: AuthEvent): boolean {\n return (\n type === AuthEventType.UNKNOWN &&\n error?.code === `auth/${AuthErrorCode.NO_AUTH_EVENT}`\n );\n}\n\nfunction isRedirectEvent(event: AuthEvent): boolean {\n switch (event.type) {\n case AuthEventType.SIGN_IN_VIA_REDIRECT:\n case AuthEventType.LINK_VIA_REDIRECT:\n case AuthEventType.REAUTH_VIA_REDIRECT:\n return true;\n case AuthEventType.UNKNOWN:\n return isNullRedirectEvent(event);\n default:\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProjectConfig } from '../../api/project_config/get_project_config';\nimport { AuthInternal } from '../../model/auth';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from './assert';\nimport { _getCurrentUrl } from './location';\n\nconst IP_ADDRESS_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\nconst HTTP_REGEX = /^https?/;\n\nexport async function _validateOrigin(auth: AuthInternal): Promise<void> {\n // Skip origin validation if we are in an emulated environment\n if (auth.config.emulator) {\n return;\n }\n\n const { authorizedDomains } = await _getProjectConfig(auth);\n\n for (const domain of authorizedDomains) {\n try {\n if (matchDomain(domain)) {\n return;\n }\n } catch {\n // Do nothing if there's a URL error; just continue searching\n }\n }\n\n // In the old SDK, this error also provides helpful messages.\n _fail(auth, AuthErrorCode.INVALID_ORIGIN);\n}\n\nfunction matchDomain(expected: string): boolean {\n const currentUrl = _getCurrentUrl();\n const { protocol, hostname } = new URL(currentUrl);\n if (expected.startsWith('chrome-extension://')) {\n const ceUrl = new URL(expected);\n\n if (ceUrl.hostname === '' && hostname === '') {\n // For some reason we're not parsing chrome URLs properly\n return (\n protocol === 'chrome-extension:' &&\n expected.replace('chrome-extension://', '') ===\n currentUrl.replace('chrome-extension://', '')\n );\n }\n\n return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;\n }\n\n if (!HTTP_REGEX.test(protocol)) {\n return false;\n }\n\n if (IP_ADDRESS_REGEX.test(expected)) {\n // The domain has to be exactly equal to the pattern, as an IP domain will\n // only contain the IP, no extra character.\n return hostname === expected;\n }\n\n // Dots in pattern should be escaped.\n const escapedDomainPattern = expected.replace(/\\./g, '\\\\.');\n // Non ip address domains.\n // domain.com = *.domain.com OR domain.com\n const re = new RegExp(\n '^(.+\\\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$',\n 'i'\n );\n return re.test(hostname);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _performApiRequest, Endpoint, HttpMethod } from '../index';\nimport { Auth } from '../../model/public_types';\n\nexport interface GetProjectConfigRequest {\n androidPackageName?: string;\n iosBundleId?: string;\n}\n\nexport interface GetProjectConfigResponse {\n authorizedDomains: string[];\n}\n\nexport async function _getProjectConfig(\n auth: Auth,\n request: GetProjectConfigRequest = {}\n): Promise<GetProjectConfigResponse> {\n return _performApiRequest<GetProjectConfigRequest, GetProjectConfigResponse>(\n auth,\n HttpMethod.GET,\n Endpoint.GET_PROJECT_CONFIG,\n request\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as js from '../load_js';\n\nconst NETWORK_TIMEOUT = new Delay(30000, 60000);\n\n/**\n * Reset unlaoded GApi modules. If gapi.load fails due to a network error,\n * it will stop working after a retrial. This is a hack to fix this issue.\n */\nfunction resetUnloadedGapiModules(): void {\n // Clear last failed gapi.load state to force next gapi.load to first\n // load the failed gapi.iframes module.\n // Get gapix.beacon context.\n const beacon = _window().___jsl;\n // Get current hint.\n if (beacon?.H) {\n // Get gapi hint.\n for (const hint of Object.keys(beacon.H)) {\n // Requested modules.\n beacon.H[hint].r = beacon.H[hint].r || [];\n // Loaded modules.\n beacon.H[hint].L = beacon.H[hint].L || [];\n // Set requested modules to a copy of the loaded modules.\n beacon.H[hint].r = [...beacon.H[hint].L];\n // Clear pending callbacks.\n if (beacon.CP) {\n for (let i = 0; i < beacon.CP.length; i++) {\n // Remove all failed pending callbacks.\n beacon.CP[i] = null;\n }\n }\n }\n }\n}\n\nfunction loadGapi(auth: AuthInternal): Promise<gapi.iframes.Context> {\n return new Promise<gapi.iframes.Context>((resolve, reject) => {\n // Function to run when gapi.load is ready.\n function loadGapiIframe(): void {\n // The developer may have tried to previously run gapi.load and failed.\n // Run this to fix that.\n resetUnloadedGapiModules();\n gapi.load('gapi.iframes', {\n callback: () => {\n resolve(gapi.iframes.getContext());\n },\n ontimeout: () => {\n // The above reset may be sufficient, but having this reset after\n // failure ensures that if the developer calls gapi.load after the\n // connection is re-established and before another attempt to embed\n // the iframe, it would work and would not be broken because of our\n // failed attempt.\n // Timeout when gapi.iframes.Iframe not loaded.\n resetUnloadedGapiModules();\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n },\n timeout: NETWORK_TIMEOUT.get()\n });\n }\n\n if (_window().gapi?.iframes?.Iframe) {\n // If gapi.iframes.Iframe available, resolve.\n resolve(gapi.iframes.getContext());\n } else if (!!_window().gapi?.load) {\n // Gapi loader ready, load gapi.iframes.\n loadGapiIframe();\n } else {\n // Create a new iframe callback when this is called so as not to overwrite\n // any previous defined callback. This happens if this method is called\n // multiple times in parallel and could result in the later callback\n // overwriting the previous one. This would end up with a iframe\n // timeout.\n const cbName = js._generateCallbackName('iframefcb');\n // GApi loader not available, dynamically load platform.js.\n _window()[cbName] = () => {\n // GApi loader should be ready.\n if (!!gapi.load) {\n loadGapiIframe();\n } else {\n // Gapi loader failed, throw error.\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n }\n };\n // Load GApi loader.\n return js\n ._loadJS(`https://apis.google.com/js/api.js?onload=${cbName}`)\n .catch(e => reject(e));\n }\n }).catch(error => {\n // Reset cached promise to allow for retrial.\n cachedGApiLoader = null;\n throw error;\n });\n}\n\nlet cachedGApiLoader: Promise<gapi.iframes.Context> | null = null;\nexport function _loadGapi(auth: AuthInternal): Promise<gapi.iframes.Context> {\n cachedGApiLoader = cachedGApiLoader || loadGapi(auth);\n return cachedGApiLoader;\n}\n\nexport function _resetLoader(): void {\n cachedGApiLoader = null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { querystring } from '@firebase/util';\nimport { DefaultConfig } from '../../../internal';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert, _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { _emulatorUrl } from '../../core/util/emulator';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as gapiLoader from './gapi';\n\nconst PING_TIMEOUT = new Delay(5000, 15000);\nconst IFRAME_PATH = '__/auth/iframe';\nconst EMULATED_IFRAME_PATH = 'emulator/auth/iframe';\n\nconst IFRAME_ATTRIBUTES = {\n style: {\n position: 'absolute',\n top: '-100px',\n width: '1px',\n height: '1px'\n },\n 'aria-hidden': 'true',\n tabindex: '-1'\n};\n\n// Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to\n// anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.\nconst EID_FROM_APIHOST = new Map([\n [DefaultConfig.API_HOST, 'p'], // production\n ['staging-identitytoolkit.sandbox.googleapis.com', 's'], // staging\n ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test\n]);\n\nfunction getIframeUrl(auth: AuthInternal): string {\n const config = auth.config;\n _assert(config.authDomain, auth, AuthErrorCode.MISSING_AUTH_DOMAIN);\n const url = config.emulator\n ? _emulatorUrl(config, EMULATED_IFRAME_PATH)\n : `https://${auth.config.authDomain}/${IFRAME_PATH}`;\n\n const params: Record<string, string> = {\n apiKey: config.apiKey,\n appName: auth.name,\n v: SDK_VERSION\n };\n const eid = EID_FROM_APIHOST.get(auth.config.apiHost);\n if (eid) {\n params.eid = eid;\n }\n const frameworks = auth._getFrameworks();\n if (frameworks.length) {\n params.fw = frameworks.join(',');\n }\n return `${url}?${querystring(params).slice(1)}`;\n}\n\nexport async function _openIframe(\n auth: AuthInternal\n): Promise<gapi.iframes.Iframe> {\n const context = await gapiLoader._loadGapi(auth);\n const gapi = _window().gapi;\n _assert(gapi, auth, AuthErrorCode.INTERNAL_ERROR);\n return context.open(\n {\n where: document.body,\n url: getIframeUrl(auth),\n messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,\n attributes: IFRAME_ATTRIBUTES,\n dontclear: true\n },\n (iframe: gapi.iframes.Iframe) =>\n new Promise(async (resolve, reject) => {\n await iframe.restyle({\n // Prevent iframe from closing on mouse out.\n setHideOnLeave: false\n });\n\n const networkError = _createError(\n auth,\n AuthErrorCode.NETWORK_REQUEST_FAILED\n );\n // Confirm iframe is correctly loaded.\n // To fallback on failure, set a timeout.\n const networkErrorTimer = _window().setTimeout(() => {\n reject(networkError);\n }, PING_TIMEOUT.get());\n // Clear timer and resolve pending iframe ready promise.\n function clearTimerAndResolve(): void {\n _window().clearTimeout(networkErrorTimer);\n resolve(iframe);\n }\n // This returns an IThenable. However the reject part does not call\n // when the iframe is not loaded.\n iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {\n reject(networkError);\n });\n })\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getUA } from '@firebase/util';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport {\n _isChromeIOS,\n _isFirefox,\n _isIOSStandalone\n} from '../../core/util/browser';\nimport { AuthInternal } from '../../model/auth';\n\nconst BASE_POPUP_OPTIONS = {\n location: 'yes',\n resizable: 'yes',\n statusbar: 'yes',\n toolbar: 'no'\n};\n\nconst DEFAULT_WIDTH = 500;\nconst DEFAULT_HEIGHT = 600;\nconst TARGET_BLANK = '_blank';\n\nconst FIREFOX_EMPTY_URL = 'http://localhost';\n\nexport class AuthPopup {\n associatedEvent: string | null = null;\n\n constructor(readonly window: Window | null) {}\n\n close(): void {\n if (this.window) {\n try {\n this.window.close();\n } catch (e) {}\n }\n }\n}\n\nexport function _open(\n auth: AuthInternal,\n url?: string,\n name?: string,\n width = DEFAULT_WIDTH,\n height = DEFAULT_HEIGHT\n): AuthPopup {\n const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();\n const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();\n let target = '';\n\n const options: { [key: string]: string } = {\n ...BASE_POPUP_OPTIONS,\n width: width.toString(),\n height: height.toString(),\n top,\n left\n };\n\n // Chrome iOS 7 and 8 is returning an undefined popup win when target is\n // specified, even though the popup is not necessarily blocked.\n const ua = getUA().toLowerCase();\n\n if (name) {\n target = _isChromeIOS(ua) ? TARGET_BLANK : name;\n }\n\n if (_isFirefox(ua)) {\n // Firefox complains when invalid URLs are popped out. Hacky way to bypass.\n url = url || FIREFOX_EMPTY_URL;\n // Firefox disables by default scrolling on popup windows, which can create\n // issues when the user has many Google accounts, for instance.\n options.scrollbars = 'yes';\n }\n\n const optionsString = Object.entries(options).reduce(\n (accum, [key, value]) => `${accum}${key}=${value},`,\n ''\n );\n\n if (_isIOSStandalone(ua) && target !== '_self') {\n openAsNewWindowIOS(url || '', target);\n return new AuthPopup(null);\n }\n\n // about:blank getting sanitized causing browsers like IE/Edge to display\n // brief error message before redirecting to handler.\n const newWin = window.open(url || '', target, optionsString);\n _assert(newWin, auth, AuthErrorCode.POPUP_BLOCKED);\n\n // Flaky on IE edge, encapsulate with a try and catch.\n try {\n newWin.focus();\n } catch (e) {}\n\n return new AuthPopup(newWin);\n}\n\nfunction openAsNewWindowIOS(url: string, target: string): void {\n const el = document.createElement('a');\n el.href = url;\n el.target = target;\n const click = document.createEvent('MouseEvent');\n click.initMouseEvent(\n 'click',\n true,\n true,\n window,\n 1,\n 0,\n 0,\n 0,\n 0,\n false,\n false,\n false,\n false,\n 1,\n null\n );\n el.dispatchEvent(click);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { AuthProvider } from '../../model/public_types';\nimport { ApiKey, AppName, AuthInternal } from '../../model/auth';\nimport { AuthEventType } from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from './assert';\nimport { isEmpty, querystring } from '@firebase/util';\nimport { _emulatorUrl } from './emulator';\nimport { FederatedAuthProvider } from '../providers/federated';\nimport { BaseOAuthProvider } from '../providers/oauth';\n\n/**\n * URL for Authentication widget which will initiate the OAuth handshake\n *\n * @internal\n */\nconst WIDGET_PATH = '__/auth/handler';\n\n/**\n * URL for emulated environment\n *\n * @internal\n */\nconst EMULATOR_WIDGET_PATH = 'emulator/auth/handler';\n\n/**\n * Fragment name for the App Check token that gets passed to the widget\n *\n * @internal\n */\nconst FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent('fac');\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ntype WidgetParams = {\n apiKey: ApiKey;\n appName: AppName;\n authType: AuthEventType;\n redirectUrl?: string;\n v: string;\n providerId?: string;\n scopes?: string;\n customParameters?: string;\n eventId?: string;\n tid?: string;\n} & { [key: string]: string | undefined };\n\nexport async function _getRedirectUrl(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n redirectUrl?: string,\n eventId?: string,\n additionalParams?: Record<string, string>\n): Promise<string> {\n _assert(auth.config.authDomain, auth, AuthErrorCode.MISSING_AUTH_DOMAIN);\n _assert(auth.config.apiKey, auth, AuthErrorCode.INVALID_API_KEY);\n\n const params: WidgetParams = {\n apiKey: auth.config.apiKey,\n appName: auth.name,\n authType,\n redirectUrl,\n v: SDK_VERSION,\n eventId\n };\n\n if (provider instanceof FederatedAuthProvider) {\n provider.setDefaultLanguage(auth.languageCode);\n params.providerId = provider.providerId || '';\n if (!isEmpty(provider.getCustomParameters())) {\n params.customParameters = JSON.stringify(provider.getCustomParameters());\n }\n\n // TODO set additionalParams from the provider as well?\n for (const [key, value] of Object.entries(additionalParams || {})) {\n params[key] = value;\n }\n }\n\n if (provider instanceof BaseOAuthProvider) {\n const scopes = provider.getScopes().filter(scope => scope !== '');\n if (scopes.length > 0) {\n params.scopes = scopes.join(',');\n }\n }\n\n if (auth.tenantId) {\n params.tid = auth.tenantId;\n }\n\n // TODO: maybe set eid as endipointId\n // TODO: maybe set fw as Frameworks.join(\",\")\n\n const paramsDict = params as Record<string, string | number>;\n for (const key of Object.keys(paramsDict)) {\n if (paramsDict[key] === undefined) {\n delete paramsDict[key];\n }\n }\n\n // Sets the App Check token to pass to the widget\n const appCheckToken = await auth._getAppCheckToken();\n const appCheckTokenFragment = appCheckToken\n ? `#${FIREBASE_APP_CHECK_FRAGMENT_ID}=${encodeURIComponent(appCheckToken)}`\n : '';\n\n // Start at index 1 to skip the leading '&' in the query string\n return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(\n 1\n )}${appCheckTokenFragment}`;\n}\n\nfunction getHandlerBase({ config }: AuthInternal): string {\n if (!config.emulator) {\n return `https://${config.authDomain}/${WIDGET_PATH}`;\n }\n\n return _emulatorUrl(config, EMULATOR_WIDGET_PATH);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider, PopupRedirectResolver } from '../model/public_types';\n\nimport { AuthEventManager } from '../core/auth/auth_event_manager';\nimport { AuthErrorCode } from '../core/errors';\nimport { _assert, debugAssert, _fail } from '../core/util/assert';\nimport { _generateEventId } from '../core/util/event_id';\nimport { _getCurrentUrl } from '../core/util/location';\nimport { _validateOrigin } from '../core/util/validate_origin';\nimport { AuthInternal } from '../model/auth';\nimport {\n AuthEventType,\n EventManager,\n GapiAuthEvent,\n GapiOutcome,\n PopupRedirectResolverInternal\n} from '../model/popup_redirect';\nimport { _setWindowLocation } from './auth_window';\nimport { _openIframe } from './iframe/iframe';\nimport { browserSessionPersistence } from './persistence/session_storage';\nimport { _open, AuthPopup } from './util/popup';\nimport { _getRedirectResult } from './strategies/redirect';\nimport { _getRedirectUrl } from '../core/util/handler';\nimport { _isIOS, _isMobileBrowser, _isSafari } from '../core/util/browser';\nimport { _overrideRedirectResult } from '../core/strategies/redirect';\n\n/**\n * The special web storage event\n *\n */\nconst WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';\n\ninterface WebStorageSupportMessage extends gapi.iframes.Message {\n [index: number]: Record<string, boolean>;\n}\n\ninterface ManagerOrPromise {\n manager?: EventManager;\n promise?: Promise<EventManager>;\n}\n\nclass BrowserPopupRedirectResolver implements PopupRedirectResolverInternal {\n private readonly eventManagers: Record<string, ManagerOrPromise> = {};\n private readonly iframes: Record<string, gapi.iframes.Iframe> = {};\n private readonly originValidationPromises: Record<string, Promise<void>> = {};\n\n readonly _redirectPersistence = browserSessionPersistence;\n\n // Wrapping in async even though we don't await anywhere in order\n // to make sure errors are raised as promise rejections\n async _openPopup(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise<AuthPopup> {\n debugAssert(\n this.eventManagers[auth._key()]?.manager,\n '_initialize() not called before _openPopup()'\n );\n\n const url = await _getRedirectUrl(\n auth,\n provider,\n authType,\n _getCurrentUrl(),\n eventId\n );\n return _open(auth, url, _generateEventId());\n }\n\n async _openRedirect(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise<never> {\n await this._originValidation(auth);\n const url = await _getRedirectUrl(\n auth,\n provider,\n authType,\n _getCurrentUrl(),\n eventId\n );\n _setWindowLocation(url);\n return new Promise(() => {});\n }\n\n _initialize(auth: AuthInternal): Promise<EventManager> {\n const key = auth._key();\n if (this.eventManagers[key]) {\n const { manager, promise } = this.eventManagers[key];\n if (manager) {\n return Promise.resolve(manager);\n } else {\n debugAssert(promise, 'If manager is not set, promise should be');\n return promise;\n }\n }\n\n const promise = this.initAndGetManager(auth);\n this.eventManagers[key] = { promise };\n\n // If the promise is rejected, the key should be removed so that the\n // operation can be retried later.\n promise.catch(() => {\n delete this.eventManagers[key];\n });\n\n return promise;\n }\n\n private async initAndGetManager(auth: AuthInternal): Promise<EventManager> {\n const iframe = await _openIframe(auth);\n const manager = new AuthEventManager(auth);\n iframe.register<GapiAuthEvent>(\n 'authEvent',\n (iframeEvent: GapiAuthEvent | null) => {\n _assert(iframeEvent?.authEvent, auth, AuthErrorCode.INVALID_AUTH_EVENT);\n // TODO: Consider splitting redirect and popup events earlier on\n\n const handled = manager.onEvent(iframeEvent.authEvent);\n return { status: handled ? GapiOutcome.ACK : GapiOutcome.ERROR };\n },\n gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER\n );\n\n this.eventManagers[auth._key()] = { manager };\n this.iframes[auth._key()] = iframe;\n return manager;\n }\n\n _isIframeWebStorageSupported(\n auth: AuthInternal,\n cb: (supported: boolean) => unknown\n ): void {\n const iframe = this.iframes[auth._key()];\n iframe.send<gapi.iframes.Message, WebStorageSupportMessage>(\n WEB_STORAGE_SUPPORT_KEY,\n { type: WEB_STORAGE_SUPPORT_KEY },\n result => {\n const isSupported = result?.[0]?.[WEB_STORAGE_SUPPORT_KEY];\n if (isSupported !== undefined) {\n cb(!!isSupported);\n }\n\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n },\n gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER\n );\n }\n\n _originValidation(auth: AuthInternal): Promise<void> {\n const key = auth._key();\n if (!this.originValidationPromises[key]) {\n this.originValidationPromises[key] = _validateOrigin(auth);\n }\n\n return this.originValidationPromises[key];\n }\n\n get _shouldInitProactively(): boolean {\n // Mobile browsers and Safari need to optimistically initialize\n return _isMobileBrowser() || _isSafari() || _isIOS();\n }\n\n _completeRedirectFn = _getRedirectResult;\n\n _overrideRedirectResult = _overrideRedirectResult;\n}\n\n/**\n * An implementation of {@link PopupRedirectResolver} suitable for browser\n * based applications.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @public\n */\nexport const browserPopupRedirectResolver: PopupRedirectResolver =\n BrowserPopupRedirectResolver;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Unsubscribe } from '@firebase/util';\nimport { FirebaseAuthInternal } from '@firebase/auth-interop-types';\n\nimport { AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { _assert } from '../util/assert';\nimport { AuthErrorCode } from '../errors';\n\ninterface TokenListener {\n (tok: string | null): unknown;\n}\n\nexport class AuthInterop implements FirebaseAuthInternal {\n private readonly internalListeners: Map<TokenListener, Unsubscribe> =\n new Map();\n\n constructor(private readonly auth: AuthInternal) {}\n\n getUid(): string | null {\n this.assertAuthConfigured();\n return this.auth.currentUser?.uid || null;\n }\n\n async getToken(\n forceRefresh?: boolean\n ): Promise<{ accessToken: string } | null> {\n this.assertAuthConfigured();\n await this.auth._initializationPromise;\n if (!this.auth.currentUser) {\n return null;\n }\n\n const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);\n return { accessToken };\n }\n\n addAuthTokenListener(listener: TokenListener): void {\n this.assertAuthConfigured();\n if (this.internalListeners.has(listener)) {\n return;\n }\n\n const unsubscribe = this.auth.onIdTokenChanged(user => {\n listener(\n (user as UserInternal | null)?.stsTokenManager.accessToken || null\n );\n });\n this.internalListeners.set(listener, unsubscribe);\n this.updateProactiveRefresh();\n }\n\n removeAuthTokenListener(listener: TokenListener): void {\n this.assertAuthConfigured();\n const unsubscribe = this.internalListeners.get(listener);\n if (!unsubscribe) {\n return;\n }\n\n this.internalListeners.delete(listener);\n unsubscribe();\n this.updateProactiveRefresh();\n }\n\n private assertAuthConfigured(): void {\n _assert(\n this.auth._initializationPromise,\n AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH\n );\n }\n\n private updateProactiveRefresh(): void {\n if (this.internalListeners.size > 0) {\n this.auth._startProactiveRefresh();\n } else {\n this.auth._stopProactiveRefresh();\n }\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, getApp, _getProvider } from '@firebase/app';\n\nimport {\n initializeAuth,\n beforeAuthStateChanged,\n onIdTokenChanged,\n connectAuthEmulator\n} from '..';\nimport { registerAuth } from '../core/auth/register';\nimport { ClientPlatform } from '../core/util/version';\nimport { browserLocalPersistence } from './persistence/local_storage';\nimport { browserSessionPersistence } from './persistence/session_storage';\nimport { indexedDBLocalPersistence } from './persistence/indexed_db';\nimport { browserPopupRedirectResolver } from './popup_redirect';\nimport { Auth, User } from '../model/public_types';\nimport { getDefaultEmulatorHost, getExperimentalSetting } from '@firebase/util';\n\nconst DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;\nconst authIdTokenMaxAge =\n getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;\n\nlet lastPostedIdToken: string | undefined | null = null;\n\nconst mintCookieFactory = (url: string) => async (user: User | null) => {\n const idTokenResult = user && (await user.getIdTokenResult());\n const idTokenAge =\n idTokenResult &&\n (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1_000;\n if (idTokenAge && idTokenAge > authIdTokenMaxAge) {\n return;\n }\n // Specifically trip null => undefined when logged out, to delete any existing cookie\n const idToken = idTokenResult?.token;\n if (lastPostedIdToken === idToken) {\n return;\n }\n lastPostedIdToken = idToken;\n await fetch(url, {\n method: idToken ? 'POST' : 'DELETE',\n headers: idToken\n ? {\n 'Authorization': `Bearer ${idToken}`\n }\n : {}\n });\n};\n\n/**\n * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.\n * If no instance exists, initializes an Auth instance with platform-specific default dependencies.\n *\n * @param app - The Firebase App.\n *\n * @public\n */\nexport function getAuth(app: FirebaseApp = getApp()): Auth {\n const provider = _getProvider(app, 'auth');\n\n if (provider.isInitialized()) {\n return provider.getImmediate();\n }\n\n const auth = initializeAuth(app, {\n popupRedirectResolver: browserPopupRedirectResolver,\n persistence: [\n indexedDBLocalPersistence,\n browserLocalPersistence,\n browserSessionPersistence\n ]\n });\n\n const authTokenSyncUrl = getExperimentalSetting('authTokenSyncURL');\n if (authTokenSyncUrl) {\n const mintCookie = mintCookieFactory(authTokenSyncUrl);\n beforeAuthStateChanged(auth, mintCookie, () =>\n mintCookie(auth.currentUser)\n );\n onIdTokenChanged(auth, user => mintCookie(user));\n }\n\n const authEmulatorHost = getDefaultEmulatorHost('auth');\n if (authEmulatorHost) {\n connectAuthEmulator(auth, `http://${authEmulatorHost}`);\n }\n\n return auth;\n}\n\nregisterAuth(ClientPlatform.BROWSER);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _registerComponent, registerVersion } from '@firebase/app';\nimport {\n Component,\n ComponentType,\n InstantiationMode\n} from '@firebase/component';\n\nimport { name, version } from '../../../package.json';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _getClientVersion, ClientPlatform } from '../util/version';\nimport { _castAuth, AuthImpl, DefaultConfig } from './auth_impl';\nimport { AuthInterop } from './firebase_internal';\nimport { ConfigInternal } from '../../model/auth';\nimport { Dependencies } from '../../model/public_types';\nimport { _initializeAuthInstance } from './initialize';\n\nexport const enum _ComponentName {\n AUTH = 'auth',\n AUTH_INTERNAL = 'auth-internal'\n}\n\nfunction getVersionForPlatform(\n clientPlatform: ClientPlatform\n): string | undefined {\n switch (clientPlatform) {\n case ClientPlatform.NODE:\n return 'node';\n case ClientPlatform.REACT_NATIVE:\n return 'rn';\n case ClientPlatform.WORKER:\n return 'webworker';\n case ClientPlatform.CORDOVA:\n return 'cordova';\n default:\n return undefined;\n }\n}\n\n/** @internal */\nexport function registerAuth(clientPlatform: ClientPlatform): void {\n _registerComponent(\n new Component(\n _ComponentName.AUTH,\n (container, { options: deps }: { options?: Dependencies }) => {\n const app = container.getProvider('app').getImmediate()!;\n const heartbeatServiceProvider =\n container.getProvider<'heartbeat'>('heartbeat');\n const appCheckServiceProvider =\n container.getProvider<'app-check-internal'>('app-check-internal');\n const { apiKey, authDomain } = app.options;\n\n _assert(\n apiKey && !apiKey.includes(':'),\n AuthErrorCode.INVALID_API_KEY,\n { appName: app.name }\n );\n\n const config: ConfigInternal = {\n apiKey,\n authDomain,\n clientPlatform,\n apiHost: DefaultConfig.API_HOST,\n tokenApiHost: DefaultConfig.TOKEN_API_HOST,\n apiScheme: DefaultConfig.API_SCHEME,\n sdkClientVersion: _getClientVersion(clientPlatform)\n };\n\n const authInstance = new AuthImpl(\n app,\n heartbeatServiceProvider,\n appCheckServiceProvider,\n config\n );\n _initializeAuthInstance(authInstance, deps);\n\n return authInstance;\n },\n ComponentType.PUBLIC\n )\n /**\n * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()\n * For why we do this, See go/firebase-next-auth-init\n */\n .setInstantiationMode(InstantiationMode.EXPLICIT)\n /**\n * Because all firebase products that depend on auth depend on auth-internal directly,\n * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.\n */\n .setInstanceCreatedCallback(\n (container, _instanceIdentifier, _instance) => {\n const authInternalProvider = container.getProvider(\n _ComponentName.AUTH_INTERNAL\n );\n authInternalProvider.initialize();\n }\n )\n );\n\n _registerComponent(\n new Component(\n _ComponentName.AUTH_INTERNAL,\n container => {\n const auth = _castAuth(\n container.getProvider(_ComponentName.AUTH).getImmediate()!\n );\n return (auth => new AuthInterop(auth))(auth);\n },\n ComponentType.PRIVATE\n ).setInstantiationMode(InstantiationMode.EXPLICIT)\n );\n\n registerVersion(name, version, getVersionForPlatform(clientPlatform));\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProvider, FirebaseApp } from '@firebase/app';\nimport { deepEqual } from '@firebase/util';\nimport { Auth, Dependencies } from '../../model/public_types';\n\nimport { AuthErrorCode } from '../errors';\nimport { PersistenceInternal } from '../persistence';\nimport { _fail } from '../util/assert';\nimport { _getInstance } from '../util/instantiator';\nimport { AuthImpl } from './auth_impl';\n\n/**\n * Initializes an {@link Auth} instance with fine-grained control over\n * {@link Dependencies}.\n *\n * @remarks\n *\n * This function allows more control over the {@link Auth} instance than\n * {@link getAuth}. `getAuth` uses platform-specific defaults to supply\n * the {@link Dependencies}. In general, `getAuth` is the easiest way to\n * initialize Auth and works for most use cases. Use `initializeAuth` if you\n * need control over which persistence layer is used, or to minimize bundle\n * size if you're not using either `signInWithPopup` or `signInWithRedirect`.\n *\n * For example, if your app only uses anonymous accounts and you only want\n * accounts saved for the current session, initialize `Auth` with:\n *\n * ```js\n * const auth = initializeAuth(app, {\n * persistence: browserSessionPersistence,\n * popupRedirectResolver: undefined,\n * });\n * ```\n *\n * @public\n */\nexport function initializeAuth(app: FirebaseApp, deps?: Dependencies): Auth {\n const provider = _getProvider(app, 'auth');\n\n if (provider.isInitialized()) {\n const auth = provider.getImmediate() as AuthImpl;\n const initialOptions = provider.getOptions() as Dependencies;\n if (deepEqual(initialOptions, deps ?? {})) {\n return auth;\n } else {\n _fail(auth, AuthErrorCode.ALREADY_INITIALIZED);\n }\n }\n\n const auth = provider.initialize({ options: deps }) as AuthImpl;\n\n return auth;\n}\n\nexport function _initializeAuthInstance(\n auth: AuthImpl,\n deps?: Dependencies\n): void {\n const persistence = deps?.persistence || [];\n const hierarchy = (\n Array.isArray(persistence) ? persistence : [persistence]\n ).map<PersistenceInternal>(_getInstance);\n if (deps?.errorMap) {\n auth._updateErrorMap(deps.errorMap);\n }\n\n // This promise is intended to float; auth initialization happens in the\n // background, meanwhile the auth object may be used by the app.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n auth._initializeWithPersistence(hierarchy, deps?.popupRedirectResolver);\n}\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Bootstrap for the Google JS Library (Closure).\n *\n * In uncompiled mode base.js will attempt to load Closure's deps file, unless\n * the global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects\n * to include their own deps file(s) from different locations.\n *\n * Avoid including base.js more than once. This is strictly discouraged and not\n * supported. goog.require(...) won't work properly in that case.\n *\n * @suppress {deprecated} Users cannot remove deprecated uses here.\n * @provideGoog\n */\n\n\n/**\n * @define {boolean} Overridden to true by the compiler.\n */\nvar COMPILED = false;\n\n\n/**\n * Base namespace for the Closure library. Checks to see goog is already\n * defined in the current scope before assigning to prevent clobbering if\n * base.js is loaded more than once.\n *\n * @const\n */\nvar goog = goog || {};\n\n/**\n * Reference to the global object.\n * https://www.ecma-international.org/ecma-262/9.0/index.html#sec-global-object\n *\n * More info on this implementation here:\n * https://docs.google.com/document/d/1NAeW4Wk7I7FV0Y2tcUFvQdGMc89k2vdgSXInw8_nvCI/edit\n *\n * @const\n * @suppress {undefinedVars} self won't be referenced unless `this` is falsy.\n * @type {!Global}\n */\ngoog.global =\n // Check `this` first for backwards compatibility.\n // Valid unless running as an ES module or in a function wrapper called\n // without setting `this` properly.\n // Note that base.js can't usefully be imported as an ES module, but it may\n // be compiled into bundles that are loadable as ES modules.\n this ||\n // https://developer.mozilla.org/en-US/docs/Web/API/Window/self\n // For in-page browser environments and workers.\n self;\n\n\n/**\n * A hook for overriding the define values in uncompiled mode.\n *\n * In uncompiled mode, `CLOSURE_UNCOMPILED_DEFINES` may be defined before\n * loading base.js. If a key is defined in `CLOSURE_UNCOMPILED_DEFINES`,\n * `goog.define` will use the value instead of the default value. This\n * allows flags to be overwritten without compilation (this is normally\n * accomplished with the compiler's \"define\" flag).\n *\n * Example:\n * <pre>\n * var CLOSURE_UNCOMPILED_DEFINES = {'goog.DEBUG': false};\n * </pre>\n *\n * @type {Object<string, (string|number|boolean)>|undefined}\n */\ngoog.global.CLOSURE_UNCOMPILED_DEFINES;\n\n\n/**\n * A hook for overriding the define values in uncompiled or compiled mode,\n * like CLOSURE_UNCOMPILED_DEFINES but effective in compiled code. In\n * uncompiled code CLOSURE_UNCOMPILED_DEFINES takes precedence.\n *\n * Also unlike CLOSURE_UNCOMPILED_DEFINES the values must be number, boolean or\n * string literals or the compiler will emit an error.\n *\n * While any @define value may be set, only those set with goog.define will be\n * effective for uncompiled code.\n *\n * Example:\n * <pre>\n * var CLOSURE_DEFINES = {'goog.DEBUG': false} ;\n * </pre>\n *\n * Currently the Closure Compiler will only recognize very simple definitions of\n * this value when looking for values to apply to compiled code and ignore all\n * other references. Specifically, it looks the value defined at the variable\n * declaration, as with the example above.\n *\n * TODO(user): Improve the recognized definitions.\n *\n * @type {!Object<string, (string|number|boolean)>|null|undefined}\n */\ngoog.global.CLOSURE_DEFINES;\n\n\n/**\n * Builds an object structure for the provided namespace path, ensuring that\n * names that already exist are not overwritten. For example:\n * \"a.b.c\" -> a = {};a.b={};a.b.c={};\n * Used by goog.provide and goog.exportSymbol.\n * @param {string} name The name of the object that this file defines.\n * @param {*=} object The object to expose at the end of the path.\n * @param {boolean=} overwriteImplicit If object is set and a previous call\n * implicitly constructed the namespace given by name, this parameter\n * controls whether object should overwrite the implicitly constructed\n * namespace or be merged into it. Defaults to false.\n * @param {?Object=} objectToExportTo The object to add the path to; if this\n * field is not specified, its value defaults to `goog.global`.\n * @private\n */\ngoog.exportPath_ = function(name, object, overwriteImplicit, objectToExportTo) {\n var parts = name.split('.');\n var cur = objectToExportTo || goog.global;\n\n // Internet Explorer exhibits strange behavior when throwing errors from\n // methods externed in this manner. See the testExportSymbolExceptions in\n // base_test.html for an example.\n if (!(parts[0] in cur) && typeof cur.execScript != 'undefined') {\n cur.execScript('var ' + parts[0]);\n }\n\n for (var part; parts.length && (part = parts.shift());) {\n if (!parts.length && object !== undefined) {\n if (!overwriteImplicit && goog.isObject(object) &&\n goog.isObject(cur[part])) {\n // Merge properties on object (the input parameter) with the existing\n // implicitly defined namespace, so as to not clobber previously\n // defined child namespaces.\n for (var prop in object) {\n if (object.hasOwnProperty(prop)) {\n cur[part][prop] = object[prop];\n }\n }\n } else {\n // Either there is no existing implicit namespace, or overwriteImplicit\n // is set to true, so directly assign object (the input parameter) to\n // the namespace.\n cur[part] = object;\n }\n } else if (cur[part] && cur[part] !== Object.prototype[part]) {\n cur = cur[part];\n } else {\n cur = cur[part] = {};\n }\n }\n};\n\n\n/**\n * Defines a named value. In uncompiled mode, the value is retrieved from\n * CLOSURE_DEFINES or CLOSURE_UNCOMPILED_DEFINES if the object is defined and\n * has the property specified, and otherwise used the defined defaultValue.\n * When compiled the default can be overridden using the compiler options or the\n * value set in the CLOSURE_DEFINES object. Returns the defined value so that it\n * can be used safely in modules. Note that the value type MUST be either\n * boolean, number, or string.\n *\n * @param {string} name The distinguished name to provide.\n * @param {T} defaultValue\n * @return {T} The defined value.\n * @template T\n */\ngoog.define = function(name, defaultValue) {\n var value = defaultValue;\n if (!COMPILED) {\n var uncompiledDefines = goog.global.CLOSURE_UNCOMPILED_DEFINES;\n var defines = goog.global.CLOSURE_DEFINES;\n if (uncompiledDefines &&\n // Anti DOM-clobbering runtime check (b/37736576).\n /** @type {?} */ (uncompiledDefines).nodeType === undefined &&\n Object.prototype.hasOwnProperty.call(uncompiledDefines, name)) {\n value = uncompiledDefines[name];\n } else if (\n defines &&\n // Anti DOM-clobbering runtime check (b/37736576).\n /** @type {?} */ (defines).nodeType === undefined &&\n Object.prototype.hasOwnProperty.call(defines, name)) {\n value = defines[name];\n }\n }\n return value;\n};\n\n\n/**\n * @define {number} Integer year indicating the set of browser features that are\n * guaranteed to be present. This is defined to include exactly features that\n * work correctly on all \"modern\" browsers that are stable on January 1 of the\n * specified year. For example,\n * ```js\n * if (goog.FEATURESET_YEAR >= 2019) {\n * // use APIs known to be available on all major stable browsers Jan 1, 2019\n * } else {\n * // polyfill for older browsers\n * }\n * ```\n * This is intended to be the primary define for removing\n * unnecessary browser compatibility code (such as ponyfills and workarounds),\n * and should inform the default value for most other defines:\n * ```js\n * const ASSUME_NATIVE_PROMISE =\n * goog.define('ASSUME_NATIVE_PROMISE', goog.FEATURESET_YEAR >= 2016);\n * ```\n *\n * The default assumption is that IE9 is the lowest supported browser, which was\n * first available Jan 1, 2012.\n *\n * TODO(user): Reference more thorough documentation when it's available.\n */\ngoog.FEATURESET_YEAR = goog.define('goog.FEATURESET_YEAR', 2012);\n\n\n/**\n * @define {boolean} DEBUG is provided as a convenience so that debugging code\n * that should not be included in a production. It can be easily stripped\n * by specifying --define goog.DEBUG=false to the Closure Compiler aka\n * JSCompiler. For example, most toString() methods should be declared inside an\n * \"if (goog.DEBUG)\" conditional because they are generally used for debugging\n * purposes and it is difficult for the JSCompiler to statically determine\n * whether they are used.\n */\ngoog.DEBUG = goog.define('goog.DEBUG', true);\n\n\n/**\n * @define {string} LOCALE defines the locale being used for compilation. It is\n * used to select locale specific data to be compiled in js binary. BUILD rule\n * can specify this value by \"--define goog.LOCALE=<locale_name>\" as a compiler\n * option.\n *\n * Take into account that the locale code format is important. You should use\n * the canonical Unicode format with hyphen as a delimiter. Language must be\n * lowercase, Language Script - Capitalized, Region - UPPERCASE.\n * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN.\n *\n * See more info about locale codes here:\n * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers\n *\n * For language codes you should use values defined by ISO 693-1. See it here\n * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from\n * this rule: the Hebrew language. For legacy reasons the old code (iw) should\n * be used instead of the new code (he).\n *\n */\ngoog.LOCALE = goog.define('goog.LOCALE', 'en'); // default to en\n\n\n/**\n * @define {boolean} Whether this code is running on trusted sites.\n *\n * On untrusted sites, several native functions can be defined or overridden by\n * external libraries like Prototype, Datejs, and JQuery and setting this flag\n * to false forces closure to use its own implementations when possible.\n *\n * If your JavaScript can be loaded by a third party site and you are wary about\n * relying on non-standard implementations, specify\n * \"--define goog.TRUSTED_SITE=false\" to the compiler.\n */\ngoog.TRUSTED_SITE = goog.define('goog.TRUSTED_SITE', true);\n\n\n/**\n * @define {boolean} Whether code that calls {@link goog.setTestOnly} should\n * be disallowed in the compilation unit.\n */\ngoog.DISALLOW_TEST_ONLY_CODE =\n goog.define('goog.DISALLOW_TEST_ONLY_CODE', COMPILED && !goog.DEBUG);\n\n\n/**\n * @define {boolean} Whether to use a Chrome app CSP-compliant method for\n * loading scripts via goog.require. @see appendScriptSrcNode_.\n */\ngoog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING =\n goog.define('goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING', false);\n\n\n/**\n * Defines a namespace in Closure.\n *\n * A namespace may only be defined once in a codebase. It may be defined using\n * goog.provide() or goog.module().\n *\n * The presence of one or more goog.provide() calls in a file indicates\n * that the file defines the given objects/namespaces.\n * Provided symbols must not be null or undefined.\n *\n * In addition, goog.provide() creates the object stubs for a namespace\n * (for example, goog.provide(\"goog.foo.bar\") will create the object\n * goog.foo.bar if it does not already exist).\n *\n * Build tools also scan for provide/require/module statements\n * to discern dependencies, build dependency files (see deps.js), etc.\n *\n * @see goog.require\n * @see goog.module\n * @param {string} name Namespace provided by this file in the form\n * \"goog.package.part\".\n * deprecated Use goog.module (see b/159289405)\n */\ngoog.provide = function(name) {\n if (goog.isInModuleLoader_()) {\n throw new Error('goog.provide cannot be used within a module.');\n }\n if (!COMPILED) {\n // Ensure that the same namespace isn't provided twice.\n // A goog.module/goog.provide maps a goog.require to a specific file\n if (goog.isProvided_(name)) {\n throw new Error('Namespace \"' + name + '\" already declared.');\n }\n }\n\n goog.constructNamespace_(name);\n};\n\n\n/**\n * @param {string} name Namespace provided by this file in the form\n * \"goog.package.part\".\n * @param {?Object=} object The object to embed in the namespace.\n * @param {boolean=} overwriteImplicit If object is set and a previous call\n * implicitly constructed the namespace given by name, this parameter\n * controls whether opt_obj should overwrite the implicitly constructed\n * namespace or be merged into it. Defaults to false.\n * @private\n */\ngoog.constructNamespace_ = function(name, object, overwriteImplicit) {\n if (!COMPILED) {\n delete goog.implicitNamespaces_[name];\n\n var namespace = name;\n while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) {\n if (goog.getObjectByName(namespace)) {\n break;\n }\n goog.implicitNamespaces_[namespace] = true;\n }\n }\n\n goog.exportPath_(name, object, overwriteImplicit);\n};\n\n\n/**\n * According to the CSP3 spec a nonce must be a valid base64 string.\n * @see https://www.w3.org/TR/CSP3/#grammardef-base64-value\n * @private @const\n */\ngoog.NONCE_PATTERN_ = /^[\\w+/_-]+[=]{0,2}$/;\n\n\n/**\n * Returns CSP nonce, if set for any script tag.\n * @param {?Window=} opt_window The window context used to retrieve the nonce.\n * Defaults to global context.\n * @return {string} CSP nonce or empty string if no nonce is present.\n * @private\n */\ngoog.getScriptNonce_ = function(opt_window) {\n var doc = (opt_window || goog.global).document;\n var script = doc.querySelector && doc.querySelector('script[nonce]');\n if (script) {\n // Try to get the nonce from the IDL property first, because browsers that\n // implement additional nonce protection features (currently only Chrome) to\n // prevent nonce stealing via CSS do not expose the nonce via attributes.\n // See https://github.com/whatwg/html/issues/2369\n var nonce = script['nonce'] || script.getAttribute('nonce');\n if (nonce && goog.NONCE_PATTERN_.test(nonce)) {\n return nonce;\n }\n }\n return '';\n};\n\n\n/**\n * Module identifier validation regexp.\n * Note: This is a conservative check, it is very possible to be more lenient,\n * the primary exclusion here is \"/\" and \"\\\" and a leading \".\", these\n * restrictions are intended to leave the door open for using goog.require\n * with relative file paths rather than module identifiers.\n * @private\n */\ngoog.VALID_MODULE_RE_ = /^[a-zA-Z_$][a-zA-Z0-9._$]*$/;\n\n\n/**\n * Defines a module in Closure.\n *\n * Marks that this file must be loaded as a module and claims the namespace.\n *\n * A namespace may only be defined once in a codebase. It may be defined using\n * goog.provide() or goog.module().\n *\n * goog.module() has three requirements:\n * - goog.module may not be used in the same file as goog.provide.\n * - goog.module must be the first statement in the file.\n * - only one goog.module is allowed per file.\n *\n * When a goog.module annotated file is loaded, it is enclosed in\n * a strict function closure. This means that:\n * - any variables declared in a goog.module file are private to the file\n * (not global), though the compiler is expected to inline the module.\n * - The code must obey all the rules of \"strict\" JavaScript.\n * - the file will be marked as \"use strict\"\n *\n * NOTE: unlike goog.provide, goog.module does not declare any symbols by\n * itself. If declared symbols are desired, use\n * goog.module.declareLegacyNamespace().\n *\n *\n * See the public goog.module proposal: http://goo.gl/Va1hin\n *\n * @param {string} name Namespace provided by this file in the form\n * \"goog.package.part\", is expected but not required.\n * @return {void}\n */\ngoog.module = function(name) {\n if (typeof name !== 'string' || !name ||\n name.search(goog.VALID_MODULE_RE_) == -1) {\n throw new Error('Invalid module identifier');\n }\n if (!goog.isInGoogModuleLoader_()) {\n throw new Error(\n 'Module ' + name + ' has been loaded incorrectly. Note, ' +\n 'modules cannot be loaded as normal scripts. They require some kind of ' +\n 'pre-processing step. You\\'re likely trying to load a module via a ' +\n 'script tag or as a part of a concatenated bundle without rewriting the ' +\n 'module. For more info see: ' +\n 'https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.');\n }\n if (goog.moduleLoaderState_.moduleName) {\n throw new Error('goog.module may only be called once per module.');\n }\n\n // Store the module name for the loader.\n goog.moduleLoaderState_.moduleName = name;\n if (!COMPILED) {\n // Ensure that the same namespace isn't provided twice.\n // A goog.module/goog.provide maps a goog.require to a specific file\n if (goog.isProvided_(name)) {\n throw new Error('Namespace \"' + name + '\" already declared.');\n }\n delete goog.implicitNamespaces_[name];\n }\n};\n\n\n/**\n * @param {string} name The module identifier.\n * @return {?} The module exports for an already loaded module or null.\n *\n * Note: This is not an alternative to goog.require, it does not\n * indicate a hard dependency, instead it is used to indicate\n * an optional dependency or to access the exports of a module\n * that has already been loaded.\n * @suppress {missingProvide}\n */\ngoog.module.get = function(name) {\n return goog.module.getInternal_(name);\n};\n\n\n/**\n * @param {string} name The module identifier.\n * @return {?} The module exports for an already loaded module or null.\n * @private\n */\ngoog.module.getInternal_ = function(name) {\n if (!COMPILED) {\n if (name in goog.loadedModules_) {\n return goog.loadedModules_[name].exports;\n } else if (!goog.implicitNamespaces_[name]) {\n var ns = goog.getObjectByName(name);\n return ns != null ? ns : null;\n }\n }\n return null;\n};\n\n/**\n * Types of modules the debug loader can load.\n * @enum {string}\n */\ngoog.ModuleType = {\n ES6: 'es6',\n GOOG: 'goog'\n};\n\n\n/**\n * @private {?{\n * moduleName: (string|undefined),\n * declareLegacyNamespace:boolean,\n * type: ?goog.ModuleType\n * }}\n */\ngoog.moduleLoaderState_ = null;\n\n\n/**\n * @private\n * @return {boolean} Whether a goog.module or an es6 module is currently being\n * initialized.\n */\ngoog.isInModuleLoader_ = function() {\n return goog.isInGoogModuleLoader_() || goog.isInEs6ModuleLoader_();\n};\n\n\n/**\n * @private\n * @return {boolean} Whether a goog.module is currently being initialized.\n */\ngoog.isInGoogModuleLoader_ = function() {\n return !!goog.moduleLoaderState_ &&\n goog.moduleLoaderState_.type == goog.ModuleType.GOOG;\n};\n\n\n/**\n * @private\n * @return {boolean} Whether an es6 module is currently being initialized.\n */\ngoog.isInEs6ModuleLoader_ = function() {\n var inLoader = !!goog.moduleLoaderState_ &&\n goog.moduleLoaderState_.type == goog.ModuleType.ES6;\n\n if (inLoader) {\n return true;\n }\n\n var jscomp = goog.global['$jscomp'];\n\n if (jscomp) {\n // jscomp may not have getCurrentModulePath if this is a compiled bundle\n // that has some of the runtime, but not all of it. This can happen if\n // optimizations are turned on so the unused runtime is removed but renaming\n // and Closure pass are off (so $jscomp is still named $jscomp and the\n // goog.provide/require calls still exist).\n if (typeof jscomp.getCurrentModulePath != 'function') {\n return false;\n }\n\n // Bundled ES6 module.\n return !!jscomp.getCurrentModulePath();\n }\n\n return false;\n};\n\n\n/**\n * Provide the module's exports as a globally accessible object under the\n * module's declared name. This is intended to ease migration to goog.module\n * for files that have existing usages.\n * @suppress {missingProvide}\n */\ngoog.module.declareLegacyNamespace = function() {\n if (!COMPILED && !goog.isInGoogModuleLoader_()) {\n throw new Error(\n 'goog.module.declareLegacyNamespace must be called from ' +\n 'within a goog.module');\n }\n if (!COMPILED && !goog.moduleLoaderState_.moduleName) {\n throw new Error(\n 'goog.module must be called prior to ' +\n 'goog.module.declareLegacyNamespace.');\n }\n goog.moduleLoaderState_.declareLegacyNamespace = true;\n};\n\n\n/**\n * Associates an ES6 module with a Closure module ID so that is available via\n * goog.require. The associated ID acts like a goog.module ID - it does not\n * create any global names, it is merely available via goog.require /\n * goog.module.get / goog.forwardDeclare / goog.requireType. goog.require and\n * goog.module.get will return the entire module as if it was import *'d. This\n * allows Closure files to reference ES6 modules for the sake of migration.\n *\n * @param {string} namespace\n * @suppress {missingProvide}\n */\ngoog.declareModuleId = function(namespace) {\n if (!COMPILED) {\n if (!goog.isInEs6ModuleLoader_()) {\n throw new Error(\n 'goog.declareModuleId may only be called from ' +\n 'within an ES6 module');\n }\n if (goog.moduleLoaderState_ && goog.moduleLoaderState_.moduleName) {\n throw new Error(\n 'goog.declareModuleId may only be called once per module.');\n }\n if (namespace in goog.loadedModules_) {\n throw new Error(\n 'Module with namespace \"' + namespace + '\" already exists.');\n }\n }\n if (goog.moduleLoaderState_) {\n // Not bundled - debug loading.\n goog.moduleLoaderState_.moduleName = namespace;\n } else {\n // Bundled - not debug loading, no module loader state.\n var jscomp = goog.global['$jscomp'];\n if (!jscomp || typeof jscomp.getCurrentModulePath != 'function') {\n throw new Error(\n 'Module with namespace \"' + namespace +\n '\" has been loaded incorrectly.');\n }\n var exports = jscomp.require(jscomp.getCurrentModulePath());\n goog.loadedModules_[namespace] = {\n exports: exports,\n type: goog.ModuleType.ES6,\n moduleId: namespace\n };\n }\n};\n\n\n/**\n * Marks that the current file should only be used for testing, and never for\n * live code in production.\n *\n * In the case of unit tests, the message may optionally be an exact namespace\n * for the test (e.g. 'goog.stringTest'). The linter will then ignore the extra\n * provide (if not explicitly defined in the code).\n *\n * @param {string=} opt_message Optional message to add to the error that's\n * raised when used in production code.\n */\ngoog.setTestOnly = function(opt_message) {\n if (goog.DISALLOW_TEST_ONLY_CODE) {\n opt_message = opt_message || '';\n throw new Error(\n 'Importing test-only code into non-debug environment' +\n (opt_message ? ': ' + opt_message : '.'));\n }\n};\n\n\n/**\n * Forward declares a symbol. This is an indication to the compiler that the\n * symbol may be used in the source yet is not required and may not be provided\n * in compilation.\n *\n * The most common usage of forward declaration is code that takes a type as a\n * function parameter but does not need to require it. By forward declaring\n * instead of requiring, no hard dependency is made, and (if not required\n * elsewhere) the namespace may never be required and thus, not be pulled\n * into the JavaScript binary. If it is required elsewhere, it will be type\n * checked as normal.\n *\n * Before using goog.forwardDeclare, please read the documentation at\n * https://github.com/google/closure-compiler/wiki/Bad-Type-Annotation to\n * understand the options and tradeoffs when working with forward declarations.\n *\n * @param {string} name The namespace to forward declare in the form of\n * \"goog.package.part\".\n * @deprecated See go/noforwarddeclaration, Use `goog.requireType` instead.\n */\ngoog.forwardDeclare = function(name) {};\n\n\n/**\n * Forward declare type information. Used to assign types to goog.global\n * referenced object that would otherwise result in unknown type references\n * and thus block property disambiguation.\n */\ngoog.forwardDeclare('Document');\ngoog.forwardDeclare('HTMLScriptElement');\ngoog.forwardDeclare('XMLHttpRequest');\n\n\nif (!COMPILED) {\n /**\n * Check if the given name has been goog.provided. This will return false for\n * names that are available only as implicit namespaces.\n * @param {string} name name of the object to look for.\n * @return {boolean} Whether the name has been provided.\n * @private\n */\n goog.isProvided_ = function(name) {\n return (name in goog.loadedModules_) ||\n (!goog.implicitNamespaces_[name] && goog.getObjectByName(name) != null);\n };\n\n /**\n * Namespaces implicitly defined by goog.provide. For example,\n * goog.provide('goog.events.Event') implicitly declares that 'goog' and\n * 'goog.events' must be namespaces.\n *\n * @type {!Object<string, (boolean|undefined)>}\n * @private\n */\n goog.implicitNamespaces_ = {'goog.module': true};\n\n // NOTE: We add goog.module as an implicit namespace as goog.module is defined\n // here and because the existing module package has not been moved yet out of\n // the goog.module namespace. This satisifies both the debug loader and\n // ahead-of-time dependency management.\n}\n\n\n/**\n * Returns an object based on its fully qualified external name. The object\n * is not found if null or undefined. If you are using a compilation pass that\n * renames property names beware that using this function will not find renamed\n * properties.\n *\n * @param {string} name The fully qualified name.\n * @param {Object=} opt_obj The object within which to look; default is\n * |goog.global|.\n * @return {?} The value (object or primitive) or, if not found, null.\n */\ngoog.getObjectByName = function(name, opt_obj) {\n var parts = name.split('.');\n var cur = opt_obj || goog.global;\n for (var i = 0; i < parts.length; i++) {\n cur = cur[parts[i]];\n if (cur == null) {\n return null;\n }\n }\n return cur;\n};\n\n\n/**\n * Adds a dependency from a file to the files it requires.\n * @param {string} relPath The path to the js file.\n * @param {!Array<string>} provides An array of strings with\n * the names of the objects this file provides.\n * @param {!Array<string>} requires An array of strings with\n * the names of the objects this file requires.\n * @param {boolean|!Object<string>=} opt_loadFlags Parameters indicating\n * how the file must be loaded. The boolean 'true' is equivalent\n * to {'module': 'goog'} for backwards-compatibility. Valid properties\n * and values include {'module': 'goog'} and {'lang': 'es6'}.\n */\ngoog.addDependency = function(relPath, provides, requires, opt_loadFlags) {\n if (!COMPILED && goog.DEPENDENCIES_ENABLED) {\n goog.debugLoader_.addDependency(relPath, provides, requires, opt_loadFlags);\n }\n};\n\n\n// NOTE(nnaze): The debug DOM loader was included in base.js as an original way\n// to do \"debug-mode\" development. The dependency system can sometimes be\n// confusing, as can the debug DOM loader's asynchronous nature.\n//\n// With the DOM loader, a call to goog.require() is not blocking -- the script\n// will not load until some point after the current script. If a namespace is\n// needed at runtime, it needs to be defined in a previous script, or loaded via\n// require() with its registered dependencies.\n//\n// User-defined namespaces may need their own deps file. For a reference on\n// creating a deps file, see:\n// Externally: https://developers.google.com/closure/library/docs/depswriter\n//\n// Because of legacy clients, the DOM loader can't be easily removed from\n// base.js. Work was done to make it disableable or replaceable for\n// different environments (DOM-less JavaScript interpreters like Rhino or V8,\n// for example). See bootstrap/ for more information.\n\n\n/**\n * @define {boolean} Whether to enable the debug loader.\n *\n * If enabled, a call to goog.require() will attempt to load the namespace by\n * appending a script tag to the DOM (if the namespace has been registered).\n *\n * If disabled, goog.require() will simply assert that the namespace has been\n * provided (and depend on the fact that some outside tool correctly ordered\n * the script).\n */\ngoog.ENABLE_DEBUG_LOADER = goog.define('goog.ENABLE_DEBUG_LOADER', false);\n\n\n/**\n * @param {string} msg\n * @private\n */\ngoog.logToConsole_ = function(msg) {\n if (goog.global.console) {\n goog.global.console['error'](msg);\n }\n};\n\n\n/**\n * Implements a system for the dynamic resolution of dependencies that works in\n * parallel with the BUILD system.\n *\n * Note that all calls to goog.require will be stripped by the compiler.\n *\n * @see goog.provide\n * @param {string} namespace Namespace (as was given in goog.provide,\n * goog.module, or goog.declareModuleId) in the form\n * \"goog.package.part\".\n * @return {?} If called within a goog.module or ES6 module file, the associated\n * namespace or module otherwise null.\n */\ngoog.require = function(namespace) {\n if (!COMPILED) {\n // Might need to lazy load on old IE.\n if (goog.ENABLE_DEBUG_LOADER) {\n goog.debugLoader_.requested(namespace);\n }\n\n // If the object already exists we do not need to do anything.\n if (goog.isProvided_(namespace)) {\n if (goog.isInModuleLoader_()) {\n return goog.module.getInternal_(namespace);\n }\n } else if (goog.ENABLE_DEBUG_LOADER) {\n var moduleLoaderState = goog.moduleLoaderState_;\n goog.moduleLoaderState_ = null;\n try {\n goog.debugLoader_.load_(namespace);\n } finally {\n goog.moduleLoaderState_ = moduleLoaderState;\n }\n }\n\n return null;\n }\n};\n\n\n/**\n * Requires a symbol for its type information. This is an indication to the\n * compiler that the symbol may appear in type annotations, yet it is not\n * referenced at runtime.\n *\n * When called within a goog.module or ES6 module file, the return value may be\n * assigned to or destructured into a variable, but it may not be otherwise used\n * in code outside of a type annotation.\n *\n * Note that all calls to goog.requireType will be stripped by the compiler.\n *\n * @param {string} namespace Namespace (as was given in goog.provide,\n * goog.module, or goog.declareModuleId) in the form\n * \"goog.package.part\".\n * @return {?}\n */\ngoog.requireType = function(namespace) {\n // Return an empty object so that single-level destructuring of the return\n // value doesn't crash at runtime when using the debug loader. Multi-level\n // destructuring isn't supported.\n return {};\n};\n\n\n/**\n * Path for included scripts.\n * @type {string}\n */\ngoog.basePath = '';\n\n\n/**\n * A hook for overriding the base path.\n * @type {string|undefined}\n */\ngoog.global.CLOSURE_BASE_PATH;\n\n\n/**\n * Whether to attempt to load Closure's deps file. By default, when uncompiled,\n * deps files will attempt to be loaded.\n * @type {boolean|undefined}\n */\ngoog.global.CLOSURE_NO_DEPS;\n\n\n/**\n * A function to import a single script. This is meant to be overridden when\n * Closure is being run in non-HTML contexts, such as web workers. It's defined\n * in the global scope so that it can be set before base.js is loaded, which\n * allows deps.js to be imported properly.\n *\n * The first parameter the script source, which is a relative URI. The second,\n * optional parameter is the script contents, in the event the script needed\n * transformation. It should return true if the script was imported, false\n * otherwise.\n * @type {(function(string, string=): boolean)|undefined}\n */\ngoog.global.CLOSURE_IMPORT_SCRIPT;\n\n\n/**\n * When defining a class Foo with an abstract method bar(), you can do:\n * Foo.prototype.bar = goog.abstractMethod\n *\n * Now if a subclass of Foo fails to override bar(), an error will be thrown\n * when bar() is invoked.\n *\n * @type {!Function}\n * @throws {Error} when invoked to indicate the method should be overridden.\n * @deprecated Use \"@abstract\" annotation instead of goog.abstractMethod in new\n * code. See\n * https://github.com/google/closure-compiler/wiki/@abstract-classes-and-methods\n */\ngoog.abstractMethod = function() {\n throw new Error('unimplemented abstract method');\n};\n\n\n/**\n * Adds a `getInstance` static method that always returns the same\n * instance object.\n * @param {!Function} ctor The constructor for the class to add the static\n * method to.\n * @suppress {missingProperties} 'instance_' isn't a property on 'Function'\n * but we don't have a better type to use here.\n */\ngoog.addSingletonGetter = function(ctor) {\n // instance_ is immediately set to prevent issues with sealed constructors\n // such as are encountered when a constructor is returned as the export object\n // of a goog.module in unoptimized code.\n // Delcare type to avoid conformance violations that ctor.instance_ is unknown\n /** @type {undefined|!Object} @suppress {underscore} */\n ctor.instance_ = undefined;\n ctor.getInstance = function() {\n if (ctor.instance_) {\n return ctor.instance_;\n }\n if (goog.DEBUG) {\n // NOTE: JSCompiler can't optimize away Array#push.\n goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor;\n }\n // Cast to avoid conformance violations that ctor.instance_ is unknown\n return /** @type {!Object|undefined} */ (ctor.instance_) = new ctor;\n };\n};\n\n\n/**\n * All singleton classes that have been instantiated, for testing. Don't read\n * it directly, use the `goog.testing.singleton` module. The compiler\n * removes this variable if unused.\n * @type {!Array<!Function>}\n * @private\n */\ngoog.instantiatedSingletons_ = [];\n\n\n/**\n * @define {boolean} Whether to load goog.modules using `eval` when using\n * the debug loader. This provides a better debugging experience as the\n * source is unmodified and can be edited using Chrome Workspaces or similar.\n * However in some environments the use of `eval` is banned\n * so we provide an alternative.\n */\ngoog.LOAD_MODULE_USING_EVAL = goog.define('goog.LOAD_MODULE_USING_EVAL', true);\n\n\n/**\n * @define {boolean} Whether the exports of goog.modules should be sealed when\n * possible.\n */\ngoog.SEAL_MODULE_EXPORTS = goog.define('goog.SEAL_MODULE_EXPORTS', goog.DEBUG);\n\n\n/**\n * The registry of initialized modules:\n * The module identifier or path to module exports map.\n * @private @const {!Object<string, {exports:?,type:string,moduleId:string}>}\n */\ngoog.loadedModules_ = {};\n\n\n/**\n * True if the debug loader enabled and used.\n * @const {boolean}\n */\ngoog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER;\n\n\n/**\n * @define {string} How to decide whether to transpile. Valid values\n * are 'always', 'never', and 'detect'. The default ('detect') is to\n * use feature detection to determine which language levels need\n * transpilation.\n */\n// NOTE(sdh): we could expand this to accept a language level to bypass\n// detection: e.g. goog.TRANSPILE == 'es5' would transpile ES6 files but\n// would leave ES3 and ES5 files alone.\ngoog.TRANSPILE = goog.define('goog.TRANSPILE', 'detect');\n\n/**\n * @define {boolean} If true assume that ES modules have already been\n * transpiled by the jscompiler (in the same way that transpile.js would\n * transpile them - to jscomp modules). Useful only for servers that wish to use\n * the debug loader and transpile server side. Thus this is only respected if\n * goog.TRANSPILE is \"never\".\n */\ngoog.ASSUME_ES_MODULES_TRANSPILED =\n goog.define('goog.ASSUME_ES_MODULES_TRANSPILED', false);\n\n\n/**\n * @define {string} Trusted Types policy name. If non-empty then Closure will\n * use Trusted Types.\n */\ngoog.TRUSTED_TYPES_POLICY_NAME =\n goog.define('goog.TRUSTED_TYPES_POLICY_NAME', 'goog');\n\n\n/**\n * @package {?boolean}\n * Visible for testing.\n */\ngoog.hasBadLetScoping = null;\n\n\n/**\n * @param {function(?):?|string} moduleDef The module definition.\n */\ngoog.loadModule = function(moduleDef) {\n // NOTE: we allow function definitions to be either in the from\n // of a string to eval (which keeps the original source intact) or\n // in a eval forbidden environment (CSP) we allow a function definition\n // which in its body must call `goog.module`, and return the exports\n // of the module.\n var previousState = goog.moduleLoaderState_;\n try {\n goog.moduleLoaderState_ = {\n moduleName: '',\n declareLegacyNamespace: false,\n type: goog.ModuleType.GOOG\n };\n var origExports = {};\n var exports = origExports;\n if (typeof moduleDef === 'function') {\n exports = moduleDef.call(undefined, exports);\n } else if (typeof moduleDef === 'string') {\n exports = goog.loadModuleFromSource_.call(undefined, exports, moduleDef);\n } else {\n throw new Error('Invalid module definition');\n }\n\n var moduleName = goog.moduleLoaderState_.moduleName;\n if (typeof moduleName === 'string' && moduleName) {\n // Don't seal legacy namespaces as they may be used as a parent of\n // another namespace\n if (goog.moduleLoaderState_.declareLegacyNamespace) {\n // Whether exports was overwritten via default export assignment.\n // This is important for legacy namespaces as it dictates whether\n // previously a previously loaded implicit namespace should be clobbered\n // or not.\n var isDefaultExport = origExports !== exports;\n goog.constructNamespace_(moduleName, exports, isDefaultExport);\n } else if (\n goog.SEAL_MODULE_EXPORTS && Object.seal &&\n typeof exports == 'object' && exports != null) {\n Object.seal(exports);\n }\n\n var data = {\n exports: exports,\n type: goog.ModuleType.GOOG,\n moduleId: goog.moduleLoaderState_.moduleName\n };\n goog.loadedModules_[moduleName] = data;\n } else {\n throw new Error('Invalid module name \\\"' + moduleName + '\\\"');\n }\n } finally {\n goog.moduleLoaderState_ = previousState;\n }\n};\n\n\n/**\n * @private @const\n */\ngoog.loadModuleFromSource_ =\n /** @type {function(!Object, string):?} */ (function(exports) {\n // NOTE: we avoid declaring parameters or local variables here to avoid\n // masking globals or leaking values into the module definition.\n 'use strict';\n eval(goog.CLOSURE_EVAL_PREFILTER_.createScript(arguments[1]));\n return exports;\n });\n\n\n/**\n * Normalize a file path by removing redundant \"..\" and extraneous \".\" file\n * path components.\n * @param {string} path\n * @return {string}\n * @private\n */\ngoog.normalizePath_ = function(path) {\n var components = path.split('/');\n var i = 0;\n while (i < components.length) {\n if (components[i] == '.') {\n components.splice(i, 1);\n } else if (\n i && components[i] == '..' && components[i - 1] &&\n components[i - 1] != '..') {\n components.splice(--i, 2);\n } else {\n i++;\n }\n }\n return components.join('/');\n};\n\n\n/**\n * Provides a hook for loading a file when using Closure's goog.require() API\n * with goog.modules. In particular this hook is provided to support Node.js.\n *\n * @type {(function(string):string)|undefined}\n */\ngoog.global.CLOSURE_LOAD_FILE_SYNC;\n\n\n/**\n * Loads file by synchronous XHR. Should not be used in production environments.\n * @param {string} src Source URL.\n * @return {?string} File contents, or null if load failed.\n * @private\n */\ngoog.loadFileSync_ = function(src) {\n if (goog.global.CLOSURE_LOAD_FILE_SYNC) {\n return goog.global.CLOSURE_LOAD_FILE_SYNC(src);\n } else {\n try {\n /** @type {XMLHttpRequest} */\n var xhr = new goog.global['XMLHttpRequest']();\n xhr.open('get', src, false);\n xhr.send();\n // NOTE: Successful http: requests have a status of 200, but successful\n // file: requests may have a status of zero. Any other status, or a\n // thrown exception (particularly in case of file: requests) indicates\n // some sort of error, which we treat as a missing or unavailable file.\n return xhr.status == 0 || xhr.status == 200 ? xhr.responseText : null;\n } catch (err) {\n // No need to rethrow or log, since errors should show up on their own.\n return null;\n }\n }\n};\n\n//==============================================================================\n// Language Enhancements\n//==============================================================================\n\n\n/**\n * This is a \"fixed\" version of the typeof operator. It differs from the typeof\n * operator in such a way that null returns 'null' and arrays return 'array'.\n * @param {?} value The value to get the type of.\n * @return {string} The name of the type.\n */\ngoog.typeOf = function(value) {\n var s = typeof value;\n\n if (s != 'object') {\n return s;\n }\n\n if (!value) {\n return 'null';\n }\n\n if (Array.isArray(value)) {\n return 'array';\n }\n return s;\n};\n\n\n/**\n * Returns true if the object looks like an array. To qualify as array like\n * the value needs to be either a NodeList or an object with a Number length\n * property. Note that for this function neither strings nor functions are\n * considered \"array-like\".\n *\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is an array.\n */\ngoog.isArrayLike = function(val) {\n var type = goog.typeOf(val);\n // We do not use goog.isObject here in order to exclude function values.\n return type == 'array' || type == 'object' && typeof val.length == 'number';\n};\n\n\n/**\n * Returns true if the object looks like a Date. To qualify as Date-like the\n * value needs to be an object and have a getFullYear() function.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is a like a Date.\n */\ngoog.isDateLike = function(val) {\n return goog.isObject(val) && typeof val.getFullYear == 'function';\n};\n\n\n/**\n * Returns true if the specified value is an object. This includes arrays and\n * functions.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is an object.\n */\ngoog.isObject = function(val) {\n var type = typeof val;\n return type == 'object' && val != null || type == 'function';\n // return Object(val) === val also works, but is slower, especially if val is\n // not an object.\n};\n\n\n/**\n * Gets a unique ID for an object. This mutates the object so that further calls\n * with the same object as a parameter returns the same value. The unique ID is\n * guaranteed to be unique across the current session amongst objects that are\n * passed into `getUid`. There is no guarantee that the ID is unique or\n * consistent across sessions. It is unsafe to generate unique ID for function\n * prototypes.\n *\n * @param {Object} obj The object to get the unique ID for.\n * @return {number} The unique ID for the object.\n */\ngoog.getUid = function(obj) {\n // TODO(arv): Make the type stricter, do not accept null.\n return Object.prototype.hasOwnProperty.call(obj, goog.UID_PROPERTY_) &&\n obj[goog.UID_PROPERTY_] ||\n (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);\n};\n\n\n/**\n * Whether the given object is already assigned a unique ID.\n *\n * This does not modify the object.\n *\n * @param {!Object} obj The object to check.\n * @return {boolean} Whether there is an assigned unique id for the object.\n */\ngoog.hasUid = function(obj) {\n return !!obj[goog.UID_PROPERTY_];\n};\n\n\n/**\n * Removes the unique ID from an object. This is useful if the object was\n * previously mutated using `goog.getUid` in which case the mutation is\n * undone.\n * @param {Object} obj The object to remove the unique ID field from.\n */\ngoog.removeUid = function(obj) {\n // TODO(arv): Make the type stricter, do not accept null.\n\n // In IE, DOM nodes are not instances of Object and throw an exception if we\n // try to delete. Instead we try to use removeAttribute.\n if (obj !== null && 'removeAttribute' in obj) {\n obj.removeAttribute(goog.UID_PROPERTY_);\n }\n\n try {\n delete obj[goog.UID_PROPERTY_];\n } catch (ex) {\n }\n};\n\n\n/**\n * Name for unique ID property. Initialized in a way to help avoid collisions\n * with other closure JavaScript on the same page.\n * @type {string}\n * @private\n */\ngoog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0);\n\n\n/**\n * Counter for UID.\n * @type {number}\n * @private\n */\ngoog.uidCounter_ = 0;\n\n\n/**\n * Clones a value. The input may be an Object, Array, or basic type. Objects and\n * arrays will be cloned recursively.\n *\n * WARNINGS:\n * <code>goog.cloneObject</code> does not detect reference loops. Objects that\n * refer to themselves will cause infinite recursion.\n *\n * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies\n * UIDs created by <code>getUid</code> into cloned results.\n *\n * @param {*} obj The value to clone.\n * @return {*} A clone of the input value.\n * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods.\n */\ngoog.cloneObject = function(obj) {\n var type = goog.typeOf(obj);\n if (type == 'object' || type == 'array') {\n if (typeof obj.clone === 'function') {\n return obj.clone();\n }\n if (typeof Map !== 'undefined' && obj instanceof Map) {\n return new Map(obj);\n } else if (typeof Set !== 'undefined' && obj instanceof Set) {\n return new Set(obj);\n }\n var clone = type == 'array' ? [] : {};\n for (var key in obj) {\n clone[key] = goog.cloneObject(obj[key]);\n }\n return clone;\n }\n\n return obj;\n};\n\n\n/**\n * A native implementation of goog.bind.\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n * function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n * function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n * invoked as a method of.\n * @template T\n * @private\n */\ngoog.bindNative_ = function(fn, selfObj, var_args) {\n return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));\n};\n\n\n/**\n * A pure-JS implementation of goog.bind.\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n * function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n * function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n * invoked as a method of.\n * @template T\n * @private\n */\ngoog.bindJs_ = function(fn, selfObj, var_args) {\n if (!fn) {\n throw new Error();\n }\n\n if (arguments.length > 2) {\n var boundArgs = Array.prototype.slice.call(arguments, 2);\n return function() {\n // Prepend the bound arguments to the current arguments.\n var newArgs = Array.prototype.slice.call(arguments);\n Array.prototype.unshift.apply(newArgs, boundArgs);\n return fn.apply(selfObj, newArgs);\n };\n\n } else {\n return function() {\n return fn.apply(selfObj, arguments);\n };\n }\n};\n\n\n/**\n * Partially applies this function to a particular 'this object' and zero or\n * more arguments. The result is a new function with some arguments of the first\n * function pre-filled and the value of this 'pre-specified'.\n *\n * Remaining arguments specified at call-time are appended to the pre-specified\n * ones.\n *\n * Also see: {@link #partial}.\n *\n * Usage:\n * <pre>var barMethBound = goog.bind(myFunction, myObj, 'arg1', 'arg2');\n * barMethBound('arg3', 'arg4');</pre>\n *\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n * function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n * function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n * invoked as a method of.\n * @template T\n * @suppress {deprecated} See above.\n * @deprecated use `=> {}` or Function.prototype.bind instead.\n */\ngoog.bind = function(fn, selfObj, var_args) {\n // TODO(nicksantos): narrow the type signature.\n if (Function.prototype.bind &&\n // NOTE(nicksantos): Somebody pulled base.js into the default Chrome\n // extension environment. This means that for Chrome extensions, they get\n // the implementation of Function.prototype.bind that calls goog.bind\n // instead of the native one. Even worse, we don't want to introduce a\n // circular dependency between goog.bind and Function.prototype.bind, so\n // we have to hack this to make sure it works correctly.\n Function.prototype.bind.toString().indexOf('native code') != -1) {\n goog.bind = goog.bindNative_;\n } else {\n goog.bind = goog.bindJs_;\n }\n return goog.bind.apply(null, arguments);\n};\n\n\n/**\n * Like goog.bind(), except that a 'this object' is not required. Useful when\n * the target function is already bound.\n *\n * Usage:\n * var g = goog.partial(f, arg1, arg2);\n * g(arg3, arg4);\n *\n * @param {Function} fn A function to partially apply.\n * @param {...*} var_args Additional arguments that are partially applied to fn.\n * @return {!Function} A partially-applied form of the function goog.partial()\n * was invoked as a method of.\n */\ngoog.partial = function(fn, var_args) {\n var args = Array.prototype.slice.call(arguments, 1);\n return function() {\n // Clone the array (with slice()) and append additional arguments\n // to the existing arguments.\n var newArgs = args.slice();\n newArgs.push.apply(newArgs, arguments);\n return fn.apply(/** @type {?} */ (this), newArgs);\n };\n};\n\n\n/**\n * @return {number} An integer value representing the number of milliseconds\n * between midnight, January 1, 1970 and the current time.\n * @deprecated Use Date.now\n */\ngoog.now = function() {\n return Date.now();\n};\n\n\n/**\n * Evals JavaScript in the global scope.\n *\n * Throws an exception if neither execScript or eval is defined.\n * @param {string|!TrustedScript} script JavaScript string.\n */\ngoog.globalEval = function(script) {\n (0, eval)(script);\n};\n\n\n/**\n * Optional map of CSS class names to obfuscated names used with\n * goog.getCssName().\n * @private {!Object<string, string>|undefined}\n * @see goog.setCssNameMapping\n */\ngoog.cssNameMapping_;\n\n\n/**\n * Optional obfuscation style for CSS class names. Should be set to either\n * 'BY_WHOLE' or 'BY_PART' if defined.\n * @type {string|undefined}\n * @private\n * @see goog.setCssNameMapping\n */\ngoog.cssNameMappingStyle_;\n\n\n\n/**\n * A hook for modifying the default behavior goog.getCssName. The function\n * if present, will receive the standard output of the goog.getCssName as\n * its input.\n *\n * @type {(function(string):string)|undefined}\n */\ngoog.global.CLOSURE_CSS_NAME_MAP_FN;\n\n\n/**\n * Handles strings that are intended to be used as CSS class names.\n *\n * This function works in tandem with @see goog.setCssNameMapping.\n *\n * Without any mapping set, the arguments are simple joined with a hyphen and\n * passed through unaltered.\n *\n * When there is a mapping, there are two possible styles in which these\n * mappings are used. In the BY_PART style, each part (i.e. in between hyphens)\n * of the passed in css name is rewritten according to the map. In the BY_WHOLE\n * style, the full css name is looked up in the map directly. If a rewrite is\n * not specified by the map, the compiler will output a warning.\n *\n * When the mapping is passed to the compiler, it will replace calls to\n * goog.getCssName with the strings from the mapping, e.g.\n * var x = goog.getCssName('foo');\n * var y = goog.getCssName(this.baseClass, 'active');\n * becomes:\n * var x = 'foo';\n * var y = this.baseClass + '-active';\n *\n * If one argument is passed it will be processed, if two are passed only the\n * modifier will be processed, as it is assumed the first argument was generated\n * as a result of calling goog.getCssName.\n *\n * @param {string} className The class name.\n * @param {string=} opt_modifier A modifier to be appended to the class name.\n * @return {string} The class name or the concatenation of the class name and\n * the modifier.\n */\ngoog.getCssName = function(className, opt_modifier) {\n // String() is used for compatibility with compiled soy where the passed\n // className can be non-string objects.\n if (String(className).charAt(0) == '.') {\n throw new Error(\n 'className passed in goog.getCssName must not start with \".\".' +\n ' You passed: ' + className);\n }\n\n var getMapping = function(cssName) {\n return goog.cssNameMapping_[cssName] || cssName;\n };\n\n var renameByParts = function(cssName) {\n // Remap all the parts individually.\n var parts = cssName.split('-');\n var mapped = [];\n for (var i = 0; i < parts.length; i++) {\n mapped.push(getMapping(parts[i]));\n }\n return mapped.join('-');\n };\n\n var rename;\n if (goog.cssNameMapping_) {\n rename =\n goog.cssNameMappingStyle_ == 'BY_WHOLE' ? getMapping : renameByParts;\n } else {\n rename = function(a) {\n return a;\n };\n }\n\n var result =\n opt_modifier ? className + '-' + rename(opt_modifier) : rename(className);\n\n // The special CLOSURE_CSS_NAME_MAP_FN allows users to specify further\n // processing of the class name.\n if (goog.global.CLOSURE_CSS_NAME_MAP_FN) {\n return goog.global.CLOSURE_CSS_NAME_MAP_FN(result);\n }\n\n return result;\n};\n\n\n/**\n * Sets the map to check when returning a value from goog.getCssName(). Example:\n * <pre>\n * goog.setCssNameMapping({\n * \"goog\": \"a\",\n * \"disabled\": \"b\",\n * });\n *\n * var x = goog.getCssName('goog');\n * // The following evaluates to: \"a a-b\".\n * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled')\n * </pre>\n * When declared as a map of string literals to string literals, the JSCompiler\n * will replace all calls to goog.getCssName() using the supplied map if the\n * --process_closure_primitives flag is set.\n *\n * @param {!Object} mapping A map of strings to strings where keys are possible\n * arguments to goog.getCssName() and values are the corresponding values\n * that should be returned.\n * @param {string=} opt_style The style of css name mapping. There are two valid\n * options: 'BY_PART', and 'BY_WHOLE'.\n * @see goog.getCssName for a description.\n */\ngoog.setCssNameMapping = function(mapping, opt_style) {\n goog.cssNameMapping_ = mapping;\n goog.cssNameMappingStyle_ = opt_style;\n};\n\n\n/**\n * To use CSS renaming in compiled mode, one of the input files should have a\n * call to goog.setCssNameMapping() with an object literal that the JSCompiler\n * can extract and use to replace all calls to goog.getCssName(). In uncompiled\n * mode, JavaScript code should be loaded before this base.js file that declares\n * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is\n * to ensure that the mapping is loaded before any calls to goog.getCssName()\n * are made in uncompiled mode.\n *\n * A hook for overriding the CSS name mapping.\n * @type {!Object<string, string>|undefined}\n */\ngoog.global.CLOSURE_CSS_NAME_MAPPING;\n\n\nif (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) {\n // This does not call goog.setCssNameMapping() because the JSCompiler\n // requires that goog.setCssNameMapping() be called with an object literal.\n goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING;\n}\n\n/**\n * Options bag type for `goog.getMsg()` third argument.\n *\n * It is important to note that these options need to be known at compile time,\n * so they must always be provided to `goog.getMsg()` as an actual object\n * literal in the function call. Otherwise, closure-compiler will report an\n * error.\n * @record\n */\ngoog.GetMsgOptions = function() {};\n\n/**\n * If `true`, escape '<' in the message string to '<'.\n *\n * Used by Closure Templates where the generated code size and performance is\n * critical which is why {@link goog.html.SafeHtmlFormatter} is not used.\n * The value must be literal `true` or `false`.\n * @type {boolean|undefined}\n */\ngoog.GetMsgOptions.prototype.html;\n\n/**\n * If `true`, unescape common html entities: >, <, ', " and\n * &.\n *\n * Used for messages not in HTML context, such as with the `textContent`\n * property.\n * The value must be literal `true` or `false`.\n * @type {boolean|undefined}\n */\ngoog.GetMsgOptions.prototype.unescapeHtmlEntities;\n\n/**\n * Associates placeholder names with strings showing how their values are\n * obtained.\n *\n * This field is intended for use in automatically generated JS code.\n * Human-written code should use meaningful placeholder names instead.\n *\n * closure-compiler uses this as the contents of the `<ph>` tag in the\n * XMB file it generates or defaults to `-` for historical reasons.\n *\n * Must be an object literal.\n * Ignored at runtime.\n * Keys are placeholder names.\n * Values are string literals indicating how the value is obtained.\n * Typically this is a snippet of source code.\n * @type {!Object<string, string>|undefined}\n */\ngoog.GetMsgOptions.prototype.original_code;\n\n/**\n * Associates placeholder names with example values.\n *\n * closure-compiler uses this as the contents of the `<ex>` tag in the\n * XMB file it generates or defaults to `-` for historical reasons.\n *\n * Must be an object literal.\n * Ignored at runtime.\n * Keys are placeholder names.\n * Values are string literals containing example placeholder values.\n * (e.g. \"George McFly\" for a name placeholder)\n * @type {!Object<string, string>|undefined}\n */\ngoog.GetMsgOptions.prototype.example;\n\n/**\n * Gets a localized message.\n *\n * This function is a compiler primitive. If you give the compiler a localized\n * message bundle, it will replace the string at compile-time with a localized\n * version, and expand goog.getMsg call to a concatenated string.\n *\n * Messages must be initialized in the form:\n * <code>\n * var MSG_NAME = goog.getMsg('Hello {$placeholder}', {'placeholder': 'world'});\n * </code>\n *\n * This function produces a string which should be treated as plain text. Use\n * {@link goog.html.SafeHtmlFormatter} in conjunction with goog.getMsg to\n * produce SafeHtml.\n *\n * @param {string} str Translatable string, places holders in the form {$foo}.\n * @param {!Object<string, string>=} opt_values Maps place holder name to value.\n * @param {!goog.GetMsgOptions=} opt_options see `goog.GetMsgOptions`\n * @return {string} message with placeholders filled.\n */\ngoog.getMsg = function(str, opt_values, opt_options) {\n if (opt_options && opt_options.html) {\n // Note that '&' is not replaced because the translation can contain HTML\n // entities.\n str = str.replace(/</g, '<');\n }\n if (opt_options && opt_options.unescapeHtmlEntities) {\n // Note that \"&\" must be the last to avoid \"creating\" new entities.\n str = str.replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/'/g, '\\'')\n .replace(/"/g, '\"')\n .replace(/&/g, '&');\n }\n if (opt_values) {\n str = str.replace(/\\{\\$([^}]+)}/g, function(match, key) {\n return (opt_values != null && key in opt_values) ? opt_values[key] :\n match;\n });\n }\n return str;\n};\n\n\n/**\n * Gets a localized message. If the message does not have a translation, gives a\n * fallback message.\n *\n * This is useful when introducing a new message that has not yet been\n * translated into all languages.\n *\n * This function is a compiler primitive. Must be used in the form:\n * <code>var x = goog.getMsgWithFallback(MSG_A, MSG_B);</code>\n * where MSG_A and MSG_B were initialized with goog.getMsg.\n *\n * @param {string} a The preferred message.\n * @param {string} b The fallback message.\n * @return {string} The best translated message.\n */\ngoog.getMsgWithFallback = function(a, b) {\n return a;\n};\n\n\n/**\n * Exposes an unobfuscated global namespace path for the given object.\n * Note that fields of the exported object *will* be obfuscated, unless they are\n * exported in turn via this function or goog.exportProperty.\n *\n * Also handy for making public items that are defined in anonymous closures.\n *\n * ex. goog.exportSymbol('public.path.Foo', Foo);\n *\n * ex. goog.exportSymbol('public.path.Foo.staticFunction', Foo.staticFunction);\n * public.path.Foo.staticFunction();\n *\n * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod',\n * Foo.prototype.myMethod);\n * new public.path.Foo().myMethod();\n *\n * @param {string} publicPath Unobfuscated name to export.\n * @param {*} object Object the name should point to.\n * @param {?Object=} objectToExportTo The object to add the path to; default\n * is goog.global.\n */\ngoog.exportSymbol = function(publicPath, object, objectToExportTo) {\n goog.exportPath_(\n publicPath, object, /* overwriteImplicit= */ true, objectToExportTo);\n};\n\n\n/**\n * Exports a property unobfuscated into the object's namespace.\n * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction);\n * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod);\n * @param {Object} object Object whose static property is being exported.\n * @param {string} publicName Unobfuscated name to export.\n * @param {*} symbol Object the name should point to.\n */\ngoog.exportProperty = function(object, publicName, symbol) {\n object[publicName] = symbol;\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * Usage:\n * <pre>\n * function ParentClass(a, b) { }\n * ParentClass.prototype.foo = function(a) { };\n *\n * function ChildClass(a, b, c) {\n * ChildClass.base(this, 'constructor', a, b);\n * }\n * goog.inherits(ChildClass, ParentClass);\n *\n * var child = new ChildClass('a', 'b', 'see');\n * child.foo(); // This works.\n * </pre>\n *\n * @param {!Function} childCtor Child class.\n * @param {!Function} parentCtor Parent class.\n * @suppress {strictMissingProperties} superClass_ and base is not defined on\n * Function.\n * @deprecated Use ECMAScript class syntax instead.\n */\ngoog.inherits = function(childCtor, parentCtor) {\n /** @constructor */\n function tempCtor() {}\n tempCtor.prototype = parentCtor.prototype;\n childCtor.superClass_ = parentCtor.prototype;\n childCtor.prototype = new tempCtor();\n /** @override */\n childCtor.prototype.constructor = childCtor;\n\n /**\n * Calls superclass constructor/method.\n *\n * This function is only available if you use goog.inherits to\n * express inheritance relationships between classes.\n *\n * NOTE: This is a replacement for goog.base and for superClass_\n * property defined in childCtor.\n *\n * @param {!Object} me Should always be \"this\".\n * @param {string} methodName The method name to call. Calling\n * superclass constructor can be done with the special string\n * 'constructor'.\n * @param {...*} var_args The arguments to pass to superclass\n * method/constructor.\n * @return {*} The return value of the superclass method/constructor.\n */\n childCtor.base = function(me, methodName, var_args) {\n // Copying using loop to avoid deop due to passing arguments object to\n // function. This is faster in many JS engines as of late 2014.\n var args = new Array(arguments.length - 2);\n for (var i = 2; i < arguments.length; i++) {\n args[i - 2] = arguments[i];\n }\n return parentCtor.prototype[methodName].apply(me, args);\n };\n};\n\n\n/**\n * Allow for aliasing within scope functions. This function exists for\n * uncompiled code - in compiled code the calls will be inlined and the aliases\n * applied. In uncompiled code the function is simply run since the aliases as\n * written are valid JavaScript.\n *\n *\n * @param {function()} fn Function to call. This function can contain aliases\n * to namespaces (e.g. \"var dom = goog.dom\") or classes\n * (e.g. \"var Timer = goog.Timer\").\n * @deprecated Use goog.module instead.\n */\ngoog.scope = function(fn) {\n if (goog.isInModuleLoader_()) {\n throw new Error('goog.scope is not supported within a module.');\n }\n fn.call(goog.global);\n};\n\n\n/*\n * To support uncompiled, strict mode bundles that use eval to divide source\n * like so:\n * eval('someSource;//# sourceUrl sourcefile.js');\n * We need to export the globally defined symbols \"goog\" and \"COMPILED\".\n * Exporting \"goog\" breaks the compiler optimizations, so we required that\n * be defined externally.\n * NOTE: We don't use goog.exportSymbol here because we don't want to trigger\n * extern generation when that compiler option is enabled.\n */\nif (!COMPILED) {\n goog.global['COMPILED'] = COMPILED;\n}\n\n\n//==============================================================================\n// goog.defineClass implementation\n//==============================================================================\n\n\n/**\n * Creates a restricted form of a Closure \"class\":\n * - from the compiler's perspective, the instance returned from the\n * constructor is sealed (no new properties may be added). This enables\n * better checks.\n * - the compiler will rewrite this definition to a form that is optimal\n * for type checking and optimization (initially this will be a more\n * traditional form).\n *\n * @param {Function} superClass The superclass, Object or null.\n * @param {goog.defineClass.ClassDescriptor} def\n * An object literal describing\n * the class. It may have the following properties:\n * \"constructor\": the constructor function\n * \"statics\": an object literal containing methods to add to the constructor\n * as \"static\" methods or a function that will receive the constructor\n * function as its only parameter to which static properties can\n * be added.\n * all other properties are added to the prototype.\n * @return {!Function} The class constructor.\n * @deprecated Use ECMAScript class syntax instead.\n */\ngoog.defineClass = function(superClass, def) {\n // TODO(johnlenz): consider making the superClass an optional parameter.\n var constructor = def.constructor;\n var statics = def.statics;\n // Wrap the constructor prior to setting up the prototype and static methods.\n if (!constructor || constructor == Object.prototype.constructor) {\n constructor = function() {\n throw new Error(\n 'cannot instantiate an interface (no constructor defined).');\n };\n }\n\n var cls = goog.defineClass.createSealingConstructor_(constructor, superClass);\n if (superClass) {\n goog.inherits(cls, superClass);\n }\n\n // Remove all the properties that should not be copied to the prototype.\n delete def.constructor;\n delete def.statics;\n\n goog.defineClass.applyProperties_(cls.prototype, def);\n if (statics != null) {\n if (statics instanceof Function) {\n statics(cls);\n } else {\n goog.defineClass.applyProperties_(cls, statics);\n }\n }\n\n return cls;\n};\n\n\n/**\n * @typedef {{\n * constructor: (!Function|undefined),\n * statics: (Object|undefined|function(Function):void)\n * }}\n */\ngoog.defineClass.ClassDescriptor;\n\n\n/**\n * @define {boolean} Whether the instances returned by goog.defineClass should\n * be sealed when possible.\n *\n * When sealing is disabled the constructor function will not be wrapped by\n * goog.defineClass, making it incompatible with ES6 class methods.\n */\ngoog.defineClass.SEAL_CLASS_INSTANCES =\n goog.define('goog.defineClass.SEAL_CLASS_INSTANCES', goog.DEBUG);\n\n\n/**\n * If goog.defineClass.SEAL_CLASS_INSTANCES is enabled and Object.seal is\n * defined, this function will wrap the constructor in a function that seals the\n * results of the provided constructor function.\n *\n * @param {!Function} ctr The constructor whose results maybe be sealed.\n * @param {Function} superClass The superclass constructor.\n * @return {!Function} The replacement constructor.\n * @private\n */\ngoog.defineClass.createSealingConstructor_ = function(ctr, superClass) {\n if (!goog.defineClass.SEAL_CLASS_INSTANCES) {\n // Do now wrap the constructor when sealing is disabled. Angular code\n // depends on this for injection to work properly.\n return ctr;\n }\n\n // NOTE: The sealing behavior has been removed\n\n /**\n * @this {Object}\n * @return {?}\n */\n var wrappedCtr = function() {\n // Don't seal an instance of a subclass when it calls the constructor of\n // its super class as there is most likely still setup to do.\n var instance = ctr.apply(this, arguments) || this;\n instance[goog.UID_PROPERTY_] = instance[goog.UID_PROPERTY_];\n\n return instance;\n };\n\n return wrappedCtr;\n};\n\n\n\n// TODO(johnlenz): share these values with the goog.object\n/**\n * The names of the fields that are defined on Object.prototype.\n * @type {!Array<string>}\n * @private\n * @const\n */\ngoog.defineClass.OBJECT_PROTOTYPE_FIELDS_ = [\n 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',\n 'toLocaleString', 'toString', 'valueOf'\n];\n\n\n// TODO(johnlenz): share this function with the goog.object\n/**\n * @param {!Object} target The object to add properties to.\n * @param {!Object} source The object to copy properties from.\n * @private\n */\ngoog.defineClass.applyProperties_ = function(target, source) {\n // TODO(johnlenz): update this to support ES5 getters/setters\n\n var key;\n for (key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n\n // For IE the for-in-loop does not contain any properties that are not\n // enumerable on the prototype object (for example isPrototypeOf from\n // Object.prototype) and it will also not include 'replace' on objects that\n // extend String and change 'replace' (not that it is common for anyone to\n // extend anything except Object).\n for (var i = 0; i < goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length; i++) {\n key = goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[i];\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n};\n\n/**\n * Returns the parameter.\n * @param {string} s\n * @return {string}\n * @private\n */\ngoog.identity_ = function(s) {\n return s;\n};\n\n\n/**\n * Creates Trusted Types policy if Trusted Types are supported by the browser.\n * The policy just blesses any string as a Trusted Type. It is not visibility\n * restricted because anyone can also call trustedTypes.createPolicy directly.\n * However, the allowed names should be restricted by a HTTP header and the\n * reference to the created policy should be visibility restricted.\n * @param {string} name\n * @return {?TrustedTypePolicy}\n */\ngoog.createTrustedTypesPolicy = function(name) {\n var policy = null;\n var policyFactory = goog.global.trustedTypes;\n if (!policyFactory || !policyFactory.createPolicy) {\n return policy;\n }\n // trustedTypes.createPolicy throws if called with a name that is already\n // registered, even in report-only mode. Until the API changes, catch the\n // error not to break the applications functionally. In such case, the code\n // will fall back to using regular Safe Types.\n // TODO(koto): Remove catching once createPolicy API stops throwing.\n try {\n policy = policyFactory.createPolicy(name, {\n createHTML: goog.identity_,\n createScript: goog.identity_,\n createScriptURL: goog.identity_\n });\n } catch (e) {\n goog.logToConsole_(e.message);\n }\n return policy;\n};\n\n// There's a bug in the compiler where without collapse properties the\n// Closure namespace defines do not guard code correctly. To help reduce code\n// size also check for !COMPILED even though it redundant until this is fixed.\nif (!COMPILED && goog.DEPENDENCIES_ENABLED) {\n\n\n /**\n * Tries to detect whether the current browser is Edge, based on the user\n * agent. This matches only pre-Chromium Edge.\n * @see https://docs.microsoft.com/en-us/microsoft-edge/web-platform/user-agent-string\n * @return {boolean} True if the current browser is Edge.\n * @private\n */\n goog.isEdge_ = function() {\n var userAgent = goog.global.navigator && goog.global.navigator.userAgent ?\n goog.global.navigator.userAgent :\n '';\n var edgeRe = /Edge\\/(\\d+)(\\.\\d)*/i;\n return !!userAgent.match(edgeRe);\n };\n\n\n /**\n * Tries to detect whether is in the context of an HTML document.\n * @return {boolean} True if it looks like HTML document.\n * @private\n */\n goog.inHtmlDocument_ = function() {\n /** @type {!Document} */\n var doc = goog.global.document;\n return doc != null && 'write' in doc; // XULDocument misses write.\n };\n\n\n /**\n * We'd like to check for if the document readyState is 'loading'; however\n * there are bugs on IE 10 and below where the readyState being anything other\n * than 'complete' is not reliable.\n * @return {boolean}\n * @private\n */\n goog.isDocumentLoading_ = function() {\n // attachEvent is available on IE 6 thru 10 only, and thus can be used to\n // detect those browsers.\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n return doc.attachEvent ? doc.readyState != 'complete' :\n doc.readyState == 'loading';\n };\n\n\n /**\n * Tries to detect the base path of base.js script that bootstraps Closure.\n * @private\n */\n goog.findBasePath_ = function() {\n if (goog.global.CLOSURE_BASE_PATH != undefined &&\n // Anti DOM-clobbering runtime check (b/37736576).\n typeof goog.global.CLOSURE_BASE_PATH === 'string') {\n goog.basePath = goog.global.CLOSURE_BASE_PATH;\n return;\n } else if (!goog.inHtmlDocument_()) {\n return;\n }\n /** @type {!Document} */\n var doc = goog.global.document;\n // If we have a currentScript available, use it exclusively.\n var currentScript = doc.currentScript;\n if (currentScript) {\n var scripts = [currentScript];\n } else {\n var scripts = doc.getElementsByTagName('SCRIPT');\n }\n // Search backwards since the current script is in almost all cases the one\n // that has base.js.\n for (var i = scripts.length - 1; i >= 0; --i) {\n var script = /** @type {!HTMLScriptElement} */ (scripts[i]);\n var src = script.src;\n var qmark = src.lastIndexOf('?');\n var l = qmark == -1 ? src.length : qmark;\n if (src.slice(l - 7, l) == 'base.js') {\n goog.basePath = src.slice(0, l - 7);\n return;\n }\n }\n };\n\n goog.findBasePath_();\n\n /**\n * Rewrites closing script tags in input to avoid ending an enclosing script\n * tag.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n goog.protectScriptTag_ = function(str) {\n return str.replace(/<\\/(SCRIPT)/ig, '\\\\x3c/$1');\n };\n\n\n /**\n * A debug loader is responsible for downloading and executing javascript\n * files in an unbundled, uncompiled environment.\n *\n * This can be custimized via the setDependencyFactory method, or by\n * CLOSURE_IMPORT_SCRIPT/CLOSURE_LOAD_FILE_SYNC.\n *\n * @struct @constructor @final @private\n */\n goog.DebugLoader_ = function() {\n /** @private @const {!Object<string, !goog.Dependency>} */\n this.dependencies_ = {};\n /** @private @const {!Object<string, string>} */\n this.idToPath_ = {};\n /** @private @const {!Object<string, boolean>} */\n this.written_ = {};\n /** @private @const {!Array<!goog.Dependency>} */\n this.loadingDeps_ = [];\n /** @private {!Array<!goog.Dependency>} */\n this.depsToLoad_ = [];\n /** @private {boolean} */\n this.paused_ = false;\n /** @private {!goog.DependencyFactory} */\n this.factory_ = new goog.DependencyFactory();\n /** @private @const {!Object<string, !Function>} */\n this.deferredCallbacks_ = {};\n /** @private @const {!Array<string>} */\n this.deferredQueue_ = [];\n };\n\n /**\n * @param {!Array<string>} namespaces\n * @param {function(): undefined} callback Function to call once all the\n * namespaces have loaded.\n */\n goog.DebugLoader_.prototype.bootstrap = function(namespaces, callback) {\n var cb = callback;\n function resolve() {\n if (cb) {\n goog.global.setTimeout(cb, 0);\n cb = null;\n }\n }\n\n if (!namespaces.length) {\n resolve();\n return;\n }\n\n var deps = [];\n for (var i = 0; i < namespaces.length; i++) {\n var path = this.getPathFromDeps_(namespaces[i]);\n if (!path) {\n throw new Error('Unregonized namespace: ' + namespaces[i]);\n }\n deps.push(this.dependencies_[path]);\n }\n\n var require = goog.require;\n var loaded = 0;\n for (var i = 0; i < namespaces.length; i++) {\n require(namespaces[i]);\n deps[i].onLoad(function() {\n if (++loaded == namespaces.length) {\n resolve();\n }\n });\n }\n };\n\n\n /**\n * Loads the Closure Dependency file.\n *\n * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base\n * loaded, setDependencyFactory called, and then this called. i.e. allows\n * custom loading of the deps file.\n */\n goog.DebugLoader_.prototype.loadClosureDeps = function() {\n // Circumvent addDependency, which would try to transpile deps.js if\n // transpile is set to always.\n var relPath = 'deps.js';\n this.depsToLoad_.push(this.factory_.createDependency(\n goog.normalizePath_(goog.basePath + relPath), relPath, [], [], {}));\n this.loadDeps_();\n };\n\n\n /**\n * Notifies the debug loader when a dependency has been requested.\n *\n * @param {string} absPathOrId Path of the dependency or goog id.\n * @param {boolean=} opt_force\n */\n goog.DebugLoader_.prototype.requested = function(absPathOrId, opt_force) {\n var path = this.getPathFromDeps_(absPathOrId);\n if (path &&\n (opt_force || this.areDepsLoaded_(this.dependencies_[path].requires))) {\n var callback = this.deferredCallbacks_[path];\n if (callback) {\n delete this.deferredCallbacks_[path];\n callback();\n }\n }\n };\n\n\n /**\n * Sets the dependency factory, which can be used to create custom\n * goog.Dependency implementations to control how dependencies are loaded.\n *\n * @param {!goog.DependencyFactory} factory\n */\n goog.DebugLoader_.prototype.setDependencyFactory = function(factory) {\n this.factory_ = factory;\n };\n\n\n /**\n * Travserses the dependency graph and queues the given dependency, and all of\n * its transitive dependencies, for loading and then starts loading if not\n * paused.\n *\n * @param {string} namespace\n * @private\n */\n goog.DebugLoader_.prototype.load_ = function(namespace) {\n if (!this.getPathFromDeps_(namespace)) {\n var errorMessage = 'goog.require could not find: ' + namespace;\n goog.logToConsole_(errorMessage);\n } else {\n var loader = this;\n\n var deps = [];\n\n /** @param {string} namespace */\n var visit = function(namespace) {\n var path = loader.getPathFromDeps_(namespace);\n\n if (!path) {\n throw new Error('Bad dependency path or symbol: ' + namespace);\n }\n\n if (loader.written_[path]) {\n return;\n }\n\n loader.written_[path] = true;\n\n var dep = loader.dependencies_[path];\n for (var i = 0; i < dep.requires.length; i++) {\n if (!goog.isProvided_(dep.requires[i])) {\n visit(dep.requires[i]);\n }\n }\n\n deps.push(dep);\n };\n\n visit(namespace);\n\n var wasLoading = !!this.depsToLoad_.length;\n this.depsToLoad_ = this.depsToLoad_.concat(deps);\n\n if (!this.paused_ && !wasLoading) {\n this.loadDeps_();\n }\n }\n };\n\n\n /**\n * Loads any queued dependencies until they are all loaded or paused.\n *\n * @private\n */\n goog.DebugLoader_.prototype.loadDeps_ = function() {\n var loader = this;\n var paused = this.paused_;\n\n while (this.depsToLoad_.length && !paused) {\n (function() {\n var loadCallDone = false;\n var dep = loader.depsToLoad_.shift();\n\n var loaded = false;\n loader.loading_(dep);\n\n var controller = {\n pause: function() {\n if (loadCallDone) {\n throw new Error('Cannot call pause after the call to load.');\n } else {\n paused = true;\n }\n },\n resume: function() {\n if (loadCallDone) {\n loader.resume_();\n } else {\n // Some dep called pause and then resume in the same load call.\n // Just keep running this same loop.\n paused = false;\n }\n },\n loaded: function() {\n if (loaded) {\n throw new Error('Double call to loaded.');\n }\n\n loaded = true;\n loader.loaded_(dep);\n },\n pending: function() {\n // Defensive copy.\n var pending = [];\n for (var i = 0; i < loader.loadingDeps_.length; i++) {\n pending.push(loader.loadingDeps_[i]);\n }\n return pending;\n },\n /**\n * @param {goog.ModuleType} type\n */\n setModuleState: function(type) {\n goog.moduleLoaderState_ = {\n type: type,\n moduleName: '',\n declareLegacyNamespace: false\n };\n },\n /** @type {function(string, string, string=)} */\n registerEs6ModuleExports: function(\n path, exports, opt_closureNamespace) {\n if (opt_closureNamespace) {\n goog.loadedModules_[opt_closureNamespace] = {\n exports: exports,\n type: goog.ModuleType.ES6,\n moduleId: opt_closureNamespace || ''\n };\n }\n },\n /** @type {function(string, ?)} */\n registerGoogModuleExports: function(moduleId, exports) {\n goog.loadedModules_[moduleId] = {\n exports: exports,\n type: goog.ModuleType.GOOG,\n moduleId: moduleId\n };\n },\n clearModuleState: function() {\n goog.moduleLoaderState_ = null;\n },\n defer: function(callback) {\n if (loadCallDone) {\n throw new Error(\n 'Cannot register with defer after the call to load.');\n }\n loader.defer_(dep, callback);\n },\n areDepsLoaded: function() {\n return loader.areDepsLoaded_(dep.requires);\n }\n };\n\n try {\n dep.load(controller);\n } finally {\n loadCallDone = true;\n }\n })();\n }\n\n if (paused) {\n this.pause_();\n }\n };\n\n\n /** @private */\n goog.DebugLoader_.prototype.pause_ = function() {\n this.paused_ = true;\n };\n\n\n /** @private */\n goog.DebugLoader_.prototype.resume_ = function() {\n if (this.paused_) {\n this.paused_ = false;\n this.loadDeps_();\n }\n };\n\n\n /**\n * Marks the given dependency as loading (load has been called but it has not\n * yet marked itself as finished). Useful for dependencies that want to know\n * what else is loading. Example: goog.modules cannot eval if there are\n * loading dependencies.\n *\n * @param {!goog.Dependency} dep\n * @private\n */\n goog.DebugLoader_.prototype.loading_ = function(dep) {\n this.loadingDeps_.push(dep);\n };\n\n\n /**\n * Marks the given dependency as having finished loading and being available\n * for require.\n *\n * @param {!goog.Dependency} dep\n * @private\n */\n goog.DebugLoader_.prototype.loaded_ = function(dep) {\n for (var i = 0; i < this.loadingDeps_.length; i++) {\n if (this.loadingDeps_[i] == dep) {\n this.loadingDeps_.splice(i, 1);\n break;\n }\n }\n\n for (var i = 0; i < this.deferredQueue_.length; i++) {\n if (this.deferredQueue_[i] == dep.path) {\n this.deferredQueue_.splice(i, 1);\n break;\n }\n }\n\n if (this.loadingDeps_.length == this.deferredQueue_.length &&\n !this.depsToLoad_.length) {\n // Something has asked to load these, but they may not be directly\n // required again later, so load them now that we know we're done loading\n // everything else. e.g. a goog module entry point.\n while (this.deferredQueue_.length) {\n this.requested(this.deferredQueue_.shift(), true);\n }\n }\n\n dep.loaded();\n };\n\n\n /**\n * @param {!Array<string>} pathsOrIds\n * @return {boolean}\n * @private\n */\n goog.DebugLoader_.prototype.areDepsLoaded_ = function(pathsOrIds) {\n for (var i = 0; i < pathsOrIds.length; i++) {\n var path = this.getPathFromDeps_(pathsOrIds[i]);\n if (!path ||\n (!(path in this.deferredCallbacks_) &&\n !goog.isProvided_(pathsOrIds[i]))) {\n return false;\n }\n }\n\n return true;\n };\n\n\n /**\n * @param {string} absPathOrId\n * @return {?string}\n * @private\n */\n goog.DebugLoader_.prototype.getPathFromDeps_ = function(absPathOrId) {\n if (absPathOrId in this.idToPath_) {\n return this.idToPath_[absPathOrId];\n } else if (absPathOrId in this.dependencies_) {\n return absPathOrId;\n } else {\n return null;\n }\n };\n\n\n /**\n * @param {!goog.Dependency} dependency\n * @param {!Function} callback\n * @private\n */\n goog.DebugLoader_.prototype.defer_ = function(dependency, callback) {\n this.deferredCallbacks_[dependency.path] = callback;\n this.deferredQueue_.push(dependency.path);\n };\n\n\n /**\n * Interface for goog.Dependency implementations to have some control over\n * loading of dependencies.\n *\n * @record\n */\n goog.LoadController = function() {};\n\n\n /**\n * Tells the controller to halt loading of more dependencies.\n */\n goog.LoadController.prototype.pause = function() {};\n\n\n /**\n * Tells the controller to resume loading of more dependencies if paused.\n */\n goog.LoadController.prototype.resume = function() {};\n\n\n /**\n * Tells the controller that this dependency has finished loading.\n *\n * This causes this to be removed from pending() and any load callbacks to\n * fire.\n */\n goog.LoadController.prototype.loaded = function() {};\n\n\n /**\n * List of dependencies on which load has been called but which have not\n * called loaded on their controller. This includes the current dependency.\n *\n * @return {!Array<!goog.Dependency>}\n */\n goog.LoadController.prototype.pending = function() {};\n\n\n /**\n * Registers an object as an ES6 module's exports so that goog.modules may\n * require it by path.\n *\n * @param {string} path Full path of the module.\n * @param {?} exports\n * @param {string=} opt_closureNamespace Closure namespace to associate with\n * this module.\n */\n goog.LoadController.prototype.registerEs6ModuleExports = function(\n path, exports, opt_closureNamespace) {};\n\n\n /**\n * Sets the current module state.\n *\n * @param {goog.ModuleType} type Type of module.\n */\n goog.LoadController.prototype.setModuleState = function(type) {};\n\n\n /**\n * Clears the current module state.\n */\n goog.LoadController.prototype.clearModuleState = function() {};\n\n\n /**\n * Registers a callback to call once the dependency is actually requested\n * via goog.require + all of the immediate dependencies have been loaded or\n * all other files have been loaded. Allows for lazy loading until\n * require'd without pausing dependency loading, which is needed on old IE.\n *\n * @param {!Function} callback\n */\n goog.LoadController.prototype.defer = function(callback) {};\n\n\n /**\n * @return {boolean}\n */\n goog.LoadController.prototype.areDepsLoaded = function() {};\n\n\n /**\n * Basic super class for all dependencies Closure Library can load.\n *\n * This default implementation is designed to load untranspiled, non-module\n * scripts in a web broswer.\n *\n * For goog.modules see {@see goog.GoogModuleDependency}.\n * For untranspiled ES6 modules {@see goog.Es6ModuleDependency}.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor\n */\n goog.Dependency = function(\n path, relativePath, provides, requires, loadFlags) {\n /** @const */\n this.path = path;\n /** @const */\n this.relativePath = relativePath;\n /** @const */\n this.provides = provides;\n /** @const */\n this.requires = requires;\n /** @const */\n this.loadFlags = loadFlags;\n /** @private {boolean} */\n this.loaded_ = false;\n /** @private {!Array<function()>} */\n this.loadCallbacks_ = [];\n };\n\n\n /**\n * @return {string} The pathname part of this dependency's path if it is a\n * URI.\n */\n goog.Dependency.prototype.getPathName = function() {\n var pathName = this.path;\n var protocolIndex = pathName.indexOf('://');\n if (protocolIndex >= 0) {\n pathName = pathName.substring(protocolIndex + 3);\n var slashIndex = pathName.indexOf('/');\n if (slashIndex >= 0) {\n pathName = pathName.substring(slashIndex + 1);\n }\n }\n return pathName;\n };\n\n\n /**\n * @param {function()} callback Callback to fire as soon as this has loaded.\n * @final\n */\n goog.Dependency.prototype.onLoad = function(callback) {\n if (this.loaded_) {\n callback();\n } else {\n this.loadCallbacks_.push(callback);\n }\n };\n\n\n /**\n * Marks this dependency as loaded and fires any callbacks registered with\n * onLoad.\n * @final\n */\n goog.Dependency.prototype.loaded = function() {\n this.loaded_ = true;\n var callbacks = this.loadCallbacks_;\n this.loadCallbacks_ = [];\n for (var i = 0; i < callbacks.length; i++) {\n callbacks[i]();\n }\n };\n\n\n /**\n * Whether or not document.written / appended script tags should be deferred.\n *\n * @private {boolean}\n */\n goog.Dependency.defer_ = false;\n\n\n /**\n * Map of script ready / state change callbacks. Old IE cannot handle putting\n * these properties on goog.global.\n *\n * @private @const {!Object<string, function(?):undefined>}\n */\n goog.Dependency.callbackMap_ = {};\n\n\n /**\n * @param {function(...?):?} callback\n * @return {string}\n * @private\n */\n goog.Dependency.registerCallback_ = function(callback) {\n var key = Math.random().toString(32);\n goog.Dependency.callbackMap_[key] = callback;\n return key;\n };\n\n\n /**\n * @param {string} key\n * @private\n */\n goog.Dependency.unregisterCallback_ = function(key) {\n delete goog.Dependency.callbackMap_[key];\n };\n\n\n /**\n * @param {string} key\n * @param {...?} var_args\n * @private\n * @suppress {unusedPrivateMembers}\n */\n goog.Dependency.callback_ = function(key, var_args) {\n if (key in goog.Dependency.callbackMap_) {\n var callback = goog.Dependency.callbackMap_[key];\n var args = [];\n for (var i = 1; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n callback.apply(undefined, args);\n } else {\n var errorMessage = 'Callback key ' + key +\n ' does not exist (was base.js loaded more than once?).';\n throw Error(errorMessage);\n }\n };\n\n\n /**\n * Starts loading this dependency. This dependency can pause loading if it\n * needs to and resume it later via the controller interface.\n *\n * When this is loaded it should call controller.loaded(). Note that this will\n * end up calling the loaded method of this dependency; there is no need to\n * call it explicitly.\n *\n * @param {!goog.LoadController} controller\n */\n goog.Dependency.prototype.load = function(controller) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n if (!goog.inHtmlDocument_()) {\n goog.logToConsole_(\n 'Cannot use default debug loader outside of HTML documents.');\n if (this.relativePath == 'deps.js') {\n // Some old code is relying on base.js auto loading deps.js failing with\n // no error before later setting CLOSURE_IMPORT_SCRIPT.\n // CLOSURE_IMPORT_SCRIPT should be set *before* base.js is loaded, or\n // CLOSURE_NO_DEPS set to true.\n goog.logToConsole_(\n 'Consider setting CLOSURE_IMPORT_SCRIPT before loading base.js, ' +\n 'or setting CLOSURE_NO_DEPS to true.');\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n\n // If the user tries to require a new symbol after document load,\n // something has gone terribly wrong. Doing a document.write would\n // wipe out the page. This does not apply to the CSP-compliant method\n // of writing script tags.\n if (doc.readyState == 'complete' &&\n !goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING) {\n // Certain test frameworks load base.js multiple times, which tries\n // to write deps.js each time. If that happens, just fail silently.\n // These frameworks wipe the page between each load of base.js, so this\n // is OK.\n var isDeps = /\\bdeps.js$/.test(this.path);\n if (isDeps) {\n controller.loaded();\n return;\n } else {\n throw Error('Cannot write \"' + this.path + '\" after document load');\n }\n }\n\n var nonce = goog.getScriptNonce_();\n if (!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING &&\n goog.isDocumentLoading_()) {\n var key;\n var callback = function(script) {\n if (script.readyState && script.readyState != 'complete') {\n script.onload = callback;\n return;\n }\n goog.Dependency.unregisterCallback_(key);\n controller.loaded();\n };\n key = goog.Dependency.registerCallback_(callback);\n\n var defer = goog.Dependency.defer_ ? ' defer' : '';\n var nonceAttr = nonce ? ' nonce=\"' + nonce + '\"' : '';\n var script = '<script src=\"' + this.path + '\"' + nonceAttr + defer +\n ' id=\"script-' + key + '\"><\\/script>';\n\n script += '<script' + nonceAttr + '>';\n\n if (goog.Dependency.defer_) {\n script += 'document.getElementById(\\'script-' + key +\n '\\').onload = function() {\\n' +\n ' goog.Dependency.callback_(\\'' + key + '\\', this);\\n' +\n '};\\n';\n } else {\n script += 'goog.Dependency.callback_(\\'' + key +\n '\\', document.getElementById(\\'script-' + key + '\\'));';\n }\n\n script += '<\\/script>';\n\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n } else {\n var scriptEl =\n /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\n scriptEl.defer = goog.Dependency.defer_;\n scriptEl.async = false;\n\n // If CSP nonces are used, propagate them to dynamically created scripts.\n // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\n if (nonce) {\n scriptEl.nonce = nonce;\n }\n\n scriptEl.onload = function() {\n scriptEl.onload = null;\n controller.loaded();\n };\n\n scriptEl.src = goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createScriptURL(this.path) :\n this.path;\n doc.head.appendChild(scriptEl);\n }\n };\n\n\n /**\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides Should be an empty array.\n * TODO(johnplaisted) add support for adding closure namespaces to ES6\n * modules for interop purposes.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor\n * @extends {goog.Dependency}\n */\n goog.Es6ModuleDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.Es6ModuleDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n };\n goog.inherits(goog.Es6ModuleDependency, goog.Dependency);\n\n\n /**\n * @override\n * @param {!goog.LoadController} controller\n */\n goog.Es6ModuleDependency.prototype.load = function(controller) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n if (!goog.inHtmlDocument_()) {\n goog.logToConsole_(\n 'Cannot use default debug loader outside of HTML documents.');\n controller.pause();\n return;\n }\n\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n\n var dep = this;\n\n // TODO(johnplaisted): Does document.writing really speed up anything? Any\n // difference between this and just waiting for interactive mode and then\n // appending?\n function write(src, contents) {\n var nonceAttr = '';\n var nonce = goog.getScriptNonce_();\n if (nonce) {\n nonceAttr = ' nonce=\"' + nonce + '\"';\n }\n\n if (contents) {\n var script = '<script type=\"module\" crossorigin' + nonceAttr + '>' +\n contents + '</' +\n 'script>';\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n } else {\n var script = '<script type=\"module\" crossorigin src=\"' + src + '\"' +\n nonceAttr + '></' +\n 'script>';\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n }\n }\n\n function append(src, contents) {\n var scriptEl =\n /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\n scriptEl.defer = true;\n scriptEl.async = false;\n scriptEl.type = 'module';\n scriptEl.setAttribute('crossorigin', true);\n\n // If CSP nonces are used, propagate them to dynamically created scripts.\n // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\n var nonce = goog.getScriptNonce_();\n if (nonce) {\n scriptEl.nonce = nonce;\n }\n\n if (contents) {\n scriptEl.text = goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createScript(contents) :\n contents;\n } else {\n scriptEl.src = goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createScriptURL(src) :\n src;\n }\n\n doc.head.appendChild(scriptEl);\n }\n\n var create;\n\n if (goog.isDocumentLoading_()) {\n create = write;\n // We can ONLY call document.write if we are guaranteed that any\n // non-module script tags document.written after this are deferred.\n // Small optimization, in theory document.writing is faster.\n goog.Dependency.defer_ = true;\n } else {\n create = append;\n }\n\n // Write 4 separate tags here:\n // 1) Sets the module state at the correct time (just before execution).\n // 2) A src node for this, which just hopefully lets the browser load it a\n // little early (no need to parse #3).\n // 3) Import the module and register it.\n // 4) Clear the module state at the correct time. Guaranteed to run even\n // if there is an error in the module (#3 will not run if there is an\n // error in the module).\n var beforeKey = goog.Dependency.registerCallback_(function() {\n goog.Dependency.unregisterCallback_(beforeKey);\n controller.setModuleState(goog.ModuleType.ES6);\n });\n create(undefined, 'goog.Dependency.callback_(\"' + beforeKey + '\")');\n\n // TODO(johnplaisted): Does this really speed up anything?\n create(this.path, undefined);\n\n var registerKey = goog.Dependency.registerCallback_(function(exports) {\n goog.Dependency.unregisterCallback_(registerKey);\n controller.registerEs6ModuleExports(\n dep.path, exports, goog.moduleLoaderState_.moduleName);\n });\n create(\n undefined,\n 'import * as m from \"' + this.path + '\"; goog.Dependency.callback_(\"' +\n registerKey + '\", m)');\n\n var afterKey = goog.Dependency.registerCallback_(function() {\n goog.Dependency.unregisterCallback_(afterKey);\n controller.clearModuleState();\n controller.loaded();\n });\n create(undefined, 'goog.Dependency.callback_(\"' + afterKey + '\")');\n };\n\n\n /**\n * Superclass of any dependency that needs to be loaded into memory,\n * transformed, and then eval'd (goog.modules and transpiled files).\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor @abstract\n * @extends {goog.Dependency}\n */\n goog.TransformedDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.TransformedDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n /** @private {?string} */\n this.contents_ = null;\n\n /**\n * Whether to lazily make the synchronous XHR (when goog.require'd) or make\n * the synchronous XHR when initially loading. On FireFox 61 there is a bug\n * where an ES6 module cannot make a synchronous XHR (rather, it can, but if\n * it does then no other ES6 modules will load after).\n *\n * tl;dr we lazy load due to bugs on older browsers and eager load due to\n * bugs on newer ones.\n *\n * https://bugzilla.mozilla.org/show_bug.cgi?id=1477090\n *\n * @private @const {boolean}\n */\n this.lazyFetch_ = !goog.inHtmlDocument_() ||\n !('noModule' in goog.global.document.createElement('script'));\n };\n goog.inherits(goog.TransformedDependency, goog.Dependency);\n\n\n /**\n * @override\n * @param {!goog.LoadController} controller\n */\n goog.TransformedDependency.prototype.load = function(controller) {\n var dep = this;\n\n function fetch() {\n dep.contents_ = goog.loadFileSync_(dep.path);\n\n if (dep.contents_) {\n dep.contents_ = dep.transform(dep.contents_);\n if (dep.contents_) {\n dep.contents_ += '\\n//# sourceURL=' + dep.path;\n }\n }\n }\n\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n fetch();\n if (this.contents_ &&\n goog.global.CLOSURE_IMPORT_SCRIPT('', this.contents_)) {\n this.contents_ = null;\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n\n var isEs6 = this.loadFlags['module'] == goog.ModuleType.ES6;\n\n if (!this.lazyFetch_) {\n fetch();\n }\n\n function load() {\n if (dep.lazyFetch_) {\n fetch();\n }\n\n if (!dep.contents_) {\n // loadFileSync_ or transform are responsible. Assume they logged an\n // error.\n return;\n }\n\n if (isEs6) {\n controller.setModuleState(goog.ModuleType.ES6);\n }\n\n var namespace;\n\n try {\n var contents = dep.contents_;\n dep.contents_ = null;\n goog.globalEval(goog.CLOSURE_EVAL_PREFILTER_.createScript(contents));\n if (isEs6) {\n namespace = goog.moduleLoaderState_.moduleName;\n }\n } finally {\n if (isEs6) {\n controller.clearModuleState();\n }\n }\n\n if (isEs6) {\n // Due to circular dependencies this may not be available for require\n // right now.\n goog.global['$jscomp']['require']['ensure'](\n [dep.getPathName()], function() {\n controller.registerEs6ModuleExports(\n dep.path,\n goog.global['$jscomp']['require'](dep.getPathName()),\n namespace);\n });\n }\n\n controller.loaded();\n }\n\n // Do not fetch now; in FireFox 47 the synchronous XHR doesn't block all\n // events. If we fetched now and then document.write'd the contents the\n // document.write would be an eval and would execute too soon! Instead write\n // a script tag to fetch and eval synchronously at the correct time.\n function fetchInOwnScriptThenLoad() {\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n\n var key = goog.Dependency.registerCallback_(function() {\n goog.Dependency.unregisterCallback_(key);\n load();\n });\n\n var nonce = goog.getScriptNonce_();\n var nonceAttr = nonce ? ' nonce=\"' + nonce + '\"' : '';\n var script = '<script' + nonceAttr + '>' +\n goog.protectScriptTag_('goog.Dependency.callback_(\"' + key + '\");') +\n '</' +\n 'script>';\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n }\n\n // If one thing is pending it is this.\n var anythingElsePending = controller.pending().length > 1;\n\n // Additionally if we are meant to defer scripts but the page is still\n // loading (e.g. an ES6 module is loading) then also defer. Or if we are\n // meant to defer and anything else is pending then defer (those may be\n // scripts that did not need transformation and are just script tags with\n // defer set to true, and we need to evaluate after that deferred script).\n var needsAsyncLoading = goog.Dependency.defer_ &&\n (anythingElsePending || goog.isDocumentLoading_());\n\n if (needsAsyncLoading) {\n // Note that we only defer when we have to rather than 100% of the time.\n // Always defering would work, but then in theory the order of\n // goog.require calls would then matter. We want to enforce that most of\n // the time the order of the require calls does not matter.\n controller.defer(function() {\n load();\n });\n return;\n }\n // TODO(johnplaisted): Externs are missing onreadystatechange for\n // HTMLDocument.\n /** @type {?} */\n var doc = goog.global.document;\n\n var isInternetExplorerOrEdge = goog.inHtmlDocument_() &&\n ('ActiveXObject' in goog.global || goog.isEdge_());\n\n // Don't delay in any version of IE or pre-Chromium Edge. There's a bug\n // around this that will cause out of order script execution. This means\n // that on older IE ES6 modules will load too early (while the document is\n // still loading + the dom is not available). The other option is to load\n // too late (when the document is complete and the onload even will never\n // fire). This seems to be the lesser of two evils as scripts already act\n // like the former.\n if (isEs6 && goog.inHtmlDocument_() && goog.isDocumentLoading_() &&\n !isInternetExplorerOrEdge) {\n goog.Dependency.defer_ = true;\n // Transpiled ES6 modules still need to load like regular ES6 modules,\n // aka only after the document is interactive.\n controller.pause();\n var oldCallback = doc.onreadystatechange;\n doc.onreadystatechange = function() {\n if (doc.readyState == 'interactive') {\n doc.onreadystatechange = oldCallback;\n load();\n controller.resume();\n }\n if (typeof oldCallback === 'function') {\n oldCallback.apply(undefined, arguments);\n }\n };\n } else {\n // Always eval on old IE.\n if (!goog.inHtmlDocument_() || !goog.isDocumentLoading_()) {\n load();\n } else {\n fetchInOwnScriptThenLoad();\n }\n }\n };\n\n\n /**\n * @param {string} contents\n * @return {string}\n * @abstract\n */\n goog.TransformedDependency.prototype.transform = function(contents) {};\n\n\n /**\n * An ES6 module dependency that was transpiled to a jscomp module outside\n * of the debug loader, e.g. server side.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor\n * @extends {goog.TransformedDependency}\n */\n goog.PreTranspiledEs6ModuleDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.PreTranspiledEs6ModuleDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n };\n goog.inherits(\n goog.PreTranspiledEs6ModuleDependency, goog.TransformedDependency);\n\n\n /**\n * @override\n * @param {string} contents\n * @return {string}\n */\n goog.PreTranspiledEs6ModuleDependency.prototype.transform = function(\n contents) {\n return contents;\n };\n\n\n /**\n * A goog.module, transpiled or not. Will always perform some minimal\n * transformation even when not transpiled to wrap in a goog.loadModule\n * statement.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor\n * @extends {goog.TransformedDependency}\n */\n goog.GoogModuleDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.GoogModuleDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n };\n goog.inherits(goog.GoogModuleDependency, goog.TransformedDependency);\n\n\n /**\n * @override\n * @param {string} contents\n * @return {string}\n */\n goog.GoogModuleDependency.prototype.transform = function(contents) {\n if (!goog.LOAD_MODULE_USING_EVAL || goog.global.JSON === undefined) {\n return '' +\n 'goog.loadModule(function(exports) {' +\n '\"use strict\";' + contents +\n '\\n' + // terminate any trailing single line comment.\n ';return exports' +\n '});' +\n '\\n//# sourceURL=' + this.path + '\\n';\n } else {\n return '' +\n 'goog.loadModule(' +\n goog.global.JSON.stringify(\n contents + '\\n//# sourceURL=' + this.path + '\\n') +\n ');';\n }\n };\n\n\n /**\n * @param {string} relPath\n * @param {!Array<string>|undefined} provides\n * @param {!Array<string>} requires\n * @param {boolean|!Object<string>=} opt_loadFlags\n * @see goog.addDependency\n */\n goog.DebugLoader_.prototype.addDependency = function(\n relPath, provides, requires, opt_loadFlags) {\n provides = provides || [];\n relPath = relPath.replace(/\\\\/g, '/');\n var path = goog.normalizePath_(goog.basePath + relPath);\n if (!opt_loadFlags || typeof opt_loadFlags === 'boolean') {\n opt_loadFlags = opt_loadFlags ? {'module': goog.ModuleType.GOOG} : {};\n }\n var dep = this.factory_.createDependency(\n path, relPath, provides, requires, opt_loadFlags);\n this.dependencies_[path] = dep;\n for (var i = 0; i < provides.length; i++) {\n this.idToPath_[provides[i]] = path;\n }\n this.idToPath_[relPath] = path;\n };\n\n\n /**\n * Creates goog.Dependency instances for the debug loader to load.\n *\n * Should be overridden to have the debug loader use custom subclasses of\n * goog.Dependency.\n *\n * @struct @constructor\n */\n goog.DependencyFactory = function() {};\n\n\n /**\n * @param {string} path Absolute path of the file.\n * @param {string} relativePath Path relative to closure’s base.js.\n * @param {!Array<string>} provides Array of provided goog.provide/module ids.\n * @param {!Array<string>} requires Array of required goog.provide/module /\n * relative ES6 module paths.\n * @param {!Object<string, string>} loadFlags\n * @return {!goog.Dependency}\n */\n goog.DependencyFactory.prototype.createDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n\n if (loadFlags['module'] == goog.ModuleType.GOOG) {\n return new goog.GoogModuleDependency(\n path, relativePath, provides, requires, loadFlags);\n } else {\n if (loadFlags['module'] == goog.ModuleType.ES6) {\n if (goog.ASSUME_ES_MODULES_TRANSPILED) {\n return new goog.PreTranspiledEs6ModuleDependency(\n path, relativePath, provides, requires, loadFlags);\n } else {\n return new goog.Es6ModuleDependency(\n path, relativePath, provides, requires, loadFlags);\n }\n } else {\n return new goog.Dependency(\n path, relativePath, provides, requires, loadFlags);\n }\n }\n };\n\n\n /** @private @const */\n goog.debugLoader_ = new goog.DebugLoader_();\n\n\n /**\n * Loads the Closure Dependency file.\n *\n * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base\n * loaded, setDependencyFactory called, and then this called. i.e. allows\n * custom loading of the deps file.\n */\n goog.loadClosureDeps = function() {\n goog.debugLoader_.loadClosureDeps();\n };\n\n\n /**\n * Sets the dependency factory, which can be used to create custom\n * goog.Dependency implementations to control how dependencies are loaded.\n *\n * Note: if you wish to call this function and provide your own implemnetation\n * it is a wise idea to set CLOSURE_NO_DEPS to true, otherwise the dependency\n * file and all of its goog.addDependency calls will use the default factory.\n * You can call goog.loadClosureDeps to load the Closure dependency file\n * later, after your factory is injected.\n *\n * @param {!goog.DependencyFactory} factory\n */\n goog.setDependencyFactory = function(factory) {\n goog.debugLoader_.setDependencyFactory(factory);\n };\n\n\n /**\n * Trusted Types policy for the debug loader.\n * @private @const {?TrustedTypePolicy}\n */\n goog.TRUSTED_TYPES_POLICY_ = goog.TRUSTED_TYPES_POLICY_NAME ?\n goog.createTrustedTypesPolicy(goog.TRUSTED_TYPES_POLICY_NAME + '#base') :\n null;\n\n if (!goog.global.CLOSURE_NO_DEPS) {\n goog.debugLoader_.loadClosureDeps();\n }\n\n\n /**\n * Bootstraps the given namespaces and calls the callback once they are\n * available either via goog.require. This is a replacement for using\n * `goog.require` to bootstrap Closure JavaScript. Previously a `goog.require`\n * in an HTML file would guarantee that the require'd namespace was available\n * in the next immediate script tag. With ES6 modules this no longer a\n * guarantee.\n *\n * @param {!Array<string>} namespaces\n * @param {function(): ?} callback Function to call once all the namespaces\n * have loaded. Always called asynchronously.\n */\n goog.bootstrap = function(namespaces, callback) {\n goog.debugLoader_.bootstrap(namespaces, callback);\n };\n}\n\n\nif (!COMPILED) {\n var isChrome87 = false;\n // Cannot run check for Chrome <87 bug in case of strict CSP environments.\n // TODO(user): Remove once Chrome <87 bug is no longer a problem.\n try {\n isChrome87 = eval(goog.global.trustedTypes.emptyScript) !==\n goog.global.trustedTypes.emptyScript;\n } catch (err) {\n }\n\n /**\n * Trusted Types for running dev servers.\n *\n * @private @const\n */\n goog.CLOSURE_EVAL_PREFILTER_ =\n // Detect Chrome <87 bug with TT and eval.\n goog.global.trustedTypes && isChrome87 &&\n goog.createTrustedTypesPolicy('goog#base#devonly#eval') ||\n {createScript: goog.identity_};\n}\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Implements the disposable interface.\n */\n\ngoog.provide('goog.Disposable');\n\ngoog.require('goog.disposable.IDisposable');\ngoog.require('goog.dispose');\n/**\n * TODO(user): Remove this require.\n * @suppress {extraRequire}\n */\ngoog.require('goog.disposeAll');\n\n/**\n * Class that provides the basic implementation for disposable objects. If your\n * class holds references or resources that can't be collected by standard GC,\n * it should extend this class or implement the disposable interface (defined\n * in goog.disposable.IDisposable). See description of\n * goog.disposable.IDisposable for examples of cleanup.\n * @constructor\n * @implements {goog.disposable.IDisposable}\n */\ngoog.Disposable = function() {\n 'use strict';\n /**\n * If monitoring the goog.Disposable instances is enabled, stores the creation\n * stack trace of the Disposable instance.\n * @type {string|undefined}\n */\n this.creationStack;\n\n if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {\n if (goog.Disposable.INCLUDE_STACK_ON_CREATION) {\n this.creationStack = new Error().stack;\n }\n goog.Disposable.instances_[goog.getUid(this)] = this;\n }\n // Support sealing\n this.disposed_ = this.disposed_;\n this.onDisposeCallbacks_ = this.onDisposeCallbacks_;\n};\n\n\n/**\n * @enum {number} Different monitoring modes for Disposable.\n */\ngoog.Disposable.MonitoringMode = {\n /**\n * No monitoring.\n */\n OFF: 0,\n /**\n * Creating and disposing the goog.Disposable instances is monitored. All\n * disposable objects need to call the `goog.Disposable` base\n * constructor. The PERMANENT mode must be switched on before creating any\n * goog.Disposable instances.\n */\n PERMANENT: 1,\n /**\n * INTERACTIVE mode can be switched on and off on the fly without producing\n * errors. It also doesn't warn if the disposable objects don't call the\n * `goog.Disposable` base constructor.\n */\n INTERACTIVE: 2\n};\n\n\n/**\n * @define {number} The monitoring mode of the goog.Disposable\n * instances. Default is OFF. Switching on the monitoring is only\n * recommended for debugging because it has a significant impact on\n * performance and memory usage. If switched off, the monitoring code\n * compiles down to 0 bytes.\n */\ngoog.Disposable.MONITORING_MODE =\n goog.define('goog.Disposable.MONITORING_MODE', 0);\n\n\n/**\n * @define {boolean} Whether to attach creation stack to each created disposable\n * instance; This is only relevant for when MonitoringMode != OFF.\n */\ngoog.Disposable.INCLUDE_STACK_ON_CREATION =\n goog.define('goog.Disposable.INCLUDE_STACK_ON_CREATION', true);\n\n\n/**\n * Maps the unique ID of every undisposed `goog.Disposable` object to\n * the object itself.\n * @type {!Object<number, !goog.Disposable>}\n * @private\n */\ngoog.Disposable.instances_ = {};\n\n\n/**\n * @return {!Array<!goog.Disposable>} All `goog.Disposable` objects that\n * haven't been disposed of.\n */\ngoog.Disposable.getUndisposedObjects = function() {\n 'use strict';\n var ret = [];\n for (var id in goog.Disposable.instances_) {\n if (goog.Disposable.instances_.hasOwnProperty(id)) {\n ret.push(goog.Disposable.instances_[Number(id)]);\n }\n }\n return ret;\n};\n\n\n/**\n * Clears the registry of undisposed objects but doesn't dispose of them.\n */\ngoog.Disposable.clearUndisposedObjects = function() {\n 'use strict';\n goog.Disposable.instances_ = {};\n};\n\n\n/**\n * Whether the object has been disposed of.\n * @type {boolean}\n * @private\n */\ngoog.Disposable.prototype.disposed_ = false;\n\n\n/**\n * Callbacks to invoke when this object is disposed.\n * @type {Array<!Function>}\n * @private\n */\ngoog.Disposable.prototype.onDisposeCallbacks_;\n\n\n/**\n * @return {boolean} Whether the object has been disposed of.\n * @override\n */\ngoog.Disposable.prototype.isDisposed = function() {\n 'use strict';\n return this.disposed_;\n};\n\n\n/**\n * @return {boolean} Whether the object has been disposed of.\n * @deprecated Use {@link #isDisposed} instead.\n */\ngoog.Disposable.prototype.getDisposed = goog.Disposable.prototype.isDisposed;\n\n\n/**\n * Disposes of the object. If the object hasn't already been disposed of, calls\n * {@link #disposeInternal}. Classes that extend `goog.Disposable` should\n * override {@link #disposeInternal} in order to cleanup references, resources\n * and other disposable objects. Reentrant.\n *\n * @return {void} Nothing.\n * @override\n */\ngoog.Disposable.prototype.dispose = function() {\n 'use strict';\n if (!this.disposed_) {\n // Set disposed_ to true first, in case during the chain of disposal this\n // gets disposed recursively.\n this.disposed_ = true;\n this.disposeInternal();\n if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {\n var uid = goog.getUid(this);\n if (goog.Disposable.MONITORING_MODE ==\n goog.Disposable.MonitoringMode.PERMANENT &&\n !goog.Disposable.instances_.hasOwnProperty(uid)) {\n throw new Error(\n this + ' did not call the goog.Disposable base ' +\n 'constructor or was disposed of after a clearUndisposedObjects ' +\n 'call');\n }\n if (goog.Disposable.MONITORING_MODE !=\n goog.Disposable.MonitoringMode.OFF &&\n this.onDisposeCallbacks_ && this.onDisposeCallbacks_.length > 0) {\n throw new Error(\n this + ' did not empty its onDisposeCallbacks queue. This ' +\n 'probably means it overrode dispose() or disposeInternal() ' +\n 'without calling the superclass\\' method.');\n }\n delete goog.Disposable.instances_[uid];\n }\n }\n};\n\n\n/**\n * Associates a disposable object with this object so that they will be disposed\n * together.\n * @param {goog.disposable.IDisposable} disposable that will be disposed when\n * this object is disposed.\n */\ngoog.Disposable.prototype.registerDisposable = function(disposable) {\n 'use strict';\n this.addOnDisposeCallback(goog.partial(goog.dispose, disposable));\n};\n\n\n/**\n * Invokes a callback function when this object is disposed. Callbacks are\n * invoked in the order in which they were added. If a callback is added to\n * an already disposed Disposable, it will be called immediately.\n * @param {function(this:T):?} callback The callback function.\n * @param {T=} opt_scope An optional scope to call the callback in.\n * @template T\n */\ngoog.Disposable.prototype.addOnDisposeCallback = function(callback, opt_scope) {\n 'use strict';\n if (this.disposed_) {\n opt_scope !== undefined ? callback.call(opt_scope) : callback();\n return;\n }\n if (!this.onDisposeCallbacks_) {\n this.onDisposeCallbacks_ = [];\n }\n\n this.onDisposeCallbacks_.push(\n opt_scope !== undefined ? goog.bind(callback, opt_scope) : callback);\n};\n\n\n/**\n * Performs appropriate cleanup. See description of goog.disposable.IDisposable\n * for examples. Classes that extend `goog.Disposable` should override this\n * method. Not reentrant. To avoid calling it twice, it must only be called from\n * the subclass' `disposeInternal` method. Everywhere else the public `dispose`\n * method must be used. For example:\n *\n * <pre>\n * mypackage.MyClass = function() {\n * mypackage.MyClass.base(this, 'constructor');\n * // Constructor logic specific to MyClass.\n * ...\n * };\n * goog.inherits(mypackage.MyClass, goog.Disposable);\n *\n * mypackage.MyClass.prototype.disposeInternal = function() {\n * // Dispose logic specific to MyClass.\n * ...\n * // Call superclass's disposeInternal at the end of the subclass's, like\n * // in C++, to avoid hard-to-catch issues.\n * mypackage.MyClass.base(this, 'disposeInternal');\n * };\n * </pre>\n *\n * @protected\n */\ngoog.Disposable.prototype.disposeInternal = function() {\n 'use strict';\n if (this.onDisposeCallbacks_) {\n while (this.onDisposeCallbacks_.length) {\n this.onDisposeCallbacks_.shift()();\n }\n }\n};\n\n\n/**\n * Returns True if we can verify the object is disposed.\n * Calls `isDisposed` on the argument if it supports it. If obj\n * is not an object with an isDisposed() method, return false.\n * @param {*} obj The object to investigate.\n * @return {boolean} True if we can verify the object is disposed.\n */\ngoog.Disposable.isDisposed = function(obj) {\n 'use strict';\n if (obj && typeof obj.isDisposed == 'function') {\n return obj.isDisposed();\n }\n return false;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for manipulating arrays.\n */\n\n\ngoog.module('goog.array');\ngoog.module.declareLegacyNamespace();\n\nconst asserts = goog.require('goog.asserts');\n\n\n/**\n * @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should\n * rely on Array.prototype functions, if available.\n *\n * The Array.prototype functions can be defined by external libraries like\n * Prototype and setting this flag to false forces closure to use its own\n * goog.array implementation.\n *\n * If your javascript can be loaded by a third party site and you are wary about\n * relying on the prototype functions, specify\n * \"--define goog.NATIVE_ARRAY_PROTOTYPES=false\" to the JSCompiler.\n *\n * Setting goog.TRUSTED_SITE to false will automatically set\n * NATIVE_ARRAY_PROTOTYPES to false.\n */\ngoog.NATIVE_ARRAY_PROTOTYPES =\n goog.define('goog.NATIVE_ARRAY_PROTOTYPES', goog.TRUSTED_SITE);\n\n\n/**\n * @define {boolean} If true, JSCompiler will use the native implementation of\n * array functions where appropriate (e.g., `Array#filter`) and remove the\n * unused pure JS implementation.\n */\nconst ASSUME_NATIVE_FUNCTIONS = goog.define(\n 'goog.array.ASSUME_NATIVE_FUNCTIONS', goog.FEATURESET_YEAR > 2012);\nexports.ASSUME_NATIVE_FUNCTIONS = ASSUME_NATIVE_FUNCTIONS;\n\n\n/**\n * Returns the last element in an array without removing it.\n * Same as {@link goog.array.last}.\n * @param {IArrayLike<T>|string} array The array.\n * @return {T} Last item in array.\n * @template T\n */\nfunction peek(array) {\n return array[array.length - 1];\n}\nexports.peek = peek;\n\n\n/**\n * Returns the last element in an array without removing it.\n * Same as {@link goog.array.peek}.\n * @param {IArrayLike<T>|string} array The array.\n * @return {T} Last item in array.\n * @template T\n */\nexports.last = peek;\n\n// NOTE(arv): Since most of the array functions are generic it allows you to\n// pass an array-like object. Strings have a length and are considered array-\n// like. However, the 'in' operator does not work on strings so we cannot just\n// use the array path even if the browser supports indexing into strings. We\n// therefore end up splitting the string.\n\n\n/**\n * Returns the index of the first element of an array with a specified value, or\n * -1 if the element is not present in the array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-indexof}\n *\n * @param {IArrayLike<T>|string} arr The array to be searched.\n * @param {T} obj The object for which we are searching.\n * @param {number=} opt_fromIndex The index at which to start the search. If\n * omitted the search starts at index 0.\n * @return {number} The index of the first matching array element.\n * @template T\n */\nconst indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.indexOf) ?\n function(arr, obj, opt_fromIndex) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.indexOf.call(arr, obj, opt_fromIndex);\n } :\n function(arr, obj, opt_fromIndex) {\n const fromIndex = opt_fromIndex == null ?\n 0 :\n (opt_fromIndex < 0 ? Math.max(0, arr.length + opt_fromIndex) :\n opt_fromIndex);\n\n if (typeof arr === 'string') {\n // Array.prototype.indexOf uses === so only strings should be found.\n if (typeof obj !== 'string' || obj.length != 1) {\n return -1;\n }\n return arr.indexOf(obj, fromIndex);\n }\n\n for (let i = fromIndex; i < arr.length; i++) {\n if (i in arr && arr[i] === obj) return i;\n }\n return -1;\n };\nexports.indexOf = indexOf;\n\n\n/**\n * Returns the index of the last element of an array with a specified value, or\n * -1 if the element is not present in the array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof}\n *\n * @param {!IArrayLike<T>|string} arr The array to be searched.\n * @param {T} obj The object for which we are searching.\n * @param {?number=} opt_fromIndex The index at which to start the search. If\n * omitted the search starts at the end of the array.\n * @return {number} The index of the last matching array element.\n * @template T\n */\nconst lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.lastIndexOf) ?\n function(arr, obj, opt_fromIndex) {\n asserts.assert(arr.length != null);\n\n // Firefox treats undefined and null as 0 in the fromIndex argument which\n // leads it to always return -1\n const fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;\n return Array.prototype.lastIndexOf.call(arr, obj, fromIndex);\n } :\n function(arr, obj, opt_fromIndex) {\n let fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;\n\n if (fromIndex < 0) {\n fromIndex = Math.max(0, arr.length + fromIndex);\n }\n\n if (typeof arr === 'string') {\n // Array.prototype.lastIndexOf uses === so only strings should be found.\n if (typeof obj !== 'string' || obj.length != 1) {\n return -1;\n }\n return arr.lastIndexOf(obj, fromIndex);\n }\n\n for (let i = fromIndex; i >= 0; i--) {\n if (i in arr && arr[i] === obj) return i;\n }\n return -1;\n };\nexports.lastIndexOf = lastIndexOf;\n\n\n/**\n * Calls a function for each element in an array. Skips holes in the array.\n * See {@link http://tinyurl.com/developer-mozilla-org-array-foreach}\n *\n * @param {IArrayLike<T>|string} arr Array or array like object over\n * which to iterate.\n * @param {?function(this: S, T, number, ?): ?} f The function to call for every\n * element. This function takes 3 arguments (the element, the index and the\n * array). The return value is ignored.\n * @param {S=} opt_obj The object to be used as the value of 'this' within f.\n * @template T,S\n */\nconst forEach = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.forEach) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n Array.prototype.forEach.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2) {\n f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\n }\n }\n };\nexports.forEach = forEach;\n\n\n/**\n * Calls a function for each element in an array, starting from the last\n * element rather than the first.\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this: S, T, number, ?): ?} f The function to call for every\n * element. This function\n * takes 3 arguments (the element, the index and the array). The return\n * value is ignored.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @template T,S\n */\nfunction forEachRight(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = l - 1; i >= 0; --i) {\n if (i in arr2) {\n f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\n }\n }\n}\nexports.forEachRight = forEachRight;\n\n\n/**\n * Calls a function for each element in an array, and if the function returns\n * true adds the element to a new array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-filter}\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?):boolean} f The function to call for\n * every element. This function\n * takes 3 arguments (the element, the index and the array) and must\n * return a Boolean. If the return value is true the element is added to the\n * result array. If it is false the element is not included.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {!Array<T>} a new array in which only elements that passed the test\n * are present.\n * @template T,S\n */\nconst filter = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.filter) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.filter.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const res = [];\n let resLength = 0;\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2) {\n const val = arr2[i]; // in case f mutates arr2\n if (f.call(/** @type {?} */ (opt_obj), val, i, arr)) {\n res[resLength++] = val;\n }\n }\n }\n return res;\n };\nexports.filter = filter;\n\n\n/**\n * Calls a function for each element in an array and inserts the result into a\n * new array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-map}\n *\n * @param {IArrayLike<VALUE>|string} arr Array or array like object\n * over which to iterate.\n * @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call\n * for every element. This function takes 3 arguments (the element,\n * the index and the array) and should return something. The result will be\n * inserted into a new array.\n * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.\n * @return {!Array<RESULT>} a new array with the results from f.\n * @template THIS, VALUE, RESULT\n */\nconst map = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.map) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.map.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const res = new Array(l);\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2) {\n res[i] = f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\n }\n }\n return res;\n };\nexports.map = map;\n\n\n/**\n * Passes every element of an array into a function and accumulates the result.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-reduce}\n * Note that this implementation differs from the native Array.prototype.reduce\n * in that the initial value is assumed to be defined (the MDN docs linked above\n * recommend not omitting this parameter, although it is technically optional).\n *\n * For example:\n * var a = [1, 2, 3, 4];\n * reduce(a, function(r, v, i, arr) {return r + v;}, 0);\n * returns 10\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {function(this:S, R, T, number, ?) : R} f The function to call for\n * every element. This function\n * takes 4 arguments (the function's previous result or the initial value,\n * the value of the current array element, the current array index, and the\n * array itself)\n * function(previousValue, currentValue, index, array).\n * @param {?} val The initial value to pass into the function on the first call.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {R} Result of evaluating f repeatedly across the values of the array.\n * @template T,S,R\n */\nconst reduce = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduce) ?\n function(arr, f, val, opt_obj) {\n asserts.assert(arr.length != null);\n if (opt_obj) {\n f = goog.bind(f, opt_obj);\n }\n return Array.prototype.reduce.call(arr, f, val);\n } :\n function(arr, f, val, opt_obj) {\n let rval = val;\n forEach(arr, function(val, index) {\n rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);\n });\n return rval;\n };\nexports.reduce = reduce;\n\n\n/**\n * Passes every element of an array into a function and accumulates the result,\n * starting from the last element and working towards the first.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright}\n *\n * For example:\n * var a = ['a', 'b', 'c'];\n * reduceRight(a, function(r, v, i, arr) {return r + v;}, '');\n * returns 'cba'\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, R, T, number, ?) : R} f The function to call for\n * every element. This function\n * takes 4 arguments (the function's previous result or the initial value,\n * the value of the current array element, the current array index, and the\n * array itself)\n * function(previousValue, currentValue, index, array).\n * @param {?} val The initial value to pass into the function on the first call.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {R} Object returned as a result of evaluating f repeatedly across the\n * values of the array.\n * @template T,S,R\n */\nconst reduceRight = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduceRight) ?\n function(arr, f, val, opt_obj) {\n asserts.assert(arr.length != null);\n asserts.assert(f != null);\n if (opt_obj) {\n f = goog.bind(f, opt_obj);\n }\n return Array.prototype.reduceRight.call(arr, f, val);\n } :\n function(arr, f, val, opt_obj) {\n let rval = val;\n forEachRight(arr, function(val, index) {\n rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);\n });\n return rval;\n };\nexports.reduceRight = reduceRight;\n\n\n/**\n * Calls f for each element of an array. If any call returns true, some()\n * returns true (without checking the remaining elements). If all calls\n * return false, some() returns false.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-some}\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\n * for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a boolean.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {boolean} true if any element passes the test.\n * @template T,S\n */\nconst some = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.some) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.some.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return true;\n }\n }\n return false;\n };\nexports.some = some;\n\n\n/**\n * Call f for each element of an array. If all calls return true, every()\n * returns true. If any call returns false, every() returns false and\n * does not continue to check the remaining elements.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-every}\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\n * for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a boolean.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {boolean} false if any element fails the test.\n * @template T,S\n */\nconst every = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.every) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.every.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2 && !f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return false;\n }\n }\n return true;\n };\nexports.every = every;\n\n\n/**\n * Counts the array elements that fulfill the predicate, i.e. for which the\n * callback function returns true. Skips holes in the array.\n *\n * @param {!IArrayLike<T>|string} arr Array or array like object\n * over which to iterate.\n * @param {function(this: S, T, number, ?): boolean} f The function to call for\n * every element. Takes 3 arguments (the element, the index and the array).\n * @param {S=} opt_obj The object to be used as the value of 'this' within f.\n * @return {number} The number of the matching elements.\n * @template T,S\n */\nfunction count(arr, f, opt_obj) {\n let count = 0;\n forEach(arr, function(element, index, arr) {\n if (f.call(/** @type {?} */ (opt_obj), element, index, arr)) {\n ++count;\n }\n }, opt_obj);\n return count;\n}\nexports.count = count;\n\n\n/**\n * Search an array for the first element that satisfies a given condition and\n * return that element.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {T|null} The first array element that passes the test, or null if no\n * element is found.\n * @template T,S\n */\nfunction find(arr, f, opt_obj) {\n const i = findIndex(arr, f, opt_obj);\n return i < 0 ? null : typeof arr === 'string' ? arr.charAt(i) : arr[i];\n}\nexports.find = find;\n\n\n/**\n * Search an array for the first element that satisfies a given condition and\n * return its index.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\n * every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {number} The index of the first array element that passes the test,\n * or -1 if no element is found.\n * @template T,S\n */\nfunction findIndex(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return i;\n }\n }\n return -1;\n}\nexports.findIndex = findIndex;\n\n\n/**\n * Search an array (in reverse order) for the last element that satisfies a\n * given condition and return that element.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {T|null} The last array element that passes the test, or null if no\n * element is found.\n * @template T,S\n */\nfunction findRight(arr, f, opt_obj) {\n const i = findIndexRight(arr, f, opt_obj);\n return i < 0 ? null : typeof arr === 'string' ? arr.charAt(i) : arr[i];\n}\nexports.findRight = findRight;\n\n\n/**\n * Search an array (in reverse order) for the last element that satisfies a\n * given condition and return its index.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {number} The index of the last array element that passes the test,\n * or -1 if no element is found.\n * @template T,S\n */\nfunction findIndexRight(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = l - 1; i >= 0; i--) {\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return i;\n }\n }\n return -1;\n}\nexports.findIndexRight = findIndexRight;\n\n\n/**\n * Whether the array contains the given object.\n * @param {IArrayLike<?>|string} arr The array to test for the presence of the\n * element.\n * @param {*} obj The object for which to test.\n * @return {boolean} true if obj is present.\n */\nfunction contains(arr, obj) {\n return indexOf(arr, obj) >= 0;\n}\nexports.contains = contains;\n\n\n/**\n * Whether the array is empty.\n * @param {IArrayLike<?>|string} arr The array to test.\n * @return {boolean} true if empty.\n */\nfunction isEmpty(arr) {\n return arr.length == 0;\n}\nexports.isEmpty = isEmpty;\n\n\n/**\n * Clears the array.\n * @param {IArrayLike<?>} arr Array or array like object to clear.\n */\nfunction clear(arr) {\n // For non real arrays we don't have the magic length so we delete the\n // indices.\n if (!Array.isArray(arr)) {\n for (let i = arr.length - 1; i >= 0; i--) {\n delete arr[i];\n }\n }\n arr.length = 0;\n}\nexports.clear = clear;\n\n\n/**\n * Pushes an item into an array, if it's not already in the array.\n * @param {Array<T>} arr Array into which to insert the item.\n * @param {T} obj Value to add.\n * @template T\n */\nfunction insert(arr, obj) {\n if (!contains(arr, obj)) {\n arr.push(obj);\n }\n}\nexports.insert = insert;\n\n\n/**\n * Inserts an object at the given index of the array.\n * @param {IArrayLike<?>} arr The array to modify.\n * @param {*} obj The object to insert.\n * @param {number=} opt_i The index at which to insert the object. If omitted,\n * treated as 0. A negative index is counted from the end of the array.\n */\nfunction insertAt(arr, obj, opt_i) {\n splice(arr, opt_i, 0, obj);\n}\nexports.insertAt = insertAt;\n\n\n/**\n * Inserts at the given index of the array, all elements of another array.\n * @param {IArrayLike<?>} arr The array to modify.\n * @param {IArrayLike<?>} elementsToAdd The array of elements to add.\n * @param {number=} opt_i The index at which to insert the object. If omitted,\n * treated as 0. A negative index is counted from the end of the array.\n */\nfunction insertArrayAt(arr, elementsToAdd, opt_i) {\n goog.partial(splice, arr, opt_i, 0).apply(null, elementsToAdd);\n}\nexports.insertArrayAt = insertArrayAt;\n\n\n/**\n * Inserts an object into an array before a specified object.\n * @param {Array<T>} arr The array to modify.\n * @param {T} obj The object to insert.\n * @param {T=} opt_obj2 The object before which obj should be inserted. If obj2\n * is omitted or not found, obj is inserted at the end of the array.\n * @template T\n */\nfunction insertBefore(arr, obj, opt_obj2) {\n let i;\n if (arguments.length == 2 || (i = indexOf(arr, opt_obj2)) < 0) {\n arr.push(obj);\n } else {\n insertAt(arr, obj, i);\n }\n}\nexports.insertBefore = insertBefore;\n\n\n/**\n * Removes the first occurrence of a particular value from an array.\n * @param {IArrayLike<T>} arr Array from which to remove\n * value.\n * @param {T} obj Object to remove.\n * @return {boolean} True if an element was removed.\n * @template T\n */\nfunction remove(arr, obj) {\n const i = indexOf(arr, obj);\n let rv;\n if ((rv = i >= 0)) {\n removeAt(arr, i);\n }\n return rv;\n}\nexports.remove = remove;\n\n\n/**\n * Removes the last occurrence of a particular value from an array.\n * @param {!IArrayLike<T>} arr Array from which to remove value.\n * @param {T} obj Object to remove.\n * @return {boolean} True if an element was removed.\n * @template T\n */\nfunction removeLast(arr, obj) {\n const i = lastIndexOf(arr, obj);\n if (i >= 0) {\n removeAt(arr, i);\n return true;\n }\n return false;\n}\nexports.removeLast = removeLast;\n\n\n/**\n * Removes from an array the element at index i\n * @param {IArrayLike<?>} arr Array or array like object from which to\n * remove value.\n * @param {number} i The index to remove.\n * @return {boolean} True if an element was removed.\n */\nfunction removeAt(arr, i) {\n asserts.assert(arr.length != null);\n\n // use generic form of splice\n // splice returns the removed items and if successful the length of that\n // will be 1\n return Array.prototype.splice.call(arr, i, 1).length == 1;\n}\nexports.removeAt = removeAt;\n\n\n/**\n * Removes the first value that satisfies the given condition.\n * @param {IArrayLike<T>} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {boolean} True if an element was removed.\n * @template T,S\n */\nfunction removeIf(arr, f, opt_obj) {\n const i = findIndex(arr, f, opt_obj);\n if (i >= 0) {\n removeAt(arr, i);\n return true;\n }\n return false;\n}\nexports.removeIf = removeIf;\n\n\n/**\n * Removes all values that satisfy the given condition.\n * @param {IArrayLike<T>} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {number} The number of items removed\n * @template T,S\n */\nfunction removeAllIf(arr, f, opt_obj) {\n let removedCount = 0;\n forEachRight(arr, function(val, index) {\n if (f.call(/** @type {?} */ (opt_obj), val, index, arr)) {\n if (removeAt(arr, index)) {\n removedCount++;\n }\n }\n });\n return removedCount;\n}\nexports.removeAllIf = removeAllIf;\n\n\n/**\n * Returns a new array that is the result of joining the arguments. If arrays\n * are passed then their items are added, however, if non-arrays are passed they\n * will be added to the return array as is.\n *\n * Note that ArrayLike objects will be added as is, rather than having their\n * items added.\n *\n * concat([1, 2], [3, 4]) -> [1, 2, 3, 4]\n * concat(0, [1, 2]) -> [0, 1, 2]\n * concat([1, 2], null) -> [1, 2, null]\n *\n * @param {...*} var_args Items to concatenate. Arrays will have each item\n * added, while primitives and objects will be added as is.\n * @return {!Array<?>} The new resultant array.\n */\nfunction concat(var_args) {\n return Array.prototype.concat.apply([], arguments);\n}\nexports.concat = concat;\n\n\n/**\n * Returns a new array that contains the contents of all the arrays passed.\n * @param {...!Array<T>} var_args\n * @return {!Array<T>}\n * @template T\n */\nfunction join(var_args) {\n return Array.prototype.concat.apply([], arguments);\n}\nexports.join = join;\n\n\n/**\n * Converts an object to an array.\n * @param {IArrayLike<T>|string} object The object to convert to an\n * array.\n * @return {!Array<T>} The object converted into an array. If object has a\n * length property, every property indexed with a non-negative number\n * less than length will be included in the result. If object does not\n * have a length property, an empty array will be returned.\n * @template T\n */\nfunction toArray(object) {\n const length = object.length;\n\n // If length is not a number the following is false. This case is kept for\n // backwards compatibility since there are callers that pass objects that are\n // not array like.\n if (length > 0) {\n const rv = new Array(length);\n for (let i = 0; i < length; i++) {\n rv[i] = object[i];\n }\n return rv;\n }\n return [];\n}\nexports.toArray = toArray;\n\n\n/**\n * Does a shallow copy of an array.\n * @param {IArrayLike<T>|string} arr Array or array-like object to\n * clone.\n * @return {!Array<T>} Clone of the input array.\n * @template T\n */\nconst clone = toArray;\nexports.clone = clone;\n\n\n/**\n * Extends an array with another array, element, or \"array like\" object.\n * This function operates 'in-place', it does not create a new Array.\n *\n * Example:\n * var a = [];\n * extend(a, [0, 1]);\n * a; // [0, 1]\n * extend(a, 2);\n * a; // [0, 1, 2]\n *\n * @param {Array<VALUE>} arr1 The array to modify.\n * @param {...(IArrayLike<VALUE>|VALUE)} var_args The elements or arrays of\n * elements to add to arr1.\n * @template VALUE\n */\nfunction extend(arr1, var_args) {\n for (let i = 1; i < arguments.length; i++) {\n const arr2 = arguments[i];\n if (goog.isArrayLike(arr2)) {\n const len1 = arr1.length || 0;\n const len2 = arr2.length || 0;\n arr1.length = len1 + len2;\n for (let j = 0; j < len2; j++) {\n arr1[len1 + j] = arr2[j];\n }\n } else {\n arr1.push(arr2);\n }\n }\n}\nexports.extend = extend;\n\n\n/**\n * Adds or removes elements from an array. This is a generic version of Array\n * splice. This means that it might work on other objects similar to arrays,\n * such as the arguments object.\n *\n * @param {IArrayLike<T>} arr The array to modify.\n * @param {number|undefined} index The index at which to start changing the\n * array. If not defined, treated as 0.\n * @param {number} howMany How many elements to remove (0 means no removal. A\n * value below 0 is treated as zero and so is any other non number. Numbers\n * are floored).\n * @param {...T} var_args Optional, additional elements to insert into the\n * array.\n * @return {!Array<T>} the removed elements.\n * @template T\n */\nfunction splice(arr, index, howMany, var_args) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.splice.apply(arr, slice(arguments, 1));\n}\nexports.splice = splice;\n\n\n/**\n * Returns a new array from a segment of an array. This is a generic version of\n * Array slice. This means that it might work on other objects similar to\n * arrays, such as the arguments object.\n *\n * @param {IArrayLike<T>|string} arr The array from\n * which to copy a segment.\n * @param {number} start The index of the first element to copy.\n * @param {number=} opt_end The index after the last element to copy.\n * @return {!Array<T>} A new array containing the specified segment of the\n * original array.\n * @template T\n */\nfunction slice(arr, start, opt_end) {\n asserts.assert(arr.length != null);\n\n // passing 1 arg to slice is not the same as passing 2 where the second is\n // null or undefined (in that case the second argument is treated as 0).\n // we could use slice on the arguments object and then use apply instead of\n // testing the length\n if (arguments.length <= 2) {\n return Array.prototype.slice.call(arr, start);\n } else {\n return Array.prototype.slice.call(arr, start, opt_end);\n }\n}\nexports.slice = slice;\n\n\n/**\n * Removes all duplicates from an array (retaining only the first\n * occurrence of each array element). This function modifies the\n * array in place and doesn't change the order of the non-duplicate items.\n *\n * For objects, duplicates are identified as having the same unique ID as\n * defined by {@link goog.getUid}.\n *\n * Alternatively you can specify a custom hash function that returns a unique\n * value for each item in the array it should consider unique.\n *\n * Runtime: N,\n * Worstcase space: 2N (no dupes)\n *\n * @param {IArrayLike<T>} arr The array from which to remove\n * duplicates.\n * @param {Array=} opt_rv An optional array in which to return the results,\n * instead of performing the removal inplace. If specified, the original\n * array will remain unchanged.\n * @param {function(T):string=} opt_hashFn An optional function to use to\n * apply to every item in the array. This function should return a unique\n * value for each item in the array it should consider unique.\n * @template T\n */\nfunction removeDuplicates(arr, opt_rv, opt_hashFn) {\n const returnArray = opt_rv || arr;\n const defaultHashFn = function(item) {\n // Prefix each type with a single character representing the type to\n // prevent conflicting keys (e.g. true and 'true').\n return goog.isObject(item) ? 'o' + goog.getUid(item) :\n (typeof item).charAt(0) + item;\n };\n const hashFn = opt_hashFn || defaultHashFn;\n\n let cursorInsert = 0;\n let cursorRead = 0;\n const seen = {};\n\n while (cursorRead < arr.length) {\n const current = arr[cursorRead++];\n const key = hashFn(current);\n if (!Object.prototype.hasOwnProperty.call(seen, key)) {\n seen[key] = true;\n returnArray[cursorInsert++] = current;\n }\n }\n returnArray.length = cursorInsert;\n}\nexports.removeDuplicates = removeDuplicates;\n\n\n/**\n * Searches the specified array for the specified target using the binary\n * search algorithm. If no opt_compareFn is specified, elements are compared\n * using <code>defaultCompare</code>, which compares the elements\n * using the built in < and > operators. This will produce the expected\n * behavior for homogeneous arrays of String(s) and Number(s). The array\n * specified <b>must</b> be sorted in ascending order (as defined by the\n * comparison function). If the array is not sorted, results are undefined.\n * If the array contains multiple instances of the specified target value, the\n * left-most instance will be found.\n *\n * Runtime: O(log n)\n *\n * @param {IArrayLike<VALUE>} arr The array to be searched.\n * @param {TARGET} target The sought value.\n * @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is ordered. Should take 2 arguments to\n * compare, the target value and an element from your array, and return a\n * negative number, zero, or a positive number depending on whether the\n * first argument is less than, equal to, or greater than the second.\n * @return {number} Lowest index of the target value if found, otherwise\n * (-(insertion point) - 1). The insertion point is where the value should\n * be inserted into arr to preserve the sorted property. Return value >= 0\n * iff target is found.\n * @template TARGET, VALUE\n */\nfunction binarySearch(arr, target, opt_compareFn) {\n return binarySearch_(\n arr, opt_compareFn || defaultCompare, false /* isEvaluator */, target);\n}\nexports.binarySearch = binarySearch;\n\n\n/**\n * Selects an index in the specified array using the binary search algorithm.\n * The evaluator receives an element and determines whether the desired index\n * is before, at, or after it. The evaluator must be consistent (formally,\n * map(map(arr, evaluator, opt_obj), goog.math.sign)\n * must be monotonically non-increasing).\n *\n * Runtime: O(log n)\n *\n * @param {IArrayLike<VALUE>} arr The array to be searched.\n * @param {function(this:THIS, VALUE, number, ?): number} evaluator\n * Evaluator function that receives 3 arguments (the element, the index and\n * the array). Should return a negative number, zero, or a positive number\n * depending on whether the desired index is before, at, or after the\n * element passed to it.\n * @param {THIS=} opt_obj The object to be used as the value of 'this'\n * within evaluator.\n * @return {number} Index of the leftmost element matched by the evaluator, if\n * such exists; otherwise (-(insertion point) - 1). The insertion point is\n * the index of the first element for which the evaluator returns negative,\n * or arr.length if no such element exists. The return value is non-negative\n * iff a match is found.\n * @template THIS, VALUE\n */\nfunction binarySelect(arr, evaluator, opt_obj) {\n return binarySearch_(\n arr, evaluator, true /* isEvaluator */, undefined /* opt_target */,\n opt_obj);\n}\nexports.binarySelect = binarySelect;\n\n\n/**\n * Implementation of a binary search algorithm which knows how to use both\n * comparison functions and evaluators. If an evaluator is provided, will call\n * the evaluator with the given optional data object, conforming to the\n * interface defined in binarySelect. Otherwise, if a comparison function is\n * provided, will call the comparison function against the given data object.\n *\n * This implementation purposefully does not use goog.bind or goog.partial for\n * performance reasons.\n *\n * Runtime: O(log n)\n *\n * @param {IArrayLike<?>} arr The array to be searched.\n * @param {function(?, ?, ?): number | function(?, ?): number} compareFn\n * Either an evaluator or a comparison function, as defined by binarySearch\n * and binarySelect above.\n * @param {boolean} isEvaluator Whether the function is an evaluator or a\n * comparison function.\n * @param {?=} opt_target If the function is a comparison function, then\n * this is the target to binary search for.\n * @param {Object=} opt_selfObj If the function is an evaluator, this is an\n * optional this object for the evaluator.\n * @return {number} Lowest index of the target value if found, otherwise\n * (-(insertion point) - 1). The insertion point is where the value should\n * be inserted into arr to preserve the sorted property. Return value >= 0\n * iff target is found.\n * @private\n */\nfunction binarySearch_(arr, compareFn, isEvaluator, opt_target, opt_selfObj) {\n let left = 0; // inclusive\n let right = arr.length; // exclusive\n let found;\n while (left < right) {\n const middle = left + ((right - left) >>> 1);\n let compareResult;\n if (isEvaluator) {\n compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);\n } else {\n // NOTE(dimvar): To avoid this cast, we'd have to use function overloading\n // for the type of binarySearch_, which the type system can't express yet.\n compareResult = /** @type {function(?, ?): number} */ (compareFn)(\n opt_target, arr[middle]);\n }\n if (compareResult > 0) {\n left = middle + 1;\n } else {\n right = middle;\n // We are looking for the lowest index so we can't return immediately.\n found = !compareResult;\n }\n }\n // left is the index if found, or the insertion point otherwise.\n // Avoiding bitwise not operator, as that causes a loss in precision for array\n // indexes outside the bounds of a 32-bit signed integer. Array indexes have\n // a maximum value of 2^32-2 https://tc39.es/ecma262/#array-index\n return found ? left : -left - 1;\n}\n\n\n/**\n * Sorts the specified array into ascending order. If no opt_compareFn is\n * specified, elements are compared using\n * <code>defaultCompare</code>, which compares the elements using\n * the built in < and > operators. This will produce the expected behavior\n * for homogeneous arrays of String(s) and Number(s), unlike the native sort,\n * but will give unpredictable results for heterogeneous lists of strings and\n * numbers with different numbers of digits.\n *\n * This sort is not guaranteed to be stable.\n *\n * Runtime: Same as `Array.prototype.sort`\n *\n * @param {Array<T>} arr The array to be sorted.\n * @param {?function(T,T):number=} opt_compareFn Optional comparison\n * function by which the\n * array is to be ordered. Should take 2 arguments to compare, and return a\n * negative number, zero, or a positive number depending on whether the\n * first argument is less than, equal to, or greater than the second.\n * @template T\n */\nfunction sort(arr, opt_compareFn) {\n // TODO(arv): Update type annotation since null is not accepted.\n arr.sort(opt_compareFn || defaultCompare);\n}\nexports.sort = sort;\n\n\n/**\n * Sorts the specified array into ascending order in a stable way. If no\n * opt_compareFn is specified, elements are compared using\n * <code>defaultCompare</code>, which compares the elements using\n * the built in < and > operators. This will produce the expected behavior\n * for homogeneous arrays of String(s) and Number(s).\n *\n * Runtime: Same as `Array.prototype.sort`, plus an additional\n * O(n) overhead of copying the array twice.\n *\n * @param {Array<T>} arr The array to be sorted.\n * @param {?function(T, T): number=} opt_compareFn Optional comparison function\n * by which the array is to be ordered. Should take 2 arguments to compare,\n * and return a negative number, zero, or a positive number depending on\n * whether the first argument is less than, equal to, or greater than the\n * second.\n * @template T\n */\nfunction stableSort(arr, opt_compareFn) {\n const compArr = new Array(arr.length);\n for (let i = 0; i < arr.length; i++) {\n compArr[i] = {index: i, value: arr[i]};\n }\n const valueCompareFn = opt_compareFn || defaultCompare;\n function stableCompareFn(obj1, obj2) {\n return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;\n }\n sort(compArr, stableCompareFn);\n for (let i = 0; i < arr.length; i++) {\n arr[i] = compArr[i].value;\n }\n}\nexports.stableSort = stableSort;\n\n\n/**\n * Sort the specified array into ascending order based on item keys\n * returned by the specified key function.\n * If no opt_compareFn is specified, the keys are compared in ascending order\n * using <code>defaultCompare</code>.\n *\n * Runtime: O(S(f(n)), where S is runtime of <code>sort</code>\n * and f(n) is runtime of the key function.\n *\n * @param {Array<T>} arr The array to be sorted.\n * @param {function(T): K} keyFn Function taking array element and returning\n * a key used for sorting this element.\n * @param {?function(K, K): number=} opt_compareFn Optional comparison function\n * by which the keys are to be ordered. Should take 2 arguments to compare,\n * and return a negative number, zero, or a positive number depending on\n * whether the first argument is less than, equal to, or greater than the\n * second.\n * @template T,K\n */\nfunction sortByKey(arr, keyFn, opt_compareFn) {\n const keyCompareFn = opt_compareFn || defaultCompare;\n sort(arr, function(a, b) {\n return keyCompareFn(keyFn(a), keyFn(b));\n });\n}\nexports.sortByKey = sortByKey;\n\n\n/**\n * Sorts an array of objects by the specified object key and compare\n * function. If no compare function is provided, the key values are\n * compared in ascending order using <code>defaultCompare</code>.\n * This won't work for keys that get renamed by the compiler. So use\n * {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}.\n * @param {Array<Object>} arr An array of objects to sort.\n * @param {string} key The object key to sort by.\n * @param {Function=} opt_compareFn The function to use to compare key\n * values.\n */\nfunction sortObjectsByKey(arr, key, opt_compareFn) {\n sortByKey(arr, function(obj) {\n return obj[key];\n }, opt_compareFn);\n}\nexports.sortObjectsByKey = sortObjectsByKey;\n\n\n/**\n * Tells if the array is sorted.\n * @param {!IArrayLike<T>} arr The array.\n * @param {?function(T,T):number=} opt_compareFn Function to compare the\n * array elements.\n * Should take 2 arguments to compare, and return a negative number, zero,\n * or a positive number depending on whether the first argument is less\n * than, equal to, or greater than the second.\n * @param {boolean=} opt_strict If true no equal elements are allowed.\n * @return {boolean} Whether the array is sorted.\n * @template T\n */\nfunction isSorted(arr, opt_compareFn, opt_strict) {\n const compare = opt_compareFn || defaultCompare;\n for (let i = 1; i < arr.length; i++) {\n const compareResult = compare(arr[i - 1], arr[i]);\n if (compareResult > 0 || compareResult == 0 && opt_strict) {\n return false;\n }\n }\n return true;\n}\nexports.isSorted = isSorted;\n\n\n/**\n * Compares two arrays for equality. Two arrays are considered equal if they\n * have the same length and their corresponding elements are equal according to\n * the comparison function.\n *\n * @param {IArrayLike<A>} arr1 The first array to compare.\n * @param {IArrayLike<B>} arr2 The second array to compare.\n * @param {?function(A,B):boolean=} opt_equalsFn Optional comparison function.\n * Should take 2 arguments to compare, and return true if the arguments\n * are equal. Defaults to {@link goog.array.defaultCompareEquality} which\n * compares the elements using the built-in '===' operator.\n * @return {boolean} Whether the two arrays are equal.\n * @template A\n * @template B\n */\nfunction equals(arr1, arr2, opt_equalsFn) {\n if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||\n arr1.length != arr2.length) {\n return false;\n }\n const l = arr1.length;\n const equalsFn = opt_equalsFn || defaultCompareEquality;\n for (let i = 0; i < l; i++) {\n if (!equalsFn(arr1[i], arr2[i])) {\n return false;\n }\n }\n return true;\n}\nexports.equals = equals;\n\n\n/**\n * 3-way array compare function.\n * @param {!IArrayLike<VALUE>} arr1 The first array to\n * compare.\n * @param {!IArrayLike<VALUE>} arr2 The second array to\n * compare.\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is to be ordered. Should take 2 arguments to\n * compare, and return a negative number, zero, or a positive number\n * depending on whether the first argument is less than, equal to, or\n * greater than the second.\n * @return {number} Negative number, zero, or a positive number depending on\n * whether the first argument is less than, equal to, or greater than the\n * second.\n * @template VALUE\n */\nfunction compare3(arr1, arr2, opt_compareFn) {\n const compare = opt_compareFn || defaultCompare;\n const l = Math.min(arr1.length, arr2.length);\n for (let i = 0; i < l; i++) {\n const result = compare(arr1[i], arr2[i]);\n if (result != 0) {\n return result;\n }\n }\n return defaultCompare(arr1.length, arr2.length);\n}\nexports.compare3 = compare3;\n\n\n/**\n * Compares its two arguments for order, using the built in < and >\n * operators.\n * @param {VALUE} a The first object to be compared.\n * @param {VALUE} b The second object to be compared.\n * @return {number} A negative number, zero, or a positive number as the first\n * argument is less than, equal to, or greater than the second,\n * respectively.\n * @template VALUE\n */\nfunction defaultCompare(a, b) {\n return a > b ? 1 : a < b ? -1 : 0;\n}\nexports.defaultCompare = defaultCompare;\n\n\n/**\n * Compares its two arguments for inverse order, using the built in < and >\n * operators.\n * @param {VALUE} a The first object to be compared.\n * @param {VALUE} b The second object to be compared.\n * @return {number} A negative number, zero, or a positive number as the first\n * argument is greater than, equal to, or less than the second,\n * respectively.\n * @template VALUE\n */\nfunction inverseDefaultCompare(a, b) {\n return -defaultCompare(a, b);\n}\nexports.inverseDefaultCompare = inverseDefaultCompare;\n\n\n/**\n * Compares its two arguments for equality, using the built in === operator.\n * @param {*} a The first object to compare.\n * @param {*} b The second object to compare.\n * @return {boolean} True if the two arguments are equal, false otherwise.\n */\nfunction defaultCompareEquality(a, b) {\n return a === b;\n}\nexports.defaultCompareEquality = defaultCompareEquality;\n\n\n/**\n * Inserts a value into a sorted array. The array is not modified if the\n * value is already present.\n * @param {IArrayLike<VALUE>} array The array to modify.\n * @param {VALUE} value The object to insert.\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is ordered. Should take 2 arguments to\n * compare, and return a negative number, zero, or a positive number\n * depending on whether the first argument is less than, equal to, or\n * greater than the second.\n * @return {boolean} True if an element was inserted.\n * @template VALUE\n */\nfunction binaryInsert(array, value, opt_compareFn) {\n const index = binarySearch(array, value, opt_compareFn);\n if (index < 0) {\n insertAt(array, value, -(index + 1));\n return true;\n }\n return false;\n}\nexports.binaryInsert = binaryInsert;\n\n\n/**\n * Removes a value from a sorted array.\n * @param {!IArrayLike<VALUE>} array The array to modify.\n * @param {VALUE} value The object to remove.\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is ordered. Should take 2 arguments to\n * compare, and return a negative number, zero, or a positive number\n * depending on whether the first argument is less than, equal to, or\n * greater than the second.\n * @return {boolean} True if an element was removed.\n * @template VALUE\n */\nfunction binaryRemove(array, value, opt_compareFn) {\n const index = binarySearch(array, value, opt_compareFn);\n return (index >= 0) ? removeAt(array, index) : false;\n}\nexports.binaryRemove = binaryRemove;\n\n\n/**\n * Splits an array into disjoint buckets according to a splitting function.\n * @param {IArrayLike<T>} array The array.\n * @param {function(this:S, T, number, !IArrayLike<T>):?} sorter Function to\n * call for every element. This takes 3 arguments (the element, the index\n * and the array) and must return a valid object key (a string, number,\n * etc), or undefined, if that object should not be placed in a bucket.\n * @param {S=} opt_obj The object to be used as the value of 'this' within\n * sorter.\n * @return {!Object<!Array<T>>} An object, with keys being all of the unique\n * return values of sorter, and values being arrays containing the items for\n * which the splitter returned that key.\n * @template T,S\n */\nfunction bucket(array, sorter, opt_obj) {\n const buckets = {};\n\n for (let i = 0; i < array.length; i++) {\n const value = array[i];\n const key = sorter.call(/** @type {?} */ (opt_obj), value, i, array);\n if (key !== undefined) {\n // Push the value to the right bucket, creating it if necessary.\n const bucket = buckets[key] || (buckets[key] = []);\n bucket.push(value);\n }\n }\n\n return buckets;\n}\nexports.bucket = bucket;\n\n\n/**\n * Splits an array into disjoint buckets according to a splitting function.\n * @param {!IArrayLike<V>} array The array.\n * @param {function(V, number, !IArrayLike<V>):(K|undefined)} sorter Function to\n * call for every element. This takes 3 arguments (the element, the index,\n * and the array) and must return a value to use as a key, or undefined, if\n * that object should not be placed in a bucket.\n * @return {!Map<K, !Array<V>>} A map, with keys being all of the unique\n * return values of sorter, and values being arrays containing the items for\n * which the splitter returned that key.\n * @template K,V\n */\nfunction bucketToMap(array, sorter) {\n const /** !Map<K, !Array<V>> */ buckets = new Map();\n\n for (let i = 0; i < array.length; i++) {\n const value = array[i];\n const key = sorter(value, i, array);\n if (key !== undefined) {\n // Push the value to the right bucket, creating it if necessary.\n let bucket = buckets.get(key);\n if (!bucket) {\n bucket = [];\n buckets.set(key, bucket);\n }\n bucket.push(value);\n }\n }\n\n return buckets;\n}\nexports.bucketToMap = bucketToMap;\n\n\n/**\n * Creates a new object built from the provided array and the key-generation\n * function.\n * @param {IArrayLike<T>} arr Array or array like object over\n * which to iterate whose elements will be the values in the new object.\n * @param {?function(this:S, T, number, ?) : string} keyFunc The function to\n * call for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a string that will be used as the\n * key for the element in the new object. If the function returns the same\n * key for more than one element, the value for that key is\n * implementation-defined.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within keyFunc.\n * @return {!Object<T>} The new object.\n * @template T,S\n */\nfunction toObject(arr, keyFunc, opt_obj) {\n const ret = {};\n forEach(arr, function(element, index) {\n ret[keyFunc.call(/** @type {?} */ (opt_obj), element, index, arr)] =\n element;\n });\n return ret;\n}\nexports.toObject = toObject;\n\n\n/**\n * Creates a new ES6 Map built from the provided array and the key-generation\n * function.\n * @param {!IArrayLike<V>} arr Array or array like object over which to iterate\n * whose elements will be the values in the new object.\n * @param {?function(V, number, ?) : K} keyFunc The function to call for every\n * element. This function takes 3 arguments (the element, the index, and the\n * array) and should return a value that will be used as the key for the\n * element in the new object. If the function returns the same key for more\n * than one element, the value for that key is implementation-defined.\n * @return {!Map<K, V>} The new map.\n * @template K,V\n */\nfunction toMap(arr, keyFunc) {\n const /** !Map<K, V> */ map = new Map();\n\n for (let i = 0; i < arr.length; i++) {\n const element = arr[i];\n map.set(keyFunc(element, i, arr), element);\n }\n\n return map;\n}\nexports.toMap = toMap;\n\n\n/**\n * Creates a range of numbers in an arithmetic progression.\n *\n * Range takes 1, 2, or 3 arguments:\n * <pre>\n * range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4]\n * range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4]\n * range(-2, -5, -1) produces [-2, -3, -4]\n * range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5.\n * </pre>\n *\n * @param {number} startOrEnd The starting value of the range if an end argument\n * is provided. Otherwise, the start value is 0, and this is the end value.\n * @param {number=} opt_end The optional end value of the range.\n * @param {number=} opt_step The step size between range values. Defaults to 1\n * if opt_step is undefined or 0.\n * @return {!Array<number>} An array of numbers for the requested range. May be\n * an empty array if adding the step would not converge toward the end\n * value.\n */\nfunction range(startOrEnd, opt_end, opt_step) {\n const array = [];\n let start = 0;\n let end = startOrEnd;\n const step = opt_step || 1;\n if (opt_end !== undefined) {\n start = startOrEnd;\n end = opt_end;\n }\n\n if (step * (end - start) < 0) {\n // Sign mismatch: start + step will never reach the end value.\n return [];\n }\n\n if (step > 0) {\n for (let i = start; i < end; i += step) {\n array.push(i);\n }\n } else {\n for (let i = start; i > end; i += step) {\n array.push(i);\n }\n }\n return array;\n}\nexports.range = range;\n\n\n/**\n * Returns an array consisting of the given value repeated N times.\n *\n * @param {VALUE} value The value to repeat.\n * @param {number} n The repeat count.\n * @return {!Array<VALUE>} An array with the repeated value.\n * @template VALUE\n */\nfunction repeat(value, n) {\n const array = [];\n for (let i = 0; i < n; i++) {\n array[i] = value;\n }\n return array;\n}\nexports.repeat = repeat;\n\n\n/**\n * Returns an array consisting of every argument with all arrays\n * expanded in-place recursively.\n *\n * @param {...*} var_args The values to flatten.\n * @return {!Array<?>} An array containing the flattened values.\n */\nfunction flatten(var_args) {\n const CHUNK_SIZE = 8192;\n\n const result = [];\n for (let i = 0; i < arguments.length; i++) {\n const element = arguments[i];\n if (Array.isArray(element)) {\n for (let c = 0; c < element.length; c += CHUNK_SIZE) {\n const chunk = slice(element, c, c + CHUNK_SIZE);\n const recurseResult = flatten.apply(null, chunk);\n for (let r = 0; r < recurseResult.length; r++) {\n result.push(recurseResult[r]);\n }\n }\n } else {\n result.push(element);\n }\n }\n return result;\n}\nexports.flatten = flatten;\n\n\n/**\n * Rotates an array in-place. After calling this method, the element at\n * index i will be the element previously at index (i - n) %\n * array.length, for all values of i between 0 and array.length - 1,\n * inclusive.\n *\n * For example, suppose list comprises [t, a, n, k, s]. After invoking\n * rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k].\n *\n * @param {!Array<T>} array The array to rotate.\n * @param {number} n The amount to rotate.\n * @return {!Array<T>} The array.\n * @template T\n */\nfunction rotate(array, n) {\n asserts.assert(array.length != null);\n\n if (array.length) {\n n %= array.length;\n if (n > 0) {\n Array.prototype.unshift.apply(array, array.splice(-n, n));\n } else if (n < 0) {\n Array.prototype.push.apply(array, array.splice(0, -n));\n }\n }\n return array;\n}\nexports.rotate = rotate;\n\n\n/**\n * Moves one item of an array to a new position keeping the order of the rest\n * of the items. Example use case: keeping a list of JavaScript objects\n * synchronized with the corresponding list of DOM elements after one of the\n * elements has been dragged to a new position.\n * @param {!IArrayLike<?>} arr The array to modify.\n * @param {number} fromIndex Index of the item to move between 0 and\n * `arr.length - 1`.\n * @param {number} toIndex Target index between 0 and `arr.length - 1`.\n */\nfunction moveItem(arr, fromIndex, toIndex) {\n asserts.assert(fromIndex >= 0 && fromIndex < arr.length);\n asserts.assert(toIndex >= 0 && toIndex < arr.length);\n // Remove 1 item at fromIndex.\n const removedItems = Array.prototype.splice.call(arr, fromIndex, 1);\n // Insert the removed item at toIndex.\n Array.prototype.splice.call(arr, toIndex, 0, removedItems[0]);\n // We don't use goog.array.insertAt and goog.array.removeAt, because they're\n // significantly slower than splice.\n}\nexports.moveItem = moveItem;\n\n\n/**\n * Creates a new array for which the element at position i is an array of the\n * ith element of the provided arrays. The returned array will only be as long\n * as the shortest array provided; additional values are ignored. For example,\n * the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]].\n *\n * This is similar to the zip() function in Python. See {@link\n * http://docs.python.org/library/functions.html#zip}\n *\n * @param {...!IArrayLike<?>} var_args Arrays to be combined.\n * @return {!Array<!Array<?>>} A new array of arrays created from\n * provided arrays.\n */\nfunction zip(var_args) {\n if (!arguments.length) {\n return [];\n }\n const result = [];\n let minLen = arguments[0].length;\n for (let i = 1; i < arguments.length; i++) {\n if (arguments[i].length < minLen) {\n minLen = arguments[i].length;\n }\n }\n for (let i = 0; i < minLen; i++) {\n const value = [];\n for (let j = 0; j < arguments.length; j++) {\n value.push(arguments[j][i]);\n }\n result.push(value);\n }\n return result;\n}\nexports.zip = zip;\n\n\n/**\n * Shuffles the values in the specified array using the Fisher-Yates in-place\n * shuffle (also known as the Knuth Shuffle). By default, calls Math.random()\n * and so resets the state of that random number generator. Similarly, may reset\n * the state of any other specified random number generator.\n *\n * Runtime: O(n)\n *\n * @param {!Array<?>} arr The array to be shuffled.\n * @param {function():number=} opt_randFn Optional random function to use for\n * shuffling.\n * Takes no arguments, and returns a random number on the interval [0, 1).\n * Defaults to Math.random() using JavaScript's built-in Math library.\n */\nfunction shuffle(arr, opt_randFn) {\n const randFn = opt_randFn || Math.random;\n\n for (let i = arr.length - 1; i > 0; i--) {\n // Choose a random array index in [0, i] (inclusive with i).\n const j = Math.floor(randFn() * (i + 1));\n\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n }\n}\nexports.shuffle = shuffle;\n\n\n/**\n * Returns a new array of elements from arr, based on the indexes of elements\n * provided by index_arr. For example, the result of index copying\n * ['a', 'b', 'c'] with index_arr [1,0,0,2] is ['b', 'a', 'a', 'c'].\n *\n * @param {!IArrayLike<T>} arr The array to get a indexed copy from.\n * @param {!IArrayLike<number>} index_arr An array of indexes to get from arr.\n * @return {!Array<T>} A new array of elements from arr in index_arr order.\n * @template T\n */\nfunction copyByIndex(arr, index_arr) {\n const result = [];\n forEach(index_arr, function(index) {\n result.push(arr[index]);\n });\n return result;\n}\nexports.copyByIndex = copyByIndex;\n\n\n/**\n * Maps each element of the input array into zero or more elements of the output\n * array.\n *\n * @param {!IArrayLike<VALUE>|string} arr Array or array like object\n * over which to iterate.\n * @param {function(this:THIS, VALUE, number, ?): !Array<RESULT>} f The function\n * to call for every element. This function takes 3 arguments (the element,\n * the index and the array) and should return an array. The result will be\n * used to extend a new array.\n * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.\n * @return {!Array<RESULT>} a new array with the concatenation of all arrays\n * returned from f.\n * @template THIS, VALUE, RESULT\n */\nfunction concatMap(arr, f, opt_obj) {\n return concat.apply([], map(arr, f, opt_obj));\n}\nexports.concatMap = concatMap;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A base class for event objects.\n */\n\n\ngoog.provide('goog.events.Event');\n\n/**\n * goog.events.Event no longer depends on goog.Disposable. Keep requiring\n * goog.Disposable here to not break projects which assume this dependency.\n * @suppress {extraRequire}\n */\ngoog.require('goog.Disposable');\ngoog.require('goog.events.EventId');\n\n\n/**\n * A base class for event objects, so that they can support preventDefault and\n * stopPropagation.\n *\n * @param {string|!goog.events.EventId} type Event Type.\n * @param {Object=} opt_target Reference to the object that is the target of\n * this event. It has to implement the `EventTarget` interface\n * declared at {@link http://developer.mozilla.org/en/DOM/EventTarget}.\n * @constructor\n */\ngoog.events.Event = function(type, opt_target) {\n 'use strict';\n /**\n * Event type.\n * @type {string}\n */\n this.type = type instanceof goog.events.EventId ? String(type) : type;\n\n /**\n * TODO(tbreisacher): The type should probably be\n * EventTarget|goog.events.EventTarget.\n *\n * Target of the event.\n * @type {Object|undefined}\n */\n this.target = opt_target;\n\n /**\n * Object that had the listener attached.\n * @type {Object|undefined}\n */\n this.currentTarget = this.target;\n\n /**\n * Whether to cancel the event in internal capture/bubble processing for IE.\n * @type {boolean}\n * @private\n */\n this.propagationStopped_ = false;\n\n /**\n * Whether the default action has been prevented.\n * This is a property to match the W3C specification at\n * {@link http://www.w3.org/TR/DOM-Level-3-Events/\n * #events-event-type-defaultPrevented}.\n * Must be treated as read-only outside the class.\n * @type {boolean}\n */\n this.defaultPrevented = false;\n};\n\n/**\n * @return {boolean} true iff internal propagation has been stopped.\n */\ngoog.events.Event.prototype.hasPropagationStopped = function() {\n 'use strict';\n return this.propagationStopped_;\n};\n\n/**\n * Stops event propagation.\n * @return {void}\n */\ngoog.events.Event.prototype.stopPropagation = function() {\n 'use strict';\n this.propagationStopped_ = true;\n};\n\n\n/**\n * Prevents the default action, for example a link redirecting to a url.\n * @return {void}\n */\ngoog.events.Event.prototype.preventDefault = function() {\n 'use strict';\n this.defaultPrevented = true;\n};\n\n\n/**\n * Stops the propagation of the event. It is equivalent to\n * `e.stopPropagation()`, but can be used as the callback argument of\n * {@link goog.events.listen} without declaring another function.\n * @param {!goog.events.Event} e An event.\n * @return {void}\n */\ngoog.events.Event.stopPropagation = function(e) {\n 'use strict';\n e.stopPropagation();\n};\n\n\n/**\n * Prevents the default action. It is equivalent to\n * `e.preventDefault()`, but can be used as the callback argument of\n * {@link goog.events.listen} without declaring another function.\n * @param {!goog.events.Event} e An event.\n * @return {void}\n */\ngoog.events.Event.preventDefault = function(e) {\n 'use strict';\n e.preventDefault();\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Browser capability checks for the events package.\n */\n\ngoog.module('goog.events.BrowserFeature');\ngoog.module.declareLegacyNamespace();\n\n\n/**\n * Tricks Closure Compiler into believing that a function is pure. The compiler\n * assumes that any `valueOf` function is pure, without analyzing its contents.\n *\n * @param {function(): T} fn\n * @return {T}\n * @template T\n */\nconst purify = (fn) => {\n return ({valueOf: fn}).valueOf();\n};\n\n\n/**\n * Enum of browser capabilities.\n * @enum {boolean}\n */\nexports = {\n /**\n * Whether touch is enabled in the browser.\n */\n TOUCH_ENABLED:\n ('ontouchstart' in goog.global ||\n !!(goog.global['document'] && document.documentElement &&\n 'ontouchstart' in document.documentElement) ||\n // IE10 uses non-standard touch events, so it has a different check.\n !!(goog.global['navigator'] &&\n (goog.global['navigator']['maxTouchPoints'] ||\n goog.global['navigator']['msMaxTouchPoints']))),\n\n /**\n * Whether addEventListener supports W3C standard pointer events.\n * http://www.w3.org/TR/pointerevents/\n */\n POINTER_EVENTS: ('PointerEvent' in goog.global),\n\n /**\n * Whether addEventListener supports MSPointer events (only used in IE10).\n * http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx\n * http://msdn.microsoft.com/library/hh673557(v=vs.85).aspx\n */\n MSPOINTER_EVENTS: false,\n\n /**\n * Whether addEventListener supports {passive: true}.\n * https://developers.google.com/web/updates/2016/06/passive-event-listeners\n */\n PASSIVE_EVENTS: purify(function() {\n // If we're in a web worker or other custom environment, we can't tell.\n if (!goog.global.addEventListener || !Object.defineProperty) { // IE 8\n return false;\n }\n\n var passive = false;\n var options = Object.defineProperty({}, 'passive', {\n get: function() {\n passive = true;\n }\n });\n try {\n goog.global.addEventListener('test', () => {}, options);\n goog.global.removeEventListener('test', () => {}, options);\n } catch (e) {\n }\n\n return passive;\n })\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview String functions called from Closure packages that couldn't\n * depend on each other. Outside Closure, use goog.string function which\n * delegate to these.\n */\n\n\ngoog.provide('goog.string.internal');\n\n\n/**\n * Fast prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the start of `str`.\n * @return {boolean} True if `str` begins with `prefix`.\n * @see goog.string.startsWith\n */\ngoog.string.internal.startsWith = function(str, prefix) {\n 'use strict';\n return str.lastIndexOf(prefix, 0) == 0;\n};\n\n\n/**\n * Fast suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix`.\n * @see goog.string.endsWith\n */\ngoog.string.internal.endsWith = function(str, suffix) {\n 'use strict';\n const l = str.length - suffix.length;\n return l >= 0 && str.indexOf(suffix, l) == l;\n};\n\n\n/**\n * Case-insensitive prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the end of `str`.\n * @return {boolean} True if `str` begins with `prefix` (ignoring\n * case).\n * @see goog.string.caseInsensitiveStartsWith\n */\ngoog.string.internal.caseInsensitiveStartsWith = function(str, prefix) {\n 'use strict';\n return (\n goog.string.internal.caseInsensitiveCompare(\n prefix, str.slice(0, prefix.length)) == 0);\n};\n\n\n/**\n * Case-insensitive suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix` (ignoring\n * case).\n * @see goog.string.caseInsensitiveEndsWith\n */\ngoog.string.internal.caseInsensitiveEndsWith = function(str, suffix) {\n 'use strict';\n return (\n goog.string.internal.caseInsensitiveCompare(\n suffix, str.slice(str.length - suffix.length)) == 0);\n};\n\n\n/**\n * Case-insensitive equality checker.\n * @param {string} str1 First string to check.\n * @param {string} str2 Second string to check.\n * @return {boolean} True if `str1` and `str2` are the same string,\n * ignoring case.\n * @see goog.string.caseInsensitiveEquals\n */\ngoog.string.internal.caseInsensitiveEquals = function(str1, str2) {\n 'use strict';\n return str1.toLowerCase() == str2.toLowerCase();\n};\n\n\n/**\n * Checks if a string is empty or contains only whitespaces.\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty or whitespace only.\n * @see goog.string.isEmptyOrWhitespace\n */\ngoog.string.internal.isEmptyOrWhitespace = function(str) {\n 'use strict';\n // testing length == 0 first is actually slower in all browsers (about the\n // same in Opera).\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return /^[\\s\\xa0]*$/.test(str);\n};\n\n\n/**\n * Trims white spaces to the left and right of a string.\n * @param {string} str The string to trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.internal.trim =\n (goog.TRUSTED_SITE && String.prototype.trim) ? function(str) {\n 'use strict';\n return str.trim();\n } : function(str) {\n 'use strict';\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s\n // character class (as required by section 7.2 of the ECMAScript spec),\n // we explicitly include it in the regexp to enforce consistent\n // cross-browser behavior.\n // NOTE: We don't use String#replace because it might have side effects\n // causing this function to not compile to 0 bytes.\n return /^[\\s\\xa0]*([\\s\\S]*?)[\\s\\xa0]*$/.exec(str)[1];\n };\n\n\n/**\n * A string comparator that ignores case.\n * -1 = str1 less than str2\n * 0 = str1 equals str2\n * 1 = str1 greater than str2\n *\n * @param {string} str1 The string to compare.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} The comparator result, as described above.\n * @see goog.string.caseInsensitiveCompare\n */\ngoog.string.internal.caseInsensitiveCompare = function(str1, str2) {\n 'use strict';\n const test1 = String(str1).toLowerCase();\n const test2 = String(str2).toLowerCase();\n\n if (test1 < test2) {\n return -1;\n } else if (test1 == test2) {\n return 0;\n } else {\n return 1;\n }\n};\n\n\n/**\n * Converts \\n to <br>s or <br />s.\n * @param {string} str The string in which to convert newlines.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} A copy of `str` with converted newlines.\n * @see goog.string.newLineToBr\n */\ngoog.string.internal.newLineToBr = function(str, opt_xml) {\n 'use strict';\n return str.replace(/(\\r\\n|\\r|\\n)/g, opt_xml ? '<br />' : '<br>');\n};\n\n\n/**\n * Escapes double quote '\"' and single quote '\\'' characters in addition to\n * '&', '<', and '>' so that a string can be included in an HTML tag attribute\n * value within double or single quotes.\n * @param {string} str string to be escaped.\n * @param {boolean=} opt_isLikelyToContainHtmlChars\n * @return {string} An escaped copy of `str`.\n * @see goog.string.htmlEscape\n */\ngoog.string.internal.htmlEscape = function(\n str, opt_isLikelyToContainHtmlChars) {\n 'use strict';\n if (opt_isLikelyToContainHtmlChars) {\n str = str.replace(goog.string.internal.AMP_RE_, '&')\n .replace(goog.string.internal.LT_RE_, '<')\n .replace(goog.string.internal.GT_RE_, '>')\n .replace(goog.string.internal.QUOT_RE_, '"')\n .replace(goog.string.internal.SINGLE_QUOTE_RE_, ''')\n .replace(goog.string.internal.NULL_RE_, '�');\n return str;\n\n } else {\n // quick test helps in the case when there are no chars to replace, in\n // worst case this makes barely a difference to the time taken\n if (!goog.string.internal.ALL_RE_.test(str)) return str;\n\n // str.indexOf is faster than regex.test in this case\n if (str.indexOf('&') != -1) {\n str = str.replace(goog.string.internal.AMP_RE_, '&');\n }\n if (str.indexOf('<') != -1) {\n str = str.replace(goog.string.internal.LT_RE_, '<');\n }\n if (str.indexOf('>') != -1) {\n str = str.replace(goog.string.internal.GT_RE_, '>');\n }\n if (str.indexOf('\"') != -1) {\n str = str.replace(goog.string.internal.QUOT_RE_, '"');\n }\n if (str.indexOf('\\'') != -1) {\n str = str.replace(goog.string.internal.SINGLE_QUOTE_RE_, ''');\n }\n if (str.indexOf('\\x00') != -1) {\n str = str.replace(goog.string.internal.NULL_RE_, '�');\n }\n return str;\n }\n};\n\n\n/**\n * Regular expression that matches an ampersand, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.AMP_RE_ = /&/g;\n\n\n/**\n * Regular expression that matches a less than sign, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.LT_RE_ = /</g;\n\n\n/**\n * Regular expression that matches a greater than sign, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.GT_RE_ = />/g;\n\n\n/**\n * Regular expression that matches a double quote, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.QUOT_RE_ = /\"/g;\n\n\n/**\n * Regular expression that matches a single quote, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.SINGLE_QUOTE_RE_ = /'/g;\n\n\n/**\n * Regular expression that matches null character, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.NULL_RE_ = /\\x00/g;\n\n\n/**\n * Regular expression that matches any character that needs to be escaped.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.ALL_RE_ = /[\\x00&<>\"']/;\n\n\n/**\n * Do escaping of whitespace to preserve spatial formatting. We use character\n * entity #160 to make it safer for xml.\n * @param {string} str The string in which to escape whitespace.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} An escaped copy of `str`.\n * @see goog.string.whitespaceEscape\n */\ngoog.string.internal.whitespaceEscape = function(str, opt_xml) {\n 'use strict';\n // This doesn't use goog.string.preserveSpaces for backwards compatibility.\n return goog.string.internal.newLineToBr(\n str.replace(/ /g, '  '), opt_xml);\n};\n\n\n/**\n * Determines whether a string contains a substring.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n * @see goog.string.contains\n */\ngoog.string.internal.contains = function(str, subString) {\n 'use strict';\n return str.indexOf(subString) != -1;\n};\n\n\n/**\n * Determines whether a string contains a substring, ignoring case.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n * @see goog.string.caseInsensitiveContains\n */\ngoog.string.internal.caseInsensitiveContains = function(str, subString) {\n 'use strict';\n return goog.string.internal.contains(\n str.toLowerCase(), subString.toLowerCase());\n};\n\n\n/**\n * Compares two version numbers.\n *\n * @param {string|number} version1 Version of first item.\n * @param {string|number} version2 Version of second item.\n *\n * @return {number} 1 if `version1` is higher.\n * 0 if arguments are equal.\n * -1 if `version2` is higher.\n * @see goog.string.compareVersions\n */\ngoog.string.internal.compareVersions = function(version1, version2) {\n 'use strict';\n let order = 0;\n // Trim leading and trailing whitespace and split the versions into\n // subversions.\n const v1Subs = goog.string.internal.trim(String(version1)).split('.');\n const v2Subs = goog.string.internal.trim(String(version2)).split('.');\n const subCount = Math.max(v1Subs.length, v2Subs.length);\n\n // Iterate over the subversions, as long as they appear to be equivalent.\n for (let subIdx = 0; order == 0 && subIdx < subCount; subIdx++) {\n let v1Sub = v1Subs[subIdx] || '';\n let v2Sub = v2Subs[subIdx] || '';\n\n do {\n // Split the subversions into pairs of numbers and qualifiers (like 'b').\n // Two different RegExp objects are use to make it clear the code\n // is side-effect free\n const v1Comp = /(\\d*)(\\D*)(.*)/.exec(v1Sub) || ['', '', '', ''];\n const v2Comp = /(\\d*)(\\D*)(.*)/.exec(v2Sub) || ['', '', '', ''];\n // Break if there are no more matches.\n if (v1Comp[0].length == 0 && v2Comp[0].length == 0) {\n break;\n }\n\n // Parse the numeric part of the subversion. A missing number is\n // equivalent to 0.\n const v1CompNum = v1Comp[1].length == 0 ? 0 : parseInt(v1Comp[1], 10);\n const v2CompNum = v2Comp[1].length == 0 ? 0 : parseInt(v2Comp[1], 10);\n\n // Compare the subversion components. The number has the highest\n // precedence. Next, if the numbers are equal, a subversion without any\n // qualifier is always higher than a subversion with any qualifier. Next,\n // the qualifiers are compared as strings.\n order = goog.string.internal.compareElements_(v1CompNum, v2CompNum) ||\n goog.string.internal.compareElements_(\n v1Comp[2].length == 0, v2Comp[2].length == 0) ||\n goog.string.internal.compareElements_(v1Comp[2], v2Comp[2]);\n // Stop as soon as an inequality is discovered.\n\n v1Sub = v1Comp[3];\n v2Sub = v2Comp[3];\n } while (order == 0);\n }\n\n return order;\n};\n\n\n/**\n * Compares elements of a version number.\n *\n * @param {string|number|boolean} left An element from a version number.\n * @param {string|number|boolean} right An element from a version number.\n *\n * @return {number} 1 if `left` is higher.\n * 0 if arguments are equal.\n * -1 if `right` is higher.\n * @private\n */\ngoog.string.internal.compareElements_ = function(left, right) {\n 'use strict';\n if (left < right) {\n return -1;\n } else if (left > right) {\n return 1;\n }\n return 0;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities used by goog.labs.userAgent tools. These functions\n * should not be used outside of goog.labs.userAgent.*.\n *\n */\n\ngoog.module('goog.labs.userAgent.util');\ngoog.module.declareLegacyNamespace();\n\nconst {caseInsensitiveContains, contains} = goog.require('goog.string.internal');\nconst {useClientHints} = goog.require('goog.labs.userAgent');\n\n/**\n * @const {boolean} If true, use navigator.userAgentData without check.\n * TODO(user): FEATURESET_YEAR >= 2024 if it supports mobile and all the\n * brands we need. See https://caniuse.com/mdn-api_navigator_useragentdata.\n */\nconst ASSUME_CLIENT_HINTS_SUPPORT = false;\n\n/**\n * Gets the native userAgent string from navigator if it exists.\n * If navigator or navigator.userAgent string is missing, returns an empty\n * string.\n * @return {string}\n */\nfunction getNativeUserAgentString() {\n const navigator = getNavigator();\n if (navigator) {\n const userAgent = navigator.userAgent;\n if (userAgent) {\n return userAgent;\n }\n }\n return '';\n}\n\n/**\n * Gets the native userAgentData object from navigator if it exists.\n * If navigator.userAgentData object is missing returns null.\n * @return {?NavigatorUAData}\n */\nfunction getNativeUserAgentData() {\n const navigator = getNavigator();\n // TODO(user): Use navigator?.userAgent ?? null once it's supported.\n if (navigator) {\n return navigator.userAgentData || null;\n }\n return null;\n}\n\n/**\n * Getter for the native navigator.\n * @return {!Navigator}\n */\nfunction getNavigator() {\n return goog.global.navigator;\n}\n\n/**\n * A possible override for applications which wish to not check\n * navigator.userAgent but use a specified value for detection instead.\n * @type {?string}\n */\nlet userAgentInternal = null;\n\n/**\n * A possible override for applications which wish to not check\n * navigator.userAgentData but use a specified value for detection instead.\n * @type {?NavigatorUAData}\n */\nlet userAgentDataInternal = getNativeUserAgentData();\n\n/**\n * Override the user agent string with the given value.\n * This should only be used for testing within the goog.labs.userAgent\n * namespace.\n * Pass `null` to use the native browser object instead.\n * @param {?string=} userAgent The userAgent override.\n * @return {void}\n */\nfunction setUserAgent(userAgent = undefined) {\n userAgentInternal =\n typeof userAgent === 'string' ? userAgent : getNativeUserAgentString();\n}\n\n/** @return {string} The user agent string. */\nfunction getUserAgent() {\n return userAgentInternal == null ? getNativeUserAgentString() :\n userAgentInternal;\n}\n\n/**\n * Override the user agent data object with the given value.\n * This should only be used for testing within the goog.labs.userAgent\n * namespace.\n * Pass `null` to specify the absence of userAgentData. Note that this behavior\n * is different from setUserAgent.\n * @param {?NavigatorUAData} userAgentData The userAgentData override.\n */\nfunction setUserAgentData(userAgentData) {\n userAgentDataInternal = userAgentData;\n}\n\n/**\n * If the user agent data object was overridden using setUserAgentData,\n * reset it so that it uses the native browser object instead, if it exists.\n */\nfunction resetUserAgentData() {\n userAgentDataInternal = getNativeUserAgentData();\n}\n\n/** @return {?NavigatorUAData} Navigator.userAgentData if exist */\nfunction getUserAgentData() {\n return userAgentDataInternal;\n}\n\n/**\n * Checks if any string in userAgentData.brands matches str.\n * Returns false if userAgentData is not supported.\n * @param {string} str\n * @return {boolean} Whether any brand string from userAgentData contains the\n * given string.\n */\nfunction matchUserAgentDataBrand(str) {\n if (!useClientHints()) return false;\n const data = getUserAgentData();\n if (!data) return false;\n return data.brands.some(({brand}) => brand && contains(brand, str));\n}\n\n/**\n * @param {string} str\n * @return {boolean} Whether the user agent contains the given string.\n */\nfunction matchUserAgent(str) {\n const userAgent = getUserAgent();\n return contains(userAgent, str);\n}\n\n/**\n * @param {string} str\n * @return {boolean} Whether the user agent contains the given string, ignoring\n * case.\n */\nfunction matchUserAgentIgnoreCase(str) {\n const userAgent = getUserAgent();\n return caseInsensitiveContains(userAgent, str);\n}\n\n/**\n * Parses the user agent into tuples for each section.\n * @param {string} userAgent\n * @return {!Array<!Array<string>>} Tuples of key, version, and the contents of\n * the parenthetical.\n */\nfunction extractVersionTuples(userAgent) {\n // Matches each section of a user agent string.\n // Example UA:\n // Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us)\n // AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405\n // This has three version tuples: Mozilla, AppleWebKit, and Mobile.\n\n const versionRegExp = new RegExp(\n // Key. Note that a key may have a space.\n // (i.e. 'Mobile Safari' in 'Mobile Safari/5.0')\n '([A-Z][\\\\w ]+)' +\n\n '/' + // slash\n '([^\\\\s]+)' + // version (i.e. '5.0b')\n '\\\\s*' + // whitespace\n '(?:\\\\((.*?)\\\\))?', // parenthetical info. parentheses not matched.\n 'g');\n\n const data = [];\n let match;\n\n // Iterate and collect the version tuples. Each iteration will be the\n // next regex match.\n while (match = versionRegExp.exec(userAgent)) {\n data.push([\n match[1], // key\n match[2], // value\n // || undefined as this is not undefined in IE7 and IE8\n match[3] || undefined // info\n ]);\n }\n\n return data;\n}\n\nexports = {\n ASSUME_CLIENT_HINTS_SUPPORT,\n extractVersionTuples,\n getNativeUserAgentString,\n getUserAgent,\n getUserAgentData,\n matchUserAgent,\n matchUserAgentDataBrand,\n matchUserAgentIgnoreCase,\n resetUserAgentData,\n setUserAgent,\n setUserAgentData,\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Useful compiler idioms.\n */\n\ngoog.provide('goog.reflect');\n\n\n/**\n * Syntax for object literal casts.\n * @see http://go/jscompiler-renaming\n * @see https://goo.gl/CRs09P\n *\n * Use this if you have an object literal whose keys need to have the same names\n * as the properties of some class even after they are renamed by the compiler.\n *\n * @param {!Function} type Type to cast to.\n * @param {Object} object Object literal to cast.\n * @return {Object} The object literal.\n */\ngoog.reflect.object = function(type, object) {\n 'use strict';\n return object;\n};\n\n/**\n * Syntax for renaming property strings.\n * @see http://go/jscompiler-renaming\n * @see https://goo.gl/CRs09P\n *\n * Use this if you have an need to access a property as a string, but want\n * to also have the property renamed by the compiler. In contrast to\n * goog.reflect.object, this method takes an instance of an object.\n *\n * Properties must be simple names (not qualified names).\n *\n * @param {string} prop Name of the property\n * @param {!Object} object Instance of the object whose type will be used\n * for renaming\n * @return {string} The renamed property.\n */\ngoog.reflect.objectProperty = function(prop, object) {\n 'use strict';\n return prop;\n};\n\n/**\n * To assert to the compiler that an operation is needed when it would\n * otherwise be stripped. For example:\n * <code>\n * // Force a layout\n * goog.reflect.sinkValue(dialog.offsetHeight);\n * </code>\n * @param {T} x\n * @return {T}\n * @template T\n */\ngoog.reflect.sinkValue = function(x) {\n 'use strict';\n goog.reflect.sinkValue[' '](x);\n return x;\n};\n\n\n/**\n * The compiler should optimize this function away iff no one ever uses\n * goog.reflect.sinkValue.\n */\ngoog.reflect.sinkValue[' '] = function() {};\n\n\n/**\n * Check if a property can be accessed without throwing an exception.\n * @param {Object} obj The owner of the property.\n * @param {string} prop The property name.\n * @return {boolean} Whether the property is accessible. Will also return true\n * if obj is null.\n */\ngoog.reflect.canAccessProperty = function(obj, prop) {\n 'use strict';\n try {\n goog.reflect.sinkValue(obj[prop]);\n return true;\n } catch (e) {\n }\n return false;\n};\n\n\n/**\n * Retrieves a value from a cache given a key. The compiler provides special\n * consideration for this call such that it is generally considered side-effect\n * free. However, if the `opt_keyFn` or `valueFn` have side-effects\n * then the entire call is considered to have side-effects.\n *\n * Conventionally storing the value on the cache would be considered a\n * side-effect and preclude unused calls from being pruned, ie. even if\n * the value was never used, it would still always be stored in the cache.\n *\n * Providing a side-effect free `valueFn` and `opt_keyFn`\n * allows unused calls to `goog.reflect.cache` to be pruned.\n *\n * @param {!Object<K, V>} cacheObj The object that contains the cached values.\n * @param {?} key The key to lookup in the cache. If it is not string or number\n * then a `opt_keyFn` should be provided. The key is also used as the\n * parameter to the `valueFn`.\n * @param {function(?):V} valueFn The value provider to use to calculate the\n * value to store in the cache. This function should be side-effect free\n * to take advantage of the optimization.\n * @param {function(?):K=} opt_keyFn The key provider to determine the cache\n * map key. This should be used if the given key is not a string or number.\n * If not provided then the given key is used. This function should be\n * side-effect free to take advantage of the optimization.\n * @return {V} The cached or calculated value.\n * @template K\n * @template V\n */\ngoog.reflect.cache = function(cacheObj, key, valueFn, opt_keyFn) {\n 'use strict';\n const storedKey = opt_keyFn ? opt_keyFn(key) : key;\n\n if (Object.prototype.hasOwnProperty.call(cacheObj, storedKey)) {\n return cacheObj[storedKey];\n }\n\n return (cacheObj[storedKey] = valueFn(key));\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Rendering engine detection.\n * @see <a href=\"http://www.useragentstring.com/\">User agent strings</a>\n * For information on the browser brand (such as Safari versus Chrome), see\n * goog.userAgent.product.\n * @see ../demos/useragent.html\n */\n\ngoog.provide('goog.userAgent');\n\ngoog.require('goog.labs.userAgent.browser');\ngoog.require('goog.labs.userAgent.engine');\ngoog.require('goog.labs.userAgent.platform');\ngoog.require('goog.labs.userAgent.util');\ngoog.require('goog.reflect');\ngoog.require('goog.string.internal');\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is IE.\n */\ngoog.userAgent.ASSUME_IE = goog.define('goog.userAgent.ASSUME_IE', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is EDGE,\n * referring to EdgeHTML based Edge.\n */\ngoog.userAgent.ASSUME_EDGE = goog.define('goog.userAgent.ASSUME_EDGE', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is GECKO.\n */\ngoog.userAgent.ASSUME_GECKO = goog.define('goog.userAgent.ASSUME_GECKO', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is WEBKIT.\n */\ngoog.userAgent.ASSUME_WEBKIT =\n goog.define('goog.userAgent.ASSUME_WEBKIT', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is a\n * mobile device running WebKit e.g. iPhone or Android.\n */\ngoog.userAgent.ASSUME_MOBILE_WEBKIT =\n goog.define('goog.userAgent.ASSUME_MOBILE_WEBKIT', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is OPERA,\n * referring to Presto-based Opera.\n */\ngoog.userAgent.ASSUME_OPERA = goog.define('goog.userAgent.ASSUME_OPERA', false);\n\n\n/**\n * @define {boolean} Whether the\n * `goog.userAgent.isVersionOrHigher`\n * function will return true for any version.\n */\ngoog.userAgent.ASSUME_ANY_VERSION =\n goog.define('goog.userAgent.ASSUME_ANY_VERSION', false);\n\n\n/**\n * Whether we know the browser engine at compile-time.\n * @type {boolean}\n * @private\n */\ngoog.userAgent.BROWSER_KNOWN_ = goog.userAgent.ASSUME_IE ||\n goog.userAgent.ASSUME_EDGE || goog.userAgent.ASSUME_GECKO ||\n goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.ASSUME_WEBKIT ||\n goog.userAgent.ASSUME_OPERA;\n\n\n/**\n * Returns the userAgent string for the current browser.\n *\n * @return {string} The userAgent string.\n */\ngoog.userAgent.getUserAgentString = function() {\n 'use strict';\n return goog.labs.userAgent.util.getUserAgent();\n};\n\n\n/**\n * @return {?Navigator} The native navigator object.\n */\ngoog.userAgent.getNavigatorTyped = function() {\n 'use strict';\n // Need a local navigator reference instead of using the global one,\n // to avoid the rare case where they reference different objects.\n // (in a WorkerPool, for example).\n return goog.global['navigator'] || null;\n};\n\n\n/**\n * TODO(nnaze): Change type to \"Navigator\" and update compilation targets.\n * @return {?Object} The native navigator object.\n */\ngoog.userAgent.getNavigator = function() {\n 'use strict';\n return goog.userAgent.getNavigatorTyped();\n};\n\n\n/**\n * Whether the user agent is Presto-based Opera.\n * @type {boolean}\n */\ngoog.userAgent.OPERA = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_OPERA :\n goog.labs.userAgent.browser.isOpera();\n\n\n/**\n * Whether the user agent is Internet Explorer.\n * @type {boolean}\n */\ngoog.userAgent.IE = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_IE :\n goog.labs.userAgent.browser.isIE();\n\n\n/**\n * Whether the user agent is Microsoft Edge (EdgeHTML based).\n * @type {boolean}\n */\ngoog.userAgent.EDGE = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_EDGE :\n goog.labs.userAgent.engine.isEdge();\n\n\n/**\n * Whether the user agent is MS Internet Explorer or MS Edge (EdgeHTML based).\n * @type {boolean}\n */\ngoog.userAgent.EDGE_OR_IE = goog.userAgent.EDGE || goog.userAgent.IE;\n\n\n/**\n * Whether the user agent is Gecko. Gecko is the rendering engine used by\n * Mozilla, Firefox, and others.\n * @type {boolean}\n */\ngoog.userAgent.GECKO = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_GECKO :\n goog.labs.userAgent.engine.isGecko();\n\n\n/**\n * Whether the user agent is WebKit. WebKit is the rendering engine that\n * Safari, Edge Chromium, Opera Chromium, Android and others use.\n * @type {boolean}\n */\ngoog.userAgent.WEBKIT = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_MOBILE_WEBKIT :\n goog.labs.userAgent.engine.isWebKit();\n\n\n/**\n * Whether the user agent is running on a mobile device.\n *\n * This is a separate function so that the logic can be tested.\n *\n * TODO(nnaze): Investigate swapping in goog.labs.userAgent.device.isMobile().\n *\n * @return {boolean} Whether the user agent is running on a mobile device.\n * @private\n */\ngoog.userAgent.isMobile_ = function() {\n 'use strict';\n return goog.userAgent.WEBKIT &&\n goog.labs.userAgent.util.matchUserAgent('Mobile');\n};\n\n\n/**\n * Whether the user agent is running on a mobile device.\n *\n * TODO(nnaze): Consider deprecating MOBILE when labs.userAgent\n * is promoted as the gecko/webkit logic is likely inaccurate.\n *\n * @type {boolean}\n */\ngoog.userAgent.MOBILE =\n goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.isMobile_();\n\n\n/**\n * Used while transitioning code to use WEBKIT instead.\n * @type {boolean}\n * @deprecated Use {@link goog.userAgent.product.SAFARI} instead.\n * TODO(nicksantos): Delete this from goog.userAgent.\n */\ngoog.userAgent.SAFARI = goog.userAgent.WEBKIT;\n\n\n/**\n * @return {string} the platform (operating system) the user agent is running\n * on. Default to empty string because navigator.platform may not be defined\n * (on Rhino, for example).\n * @private\n */\ngoog.userAgent.determinePlatform_ = function() {\n 'use strict';\n var navigator = goog.userAgent.getNavigatorTyped();\n return navigator && navigator.platform || '';\n};\n\n\n/**\n * The platform (operating system) the user agent is running on. Default to\n * empty string because navigator.platform may not be defined (on Rhino, for\n * example).\n * @type {string}\n */\ngoog.userAgent.PLATFORM = goog.userAgent.determinePlatform_();\n\n\n/**\n * @define {boolean} Whether the user agent is running on a Macintosh operating\n * system.\n */\ngoog.userAgent.ASSUME_MAC = goog.define('goog.userAgent.ASSUME_MAC', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on a Windows operating\n * system.\n */\ngoog.userAgent.ASSUME_WINDOWS =\n goog.define('goog.userAgent.ASSUME_WINDOWS', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on a Linux operating\n * system.\n */\ngoog.userAgent.ASSUME_LINUX = goog.define('goog.userAgent.ASSUME_LINUX', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on a X11 windowing\n * system.\n */\ngoog.userAgent.ASSUME_X11 = goog.define('goog.userAgent.ASSUME_X11', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on Android.\n */\ngoog.userAgent.ASSUME_ANDROID =\n goog.define('goog.userAgent.ASSUME_ANDROID', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPhone.\n */\ngoog.userAgent.ASSUME_IPHONE =\n goog.define('goog.userAgent.ASSUME_IPHONE', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPad.\n */\ngoog.userAgent.ASSUME_IPAD = goog.define('goog.userAgent.ASSUME_IPAD', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPod.\n */\ngoog.userAgent.ASSUME_IPOD = goog.define('goog.userAgent.ASSUME_IPOD', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on KaiOS.\n */\ngoog.userAgent.ASSUME_KAIOS = goog.define('goog.userAgent.ASSUME_KAIOS', false);\n\n\n/**\n * @type {boolean}\n * @private\n */\ngoog.userAgent.PLATFORM_KNOWN_ = goog.userAgent.ASSUME_MAC ||\n goog.userAgent.ASSUME_WINDOWS || goog.userAgent.ASSUME_LINUX ||\n goog.userAgent.ASSUME_X11 || goog.userAgent.ASSUME_ANDROID ||\n goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD ||\n goog.userAgent.ASSUME_IPOD;\n\n\n/**\n * Whether the user agent is running on a Macintosh operating system.\n * @type {boolean}\n */\ngoog.userAgent.MAC = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_MAC :\n goog.labs.userAgent.platform.isMacintosh();\n\n\n/**\n * Whether the user agent is running on a Windows operating system.\n * @type {boolean}\n */\ngoog.userAgent.WINDOWS = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_WINDOWS :\n goog.labs.userAgent.platform.isWindows();\n\n\n/**\n * Whether the user agent is Linux per the legacy behavior of\n * goog.userAgent.LINUX, which considered ChromeOS to also be\n * Linux.\n * @return {boolean}\n * @private\n */\ngoog.userAgent.isLegacyLinux_ = function() {\n 'use strict';\n return goog.labs.userAgent.platform.isLinux() ||\n goog.labs.userAgent.platform.isChromeOS();\n};\n\n\n/**\n * Whether the user agent is running on a Linux operating system.\n *\n * Note that goog.userAgent.LINUX considers ChromeOS to be Linux,\n * while goog.labs.userAgent.platform considers ChromeOS and\n * Linux to be different OSes.\n *\n * @type {boolean}\n */\ngoog.userAgent.LINUX = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_LINUX :\n goog.userAgent.isLegacyLinux_();\n\n\n/**\n * @return {boolean} Whether the user agent is an X11 windowing system.\n * @private\n */\ngoog.userAgent.isX11_ = function() {\n 'use strict';\n var navigator = goog.userAgent.getNavigatorTyped();\n return !!navigator &&\n goog.string.internal.contains(navigator['appVersion'] || '', 'X11');\n};\n\n\n/**\n * Whether the user agent is running on a X11 windowing system.\n * @type {boolean}\n */\ngoog.userAgent.X11 = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_X11 :\n goog.userAgent.isX11_();\n\n\n/**\n * Whether the user agent is running on Android.\n * @type {boolean}\n */\ngoog.userAgent.ANDROID = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_ANDROID :\n goog.labs.userAgent.platform.isAndroid();\n\n\n/**\n * Whether the user agent is running on an iPhone.\n * @type {boolean}\n */\ngoog.userAgent.IPHONE = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPHONE :\n goog.labs.userAgent.platform.isIphone();\n\n\n/**\n * Whether the user agent is running on an iPad.\n * @type {boolean}\n */\ngoog.userAgent.IPAD = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPAD :\n goog.labs.userAgent.platform.isIpad();\n\n\n/**\n * Whether the user agent is running on an iPod.\n * @type {boolean}\n */\ngoog.userAgent.IPOD = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPOD :\n goog.labs.userAgent.platform.isIpod();\n\n\n/**\n * Whether the user agent is running on iOS.\n * @type {boolean}\n */\ngoog.userAgent.IOS = goog.userAgent.PLATFORM_KNOWN_ ?\n (goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD ||\n goog.userAgent.ASSUME_IPOD) :\n goog.labs.userAgent.platform.isIos();\n\n/**\n * Whether the user agent is running on KaiOS.\n * @type {boolean}\n */\ngoog.userAgent.KAIOS = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_KAIOS :\n goog.labs.userAgent.platform.isKaiOS();\n\n\n/**\n * @return {string} The string that describes the version number of the user\n * agent.\n * @private\n */\ngoog.userAgent.determineVersion_ = function() {\n 'use strict';\n // All browsers have different ways to detect the version and they all have\n // different naming schemes.\n // version is a string rather than a number because it may contain 'b', 'a',\n // and so on.\n var version = '';\n var arr = goog.userAgent.getVersionRegexResult_();\n if (arr) {\n version = arr ? arr[1] : '';\n }\n\n if (goog.userAgent.IE) {\n // IE9 can be in document mode 9 but be reporting an inconsistent user agent\n // version. If it is identifying as a version lower than 9 we take the\n // documentMode as the version instead. IE8 has similar behavior.\n // It is recommended to set the X-UA-Compatible header to ensure that IE9\n // uses documentMode 9.\n var docMode = goog.userAgent.getDocumentMode_();\n if (docMode != null && docMode > parseFloat(version)) {\n return String(docMode);\n }\n }\n\n return version;\n};\n\n\n/**\n * @return {?IArrayLike<string>|undefined} The version regex matches from\n * parsing the user\n * agent string. These regex statements must be executed inline so they can\n * be compiled out by the closure compiler with the rest of the useragent\n * detection logic when ASSUME_* is specified.\n * @private\n */\ngoog.userAgent.getVersionRegexResult_ = function() {\n 'use strict';\n var userAgent = goog.userAgent.getUserAgentString();\n if (goog.userAgent.GECKO) {\n return /rv\\:([^\\);]+)(\\)|;)/.exec(userAgent);\n }\n if (goog.userAgent.EDGE) {\n return /Edge\\/([\\d\\.]+)/.exec(userAgent);\n }\n if (goog.userAgent.IE) {\n return /\\b(?:MSIE|rv)[: ]([^\\);]+)(\\)|;)/.exec(userAgent);\n }\n if (goog.userAgent.WEBKIT) {\n // WebKit/125.4\n return /WebKit\\/(\\S+)/.exec(userAgent);\n }\n if (goog.userAgent.OPERA) {\n // If none of the above browsers were detected but the browser is Opera, the\n // only string that is of interest is 'Version/<number>'.\n return /(?:Version)[ \\/]?(\\S+)/.exec(userAgent);\n }\n return undefined;\n};\n\n\n/**\n * @return {number|undefined} Returns the document mode (for testing).\n * @private\n */\ngoog.userAgent.getDocumentMode_ = function() {\n 'use strict';\n // NOTE(user): goog.userAgent may be used in context where there is no DOM.\n var doc = goog.global['document'];\n return doc ? doc['documentMode'] : undefined;\n};\n\n\n/**\n * The version of the user agent. This is a string because it might contain\n * 'b' (as in beta) as well as multiple dots.\n * @type {string}\n */\ngoog.userAgent.VERSION = goog.userAgent.determineVersion_();\n\n\n/**\n * Compares two version numbers.\n *\n * @param {string} v1 Version of first item.\n * @param {string} v2 Version of second item.\n *\n * @return {number} 1 if first argument is higher\n * 0 if arguments are equal\n * -1 if second argument is higher.\n * @deprecated Use goog.string.compareVersions.\n */\ngoog.userAgent.compare = function(v1, v2) {\n 'use strict';\n return goog.string.internal.compareVersions(v1, v2);\n};\n\n\n/**\n * Cache for {@link goog.userAgent.isVersionOrHigher}.\n * Calls to compareVersions are surprisingly expensive and, as a browser's\n * version number is unlikely to change during a session, we cache the results.\n * @const\n * @private\n */\ngoog.userAgent.isVersionOrHigherCache_ = {};\n\n\n/**\n * Whether the user agent version is higher or the same as the given version.\n * NOTE: When checking the version numbers for Firefox and Safari, be sure to\n * use the engine's version, not the browser's version number. For example,\n * Firefox 3.0 corresponds to Gecko 1.9 and Safari 3.0 to Webkit 522.11.\n * Opera and Internet Explorer versions match the product release number.<br>\n * @see <a href=\"http://en.wikipedia.org/wiki/Safari_version_history\">\n * Webkit</a>\n * @see <a href=\"http://en.wikipedia.org/wiki/Gecko_engine\">Gecko</a>\n *\n * @param {string|number} version The version to check.\n * @return {boolean} Whether the user agent version is higher or the same as\n * the given version.\n */\ngoog.userAgent.isVersionOrHigher = function(version) {\n 'use strict';\n return goog.userAgent.ASSUME_ANY_VERSION ||\n goog.reflect.cache(\n goog.userAgent.isVersionOrHigherCache_, version, function() {\n 'use strict';\n return goog.string.internal.compareVersions(\n goog.userAgent.VERSION, version) >= 0;\n });\n};\n\n\n/**\n * Whether the IE effective document mode is higher or the same as the given\n * document mode version.\n * NOTE: Only for IE, return false for another browser.\n *\n * @param {number} documentMode The document mode version to check.\n * @return {boolean} Whether the IE effective document mode is higher or the\n * same as the given version.\n */\ngoog.userAgent.isDocumentModeOrHigher = function(documentMode) {\n 'use strict';\n return Number(goog.userAgent.DOCUMENT_MODE) >= documentMode;\n};\n\n\n/**\n * Deprecated alias to `goog.userAgent.isDocumentModeOrHigher`.\n * @param {number} version The version to check.\n * @return {boolean} Whether the IE effective document mode is higher or the\n * same as the given version.\n * @deprecated Use goog.userAgent.isDocumentModeOrHigher().\n */\ngoog.userAgent.isDocumentMode = goog.userAgent.isDocumentModeOrHigher;\n\n\n/**\n * For IE version < 7, documentMode is undefined, so attempt to use the\n * CSS1Compat property to see if we are in standards mode. If we are in\n * standards mode, treat the browser version as the document mode. Otherwise,\n * IE is emulating version 5.\n *\n * NOTE(user): Support for IE < 7 is long gone, so this is now simplified.\n * It returns document.documentMode for IE and undefined for everything else.\n *\n * @type {number|undefined}\n * @const\n */\ngoog.userAgent.DOCUMENT_MODE = (function() {\n 'use strict';\n var doc = goog.global['document'];\n if (!doc || !goog.userAgent.IE) return undefined;\n // This must be an IE user agent.\n var documentMode = goog.userAgent.getDocumentMode_();\n if (documentMode) return documentMode;\n // The user agent version string begins with the major version.\n // Parse the major version and truncate anything following.\n var ieVersion = parseInt(goog.userAgent.VERSION, 10);\n return ieVersion || undefined;\n})();\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Closure user agent detection (Browser).\n * @see <a href=\"http://www.useragentstring.com/\">User agent strings</a>\n * For more information on rendering engine, platform, or device see the other\n * sub-namespaces in goog.labs.userAgent, goog.labs.userAgent.platform,\n * goog.labs.userAgent.device respectively.)\n */\n\ngoog.module('goog.labs.userAgent.browser');\ngoog.module.declareLegacyNamespace();\n\nconst util = goog.require('goog.labs.userAgent.util');\nconst {AsyncValue, Version} = goog.require('goog.labs.userAgent.highEntropy.highEntropyValue');\nconst {assert, assertExists} = goog.require('goog.asserts');\nconst {compareVersions} = goog.require('goog.string.internal');\nconst {fullVersionList} = goog.require('goog.labs.userAgent.highEntropy.highEntropyData');\nconst {useClientHints} = goog.require('goog.labs.userAgent');\n\n// TODO(nnaze): Refactor to remove excessive exclusion logic in matching\n// functions.\n\n/**\n * A browser brand represents an opaque string that is used for making\n * brand-specific version checks in userAgentData.\n * @enum {string}\n */\nconst Brand = {\n /**\n * The browser brand for Android Browser.\n * Do not depend on the value of this string. Because Android Browser has not\n * implemented userAgentData yet, the value of this string is not guaranteed\n * to stay the same in future revisions.\n */\n ANDROID_BROWSER: 'Android Browser',\n /**\n * The browser brand for Chromium, including Chromium-based Edge and Opera.\n */\n CHROMIUM: 'Chromium',\n /**\n * The browser brand for Edge.\n * This brand can be used to get the version of both EdgeHTML and\n * Chromium-based Edge.\n */\n EDGE: 'Microsoft Edge',\n /**\n * The browser brand for Firefox.\n * Do not depend on the value of this string. Because Firefox has not\n * implemented userAgentData yet, the value of this string is not guaranteed\n * to stay the same in future revisions.\n */\n FIREFOX: 'Firefox',\n /**\n * The browser brand for Internet Explorer.\n * Do not depend on the value of this string. Because IE will never support\n * userAgentData, the value of this string should be treated as opaque (it's\n * used internally for legacy-userAgent fallback).\n */\n IE: 'Internet Explorer',\n /**\n * The browser brand for Opera.\n * This brand can be used to get the version of both Presto- and\n * Chromium-based Opera.\n */\n OPERA: 'Opera',\n /**\n * The browser brand for Safari.\n * Do not depend on the value of this string. Because Safari has not\n * implemented userAgentData yet, the value of this string is not guaranteed\n * to stay the same in future revisions.\n */\n SAFARI: 'Safari',\n /**\n * The browser brand for Silk.\n * See\n * https://docs.aws.amazon.com/silk/latest/developerguide/what-is-silk.html\n * Do not depend on the value of this string. Because Silk does not\n * identify itself in userAgentData yet, the value of this string is not\n * guaranteed to stay the same in future revisions.\n */\n SILK: 'Silk',\n};\nexports.Brand = Brand;\n\n/**\n * @param {boolean=} ignoreClientHintsFlag Iff truthy, the `useClientHints`\n * function will not be called when evaluating if User-Agent Client Hints\n * Brand data can be used. For existing labs.userAgent API surfaces with\n * widespread use, this should be a falsy value so that usage of the Client\n * Hints APIs can be gated behind flags / experiment rollouts.\n * @return {boolean} Whether to use navigator.userAgentData to determine\n * browser's brand.\n */\nfunction useUserAgentDataBrand(ignoreClientHintsFlag = false) {\n if (util.ASSUME_CLIENT_HINTS_SUPPORT) return true;\n // High-entropy API surfaces should not be gated behind the useClientHints\n // check (as in production it is gated behind a define).\n if (!ignoreClientHintsFlag && !useClientHints()) return false;\n const userAgentData = util.getUserAgentData();\n return !!userAgentData && userAgentData.brands.length > 0;\n}\n\n/**\n * @return {boolean} Whether this browser is likely to have the fullVersionList\n * high-entropy Client Hint.\n */\nfunction hasFullVersionList() {\n // https://chromiumdash.appspot.com/commits?commit=1eb643c3057e64ff4d22468432ad16c4cab12879&platform=Linux\n // indicates that for all platforms Chromium 98 shipped this feature.\n // See also\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-CH-UA-Full-Version-List#browser_compatibility\n return isAtLeast(Brand.CHROMIUM, 98);\n}\n\n/**\n * @return {boolean} Whether the user's browser is Opera. Note: Chromium based\n * Opera (Opera 15+) is detected as Chrome to avoid unnecessary special\n * casing.\n */\nfunction matchOpera() {\n if (useUserAgentDataBrand()) {\n // Pre-Chromium Edge doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Opera');\n}\n\n/** @return {boolean} Whether the user's browser is IE. */\nfunction matchIE() {\n if (useUserAgentDataBrand()) {\n // IE doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Trident') || util.matchUserAgent('MSIE');\n}\n\n/**\n * @return {boolean} Whether the user's browser is Edge. This refers to\n * EdgeHTML based Edge.\n */\nfunction matchEdgeHtml() {\n if (useUserAgentDataBrand()) {\n // Pre-Chromium Edge doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Edge');\n}\n\n/** @return {boolean} Whether the user's browser is Chromium based Edge. */\nfunction matchEdgeChromium() {\n if (useUserAgentDataBrand()) {\n return util.matchUserAgentDataBrand(Brand.EDGE);\n }\n return util.matchUserAgent('Edg/');\n}\n\n/** @return {boolean} Whether the user's browser is Chromium based Opera. */\nfunction matchOperaChromium() {\n if (useUserAgentDataBrand()) {\n return util.matchUserAgentDataBrand(Brand.OPERA);\n }\n return util.matchUserAgent('OPR');\n}\n\n/** @return {boolean} Whether the user's browser is Firefox. */\nfunction matchFirefox() {\n // Firefox doesn't support navigator.userAgentData yet, so use\n // navigator.userAgent.\n return util.matchUserAgent('Firefox') || util.matchUserAgent('FxiOS');\n}\n\n/** @return {boolean} Whether the user's browser is Safari. */\nfunction matchSafari() {\n // Apple-based browsers don't support navigator.userAgentData yet, so use\n // navigator.userAgent.\n return util.matchUserAgent('Safari') &&\n !(matchChrome() || matchCoast() || matchOpera() || matchEdgeHtml() ||\n matchEdgeChromium() || matchOperaChromium() || matchFirefox() ||\n isSilk() || util.matchUserAgent('Android'));\n}\n\n/**\n * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based\n * iOS browser).\n */\nfunction matchCoast() {\n if (useUserAgentDataBrand()) {\n // Coast doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Coast');\n}\n\n/** @return {boolean} Whether the user's browser is iOS Webview. */\nfunction matchIosWebview() {\n // Apple-based browsers don't support navigator.userAgentData yet, so use\n // navigator.userAgent.\n // iOS Webview does not show up as Chrome or Safari.\n return (util.matchUserAgent('iPad') || util.matchUserAgent('iPhone')) &&\n !matchSafari() && !matchChrome() && !matchCoast() && !matchFirefox() &&\n util.matchUserAgent('AppleWebKit');\n}\n\n/**\n * @return {boolean} Whether the user's browser is any Chromium browser. This\n * returns true for Chrome, Opera 15+, and Edge Chromium.\n */\nfunction matchChrome() {\n if (useUserAgentDataBrand()) {\n return util.matchUserAgentDataBrand(Brand.CHROMIUM);\n }\n return ((util.matchUserAgent('Chrome') || util.matchUserAgent('CriOS')) &&\n !matchEdgeHtml()) ||\n isSilk();\n}\n\n/** @return {boolean} Whether the user's browser is the Android browser. */\nfunction matchAndroidBrowser() {\n // Android can appear in the user agent string for Chrome on Android.\n // This is not the Android standalone browser if it does.\n return util.matchUserAgent('Android') &&\n !(isChrome() || isFirefox() || isOpera() || isSilk());\n}\n\n/** @return {boolean} Whether the user's browser is Opera. */\nconst isOpera = matchOpera;\nexports.isOpera = isOpera;\n\n/** @return {boolean} Whether the user's browser is IE. */\nconst isIE = matchIE;\nexports.isIE = isIE;\n\n/** @return {boolean} Whether the user's browser is EdgeHTML based Edge. */\nconst isEdge = matchEdgeHtml;\nexports.isEdge = isEdge;\n\n/** @return {boolean} Whether the user's browser is Chromium based Edge. */\nconst isEdgeChromium = matchEdgeChromium;\nexports.isEdgeChromium = isEdgeChromium;\n\n/** @return {boolean} Whether the user's browser is Chromium based Opera. */\nconst isOperaChromium = matchOperaChromium;\nexports.isOperaChromium = isOperaChromium;\n\n/** @return {boolean} Whether the user's browser is Firefox. */\nconst isFirefox = matchFirefox;\nexports.isFirefox = isFirefox;\n\n/** @return {boolean} Whether the user's browser is Safari. */\nconst isSafari = matchSafari;\nexports.isSafari = isSafari;\n\n/**\n * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based\n * iOS browser).\n */\nconst isCoast = matchCoast;\nexports.isCoast = isCoast;\n\n/** @return {boolean} Whether the user's browser is iOS Webview. */\nconst isIosWebview = matchIosWebview;\nexports.isIosWebview = isIosWebview;\n\n/**\n * @return {boolean} Whether the user's browser is any Chromium based browser (\n * Chrome, Blink-based Opera (15+) and Edge Chromium).\n */\nconst isChrome = matchChrome;\nexports.isChrome = isChrome;\n\n/** @return {boolean} Whether the user's browser is the Android browser. */\nconst isAndroidBrowser = matchAndroidBrowser;\nexports.isAndroidBrowser = isAndroidBrowser;\n\n/**\n * For more information, see:\n * http://docs.aws.amazon.com/silk/latest/developerguide/user-agent.html\n * @return {boolean} Whether the user's browser is Silk.\n */\nfunction isSilk() {\n // As of Silk 93, Silk does not identify itself in userAgentData.brands.\n // When Silk changes this behavior, update this method to call\n // matchUserAgentDataBrand (akin to isChrome, etc.)\n return util.matchUserAgent('Silk');\n}\nexports.isSilk = isSilk;\n\n/**\n * A helper function that returns a function mapping a list of candidate\n * version tuple keys to the first version string present under a key.\n * Ex:\n * <code>\n * // Arg extracted from \"Foo/1.2.3 Bar/0.2021\"\n * const mapVersion = createVersionMap([[\"Foo\", \"1.2.3\"], [\"Bar\", \"0.2021\"]]);\n * mapVersion([\"Bar\", \"Foo\"]); // returns \"0.2021\"\n * mapVersion([\"Baz\", \"Foo\"]); // returns \"1.2.3\"\n * mapVersion([\"Baz\", \"???\"]); // returns \"\"\n * </code>\n * @param {!Array<!Array<string>>} versionTuples Version tuples pre-extracted\n * from a user agent string.\n * @return {function(!Array<string>): string} The version string, or empty\n * string if it doesn't exist under the given key.\n */\nfunction createVersionMap(versionTuples) {\n // Construct a map for easy lookup.\n const versionMap = {};\n versionTuples.forEach((tuple) => {\n // Note that the tuple is of length three, but we only care about the\n // first two.\n const key = tuple[0];\n const value = tuple[1];\n versionMap[key] = value;\n });\n\n // Gives the value with the first key it finds, otherwise empty string.\n return (keys) => versionMap[keys.find((key) => key in versionMap)] || '';\n}\n\n/**\n * Returns the browser version.\n *\n * Note that for browsers with multiple brands, this function assumes a primary\n * brand and returns the version for that brand.\n *\n * Additionally, this function is not userAgentData-aware and will return\n * incorrect values when the User Agent string is frozen. The current status of\n * User Agent string freezing is available here:\n * https://www.chromestatus.com/feature/5704553745874944\n *\n * To mitigate both of these potential issues, use\n * getVersionStringForLogging() or fullVersionOf() instead.\n *\n * @return {string} The browser version or empty string if version cannot be\n * determined. Note that for Internet Explorer, this returns the version of\n * the browser, not the version of the rendering engine. (IE 8 in\n * compatibility mode will return 8.0 rather than 7.0. To determine the\n * rendering engine version, look at document.documentMode instead. See\n * http://msdn.microsoft.com/en-us/library/cc196988(v=vs.85).aspx for more\n * details.)\n */\nfunction getVersion() {\n const userAgentString = util.getUserAgent();\n\n // Special case IE since IE's version is inside the parenthesis and\n // without the '/'.\n if (isIE()) {\n return getIEVersion(userAgentString);\n }\n\n const versionTuples = util.extractVersionTuples(userAgentString);\n const lookUpValueWithKeys = createVersionMap(versionTuples);\n\n // Check Opera before Chrome since Opera 15+ has \"Chrome\" in the string.\n // See\n // http://my.opera.com/ODIN/blog/2013/07/15/opera-user-agent-strings-opera-15-and-beyond\n if (isOpera()) {\n // Opera 10 has Version/10.0 but Opera/9.8, so look for \"Version\" first.\n // Opera uses 'OPR' for more recent UAs.\n return lookUpValueWithKeys(['Version', 'Opera']);\n }\n\n // Check Edge before Chrome since it has Chrome in the string.\n if (isEdge()) {\n return lookUpValueWithKeys(['Edge']);\n }\n\n // Check Chromium Edge before Chrome since it has Chrome in the string.\n if (isEdgeChromium()) {\n return lookUpValueWithKeys(['Edg']);\n }\n\n // Check Silk before Chrome since it may have Chrome in its string and be\n // treated as Chrome.\n if (isSilk()) {\n return lookUpValueWithKeys(['Silk']);\n }\n\n if (isChrome()) {\n return lookUpValueWithKeys(['Chrome', 'CriOS', 'HeadlessChrome']);\n }\n\n // Usually products browser versions are in the third tuple after \"Mozilla\"\n // and the engine.\n const tuple = versionTuples[2];\n return tuple && tuple[1] || '';\n}\nexports.getVersion = getVersion;\n\n/**\n * Returns whether the current browser's version is at least as high as the\n * given one.\n *\n * Note that for browsers with multiple brands, this function assumes a primary\n * brand and checks the version for that brand.\n *\n * Additionally, this function is not userAgentData-aware and will return\n * incorrect values when the User Agent string is frozen. The current status of\n * User Agent string freezing is available here:\n * https://www.chromestatus.com/feature/5704553745874944\n *\n * To mitigate both of these potential issues, use isAtLeast()/isAtMost() or\n * fullVersionOf() instead.\n *\n * @param {string|number} version The version to check.\n * @return {boolean} Whether the browser version is higher or the same as the\n * given version.\n * @deprecated Use isAtLeast()/isAtMost() instead.\n */\nfunction isVersionOrHigher(version) {\n return compareVersions(getVersion(), version) >= 0;\n}\nexports.isVersionOrHigher = isVersionOrHigher;\n\n/**\n * A helper function to determine IE version. More information:\n * http://msdn.microsoft.com/en-us/library/ie/bg182625(v=vs.85).aspx#uaString\n * http://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx\n * http://blogs.msdn.com/b/ie/archive/2010/03/23/introducing-ie9-s-user-agent-string.aspx\n * http://blogs.msdn.com/b/ie/archive/2009/01/09/the-internet-explorer-8-user-agent-string-updated-edition.aspx\n * @param {string} userAgent the User-Agent.\n * @return {string}\n */\nfunction getIEVersion(userAgent) {\n // IE11 may identify itself as MSIE 9.0 or MSIE 10.0 due to an IE 11 upgrade\n // bug. Example UA:\n // Mozilla/5.0 (MSIE 9.0; Windows NT 6.1; WOW64; Trident/7.0; rv:11.0)\n // like Gecko.\n // See http://www.whatismybrowser.com/developers/unknown-user-agent-fragments.\n const rv = /rv: *([\\d\\.]*)/.exec(userAgent);\n if (rv && rv[1]) {\n return rv[1];\n }\n\n let version = '';\n const msie = /MSIE +([\\d\\.]+)/.exec(userAgent);\n if (msie && msie[1]) {\n // IE in compatibility mode usually identifies itself as MSIE 7.0; in this\n // case, use the Trident version to determine the version of IE. For more\n // details, see the links above.\n const tridentVersion = /Trident\\/(\\d.\\d)/.exec(userAgent);\n if (msie[1] == '7.0') {\n if (tridentVersion && tridentVersion[1]) {\n switch (tridentVersion[1]) {\n case '4.0':\n version = '8.0';\n break;\n case '5.0':\n version = '9.0';\n break;\n case '6.0':\n version = '10.0';\n break;\n case '7.0':\n version = '11.0';\n break;\n }\n } else {\n version = '7.0';\n }\n } else {\n version = msie[1];\n }\n }\n return version;\n}\n\n/**\n * A helper function to return the navigator.userAgent-supplied full version\n * number of the current browser or an empty string, based on whether the\n * current browser is the one specified.\n * @param {string} browser The brand whose version should be returned.\n * @return {string}\n */\nfunction getFullVersionFromUserAgentString(browser) {\n const userAgentString = util.getUserAgent();\n // Special case IE since IE's version is inside the parenthesis and\n // without the '/'.\n if (browser === Brand.IE) {\n return isIE() ? getIEVersion(userAgentString) : '';\n }\n\n const versionTuples = util.extractVersionTuples(userAgentString);\n const lookUpValueWithKeys = createVersionMap(versionTuples);\n switch (browser) {\n case Brand.OPERA:\n // Opera 10 has Version/10.0 but Opera/9.8, so look for \"Version\"\n // first. Opera uses 'OPR' for more recent UAs.\n if (isOpera()) {\n return lookUpValueWithKeys(['Version', 'Opera']);\n } else if (isOperaChromium()) {\n return lookUpValueWithKeys(['OPR']);\n }\n break;\n case Brand.EDGE:\n if (isEdge()) {\n return lookUpValueWithKeys(['Edge']);\n } else if (isEdgeChromium()) {\n return lookUpValueWithKeys(['Edg']);\n }\n break;\n case Brand.CHROMIUM:\n if (isChrome()) {\n return lookUpValueWithKeys(['Chrome', 'CriOS', 'HeadlessChrome']);\n }\n break;\n }\n\n // For the following browsers, the browser version is in the third tuple after\n // \"Mozilla\" and the engine.\n if ((browser === Brand.FIREFOX && isFirefox()) ||\n (browser === Brand.SAFARI && isSafari()) ||\n (browser === Brand.ANDROID_BROWSER && isAndroidBrowser()) ||\n (browser === Brand.SILK && isSilk())) {\n const tuple = versionTuples[2];\n return tuple && tuple[1] || '';\n }\n\n return '';\n}\n\n/**\n * Returns the major version of the given browser brand, or NaN if the current\n * browser is not the given brand.\n * Note that the major version number may be different depending on which\n * browser is specified. The returned value can be used to make browser version\n * comparisons using comparison operators.\n * @private\n * @param {!Brand} browser The brand whose version should be returned.\n * @return {number} The major version number associated with the current\n * browser under the given brand, or NaN if the current browser doesn't match\n * the given brand.\n */\nfunction versionOf_(browser) {\n let versionParts;\n // Silk currently does not identify itself in its userAgentData.brands array,\n // so if checking its version, always fall back to the user agent string.\n if (useUserAgentDataBrand() && browser !== Brand.SILK) {\n const data = util.getUserAgentData();\n const matchingBrand = data.brands.find(({brand}) => brand === browser);\n if (!matchingBrand || !matchingBrand.version) {\n return NaN;\n }\n versionParts = matchingBrand.version.split('.');\n } else {\n const fullVersion = getFullVersionFromUserAgentString(browser);\n if (fullVersion === '') {\n return NaN;\n }\n versionParts = fullVersion.split('.');\n }\n if (versionParts.length === 0) {\n return NaN;\n }\n const majorVersion = versionParts[0];\n return Number(majorVersion); // Returns NaN if it is not parseable.\n}\n\n/**\n * Returns true if the current browser matches the given brand and is at least\n * the given major version. The major version must be a whole number (i.e.\n * decimals should not be used to represent a minor version).\n * @param {!Brand} brand The brand whose version should be returned.\n * @param {number} majorVersion The major version number to compare against.\n * This must be a whole number.\n * @return {boolean} Whether the current browser both matches the given brand\n * and is at least the given version.\n */\nfunction isAtLeast(brand, majorVersion) {\n assert(\n Math.floor(majorVersion) === majorVersion,\n 'Major version must be an integer');\n return versionOf_(brand) >= majorVersion;\n}\nexports.isAtLeast = isAtLeast;\n\n/**\n * Returns true if the current browser matches the given brand and is at most\n * the given version. The major version must be a whole number (i.e. decimals\n * should not be used to represent a minor version).\n * @param {!Brand} brand The brand whose version should be returned.\n * @param {number} majorVersion The major version number to compare against.\n * This must be a whole number.\n * @return {boolean} Whether the current browser both matches the given brand\n * and is at most the given version.\n */\nfunction isAtMost(brand, majorVersion) {\n assert(\n Math.floor(majorVersion) === majorVersion,\n 'Major version must be an integer');\n return versionOf_(brand) <= majorVersion;\n}\nexports.isAtMost = isAtMost;\n\n/**\n * Loads the high-entropy browser brand/version data and wraps the correct\n * version string in a Version object.\n * @implements {AsyncValue<!Version>}\n */\nclass HighEntropyBrandVersion {\n /**\n * @param {string} brand The brand whose version is retrieved in this\n * container.\n * @param {boolean} useUach Whether to attempt to use the User-Agent Client\n * Hints (UACH) API surface.\n * @param {string} fallbackVersion The fallback version derived from the\n * userAgent string.\n */\n constructor(brand, useUach, fallbackVersion) {\n /** @private @const {string} */\n this.brand_ = brand;\n\n /** @private @const {!Version} */\n this.version_ = new Version(fallbackVersion);\n\n /** @private @const {boolean} */\n this.useUach_ = useUach;\n }\n\n /**\n * @return {!Version|undefined}\n * @override\n */\n getIfLoaded() {\n if (this.useUach_) {\n const loadedVersionList = fullVersionList.getIfLoaded();\n if (loadedVersionList !== undefined) {\n const matchingBrand =\n loadedVersionList.find(({brand}) => this.brand_ === brand);\n // We assumed in fullVersionOf that if the fullVersionList is defined\n // the brands must match. Double-check this here.\n assertExists(matchingBrand);\n return new Version(matchingBrand.version);\n }\n // Fallthrough to fallback on Pre-UACH implementation\n }\n // We want to make sure the loading semantics of the Pre-UACH implementation\n // match those of the UACH implementation. Loading must happen before any\n // data can be retrieved from getIfLoaded.\n // For HighEntropyBrandVersion, loading can either be done by calling #load\n // or by calling the module-local loadFullVersions function.\n if (preUachHasLoaded) {\n return this.version_;\n }\n return;\n }\n\n /**\n * @return {!Promise<!Version>}\n * @override\n */\n async load() {\n if (this.useUach_) {\n const loadedVersionList = await fullVersionList.load();\n if (loadedVersionList !== undefined) {\n const matchingBrand =\n loadedVersionList.find(({brand}) => this.brand_ === brand);\n assertExists(matchingBrand);\n return new Version(matchingBrand.version);\n }\n // Fallthrough to fallback on Pre-UACH implementation\n } else {\n // Await something so that calling load with or without UACH API\n // availability results in waiting at least one macrotask before allowing\n // access to the cached version information.\n await 0;\n }\n // Regardless of whether we are using UACH APIs, we can now allow access to\n // the fallback case\n preUachHasLoaded = true;\n return this.version_;\n }\n}\n\n/**\n * Whether full version data should be considered available when using UACH\n * fallback implementations. This is flipped to true when either\n * loadFullVersions or HighEntropyBrandVersion.prototype.load are called,\n * matching the global singleton semantics of the UACH codepaths.\n */\nlet preUachHasLoaded = false;\n\n/**\n * Requests all full browser versions to be cached. When the returned promise\n * resolves, subsequent calls to `fullVersionOf(...).getIfLoaded()` will return\n * a value.\n *\n * This method should be avoided in favor of directly awaiting\n * `fullVersionOf(...).load()` where it is used.\n *\n * @return {!Promise<void>}\n */\nasync function loadFullVersions() {\n if (useUserAgentDataBrand(true)) {\n await fullVersionList.load();\n }\n preUachHasLoaded = true;\n}\nexports.loadFullVersions = loadFullVersions;\n\n/**\n * Resets module-local caches used by functionality in this module.\n * This is only for use by goog.labs.userAgent.testUtil.resetUserAgent (and\n * labs.userAgent tests).\n * @package\n */\nexports.resetForTesting = () => {\n preUachHasLoaded = false;\n fullVersionList.resetForTesting();\n};\n\n\n/**\n * Returns an object that provides access to the full version string of the\n * current browser -- or undefined, based on whether the current browser matches\n * the requested browser brand. Note that the full version string is a\n * high-entropy value, and must be asynchronously loaded before it can be\n * accessed synchronously.\n * @param {!Brand} browser The brand whose version should be returned.\n * @return {!AsyncValue<!Version>|undefined} An object that can be used\n * to get or load the full version string as a high-entropy value, or\n * undefined if the current browser doesn't match the given brand.\n */\nfunction fullVersionOf(browser) {\n let fallbackVersionString = '';\n // If we are reasonably certain now that the browser we are on has the\n // fullVersionList high-entropy hint, then we can skip computing the fallback\n // value as we won't end up using it.\n if (!hasFullVersionList()) {\n fallbackVersionString = getFullVersionFromUserAgentString(browser);\n }\n // Silk has the UACH API surface, but currently does not identify itself in\n // the userAgentData.brands array. Fallback to using userAgent string version\n // for Silk.\n const useUach = browser !== Brand.SILK && useUserAgentDataBrand(true);\n if (useUach) {\n const data = util.getUserAgentData();\n // Operate under the assumption that the low-entropy and high-entropy lists\n // of brand/version pairs contain an identical set of brands. Therefore, if\n // the low-entropy list doesn't contain the given brand, return undefined.\n if (!data.brands.find(({brand}) => brand === browser)) {\n return undefined;\n }\n } else if (fallbackVersionString === '') {\n return undefined;\n }\n return new HighEntropyBrandVersion(browser, useUach, fallbackVersionString);\n}\nexports.fullVersionOf = fullVersionOf;\n\n\n/**\n * Returns a version string for the current browser or undefined, based on\n * whether the current browser is the one specified.\n * This value should ONLY be used for logging/debugging purposes. Do not use it\n * to branch code paths. For comparing versions, use isAtLeast()/isAtMost() or\n * fullVersionOf() instead.\n * @param {!Brand} browser The brand whose version should be returned.\n * @return {string} The version as a string.\n */\nfunction getVersionStringForLogging(browser) {\n if (useUserAgentDataBrand(true)) {\n const fullVersionObj = fullVersionOf(browser);\n if (fullVersionObj) {\n const fullVersion = fullVersionObj.getIfLoaded();\n if (fullVersion) {\n return fullVersion.toVersionStringForLogging();\n }\n // No full version, return the major version instead.\n const data = util.getUserAgentData();\n const matchingBrand = data.brands.find(({brand}) => brand === browser);\n // Checking for the existence of matchingBrand is not necessary because\n // the existence of fullVersionObj implies that there is already a\n // matching brand.\n assertExists(matchingBrand);\n return matchingBrand.version;\n }\n // If fullVersionObj is undefined, this doesn't mean that the full version\n // is unavailable, but rather that the current browser doesn't match the\n // input `browser` argument.\n return '';\n } else {\n return getFullVersionFromUserAgentString(browser);\n }\n}\nexports.getVersionStringForLogging = getVersionStringForLogging;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Closure user agent detection.\n * @see http://en.wikipedia.org/wiki/User_agent\n * For more information on browser brand, platform, or device see the other\n * sub-namespaces in goog.labs.userAgent (browser, platform, and device).\n */\n\ngoog.module('goog.labs.userAgent.engine');\ngoog.module.declareLegacyNamespace();\n\nconst googArray = goog.require('goog.array');\nconst googString = goog.require('goog.string.internal');\nconst util = goog.require('goog.labs.userAgent.util');\n\n/**\n * @return {boolean} Whether the rendering engine is Presto.\n */\nfunction isPresto() {\n return util.matchUserAgent('Presto');\n}\n\n/**\n * @return {boolean} Whether the rendering engine is Trident.\n */\nfunction isTrident() {\n // IE only started including the Trident token in IE8.\n return util.matchUserAgent('Trident') || util.matchUserAgent('MSIE');\n}\n\n/**\n * @return {boolean} Whether the rendering engine is EdgeHTML.\n */\nfunction isEdge() {\n return util.matchUserAgent('Edge');\n}\n\n/**\n * @return {boolean} Whether the rendering engine is WebKit. This will return\n * true for Chrome, Blink-based Opera (15+), Edge Chromium and Safari.\n */\nfunction isWebKit() {\n return util.matchUserAgentIgnoreCase('WebKit') && !isEdge();\n}\n\n/**\n * @return {boolean} Whether the rendering engine is Gecko.\n */\nfunction isGecko() {\n return util.matchUserAgent('Gecko') && !isWebKit() && !isTrident() &&\n !isEdge();\n}\n\n/**\n * @return {string} The rendering engine's version or empty string if version\n * can't be determined.\n */\nfunction getVersion() {\n const userAgentString = util.getUserAgent();\n if (userAgentString) {\n const tuples = util.extractVersionTuples(userAgentString);\n\n const engineTuple = getEngineTuple(tuples);\n if (engineTuple) {\n // In Gecko, the version string is either in the browser info or the\n // Firefox version. See Gecko user agent string reference:\n // http://goo.gl/mULqa\n if (engineTuple[0] == 'Gecko') {\n return getVersionForKey(tuples, 'Firefox');\n }\n\n return engineTuple[1];\n }\n\n // MSIE has only one version identifier, and the Trident version is\n // specified in the parenthetical. IE Edge is covered in the engine tuple\n // detection.\n const browserTuple = tuples[0];\n let info;\n if (browserTuple && (info = browserTuple[2])) {\n const match = /Trident\\/([^\\s;]+)/.exec(info);\n if (match) {\n return match[1];\n }\n }\n }\n return '';\n}\n\n/**\n * @param {!Array<!Array<string>>} tuples Extracted version tuples.\n * @return {!Array<string>|undefined} The engine tuple or undefined if not\n * found.\n */\nfunction getEngineTuple(tuples) {\n if (!isEdge()) {\n return tuples[1];\n }\n for (let i = 0; i < tuples.length; i++) {\n const tuple = tuples[i];\n if (tuple[0] == 'Edge') {\n return tuple;\n }\n }\n}\n\n/**\n * @param {string|number} version The version to check.\n * @return {boolean} Whether the rendering engine version is higher or the same\n * as the given version.\n */\nfunction isVersionOrHigher(version) {\n return googString.compareVersions(getVersion(), version) >= 0;\n}\n\n/**\n * @param {!Array<!Array<string>>} tuples Version tuples.\n * @param {string} key The key to look for.\n * @return {string} The version string of the given key, if present.\n * Otherwise, the empty string.\n */\nfunction getVersionForKey(tuples, key) {\n // TODO(nnaze): Move to util if useful elsewhere.\n\n const pair = googArray.find(tuples, function(pair) {\n return key == pair[0];\n });\n\n return pair && pair[1] || '';\n}\n\nexports = {\n getVersion,\n isEdge,\n isGecko,\n isPresto,\n isTrident,\n isVersionOrHigher,\n isWebKit,\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A patched, standardized event object for browser events.\n *\n * <pre>\n * The patched event object contains the following members:\n * - type {string} Event type, e.g. 'click'\n * - target {Object} The element that actually triggered the event\n * - currentTarget {Object} The element the listener is attached to\n * - relatedTarget {Object} For mouseover and mouseout, the previous object\n * - offsetX {number} X-coordinate relative to target\n * - offsetY {number} Y-coordinate relative to target\n * - clientX {number} X-coordinate relative to viewport\n * - clientY {number} Y-coordinate relative to viewport\n * - screenX {number} X-coordinate relative to the edge of the screen\n * - screenY {number} Y-coordinate relative to the edge of the screen\n * - button {number} Mouse button. Use isButton() to test.\n * - keyCode {number} Key-code\n * - ctrlKey {boolean} Was ctrl key depressed\n * - altKey {boolean} Was alt key depressed\n * - shiftKey {boolean} Was shift key depressed\n * - metaKey {boolean} Was meta key depressed\n * - pointerId {number} Pointer ID\n * - pointerType {string} Pointer type, e.g. 'mouse', 'pen', or 'touch'\n * - defaultPrevented {boolean} Whether the default action has been prevented\n * - state {Object} History state object\n *\n * NOTE: The keyCode member contains the raw browser keyCode. For normalized\n * key and character code use {@link goog.events.KeyHandler}.\n * </pre>\n */\n\ngoog.provide('goog.events.BrowserEvent');\ngoog.provide('goog.events.BrowserEvent.MouseButton');\ngoog.provide('goog.events.BrowserEvent.PointerType');\n\ngoog.require('goog.debug');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.EventType');\ngoog.require('goog.reflect');\ngoog.require('goog.userAgent');\n\n/**\n * Accepts a browser event object and creates a patched, cross browser event\n * object.\n * The content of this object will not be initialized if no event object is\n * provided. If this is the case, init() needs to be invoked separately.\n * @param {Event=} opt_e Browser event object.\n * @param {EventTarget=} opt_currentTarget Current target for event.\n * @constructor\n * @extends {goog.events.Event}\n */\ngoog.events.BrowserEvent = function(opt_e, opt_currentTarget) {\n 'use strict';\n goog.events.BrowserEvent.base(this, 'constructor', opt_e ? opt_e.type : '');\n\n /**\n * Target that fired the event.\n * @override\n * @type {?Node}\n */\n this.target = null;\n\n /**\n * Node that had the listener attached.\n * @override\n * @type {?Node|undefined}\n */\n this.currentTarget = null;\n\n /**\n * For mouseover and mouseout events, the related object for the event.\n * @type {?Node}\n */\n this.relatedTarget = null;\n\n /**\n * X-coordinate relative to target.\n * @type {number}\n */\n this.offsetX = 0;\n\n /**\n * Y-coordinate relative to target.\n * @type {number}\n */\n this.offsetY = 0;\n\n /**\n * X-coordinate relative to the window.\n * @type {number}\n */\n this.clientX = 0;\n\n /**\n * Y-coordinate relative to the window.\n * @type {number}\n */\n this.clientY = 0;\n\n /**\n * X-coordinate relative to the monitor.\n * @type {number}\n */\n this.screenX = 0;\n\n /**\n * Y-coordinate relative to the monitor.\n * @type {number}\n */\n this.screenY = 0;\n\n /**\n * Which mouse button was pressed.\n * @type {number}\n */\n this.button = 0;\n\n /**\n * Key of key press.\n * @type {string}\n */\n this.key = '';\n\n /**\n * Keycode of key press.\n * @type {number}\n */\n this.keyCode = 0;\n\n /**\n * Keycode of key press.\n * @type {number}\n */\n this.charCode = 0;\n\n /**\n * Whether control was pressed at time of event.\n * @type {boolean}\n */\n this.ctrlKey = false;\n\n /**\n * Whether alt was pressed at time of event.\n * @type {boolean}\n */\n this.altKey = false;\n\n /**\n * Whether shift was pressed at time of event.\n * @type {boolean}\n */\n this.shiftKey = false;\n\n /**\n * Whether the meta key was pressed at time of event.\n * @type {boolean}\n */\n this.metaKey = false;\n\n /**\n * History state object, only set for PopState events where it's a copy of the\n * state object provided to pushState or replaceState.\n * @type {?Object}\n */\n this.state = null;\n\n /**\n * Whether the default platform modifier key was pressed at time of event.\n * (This is control for all platforms except Mac, where it's Meta.)\n * @type {boolean}\n */\n this.platformModifierKey = false;\n\n /**\n * @type {number}\n */\n this.pointerId = 0;\n\n /**\n * @type {string}\n */\n this.pointerType = '';\n\n /**\n * The browser event object.\n * @private {?Event}\n */\n this.event_ = null;\n\n if (opt_e) {\n this.init(opt_e, opt_currentTarget);\n }\n};\ngoog.inherits(goog.events.BrowserEvent, goog.events.Event);\n\n/**\n * @define {boolean} If true, use the layerX and layerY properties of a native\n * browser event over the offsetX and offsetY properties, which cause expensive\n * reflow. If layerX or layerY is not defined, offsetX and offsetY will be used\n * as usual.\n */\ngoog.events.BrowserEvent.USE_LAYER_XY_AS_OFFSET_XY =\n goog.define('goog.events.BrowserEvent.USE_LAYER_XY_AS_OFFSET_XY', false);\n\n\n/**\n * Normalized button constants for the mouse.\n * @enum {number}\n */\ngoog.events.BrowserEvent.MouseButton = {\n LEFT: 0,\n MIDDLE: 1,\n RIGHT: 2,\n BACK: 3,\n FORWARD: 4,\n};\n\n\n/**\n * Normalized pointer type constants for pointer events.\n * @enum {string}\n */\ngoog.events.BrowserEvent.PointerType = {\n MOUSE: 'mouse',\n PEN: 'pen',\n TOUCH: 'touch'\n};\n\n\n/**\n * Static data for mapping mouse buttons.\n * @type {!Array<number>}\n * @deprecated Use `goog.events.BrowserEvent.IE_BUTTON_MAP` instead.\n */\ngoog.events.BrowserEvent.IEButtonMap = goog.debug.freeze([\n 1, // LEFT\n 4, // MIDDLE\n 2 // RIGHT\n]);\n\n\n/**\n * Static data for mapping mouse buttons.\n * @const {!Array<number>}\n */\ngoog.events.BrowserEvent.IE_BUTTON_MAP = goog.events.BrowserEvent.IEButtonMap;\n\n\n/**\n * Static data for mapping MSPointerEvent types to PointerEvent types.\n * @const {!Object<number, goog.events.BrowserEvent.PointerType>}\n */\ngoog.events.BrowserEvent.IE_POINTER_TYPE_MAP = goog.debug.freeze({\n 2: goog.events.BrowserEvent.PointerType.TOUCH,\n 3: goog.events.BrowserEvent.PointerType.PEN,\n 4: goog.events.BrowserEvent.PointerType.MOUSE\n});\n\n\n/**\n * Accepts a browser event object and creates a patched, cross browser event\n * object.\n * @param {Event} e Browser event object.\n * @param {EventTarget=} opt_currentTarget Current target for event.\n */\ngoog.events.BrowserEvent.prototype.init = function(e, opt_currentTarget) {\n 'use strict';\n var type = this.type = e.type;\n\n /**\n * On touch devices use the first \"changed touch\" as the relevant touch.\n * @type {?Touch}\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\n var relevantTouch =\n e.changedTouches && e.changedTouches.length ? e.changedTouches[0] : null;\n\n // TODO(nicksantos): Change this.target to type EventTarget.\n this.target = /** @type {Node} */ (e.target) || e.srcElement;\n\n // TODO(nicksantos): Change this.currentTarget to type EventTarget.\n this.currentTarget = /** @type {Node} */ (opt_currentTarget);\n\n var relatedTarget = /** @type {Node} */ (e.relatedTarget);\n if (relatedTarget) {\n // There's a bug in FireFox where sometimes, relatedTarget will be a\n // chrome element, and accessing any property of it will get a permission\n // denied exception. See:\n // https://bugzilla.mozilla.org/show_bug.cgi?id=497780\n if (goog.userAgent.GECKO) {\n if (!goog.reflect.canAccessProperty(relatedTarget, 'nodeName')) {\n relatedTarget = null;\n }\n }\n } else if (type == goog.events.EventType.MOUSEOVER) {\n relatedTarget = e.fromElement;\n } else if (type == goog.events.EventType.MOUSEOUT) {\n relatedTarget = e.toElement;\n }\n\n this.relatedTarget = relatedTarget;\n\n if (relevantTouch) {\n this.clientX = relevantTouch.clientX !== undefined ? relevantTouch.clientX :\n relevantTouch.pageX;\n this.clientY = relevantTouch.clientY !== undefined ? relevantTouch.clientY :\n relevantTouch.pageY;\n this.screenX = relevantTouch.screenX || 0;\n this.screenY = relevantTouch.screenY || 0;\n } else {\n if (goog.events.BrowserEvent.USE_LAYER_XY_AS_OFFSET_XY) {\n this.offsetX = (e.layerX !== undefined) ? e.layerX : e.offsetX;\n this.offsetY = (e.layerY !== undefined) ? e.layerY : e.offsetY;\n } else {\n // Webkit emits a lame warning whenever layerX/layerY is accessed.\n // http://code.google.com/p/chromium/issues/detail?id=101733\n this.offsetX = (goog.userAgent.WEBKIT || e.offsetX !== undefined) ?\n e.offsetX :\n e.layerX;\n this.offsetY = (goog.userAgent.WEBKIT || e.offsetY !== undefined) ?\n e.offsetY :\n e.layerY;\n }\n this.clientX = e.clientX !== undefined ? e.clientX : e.pageX;\n this.clientY = e.clientY !== undefined ? e.clientY : e.pageY;\n this.screenX = e.screenX || 0;\n this.screenY = e.screenY || 0;\n }\n\n this.button = e.button;\n\n this.keyCode = e.keyCode || 0;\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n this.key = e.key || '';\n this.charCode = e.charCode || (type == 'keypress' ? e.keyCode : 0);\n this.ctrlKey = e.ctrlKey;\n this.altKey = e.altKey;\n this.shiftKey = e.shiftKey;\n this.metaKey = e.metaKey;\n this.platformModifierKey = goog.userAgent.MAC ? e.metaKey : e.ctrlKey;\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n this.pointerId = e.pointerId || 0;\n this.pointerType = goog.events.BrowserEvent.getPointerType_(e);\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n this.state = e.state;\n this.event_ = e;\n if (e.defaultPrevented) {\n // Sync native event state to internal state via super class, where default\n // prevention is implemented and managed.\n goog.events.BrowserEvent.superClass_.preventDefault.call(this);\n }\n};\n\n\n/**\n * Tests to see which button was pressed during the event. This is really only\n * useful in IE and Gecko browsers. And in IE, it's only useful for\n * mousedown/mouseup events, because click only fires for the left mouse button.\n *\n * Safari 2 only reports the left button being clicked, and uses the value '1'\n * instead of 0. Opera only reports a mousedown event for the middle button, and\n * no mouse events for the right button. Opera has default behavior for left and\n * middle click that can only be overridden via a configuration setting.\n *\n * There's a nice table of this mess at http://www.unixpapa.com/js/mouse.html.\n *\n * @param {goog.events.BrowserEvent.MouseButton} button The button\n * to test for.\n * @return {boolean} True if button was pressed.\n */\ngoog.events.BrowserEvent.prototype.isButton = function(button) {\n 'use strict';\n return this.event_.button == button;\n};\n\n\n/**\n * Whether this has an \"action\"-producing mouse button.\n *\n * By definition, this includes left-click on windows/linux, and left-click\n * without the ctrl key on Macs.\n *\n * @return {boolean} The result.\n */\ngoog.events.BrowserEvent.prototype.isMouseActionButton = function() {\n 'use strict';\n // Ctrl+click should never behave like a left-click on mac, regardless of\n // whether or not the browser will actually ever emit such an event. If\n // we see it, treat it like right-click always.\n return this.isButton(goog.events.BrowserEvent.MouseButton.LEFT) &&\n !(goog.userAgent.MAC && this.ctrlKey);\n};\n\n\n/**\n * @override\n */\ngoog.events.BrowserEvent.prototype.stopPropagation = function() {\n 'use strict';\n goog.events.BrowserEvent.superClass_.stopPropagation.call(this);\n if (this.event_.stopPropagation) {\n this.event_.stopPropagation();\n } else {\n this.event_.cancelBubble = true;\n }\n};\n\n\n/**\n * @override\n */\ngoog.events.BrowserEvent.prototype.preventDefault = function() {\n 'use strict';\n goog.events.BrowserEvent.superClass_.preventDefault.call(this);\n var be = this.event_;\n if (!be.preventDefault) {\n be.returnValue = false;\n } else {\n be.preventDefault();\n }\n};\n\n\n/**\n * @return {Event} The underlying browser event object.\n */\ngoog.events.BrowserEvent.prototype.getBrowserEvent = function() {\n 'use strict';\n return this.event_;\n};\n\n\n/**\n * Extracts the pointer type from the given event.\n * @param {!Event} e\n * @return {string} The pointer type, e.g. 'mouse', 'pen', or 'touch'.\n * @private\n */\ngoog.events.BrowserEvent.getPointerType_ = function(e) {\n 'use strict';\n if (typeof (e.pointerType) === 'string') {\n return e.pointerType;\n }\n // IE10 uses integer codes for pointer type.\n // https://msdn.microsoft.com/en-us/library/hh772359(v=vs.85).aspx\n return goog.events.BrowserEvent.IE_POINTER_TYPE_MAP[e.pointerType] || '';\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.provide('goog.events.EventType');\n\ngoog.require('goog.events.eventTypeHelpers');\ngoog.require('goog.userAgent');\n\n\n/**\n * Constants for event names.\n * @enum {string}\n */\ngoog.events.EventType = {\n // Mouse events\n CLICK: 'click',\n RIGHTCLICK: 'rightclick',\n DBLCLICK: 'dblclick',\n AUXCLICK: 'auxclick',\n MOUSEDOWN: 'mousedown',\n MOUSEUP: 'mouseup',\n MOUSEOVER: 'mouseover',\n MOUSEOUT: 'mouseout',\n MOUSEMOVE: 'mousemove',\n MOUSEENTER: 'mouseenter',\n MOUSELEAVE: 'mouseleave',\n\n // Non-existent event; will never fire. This exists as a mouse counterpart to\n // POINTERCANCEL.\n MOUSECANCEL: 'mousecancel',\n\n // Selection events.\n // https://www.w3.org/TR/selection-api/\n SELECTIONCHANGE: 'selectionchange',\n SELECTSTART: 'selectstart', // IE, Safari, Chrome\n\n // Wheel events\n // http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents\n WHEEL: 'wheel',\n\n // Key events\n KEYPRESS: 'keypress',\n KEYDOWN: 'keydown',\n KEYUP: 'keyup',\n\n // Focus\n BLUR: 'blur',\n FOCUS: 'focus',\n DEACTIVATE: 'deactivate', // IE only\n FOCUSIN: 'focusin',\n FOCUSOUT: 'focusout',\n\n // Forms\n CHANGE: 'change',\n RESET: 'reset',\n SELECT: 'select',\n SUBMIT: 'submit',\n INPUT: 'input',\n PROPERTYCHANGE: 'propertychange', // IE only\n\n // Drag and drop\n DRAGSTART: 'dragstart',\n DRAG: 'drag',\n DRAGENTER: 'dragenter',\n DRAGOVER: 'dragover',\n DRAGLEAVE: 'dragleave',\n DROP: 'drop',\n DRAGEND: 'dragend',\n\n // Touch events\n // Note that other touch events exist, but we should follow the W3C list here.\n // http://www.w3.org/TR/touch-events/#list-of-touchevent-types\n TOUCHSTART: 'touchstart',\n TOUCHMOVE: 'touchmove',\n TOUCHEND: 'touchend',\n TOUCHCANCEL: 'touchcancel',\n\n // Misc\n BEFOREUNLOAD: 'beforeunload',\n CONSOLEMESSAGE: 'consolemessage',\n CONTEXTMENU: 'contextmenu',\n DEVICECHANGE: 'devicechange',\n DEVICEMOTION: 'devicemotion',\n DEVICEORIENTATION: 'deviceorientation',\n DOMCONTENTLOADED: 'DOMContentLoaded',\n ERROR: 'error',\n HELP: 'help',\n LOAD: 'load',\n LOSECAPTURE: 'losecapture',\n ORIENTATIONCHANGE: 'orientationchange',\n READYSTATECHANGE: 'readystatechange',\n RESIZE: 'resize',\n SCROLL: 'scroll',\n UNLOAD: 'unload',\n\n // Media events\n CANPLAY: 'canplay',\n CANPLAYTHROUGH: 'canplaythrough',\n DURATIONCHANGE: 'durationchange',\n EMPTIED: 'emptied',\n ENDED: 'ended',\n LOADEDDATA: 'loadeddata',\n LOADEDMETADATA: 'loadedmetadata',\n PAUSE: 'pause',\n PLAY: 'play',\n PLAYING: 'playing',\n PROGRESS: 'progress',\n RATECHANGE: 'ratechange',\n SEEKED: 'seeked',\n SEEKING: 'seeking',\n STALLED: 'stalled',\n SUSPEND: 'suspend',\n TIMEUPDATE: 'timeupdate',\n VOLUMECHANGE: 'volumechange',\n WAITING: 'waiting',\n\n // Media Source Extensions events\n // https://www.w3.org/TR/media-source/#mediasource-events\n SOURCEOPEN: 'sourceopen',\n SOURCEENDED: 'sourceended',\n SOURCECLOSED: 'sourceclosed',\n // https://www.w3.org/TR/media-source/#sourcebuffer-events\n ABORT: 'abort',\n UPDATE: 'update',\n UPDATESTART: 'updatestart',\n UPDATEEND: 'updateend',\n\n // HTML 5 History events\n // See http://www.w3.org/TR/html5/browsers.html#event-definitions-0\n HASHCHANGE: 'hashchange',\n PAGEHIDE: 'pagehide',\n PAGESHOW: 'pageshow',\n POPSTATE: 'popstate',\n\n // Copy and Paste\n // Support is limited. Make sure it works on your favorite browser\n // before using.\n // http://www.quirksmode.org/dom/events/cutcopypaste.html\n COPY: 'copy',\n PASTE: 'paste',\n CUT: 'cut',\n BEFORECOPY: 'beforecopy',\n BEFORECUT: 'beforecut',\n BEFOREPASTE: 'beforepaste',\n\n // HTML5 online/offline events.\n // http://www.w3.org/TR/offline-webapps/#related\n ONLINE: 'online',\n OFFLINE: 'offline',\n\n // HTML 5 worker events\n MESSAGE: 'message',\n CONNECT: 'connect',\n\n // Service Worker Events - ServiceWorkerGlobalScope context\n // See https://w3c.github.io/ServiceWorker/#execution-context-events\n // Note: message event defined in worker events section\n INSTALL: 'install',\n ACTIVATE: 'activate',\n FETCH: 'fetch',\n FOREIGNFETCH: 'foreignfetch',\n MESSAGEERROR: 'messageerror',\n\n // Service Worker Events - Document context\n // See https://w3c.github.io/ServiceWorker/#document-context-events\n STATECHANGE: 'statechange',\n UPDATEFOUND: 'updatefound',\n CONTROLLERCHANGE: 'controllerchange',\n\n // CSS animation events.\n ANIMATIONSTART:\n goog.events.eventTypeHelpers.getVendorPrefixedName('AnimationStart'),\n ANIMATIONEND:\n goog.events.eventTypeHelpers.getVendorPrefixedName('AnimationEnd'),\n ANIMATIONITERATION:\n goog.events.eventTypeHelpers.getVendorPrefixedName('AnimationIteration'),\n\n // CSS transition events. Based on the browser support described at:\n // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility\n TRANSITIONEND:\n goog.events.eventTypeHelpers.getVendorPrefixedName('TransitionEnd'),\n\n // W3C Pointer Events\n // http://www.w3.org/TR/pointerevents/\n POINTERDOWN: 'pointerdown',\n POINTERUP: 'pointerup',\n POINTERCANCEL: 'pointercancel',\n POINTERMOVE: 'pointermove',\n POINTEROVER: 'pointerover',\n POINTEROUT: 'pointerout',\n POINTERENTER: 'pointerenter',\n POINTERLEAVE: 'pointerleave',\n GOTPOINTERCAPTURE: 'gotpointercapture',\n LOSTPOINTERCAPTURE: 'lostpointercapture',\n\n // IE specific events.\n // See http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx\n // Note: these events will be supplanted in IE11.\n MSGESTURECHANGE: 'MSGestureChange',\n MSGESTUREEND: 'MSGestureEnd',\n MSGESTUREHOLD: 'MSGestureHold',\n MSGESTURESTART: 'MSGestureStart',\n MSGESTURETAP: 'MSGestureTap',\n MSGOTPOINTERCAPTURE: 'MSGotPointerCapture',\n MSINERTIASTART: 'MSInertiaStart',\n MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture',\n MSPOINTERCANCEL: 'MSPointerCancel',\n MSPOINTERDOWN: 'MSPointerDown',\n MSPOINTERENTER: 'MSPointerEnter',\n MSPOINTERHOVER: 'MSPointerHover',\n MSPOINTERLEAVE: 'MSPointerLeave',\n MSPOINTERMOVE: 'MSPointerMove',\n MSPOINTEROUT: 'MSPointerOut',\n MSPOINTEROVER: 'MSPointerOver',\n MSPOINTERUP: 'MSPointerUp',\n\n // Native IMEs/input tools events.\n TEXT: 'text',\n // The textInput event is supported in IE9+, but only in lower case. All other\n // browsers use the camel-case event name.\n TEXTINPUT: goog.userAgent.IE ? 'textinput' : 'textInput',\n COMPOSITIONSTART: 'compositionstart',\n COMPOSITIONUPDATE: 'compositionupdate',\n COMPOSITIONEND: 'compositionend',\n\n // The beforeinput event is initially only supported in Safari. See\n // https://bugs.chromium.org/p/chromium/issues/detail?id=342670 for Chrome\n // implementation tracking.\n BEFOREINPUT: 'beforeinput',\n\n // Fullscreen API events. See https://fullscreen.spec.whatwg.org/.\n FULLSCREENCHANGE: 'fullscreenchange',\n // iOS-only fullscreen events. See\n // https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/ControllingMediaWithJavaScript/ControllingMediaWithJavaScript.html\n WEBKITBEGINFULLSCREEN: 'webkitbeginfullscreen',\n WEBKITENDFULLSCREEN: 'webkitendfullscreen',\n\n // Webview tag events\n // See https://developer.chrome.com/apps/tags/webview\n EXIT: 'exit',\n LOADABORT: 'loadabort',\n LOADCOMMIT: 'loadcommit',\n LOADREDIRECT: 'loadredirect',\n LOADSTART: 'loadstart',\n LOADSTOP: 'loadstop',\n RESPONSIVE: 'responsive',\n SIZECHANGED: 'sizechanged',\n UNRESPONSIVE: 'unresponsive',\n\n // HTML5 Page Visibility API. See details at\n // `goog.labs.dom.PageVisibilityMonitor`.\n VISIBILITYCHANGE: 'visibilitychange',\n\n // LocalStorage event.\n STORAGE: 'storage',\n\n // DOM Level 2 mutation events (deprecated).\n DOMSUBTREEMODIFIED: 'DOMSubtreeModified',\n DOMNODEINSERTED: 'DOMNodeInserted',\n DOMNODEREMOVED: 'DOMNodeRemoved',\n DOMNODEREMOVEDFROMDOCUMENT: 'DOMNodeRemovedFromDocument',\n DOMNODEINSERTEDINTODOCUMENT: 'DOMNodeInsertedIntoDocument',\n DOMATTRMODIFIED: 'DOMAttrModified',\n DOMCHARACTERDATAMODIFIED: 'DOMCharacterDataModified',\n\n // Print events.\n BEFOREPRINT: 'beforeprint',\n AFTERPRINT: 'afterprint',\n\n // Web app manifest events.\n BEFOREINSTALLPROMPT: 'beforeinstallprompt',\n APPINSTALLED: 'appinstalled',\n\n // Web Animation API (WAAPI) playback events\n // https://www.w3.org/TR/web-animations-1/#animation-playback-event-types\n CANCEL: 'cancel',\n FINISH: 'finish',\n REMOVE: 'remove'\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview An interface for a listenable JavaScript object.\n */\n\ngoog.provide('goog.events.Listenable');\n\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventLike');\ngoog.requireType('goog.events.ListenableKey');\n\n\n/**\n * A listenable interface. A listenable is an object with the ability\n * to dispatch/broadcast events to \"event listeners\" registered via\n * listen/listenOnce.\n *\n * The interface allows for an event propagation mechanism similar\n * to one offered by native browser event targets, such as\n * capture/bubble mechanism, stopping propagation, and preventing\n * default actions. Capture/bubble mechanism depends on the ancestor\n * tree constructed via `#getParentEventTarget`; this tree\n * must be directed acyclic graph. The meaning of default action(s)\n * in preventDefault is specific to a particular use case.\n *\n * Implementations that do not support capture/bubble or can not have\n * a parent listenable can simply not implement any ability to set the\n * parent listenable (and have `#getParentEventTarget` return\n * null).\n *\n * Implementation of this class can be used with or independently from\n * goog.events.\n *\n * Implementation must call `#addImplementation(implClass)`.\n *\n * @interface\n * @see goog.events\n * @see http://www.w3.org/TR/DOM-Level-2-Events/events.html\n */\ngoog.events.Listenable = function() {};\n\n\n/**\n * An expando property to indicate that an object implements\n * goog.events.Listenable.\n *\n * See addImplementation/isImplementedBy.\n *\n * @type {string}\n * @const\n */\ngoog.events.Listenable.IMPLEMENTED_BY_PROP =\n 'closure_listenable_' + ((Math.random() * 1e6) | 0);\n\n\n/**\n * Marks a given class (constructor) as an implementation of\n * Listenable, so that we can query that fact at runtime. The class\n * must have already implemented the interface.\n * @param {function(new:goog.events.Listenable,...)} cls The class constructor.\n * The corresponding class must have already implemented the interface.\n */\ngoog.events.Listenable.addImplementation = function(cls) {\n 'use strict';\n cls.prototype[goog.events.Listenable.IMPLEMENTED_BY_PROP] = true;\n};\n\n\n/**\n * @param {?Object} obj The object to check.\n * @return {boolean} Whether a given instance implements Listenable. The\n * class/superclass of the instance must call addImplementation.\n */\ngoog.events.Listenable.isImplementedBy = function(obj) {\n 'use strict';\n return !!(obj && obj[goog.events.Listenable.IMPLEMENTED_BY_PROP]);\n};\n\n\n/**\n * Adds an event listener. A listener can only be added once to an\n * object and if it is added again the key for the listener is\n * returned. Note that if the existing listener is a one-off listener\n * (registered via listenOnce), it will no longer be a one-off\n * listener after a call to listen().\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.listen = function(\n type, listener, opt_useCapture, opt_listenerScope) {};\n\n\n/**\n * Adds an event listener that is removed automatically after the\n * listener fired once.\n *\n * If an existing listener already exists, listenOnce will do\n * nothing. In particular, if the listener was previously registered\n * via listen(), listenOnce() will not turn the listener into a\n * one-off listener. Similarly, if there is already an existing\n * one-off listener, listenOnce does not modify the listeners (it is\n * still a once listener).\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.listenOnce = function(\n type, listener, opt_useCapture, opt_listenerScope) {};\n\n\n/**\n * Removes an event listener which was added with listen() or listenOnce().\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call\n * the listener.\n * @return {boolean} Whether any listener was removed.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.unlisten = function(\n type, listener, opt_useCapture, opt_listenerScope) {};\n\n\n/**\n * Removes an event listener which was added with listen() by the key\n * returned by listen().\n *\n * @param {!goog.events.ListenableKey} key The key returned by\n * listen() or listenOnce().\n * @return {boolean} Whether any listener was removed.\n */\ngoog.events.Listenable.prototype.unlistenByKey = function(key) {};\n\n\n/**\n * Dispatches an event (or event like object) and calls all listeners\n * listening for events of this type. The type of the event is decided by the\n * type property on the event object.\n *\n * If any of the listeners returns false OR calls preventDefault then this\n * function will return false. If one of the capture listeners calls\n * stopPropagation, then the bubble listeners won't fire.\n *\n * @param {?goog.events.EventLike} e Event object.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the listeners returns false) this will also return false.\n */\ngoog.events.Listenable.prototype.dispatchEvent = function(e) {};\n\n\n/**\n * Removes all listeners from this listenable. If type is specified,\n * it will only remove listeners of the particular type. otherwise all\n * registered listeners will be removed.\n *\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove,\n * default is to remove all types.\n * @return {number} Number of listeners removed.\n */\ngoog.events.Listenable.prototype.removeAllListeners = function(opt_type) {};\n\n\n/**\n * Returns the parent of this event target to use for capture/bubble\n * mechanism.\n *\n * NOTE(chrishenry): The name reflects the original implementation of\n * custom event target (`goog.events.EventTarget`). We decided\n * that changing the name is not worth it.\n *\n * @return {?goog.events.Listenable} The parent EventTarget or null if\n * there is no parent.\n */\ngoog.events.Listenable.prototype.getParentEventTarget = function() {};\n\n\n/**\n * Fires all registered listeners in this listenable for the given\n * type and capture mode, passing them the given eventObject. This\n * does not perform actual capture/bubble. Only implementors of the\n * interface should be using this.\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The type of the\n * listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @param {EVENTOBJ} eventObject The event object to fire.\n * @return {boolean} Whether all listeners succeeded without\n * attempting to prevent default behavior. If any listener returns\n * false or called goog.events.Event#preventDefault, this returns\n * false.\n * @template EVENTOBJ\n */\ngoog.events.Listenable.prototype.fireListeners = function(\n type, capture, eventObject) {};\n\n\n/**\n * Gets all listeners in this listenable for the given type and\n * capture mode.\n *\n * @param {string|!goog.events.EventId} type The type of the listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @return {!Array<!goog.events.ListenableKey>} An array of registered\n * listeners.\n * @template EVENTOBJ\n */\ngoog.events.Listenable.prototype.getListeners = function(type, capture) {};\n\n\n/**\n * Gets the goog.events.ListenableKey for the event or null if no such\n * listener is in use.\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The name of the event\n * without the 'on' prefix.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener The\n * listener function to get.\n * @param {boolean} capture Whether the listener is a capturing listener.\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {?goog.events.ListenableKey} the found listener or null if not found.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.getListener = function(\n type, listener, capture, opt_listenerScope) {};\n\n\n/**\n * Whether there is any active listeners matching the specified\n * signature. If either the type or capture parameters are\n * unspecified, the function will match on the remaining criteria.\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>=} opt_type Event type.\n * @param {boolean=} opt_capture Whether to check for capture or bubble\n * listeners.\n * @return {boolean} Whether there is any active listeners matching\n * the requested type and/or capture phase.\n * @template EVENTOBJ\n */\ngoog.events.Listenable.prototype.hasListener = function(\n opt_type, opt_capture) {};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview An interface that describes a single registered listener.\n */\ngoog.provide('goog.events.ListenableKey');\n\ngoog.requireType('goog.events.Listenable');\n\n\n/**\n * An interface that describes a single registered listener.\n * @interface\n */\ngoog.events.ListenableKey = function() {};\n\n\n/**\n * Counter used to create a unique key\n * @type {number}\n * @private\n */\ngoog.events.ListenableKey.counter_ = 0;\n\n\n/**\n * Reserves a key to be used for ListenableKey#key field.\n * @return {number} A number to be used to fill ListenableKey#key\n * field.\n */\ngoog.events.ListenableKey.reserveKey = function() {\n 'use strict';\n return ++goog.events.ListenableKey.counter_;\n};\n\n\n/**\n * The source event target.\n * @type {?Object|?goog.events.Listenable}\n */\ngoog.events.ListenableKey.prototype.src;\n\n\n/**\n * The event type the listener is listening to.\n * @type {string}\n */\ngoog.events.ListenableKey.prototype.type;\n\n\n/**\n * The listener function.\n * @type {function(?):?|{handleEvent:function(?):?}|null}\n */\ngoog.events.ListenableKey.prototype.listener;\n\n\n/**\n * Whether the listener works on capture phase.\n * @type {boolean}\n */\ngoog.events.ListenableKey.prototype.capture;\n\n\n/**\n * The 'this' object for the listener function's scope.\n * @type {?Object|undefined}\n */\ngoog.events.ListenableKey.prototype.handler;\n\n\n/**\n * A globally unique number to identify the key.\n * @type {number}\n */\ngoog.events.ListenableKey.prototype.key;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Listener object.\n * @see ../demos/events.html\n */\n\ngoog.provide('goog.events.Listener');\n\ngoog.require('goog.events.ListenableKey');\ngoog.requireType('goog.events.Listenable');\n\n\n\n/**\n * Simple class that stores information about a listener\n * @param {function(?):?} listener Callback function.\n * @param {Function} proxy Wrapper for the listener that patches the event.\n * @param {EventTarget|goog.events.Listenable} src Source object for\n * the event.\n * @param {string} type Event type.\n * @param {boolean} capture Whether in capture or bubble phase.\n * @param {Object=} opt_handler Object in whose context to execute the callback.\n * @implements {goog.events.ListenableKey}\n * @constructor\n */\ngoog.events.Listener = function(\n listener, proxy, src, type, capture, opt_handler) {\n 'use strict';\n if (goog.events.Listener.ENABLE_MONITORING) {\n this.creationStack = new Error().stack;\n }\n\n /** @override */\n this.listener = listener;\n\n /**\n * A wrapper over the original listener. This is used solely to\n * handle native browser events (it is used to simulate the capture\n * phase and to patch the event object).\n * @type {Function}\n */\n this.proxy = proxy;\n\n /**\n * Object or node that callback is listening to\n * @type {EventTarget|goog.events.Listenable}\n */\n this.src = src;\n\n /**\n * The event type.\n * @const {string}\n */\n this.type = type;\n\n /**\n * Whether the listener is being called in the capture or bubble phase\n * @const {boolean}\n */\n this.capture = !!capture;\n\n /**\n * Optional object whose context to execute the listener in\n * @type {Object|undefined}\n */\n this.handler = opt_handler;\n\n /**\n * The key of the listener.\n * @const {number}\n * @override\n */\n this.key = goog.events.ListenableKey.reserveKey();\n\n /**\n * Whether to remove the listener after it has been called.\n * @type {boolean}\n */\n this.callOnce = false;\n\n /**\n * Whether the listener has been removed.\n * @type {boolean}\n */\n this.removed = false;\n};\n\n\n/**\n * @define {boolean} Whether to enable the monitoring of the\n * goog.events.Listener instances. Switching on the monitoring is only\n * recommended for debugging because it has a significant impact on\n * performance and memory usage. If switched off, the monitoring code\n * compiles down to 0 bytes.\n */\ngoog.events.Listener.ENABLE_MONITORING =\n goog.define('goog.events.Listener.ENABLE_MONITORING', false);\n\n\n/**\n * If monitoring the goog.events.Listener instances is enabled, stores the\n * creation stack trace of the Disposable instance.\n * @type {string}\n */\ngoog.events.Listener.prototype.creationStack;\n\n\n/**\n * Marks this listener as removed. This also remove references held by\n * this listener object (such as listener and event source).\n */\ngoog.events.Listener.prototype.markAsRemoved = function() {\n 'use strict';\n this.removed = true;\n this.listener = null;\n this.proxy = null;\n this.src = null;\n this.handler = null;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A map of listeners that provides utility functions to\n * deal with listeners on an event target. Used by\n * `goog.events.EventTarget`.\n *\n * WARNING: Do not use this class from outside goog.events package.\n *\n */\n\ngoog.provide('goog.events.ListenerMap');\n\ngoog.require('goog.array');\ngoog.require('goog.events.Listener');\ngoog.require('goog.object');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.Listenable');\ngoog.requireType('goog.events.ListenableKey');\n\n\n\n/**\n * Creates a new listener map.\n * @param {EventTarget|goog.events.Listenable} src The src object.\n * @constructor\n * @final\n */\ngoog.events.ListenerMap = function(src) {\n 'use strict';\n /** @type {EventTarget|goog.events.Listenable} */\n this.src = src;\n\n /**\n * Maps of event type to an array of listeners.\n * @type {!Object<string, !Array<!goog.events.Listener>>}\n */\n this.listeners = {};\n\n /**\n * The count of types in this map that have registered listeners.\n * @private {number}\n */\n this.typeCount_ = 0;\n};\n\n\n/**\n * @return {number} The count of event types in this map that actually\n * have registered listeners.\n */\ngoog.events.ListenerMap.prototype.getTypeCount = function() {\n 'use strict';\n return this.typeCount_;\n};\n\n\n/**\n * @return {number} Total number of registered listeners.\n */\ngoog.events.ListenerMap.prototype.getListenerCount = function() {\n 'use strict';\n var count = 0;\n for (var type in this.listeners) {\n count += this.listeners[type].length;\n }\n return count;\n};\n\n\n/**\n * Adds an event listener. A listener can only be added once to an\n * object and if it is added again the key for the listener is\n * returned.\n *\n * Note that a one-off listener will not change an existing listener,\n * if any. On the other hand a normal listener will change existing\n * one-off listener to become a normal listener.\n *\n * @param {string|!goog.events.EventId} type The listener event type.\n * @param {!Function} listener This listener callback method.\n * @param {boolean} callOnce Whether the listener is a one-off\n * listener.\n * @param {boolean=} opt_useCapture The capture mode of the listener.\n * @param {Object=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n */\ngoog.events.ListenerMap.prototype.add = function(\n type, listener, callOnce, opt_useCapture, opt_listenerScope) {\n 'use strict';\n var typeStr = type.toString();\n var listenerArray = this.listeners[typeStr];\n if (!listenerArray) {\n listenerArray = this.listeners[typeStr] = [];\n this.typeCount_++;\n }\n\n var listenerObj;\n var index = goog.events.ListenerMap.findListenerIndex_(\n listenerArray, listener, opt_useCapture, opt_listenerScope);\n if (index > -1) {\n listenerObj = listenerArray[index];\n if (!callOnce) {\n // Ensure that, if there is an existing callOnce listener, it is no\n // longer a callOnce listener.\n listenerObj.callOnce = false;\n }\n } else {\n listenerObj = new goog.events.Listener(\n listener, null, this.src, typeStr, !!opt_useCapture, opt_listenerScope);\n listenerObj.callOnce = callOnce;\n listenerArray.push(listenerObj);\n }\n return listenerObj;\n};\n\n\n/**\n * Removes a matching listener.\n * @param {string|!goog.events.EventId} type The listener event type.\n * @param {!Function} listener This listener callback method.\n * @param {boolean=} opt_useCapture The capture mode of the listener.\n * @param {Object=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {boolean} Whether any listener was removed.\n */\ngoog.events.ListenerMap.prototype.remove = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n var typeStr = type.toString();\n if (!(typeStr in this.listeners)) {\n return false;\n }\n\n var listenerArray = this.listeners[typeStr];\n var index = goog.events.ListenerMap.findListenerIndex_(\n listenerArray, listener, opt_useCapture, opt_listenerScope);\n if (index > -1) {\n var listenerObj = listenerArray[index];\n listenerObj.markAsRemoved();\n goog.array.removeAt(listenerArray, index);\n if (listenerArray.length == 0) {\n delete this.listeners[typeStr];\n this.typeCount_--;\n }\n return true;\n }\n return false;\n};\n\n\n/**\n * Removes the given listener object.\n * @param {!goog.events.ListenableKey} listener The listener to remove.\n * @return {boolean} Whether the listener is removed.\n */\ngoog.events.ListenerMap.prototype.removeByKey = function(listener) {\n 'use strict';\n var type = listener.type;\n if (!(type in this.listeners)) {\n return false;\n }\n\n var removed = goog.array.remove(this.listeners[type], listener);\n if (removed) {\n /** @type {!goog.events.Listener} */ (listener).markAsRemoved();\n if (this.listeners[type].length == 0) {\n delete this.listeners[type];\n this.typeCount_--;\n }\n }\n return removed;\n};\n\n\n/**\n * Removes all listeners from this map. If opt_type is provided, only\n * listeners that match the given type are removed.\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove.\n * @return {number} Number of listeners removed.\n */\ngoog.events.ListenerMap.prototype.removeAll = function(opt_type) {\n 'use strict';\n var typeStr = opt_type && opt_type.toString();\n var count = 0;\n for (var type in this.listeners) {\n if (!typeStr || type == typeStr) {\n var listenerArray = this.listeners[type];\n for (var i = 0; i < listenerArray.length; i++) {\n ++count;\n listenerArray[i].markAsRemoved();\n }\n delete this.listeners[type];\n this.typeCount_--;\n }\n }\n return count;\n};\n\n\n/**\n * Gets all listeners that match the given type and capture mode. The\n * returned array is a copy (but the listener objects are not).\n * @param {string|!goog.events.EventId} type The type of the listeners\n * to retrieve.\n * @param {boolean} capture The capture mode of the listeners to retrieve.\n * @return {!Array<!goog.events.ListenableKey>} An array of matching\n * listeners.\n */\ngoog.events.ListenerMap.prototype.getListeners = function(type, capture) {\n 'use strict';\n var listenerArray = this.listeners[type.toString()];\n var rv = [];\n if (listenerArray) {\n for (var i = 0; i < listenerArray.length; ++i) {\n var listenerObj = listenerArray[i];\n if (listenerObj.capture == capture) {\n rv.push(listenerObj);\n }\n }\n }\n return rv;\n};\n\n\n/**\n * Gets the goog.events.ListenableKey for the event or null if no such\n * listener is in use.\n *\n * @param {string|!goog.events.EventId} type The type of the listener\n * to retrieve.\n * @param {!Function} listener The listener function to get.\n * @param {boolean} capture Whether the listener is a capturing listener.\n * @param {Object=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {goog.events.ListenableKey} the found listener or null if not found.\n */\ngoog.events.ListenerMap.prototype.getListener = function(\n type, listener, capture, opt_listenerScope) {\n 'use strict';\n var listenerArray = this.listeners[type.toString()];\n var i = -1;\n if (listenerArray) {\n i = goog.events.ListenerMap.findListenerIndex_(\n listenerArray, listener, capture, opt_listenerScope);\n }\n return i > -1 ? listenerArray[i] : null;\n};\n\n\n/**\n * Whether there is a matching listener. If either the type or capture\n * parameters are unspecified, the function will match on the\n * remaining criteria.\n *\n * @param {string|!goog.events.EventId=} opt_type The type of the listener.\n * @param {boolean=} opt_capture The capture mode of the listener.\n * @return {boolean} Whether there is an active listener matching\n * the requested type and/or capture phase.\n */\ngoog.events.ListenerMap.prototype.hasListener = function(\n opt_type, opt_capture) {\n 'use strict';\n var hasType = (opt_type !== undefined);\n var typeStr = hasType ? opt_type.toString() : '';\n var hasCapture = (opt_capture !== undefined);\n\n return goog.object.some(this.listeners, function(listenerArray, type) {\n 'use strict';\n for (var i = 0; i < listenerArray.length; ++i) {\n if ((!hasType || listenerArray[i].type == typeStr) &&\n (!hasCapture || listenerArray[i].capture == opt_capture)) {\n return true;\n }\n }\n\n return false;\n });\n};\n\n\n/**\n * Finds the index of a matching goog.events.Listener in the given\n * listenerArray.\n * @param {!Array<!goog.events.Listener>} listenerArray Array of listener.\n * @param {!Function} listener The listener function.\n * @param {boolean=} opt_useCapture The capture flag for the listener.\n * @param {Object=} opt_listenerScope The listener scope.\n * @return {number} The index of the matching listener within the\n * listenerArray.\n * @private\n */\ngoog.events.ListenerMap.findListenerIndex_ = function(\n listenerArray, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n for (var i = 0; i < listenerArray.length; ++i) {\n var listenerObj = listenerArray[i];\n if (!listenerObj.removed && listenerObj.listener == listener &&\n listenerObj.capture == !!opt_useCapture &&\n listenerObj.handler == opt_listenerScope) {\n return i;\n }\n }\n return -1;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for manipulating objects/maps/hashes.\n */\ngoog.module('goog.object');\ngoog.module.declareLegacyNamespace();\n\n/**\n * Calls a function for each element in an object/map/hash.\n * @param {?Object<K,V>} obj The object over which to iterate.\n * @param {function(this:T,V,?,?Object<K,V>):?} f The function to call for every\n * element. This function takes 3 arguments (the value, the key and the\n * object) and the return value is ignored.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {void}\n * @template T,K,V\n */\nfunction forEach(obj, f, opt_obj) {\n for (const key in obj) {\n f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);\n }\n}\n\n/**\n * Calls a function for each element in an object/map/hash. If that call returns\n * true, adds the element to a new object.\n * @param {?Object<K,V>} obj The object over which to iterate.\n * @param {function(this:T,V,?,?Object<K,V>):boolean} f The function to call for\n * every element. This function takes 3 arguments (the value, the key and\n * the object) and should return a boolean. If the return value is true the\n * element is added to the result object. If it is false the element is not\n * included.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {!Object<K,V>} a new object in which only elements that passed the\n * test are present.\n * @template T,K,V\n */\nfunction filter(obj, f, opt_obj) {\n const res = {};\n for (const key in obj) {\n if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n res[key] = obj[key];\n }\n }\n return res;\n}\n\n/**\n * For every element in an object/map/hash calls a function and inserts the\n * result into a new object.\n * @param {?Object<K,V>} obj The object over which to iterate.\n * @param {function(this:T,V,?,?Object<K,V>):R} f The function to call for every\n * element. This function takes 3 arguments (the value, the key and the\n * object) and should return something. The result will be inserted into a\n * new object.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {!Object<K,R>} a new object with the results from f.\n * @template T,K,V,R\n */\nfunction map(obj, f, opt_obj) {\n const res = {};\n for (const key in obj) {\n res[key] = f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);\n }\n return res;\n}\n\n/**\n * Calls a function for each element in an object/map/hash. If any\n * call returns true, returns true (without checking the rest). If\n * all calls return false, returns false.\n * @param {?Object<K,V>} obj The object to check.\n * @param {function(this:T,V,?,?Object<K,V>):boolean} f The function to call for\n * every element. This function takes 3 arguments (the value, the key and\n * the object) and should return a boolean.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {boolean} true if any element passes the test.\n * @template T,K,V\n */\nfunction some(obj, f, opt_obj) {\n for (const key in obj) {\n if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Calls a function for each element in an object/map/hash. If\n * all calls return true, returns true. If any call returns false, returns\n * false at this point and does not continue to check the remaining elements.\n * @param {?Object<K,V>} obj The object to check.\n * @param {?function(this:T,V,?,?Object<K,V>):boolean} f The function to call\n * for every element. This function takes 3 arguments (the value, the key\n * and the object) and should return a boolean.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {boolean} false if any element fails the test.\n * @template T,K,V\n */\nfunction every(obj, f, opt_obj) {\n for (const key in obj) {\n if (!f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Returns the number of key-value pairs in the object map.\n * @param {?Object} obj The object for which to get the number of key-value\n * pairs.\n * @return {number} The number of key-value pairs in the object map.\n */\nfunction getCount(obj) {\n let rv = 0;\n for (const key in obj) {\n rv++;\n }\n return rv;\n}\n\n/**\n * Returns one key from the object map, if any exists.\n * For map literals the returned key will be the first one in most of the\n * browsers (a know exception is Konqueror).\n * @param {?Object} obj The object to pick a key from.\n * @return {string|undefined} The key or undefined if the object is empty.\n */\nfunction getAnyKey(obj) {\n for (const key in obj) {\n return key;\n }\n}\n\n/**\n * Returns one value from the object map, if any exists.\n * For map literals the returned value will be the first one in most of the\n * browsers (a know exception is Konqueror).\n * @param {?Object<K,V>} obj The object to pick a value from.\n * @return {V|undefined} The value or undefined if the object is empty.\n * @template K,V\n */\nfunction getAnyValue(obj) {\n for (const key in obj) {\n return obj[key];\n }\n}\n\n/**\n * Whether the object/hash/map contains the given object as a value.\n * An alias for containsValue(obj, val).\n * @param {?Object<K,V>} obj The object in which to look for val.\n * @param {V} val The object for which to check.\n * @return {boolean} true if val is present.\n * @template K,V\n */\nfunction contains(obj, val) {\n return containsValue(obj, val);\n}\n\n/**\n * Returns the values of the object/map/hash.\n * @param {?Object<K,V>} obj The object from which to get the values.\n * @return {!Array<V>} The values in the object/map/hash.\n * @template K,V\n */\nfunction getValues(obj) {\n const res = [];\n let i = 0;\n for (const key in obj) {\n res[i++] = obj[key];\n }\n return res;\n}\n\n/**\n * Returns the keys of the object/map/hash.\n * @param {?Object} obj The object from which to get the keys.\n * @return {!Array<string>} Array of property keys.\n */\nfunction getKeys(obj) {\n const res = [];\n let i = 0;\n for (const key in obj) {\n res[i++] = key;\n }\n return res;\n}\n\n/**\n * Get a value from an object multiple levels deep. This is useful for\n * pulling values from deeply nested objects, such as JSON responses.\n * Example usage: getValueByKeys(jsonObj, 'foo', 'entries', 3)\n * @param {?Object} obj An object to get the value from. Can be array-like.\n * @param {...(string|number|!IArrayLike<number|string>)} var_args A number of\n * keys (as strings, or numbers, for array-like objects). Can also be\n * specified as a single array of keys.\n * @return {*} The resulting value. If, at any point, the value for a key in the\n * current object is null or undefined, returns undefined.\n */\nfunction getValueByKeys(obj, var_args) {\n const isArrayLike = goog.isArrayLike(var_args);\n const keys = isArrayLike ?\n /** @type {!IArrayLike<number|string>} */ (var_args) :\n arguments;\n\n // Start with the 2nd parameter for the variable parameters syntax.\n for (let i = isArrayLike ? 0 : 1; i < keys.length; i++) {\n if (obj == null) return undefined;\n obj = obj[keys[i]];\n }\n\n return obj;\n}\n\n/**\n * Whether the object/map/hash contains the given key.\n * @param {?Object} obj The object in which to look for key.\n * @param {?} key The key for which to check.\n * @return {boolean} true If the map contains the key.\n */\nfunction containsKey(obj, key) {\n return obj !== null && key in obj;\n}\n\n/**\n * Whether the object/map/hash contains the given value. This is O(n).\n * @param {?Object<K,V>} obj The object in which to look for val.\n * @param {V} val The value for which to check.\n * @return {boolean} true If the map contains the value.\n * @template K,V\n */\nfunction containsValue(obj, val) {\n for (const key in obj) {\n if (obj[key] == val) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Searches an object for an element that satisfies the given condition and\n * returns its key.\n * @param {?Object<K,V>} obj The object to search in.\n * @param {function(this:T,V,string,?Object<K,V>):boolean} f The function to\n * call for every element. Takes 3 arguments (the value, the key and the\n * object) and should return a boolean.\n * @param {T=} thisObj An optional \"this\" context for the function.\n * @return {string|undefined} The key of an element for which the function\n * returns true or undefined if no such element is found.\n * @template T,K,V\n */\nfunction findKey(obj, f, thisObj = undefined) {\n for (const key in obj) {\n if (f.call(/** @type {?} */ (thisObj), obj[key], key, obj)) {\n return key;\n }\n }\n return undefined;\n}\n\n/**\n * Searches an object for an element that satisfies the given condition and\n * returns its value.\n * @param {?Object<K,V>} obj The object to search in.\n * @param {function(this:T,V,string,?Object<K,V>):boolean} f The function to\n * call for every element. Takes 3 arguments (the value, the key and the\n * object) and should return a boolean.\n * @param {T=} thisObj An optional \"this\" context for the function.\n * @return {V} The value of an element for which the function returns true or\n * undefined if no such element is found.\n * @template T,K,V\n */\nfunction findValue(obj, f, thisObj = undefined) {\n const key = findKey(obj, f, thisObj);\n return key && obj[key];\n}\n\n/**\n * Whether the object/map/hash is empty.\n * @param {?Object} obj The object to test.\n * @return {boolean} true if obj is empty.\n */\nfunction isEmpty(obj) {\n for (const key in obj) {\n return false;\n }\n return true;\n}\n\n/**\n * Removes all key value pairs from the object/map/hash.\n * @param {?Object} obj The object to clear.\n * @return {void}\n */\nfunction clear(obj) {\n for (const i in obj) {\n delete obj[i];\n }\n}\n\n/**\n * Removes a key-value pair based on the key.\n * @param {?Object} obj The object from which to remove the key.\n * @param {?} key The key to remove.\n * @return {boolean} Whether an element was removed.\n */\nfunction remove(obj, key) {\n let rv;\n if (rv = key in /** @type {!Object} */ (obj)) {\n delete obj[key];\n }\n return rv;\n}\n\n/**\n * Adds a key-value pair to the object. Throws an exception if the key is\n * already in use. Use set if you want to change an existing pair.\n * @param {?Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {V} val The value to add.\n * @return {void}\n * @template K,V\n */\nfunction add(obj, key, val) {\n if (obj !== null && key in obj) {\n throw new Error(`The object already contains the key \"${key}\"`);\n }\n set(obj, key, val);\n}\n\n/**\n * Returns the value for the given key.\n * @param {?Object<K,V>} obj The object from which to get the value.\n * @param {string} key The key for which to get the value.\n * @param {R=} val The value to return if no item is found for the given key\n * (default is undefined).\n * @return {V|R|undefined} The value for the given key.\n * @template K,V,R\n */\nfunction get(obj, key, val = undefined) {\n if (obj !== null && key in obj) {\n return obj[key];\n }\n return val;\n}\n\n/**\n * Adds a key-value pair to the object/map/hash.\n * @param {?Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {V} value The value to add.\n * @template K,V\n * @return {void}\n */\nfunction set(obj, key, value) {\n obj[key] = value;\n}\n\n/**\n * Adds a key-value pair to the object/map/hash if it doesn't exist yet.\n * @param {?Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {V} value The value to add if the key wasn't present.\n * @return {V} The value of the entry at the end of the function.\n * @template K,V\n */\nfunction setIfUndefined(obj, key, value) {\n return key in /** @type {!Object} */ (obj) ? obj[key] : (obj[key] = value);\n}\n\n/**\n * Sets a key and value to an object if the key is not set. The value will be\n * the return value of the given function. If the key already exists, the\n * object will not be changed and the function will not be called (the function\n * will be lazily evaluated -- only called if necessary).\n * This function is particularly useful when used with an `Object` which is\n * acting as a cache.\n * @param {?Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {function():V} f The value to add if the key wasn't present.\n * @return {V} The value of the entry at the end of the function.\n * @template K,V\n */\nfunction setWithReturnValueIfNotSet(obj, key, f) {\n if (key in obj) {\n return obj[key];\n }\n\n const val = f();\n obj[key] = val;\n return val;\n}\n\n/**\n * Compares two objects for equality using === on the values.\n * @param {!Object<K,V>} a\n * @param {!Object<K,V>} b\n * @return {boolean}\n * @template K,V\n */\nfunction equals(a, b) {\n for (const k in a) {\n if (!(k in b) || a[k] !== b[k]) {\n return false;\n }\n }\n for (const k in b) {\n if (!(k in a)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Returns a shallow clone of the object.\n * @param {?Object<K,V>} obj Object to clone.\n * @return {!Object<K,V>} Clone of the input object.\n * @template K,V\n */\nfunction clone(obj) {\n const res = {};\n for (const key in obj) {\n res[key] = obj[key];\n }\n return res;\n}\n\n/**\n * Clones a value. The input may be an Object, Array, or basic type. Objects and\n * arrays will be cloned recursively.\n * WARNINGS:\n * <code>unsafeClone</code> does not detect reference loops. Objects\n * that refer to themselves will cause infinite recursion.\n * <code>unsafeClone</code> is unaware of unique identifiers, and\n * copies UIDs created by <code>getUid</code> into cloned results.\n * @param {T} obj The value to clone.\n * @return {T} A clone of the input value.\n * @template T\n */\nfunction unsafeClone(obj) {\n if (!obj || typeof obj !== 'object') return obj;\n if (typeof obj.clone === 'function') return obj.clone();\n if (typeof Map !== 'undefined' && obj instanceof Map) {\n return new Map(obj);\n } else if (typeof Set !== 'undefined' && obj instanceof Set) {\n return new Set(obj);\n } else if (obj instanceof Date) {\n return new Date(obj.getTime());\n }\n const clone = Array.isArray(obj) ? [] :\n typeof ArrayBuffer === 'function' &&\n typeof ArrayBuffer.isView === 'function' && ArrayBuffer.isView(obj) &&\n !(obj instanceof DataView) ?\n new obj.constructor(obj.length) :\n {};\n for (const key in obj) {\n clone[key] = unsafeClone(obj[key]);\n }\n return clone;\n}\n\n/**\n * Returns a new object in which all the keys and values are interchanged\n * (keys become values and values become keys). If multiple keys map to the\n * same value, the chosen transposed value is implementation-dependent.\n * @param {?Object} obj The object to transpose.\n * @return {!Object} The transposed object.\n */\nfunction transpose(obj) {\n const transposed = {};\n for (const key in obj) {\n transposed[obj[key]] = key;\n }\n return transposed;\n}\n\n/**\n * The names of the fields that are defined on Object.prototype.\n * @type {!Array<string>}\n */\nconst PROTOTYPE_FIELDS = [\n 'constructor',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'toLocaleString',\n 'toString',\n 'valueOf',\n];\n\n/**\n * Extends an object with another object.\n * This operates 'in-place'; it does not create a new Object.\n * Example:\n * var o = {};\n * extend(o, {a: 0, b: 1});\n * o; // {a: 0, b: 1}\n * extend(o, {b: 2, c: 3});\n * o; // {a: 0, b: 2, c: 3}\n * @param {?Object} target The object to modify. Existing properties will be\n * overwritten if they are also present in one of the objects in `var_args`.\n * @param {...(?Object|undefined)} var_args The objects from which values\n * will be copied.\n * @return {void}\n * @deprecated Prefer Object.assign\n */\nfunction extend(target, var_args) {\n let key;\n let source;\n for (let i = 1; i < arguments.length; i++) {\n source = arguments[i];\n for (key in source) {\n target[key] = source[key];\n }\n\n // For IE the for-in-loop does not contain any properties that are not\n // enumerable on the prototype object (for example isPrototypeOf from\n // Object.prototype) and it will also not include 'replace' on objects that\n // extend String and change 'replace' (not that it is common for anyone to\n // extend anything except Object).\n\n for (let j = 0; j < PROTOTYPE_FIELDS.length; j++) {\n key = PROTOTYPE_FIELDS[j];\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n}\n\n/**\n * Creates a new object built from the key-value pairs provided as arguments.\n * @param {...*} var_args If only one argument is provided and it is an array\n * then this is used as the arguments, otherwise even arguments are used as\n * the property names and odd arguments are used as the property values.\n * @return {!Object} The new object.\n * @throws {!Error} If there are uneven number of arguments or there is only one\n * non array argument.\n */\nfunction create(var_args) {\n const argLength = arguments.length;\n if (argLength == 1 && Array.isArray(arguments[0])) {\n return create.apply(null, arguments[0]);\n }\n\n if (argLength % 2) {\n throw new Error('Uneven number of arguments');\n }\n\n const rv = {};\n for (let i = 0; i < argLength; i += 2) {\n rv[arguments[i]] = arguments[i + 1];\n }\n return rv;\n}\n\n/**\n * Creates a new object where the property names come from the arguments but\n * the value is always set to true\n * @param {...*} var_args If only one argument is provided and it is an array\n * then this is used as the arguments, otherwise the arguments are used as\n * the property names.\n * @return {!Object} The new object.\n */\nfunction createSet(var_args) {\n const argLength = arguments.length;\n if (argLength == 1 && Array.isArray(arguments[0])) {\n return createSet.apply(null, arguments[0]);\n }\n\n const rv = {};\n for (let i = 0; i < argLength; i++) {\n rv[arguments[i]] = true;\n }\n return rv;\n}\n\n/**\n * Creates an immutable view of the underlying object, if the browser\n * supports immutable objects.\n * In default mode, writes to this view will fail silently. In strict mode,\n * they will throw an error.\n * @param {!Object<K,V>} obj An object.\n * @return {!Object<K,V>} An immutable view of that object, or the original\n * object if this browser does not support immutables.\n * @template K,V\n */\nfunction createImmutableView(obj) {\n let result = obj;\n if (Object.isFrozen && !Object.isFrozen(obj)) {\n result = Object.create(obj);\n Object.freeze(result);\n }\n return result;\n}\n\n/**\n * @param {!Object} obj An object.\n * @return {boolean} Whether this is an immutable view of the object.\n */\nfunction isImmutableView(obj) {\n return !!Object.isFrozen && Object.isFrozen(obj);\n}\n\n/**\n * Get all properties names on a given Object regardless of enumerability.\n * <p> If the browser does not support `Object.getOwnPropertyNames` nor\n * `Object.getPrototypeOf` then this is equivalent to using\n * `getKeys`\n * @param {?Object} obj The object to get the properties of.\n * @param {boolean=} includeObjectPrototype Whether properties defined on\n * `Object.prototype` should be included in the result.\n * @param {boolean=} includeFunctionPrototype Whether properties defined on\n * `Function.prototype` should be included in the result.\n * @return {!Array<string>}\n * @public\n */\nfunction getAllPropertyNames(\n obj, includeObjectPrototype = undefined,\n includeFunctionPrototype = undefined) {\n if (!obj) {\n return [];\n }\n\n // Naively use a for..in loop to get the property names if the browser doesn't\n // support any other APIs for getting it.\n if (!Object.getOwnPropertyNames || !Object.getPrototypeOf) {\n return getKeys(obj);\n }\n\n const visitedSet = {};\n\n // Traverse the prototype chain and add all properties to the visited set.\n let proto = obj;\n while (proto && (proto !== Object.prototype || !!includeObjectPrototype) &&\n (proto !== Function.prototype || !!includeFunctionPrototype)) {\n const names = Object.getOwnPropertyNames(proto);\n for (let i = 0; i < names.length; i++) {\n visitedSet[names[i]] = true;\n }\n proto = Object.getPrototypeOf(proto);\n }\n\n return getKeys(visitedSet);\n}\n\n/**\n * Given a ES5 or ES6 class reference, return its super class / super\n * constructor.\n * This should be used in rare cases where you need to walk up the inheritance\n * tree (this is generally a bad idea). But this work with ES5 and ES6 classes,\n * unlike relying on the superClass_ property.\n * Note: To start walking up the hierarchy from an instance call this with its\n * `constructor` property; e.g. `getSuperClass(instance.constructor)`.\n * @param {function(new: ?)} constructor\n * @return {?Object}\n */\nfunction getSuperClass(constructor) {\n const proto = Object.getPrototypeOf(constructor.prototype);\n return proto && proto.constructor;\n}\n\nexports = {\n add,\n clear,\n clone,\n contains,\n containsKey,\n containsValue,\n create,\n createImmutableView,\n createSet,\n equals,\n every,\n extend,\n filter,\n findKey,\n findValue,\n forEach,\n get,\n getAllPropertyNames,\n getAnyKey,\n getAnyValue,\n getCount,\n getKeys,\n getSuperClass,\n getValueByKeys,\n getValues,\n isEmpty,\n isImmutableView,\n map,\n remove,\n set,\n setIfUndefined,\n setWithReturnValueIfNotSet,\n some,\n transpose,\n unsafeClone,\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview An event manager for both native browser event\n * targets and custom JavaScript event targets\n * (`goog.events.Listenable`). This provides an abstraction\n * over browsers' event systems.\n *\n * It also provides a simulation of W3C event model's capture phase in\n * Internet Explorer (IE 8 and below). Caveat: the simulation does not\n * interact well with listeners registered directly on the elements\n * (bypassing goog.events) or even with listeners registered via\n * goog.events in a separate JS binary. In these cases, we provide\n * no ordering guarantees.\n *\n * The listeners will receive a \"patched\" event object. Such event object\n * contains normalized values for certain event properties that differs in\n * different browsers.\n *\n * Example usage:\n * <pre>\n * goog.events.listen(myNode, 'click', function(e) { alert('woo') });\n * goog.events.listen(myNode, 'mouseover', mouseHandler, true);\n * goog.events.unlisten(myNode, 'mouseover', mouseHandler, true);\n * goog.events.removeAll(myNode);\n * </pre>\n *\n * in IE and event object patching]\n *\n * @see ../demos/events.html\n * @see ../demos/event-propagation.html\n * @see ../demos/stopevent.html\n */\n\n// IMPLEMENTATION NOTES:\n// goog.events stores an auxiliary data structure on each EventTarget\n// source being listened on. This allows us to take advantage of GC,\n// having the data structure GC'd when the EventTarget is GC'd. This\n// GC behavior is equivalent to using W3C DOM Events directly.\n\ngoog.provide('goog.events');\ngoog.provide('goog.events.CaptureSimulationMode');\ngoog.provide('goog.events.Key');\ngoog.provide('goog.events.ListenableType');\n\ngoog.require('goog.asserts');\ngoog.require('goog.debug.entryPointRegistry');\ngoog.require('goog.events.BrowserEvent');\ngoog.require('goog.events.BrowserFeature');\ngoog.require('goog.events.Listenable');\ngoog.require('goog.events.ListenerMap');\ngoog.requireType('goog.debug.ErrorHandler');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventLike');\ngoog.requireType('goog.events.EventWrapper');\ngoog.requireType('goog.events.ListenableKey');\ngoog.requireType('goog.events.Listener');\n\n\n/**\n * @typedef {number|goog.events.ListenableKey}\n */\ngoog.events.Key;\n\n\n/**\n * @typedef {EventTarget|goog.events.Listenable}\n */\ngoog.events.ListenableType;\n\n\n/**\n * Property name on a native event target for the listener map\n * associated with the event target.\n * @private @const {string}\n */\ngoog.events.LISTENER_MAP_PROP_ = 'closure_lm_' + ((Math.random() * 1e6) | 0);\n\n\n/**\n * String used to prepend to IE event types.\n * @const\n * @private\n */\ngoog.events.onString_ = 'on';\n\n\n/**\n * Map of computed \"on<eventname>\" strings for IE event types. Caching\n * this removes an extra object allocation in goog.events.listen which\n * improves IE6 performance.\n * @const\n * @dict\n * @private\n */\ngoog.events.onStringMap_ = {};\n\n\n/**\n * @enum {number} Different capture simulation mode for IE8-.\n */\ngoog.events.CaptureSimulationMode = {\n /**\n * Does not perform capture simulation. Will asserts in IE8- when you\n * add capture listeners.\n */\n OFF_AND_FAIL: 0,\n\n /**\n * Does not perform capture simulation, silently ignore capture\n * listeners.\n */\n OFF_AND_SILENT: 1,\n\n /**\n * Performs capture simulation.\n */\n ON: 2\n};\n\n\n/**\n * @define {number} The capture simulation mode for IE8-. By default,\n * this is ON.\n */\ngoog.events.CAPTURE_SIMULATION_MODE =\n goog.define('goog.events.CAPTURE_SIMULATION_MODE', 2);\n\n\n/**\n * Estimated count of total native listeners.\n * @private {number}\n */\ngoog.events.listenerCountEstimate_ = 0;\n\n\n/**\n * Adds an event listener for a specific event on a native event\n * target (such as a DOM element) or an object that has implemented\n * {@link goog.events.Listenable}. A listener can only be added once\n * to an object and if it is added again the key for the listener is\n * returned. Note that if the existing listener is a one-off listener\n * (registered via listenOnce), it will no longer be a one-off\n * listener after a call to listen().\n *\n * @param {EventTarget|goog.events.Listenable} src The node to listen\n * to events on.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null}\n * listener Callback method, or an object with a handleEvent function.\n * WARNING: passing an Object is now softly deprecated.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {T=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.Key} Unique key for the listener.\n * @template T,EVENTOBJ\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.listen = function(src, type, listener, opt_options, opt_handler) {\n 'use strict';\n if (opt_options && opt_options.once) {\n return goog.events.listenOnce(\n src, type, listener, opt_options, opt_handler);\n }\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.listen(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n return src.listen(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n } else {\n return goog.events.listen_(\n /** @type {!EventTarget} */ (src), type, listener,\n /* callOnce */ false, opt_options, opt_handler);\n }\n};\n\n\n/**\n * Adds an event listener for a specific event on a native event\n * target. A listener can only be added once to an object and if it\n * is added again the key for the listener is returned.\n *\n * Note that a one-off listener will not change an existing listener,\n * if any. On the other hand a normal listener will change existing\n * one-off listener to become a normal listener.\n *\n * @param {EventTarget} src The node to listen to events on.\n * @param {string|?goog.events.EventId<EVENTOBJ>} type Event type.\n * @param {!Function} listener Callback function.\n * @param {boolean} callOnce Whether the listener is a one-off\n * listener or otherwise.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.ListenableKey} Unique key for the listener.\n * @template EVENTOBJ\n * @private\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.listen_ = function(\n src, type, listener, callOnce, opt_options, opt_handler) {\n 'use strict';\n if (!type) {\n throw new Error('Invalid event type');\n }\n\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n\n var listenerMap = goog.events.getListenerMap_(src);\n if (!listenerMap) {\n src[goog.events.LISTENER_MAP_PROP_] = listenerMap =\n new goog.events.ListenerMap(src);\n }\n\n var listenerObj = /** @type {goog.events.Listener} */ (\n listenerMap.add(type, listener, callOnce, capture, opt_handler));\n\n // If the listenerObj already has a proxy, it has been set up\n // previously. We simply return.\n if (listenerObj.proxy) {\n return listenerObj;\n }\n\n var proxy = goog.events.getProxy();\n listenerObj.proxy = proxy;\n\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n proxy.src = src;\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n proxy.listener = listenerObj;\n\n // Attach the proxy through the browser's API\n if (src.addEventListener) {\n // Don't pass an object as `capture` if the browser doesn't support that.\n if (!goog.events.BrowserFeature.PASSIVE_EVENTS) {\n opt_options = capture;\n }\n // Don't break tests that expect a boolean.\n if (opt_options === undefined) opt_options = false;\n src.addEventListener(type.toString(), proxy, opt_options);\n } else if (src.attachEvent) {\n // The else if above used to be an unconditional else. It would call\n // attachEvent come gws or high water. This would sometimes throw an\n // exception on IE11, spoiling the day of some callers. The previous\n // incarnation of this code, from 2007, indicates that it replaced an\n // earlier still version that caused excess allocations on IE6.\n src.attachEvent(goog.events.getOnString_(type.toString()), proxy);\n } else if (src.addListener && src.removeListener) {\n // In IE, MediaQueryList uses addListener() insteadd of addEventListener. In\n // Safari, there is no global for the MediaQueryList constructor, so we just\n // check whether the object \"looks like\" MediaQueryList.\n goog.asserts.assert(\n type === 'change', 'MediaQueryList only has a change event');\n src.addListener(proxy);\n } else {\n throw new Error('addEventListener and attachEvent are unavailable.');\n }\n\n goog.events.listenerCountEstimate_++;\n return listenerObj;\n};\n\n\n/**\n * Helper function for returning a proxy function.\n * @return {!Function} A new or reused function object.\n */\ngoog.events.getProxy = function() {\n 'use strict';\n const proxyCallbackFunction = goog.events.handleBrowserEvent_;\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n const f = function(eventObject) {\n return proxyCallbackFunction.call(f.src, f.listener, eventObject);\n };\n return f;\n};\n\n\n/**\n * Adds an event listener for a specific event on a native event\n * target (such as a DOM element) or an object that has implemented\n * {@link goog.events.Listenable}. After the event has fired the event\n * listener is removed from the target.\n *\n * If an existing listener already exists, listenOnce will do\n * nothing. In particular, if the listener was previously registered\n * via listen(), listenOnce() will not turn the listener into a\n * one-off listener. Similarly, if there is already an existing\n * one-off listener, listenOnce does not modify the listeners (it is\n * still a once listener).\n *\n * @param {EventTarget|goog.events.Listenable} src The node to listen\n * to events on.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null}\n * listener Callback method.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {T=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.Key} Unique key for the listener.\n * @template T,EVENTOBJ\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.listenOnce = function(\n src, type, listener, opt_options, opt_handler) {\n 'use strict';\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.listenOnce(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n return src.listenOnce(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n } else {\n return goog.events.listen_(\n /** @type {!EventTarget} */ (src), type, listener,\n /* callOnce */ true, opt_options, opt_handler);\n }\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.Listenable}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.Listenable} src The target to\n * listen to events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(this:T, ?):?|{handleEvent:function(?):?}|null} listener\n * Callback method, or an object with a handleEvent function.\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\n * false).\n * @param {T=} opt_handler Element in whose scope to call the listener.\n * @template T\n */\ngoog.events.listenWithWrapper = function(\n src, wrapper, listener, opt_capt, opt_handler) {\n 'use strict';\n wrapper.listen(src, listener, opt_capt, opt_handler);\n};\n\n\n/**\n * Removes an event listener which was added with listen().\n *\n * @param {EventTarget|goog.events.Listenable} src The target to stop\n * listening to events on.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types to unlisten to.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\n * listener function to remove.\n * @param {(boolean|!EventListenerOptions)=} opt_options\n * whether the listener is fired during the capture or bubble phase of the\n * event.\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n * @return {?boolean} indicating whether the listener was there to remove.\n * @template EVENTOBJ\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.unlisten = function(src, type, listener, opt_options, opt_handler) {\n 'use strict';\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.unlisten(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n return src.unlisten(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n }\n\n if (!src) {\n // TODO(chrishenry): We should tighten the API to only accept\n // non-null objects, or add an assertion here.\n return false;\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (src));\n if (listenerMap) {\n var listenerObj = listenerMap.getListener(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n if (listenerObj) {\n return goog.events.unlistenByKey(listenerObj);\n }\n }\n\n return false;\n};\n\n\n/**\n * Removes an event listener which was added with listen() by the key\n * returned by listen().\n *\n * @param {goog.events.Key} key The key returned by listen() for this\n * event listener.\n * @return {boolean} indicating whether the listener was there to remove.\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.unlistenByKey = function(key) {\n 'use strict';\n // TODO(chrishenry): Remove this check when tests that rely on this\n // are fixed.\n if (typeof key === 'number') {\n return false;\n }\n\n var listener = key;\n if (!listener || listener.removed) {\n return false;\n }\n\n var src = listener.src;\n if (goog.events.Listenable.isImplementedBy(src)) {\n return /** @type {!goog.events.Listenable} */ (src).unlistenByKey(listener);\n }\n\n var type = listener.type;\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n var proxy = listener.proxy;\n if (src.removeEventListener) {\n src.removeEventListener(type, proxy, listener.capture);\n } else if (src.detachEvent) {\n src.detachEvent(goog.events.getOnString_(type), proxy);\n } else if (src.addListener && src.removeListener) {\n src.removeListener(proxy);\n }\n goog.events.listenerCountEstimate_--;\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (src));\n // TODO(chrishenry): Try to remove this conditional and execute the\n // first branch always. This should be safe.\n if (listenerMap) {\n listenerMap.removeByKey(listener);\n if (listenerMap.getTypeCount() == 0) {\n // Null the src, just because this is simple to do (and useful\n // for IE <= 7).\n listenerMap.src = null;\n // We don't use delete here because IE does not allow delete\n // on a window object.\n src[goog.events.LISTENER_MAP_PROP_] = null;\n }\n } else {\n /** @type {!goog.events.Listener} */ (listener).markAsRemoved();\n }\n\n return true;\n};\n\n\n/**\n * Removes an event listener which was added with listenWithWrapper().\n *\n * @param {EventTarget|goog.events.Listenable} src The target to stop\n * listening to events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\n * listener function to remove.\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase of the\n * event.\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n */\ngoog.events.unlistenWithWrapper = function(\n src, wrapper, listener, opt_capt, opt_handler) {\n 'use strict';\n wrapper.unlisten(src, listener, opt_capt, opt_handler);\n};\n\n\n/**\n * Removes all listeners from an object. You can also optionally\n * remove listeners of a particular type.\n *\n * @param {Object|undefined} obj Object to remove listeners from. Must be an\n * EventTarget or a goog.events.Listenable.\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove.\n * Default is all types.\n * @return {number} Number of listeners removed.\n */\ngoog.events.removeAll = function(obj, opt_type) {\n 'use strict';\n // TODO(chrishenry): Change the type of obj to\n // (!EventTarget|!goog.events.Listenable).\n\n if (!obj) {\n return 0;\n }\n\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return /** @type {?} */ (obj).removeAllListeners(opt_type);\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (obj));\n if (!listenerMap) {\n return 0;\n }\n\n var count = 0;\n var typeStr = opt_type && opt_type.toString();\n for (var type in listenerMap.listeners) {\n if (!typeStr || type == typeStr) {\n // Clone so that we don't need to worry about unlistenByKey\n // changing the content of the ListenerMap.\n var listeners = listenerMap.listeners[type].concat();\n for (var i = 0; i < listeners.length; ++i) {\n if (goog.events.unlistenByKey(listeners[i])) {\n ++count;\n }\n }\n }\n }\n return count;\n};\n\n\n/**\n * Gets the listeners for a given object, type and capture phase.\n *\n * @param {Object} obj Object to get listeners for.\n * @param {string|!goog.events.EventId} type Event type.\n * @param {boolean} capture Capture phase?.\n * @return {!Array<!goog.events.Listener>} Array of listener objects.\n */\ngoog.events.getListeners = function(obj, type, capture) {\n 'use strict';\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return /** @type {!goog.events.Listenable} */ (obj).getListeners(\n type, capture);\n } else {\n if (!obj) {\n // TODO(chrishenry): We should tighten the API to accept\n // !EventTarget|goog.events.Listenable, and add an assertion here.\n return [];\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (obj));\n return listenerMap ? listenerMap.getListeners(type, capture) : [];\n }\n};\n\n\n/**\n * Gets the goog.events.Listener for the event or null if no such listener is\n * in use.\n *\n * @param {EventTarget|goog.events.Listenable} src The target from\n * which to get listeners.\n * @param {?string|!goog.events.EventId<EVENTOBJ>} type The type of the event.\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null} listener The\n * listener function to get.\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\n * whether the listener is fired during the\n * capture or bubble phase of the event.\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.ListenableKey} the found listener or null if not found.\n * @template EVENTOBJ\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.getListener = function(src, type, listener, opt_capt, opt_handler) {\n 'use strict';\n // TODO(chrishenry): Change type from ?string to string, or add assertion.\n type = /** @type {string} */ (type);\n listener = goog.events.wrapListener(listener);\n var capture = !!opt_capt;\n if (goog.events.Listenable.isImplementedBy(src)) {\n return src.getListener(type, listener, capture, opt_handler);\n }\n\n if (!src) {\n // TODO(chrishenry): We should tighten the API to only accept\n // non-null objects, or add an assertion here.\n return null;\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (src));\n if (listenerMap) {\n return listenerMap.getListener(type, listener, capture, opt_handler);\n }\n return null;\n};\n\n\n/**\n * Returns whether an event target has any active listeners matching the\n * specified signature. If either the type or capture parameters are\n * unspecified, the function will match on the remaining criteria.\n *\n * @param {EventTarget|goog.events.Listenable} obj Target to get\n * listeners for.\n * @param {string|!goog.events.EventId=} opt_type Event type.\n * @param {boolean=} opt_capture Whether to check for capture or bubble-phase\n * listeners.\n * @return {boolean} Whether an event target has one or more listeners matching\n * the requested type and/or capture phase.\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.hasListener = function(obj, opt_type, opt_capture) {\n 'use strict';\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return obj.hasListener(opt_type, opt_capture);\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (obj));\n return !!listenerMap && listenerMap.hasListener(opt_type, opt_capture);\n};\n\n\n/**\n * Provides a nice string showing the normalized event objects public members\n * @param {Object} e Event Object.\n * @return {string} String of the public members of the normalized event object.\n */\ngoog.events.expose = function(e) {\n 'use strict';\n var str = [];\n for (var key in e) {\n if (e[key] && e[key].id) {\n str.push(key + ' = ' + e[key] + ' (' + e[key].id + ')');\n } else {\n str.push(key + ' = ' + e[key]);\n }\n }\n return str.join('\\n');\n};\n\n\n/**\n * Returns a string with on prepended to the specified type. This is used for IE\n * which expects \"on\" to be prepended. This function caches the string in order\n * to avoid extra allocations in steady state.\n * @param {string} type Event type.\n * @return {string} The type string with 'on' prepended.\n * @private\n */\ngoog.events.getOnString_ = function(type) {\n 'use strict';\n if (type in goog.events.onStringMap_) {\n return goog.events.onStringMap_[type];\n }\n return goog.events.onStringMap_[type] = goog.events.onString_ + type;\n};\n\n\n/**\n * Fires an object's listeners of a particular type and phase\n *\n * @param {Object} obj Object whose listeners to call.\n * @param {string|!goog.events.EventId} type Event type.\n * @param {boolean} capture Which event phase.\n * @param {Object} eventObject Event object to be passed to listener.\n * @return {boolean} True if all listeners returned true else false.\n */\ngoog.events.fireListeners = function(obj, type, capture, eventObject) {\n 'use strict';\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return /** @type {!goog.events.Listenable} */ (obj).fireListeners(\n type, capture, eventObject);\n }\n\n return goog.events.fireListeners_(obj, type, capture, eventObject);\n};\n\n\n/**\n * Fires an object's listeners of a particular type and phase.\n * @param {Object} obj Object whose listeners to call.\n * @param {string|!goog.events.EventId} type Event type.\n * @param {boolean} capture Which event phase.\n * @param {Object} eventObject Event object to be passed to listener.\n * @return {boolean} True if all listeners returned true else false.\n * @private\n */\ngoog.events.fireListeners_ = function(obj, type, capture, eventObject) {\n 'use strict';\n /** @type {boolean} */\n var retval = true;\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {EventTarget} */ (obj));\n if (listenerMap) {\n // TODO(chrishenry): Original code avoids array creation when there\n // is no listener, so we do the same. If this optimization turns\n // out to be not required, we can replace this with\n // listenerMap.getListeners(type, capture) instead, which is simpler.\n var listenerArray = listenerMap.listeners[type.toString()];\n if (listenerArray) {\n listenerArray = listenerArray.concat();\n for (var i = 0; i < listenerArray.length; i++) {\n var listener = listenerArray[i];\n // We might not have a listener if the listener was removed.\n if (listener && listener.capture == capture && !listener.removed) {\n var result = goog.events.fireListener(listener, eventObject);\n retval = retval && (result !== false);\n }\n }\n }\n }\n return retval;\n};\n\n\n/**\n * Fires a listener with a set of arguments\n *\n * @param {goog.events.Listener} listener The listener object to call.\n * @param {Object} eventObject The event object to pass to the listener.\n * @return {*} Result of listener.\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.fireListener = function(listener, eventObject) {\n 'use strict';\n var listenerFn = listener.listener;\n var listenerHandler = listener.handler || listener.src;\n\n if (listener.callOnce) {\n goog.events.unlistenByKey(listener);\n }\n return listenerFn.call(listenerHandler, eventObject);\n};\n\n\n/**\n * Gets the total number of listeners currently in the system.\n * @return {number} Number of listeners.\n * @deprecated This returns estimated count, now that Closure no longer\n * stores a central listener registry. We still return an estimation\n * to keep existing listener-related tests passing. In the near future,\n * this function will be removed.\n */\ngoog.events.getTotalListenerCount = function() {\n 'use strict';\n return goog.events.listenerCountEstimate_;\n};\n\n\n/**\n * Dispatches an event (or event like object) and calls all listeners\n * listening for events of this type. The type of the event is decided by the\n * type property on the event object.\n *\n * If any of the listeners returns false OR calls preventDefault then this\n * function will return false. If one of the capture listeners calls\n * stopPropagation, then the bubble listeners won't fire.\n *\n * @param {goog.events.Listenable} src The event target.\n * @param {goog.events.EventLike} e Event object.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the handlers returns false) this will also return false.\n * If there are no handlers, or if all handlers return true, this returns\n * true.\n */\ngoog.events.dispatchEvent = function(src, e) {\n 'use strict';\n goog.asserts.assert(\n goog.events.Listenable.isImplementedBy(src),\n 'Can not use goog.events.dispatchEvent with ' +\n 'non-goog.events.Listenable instance.');\n return src.dispatchEvent(e);\n};\n\n\n/**\n * Installs exception protection for the browser event entry point using the\n * given error handler.\n *\n * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to\n * protect the entry point.\n */\ngoog.events.protectBrowserEventEntryPoint = function(errorHandler) {\n 'use strict';\n goog.events.handleBrowserEvent_ =\n errorHandler.protectEntryPoint(goog.events.handleBrowserEvent_);\n};\n\n\n/**\n * Handles an event and dispatches it to the correct listeners. This\n * function is a proxy for the real listener the user specified.\n *\n * @param {goog.events.Listener} listener The listener object.\n * @param {Event=} opt_evt Optional event object that gets passed in via the\n * native event handlers.\n * @return {*} Result of the event handler.\n * @this {EventTarget} The object or Element that fired the event.\n * @private\n */\ngoog.events.handleBrowserEvent_ = function(listener, opt_evt) {\n 'use strict';\n if (listener.removed) {\n return true;\n }\n\n // Otherwise, simply fire the listener.\n return goog.events.fireListener(\n listener, new goog.events.BrowserEvent(opt_evt, this));\n};\n\n\n/**\n * This is used to mark the IE event object so we do not do the Closure pass\n * twice for a bubbling event.\n * @param {Event} e The IE browser event.\n * @private\n */\ngoog.events.markIeEvent_ = function(e) {\n 'use strict';\n // Only the keyCode and the returnValue can be changed. We use keyCode for\n // non keyboard events.\n // event.returnValue is a bit more tricky. It is undefined by default. A\n // boolean false prevents the default action. In a window.onbeforeunload and\n // the returnValue is non undefined it will be alerted. However, we will only\n // modify the returnValue for keyboard events. We can get a problem if non\n // closure events sets the keyCode or the returnValue\n\n var useReturnValue = false;\n\n if (e.keyCode == 0) {\n // We cannot change the keyCode in case that srcElement is input[type=file].\n // We could test that that is the case but that would allocate 3 objects.\n // If we use try/catch we will only allocate extra objects in the case of a\n // failure.\n\n try {\n e.keyCode = -1;\n return;\n } catch (ex) {\n useReturnValue = true;\n }\n }\n\n if (useReturnValue ||\n /** @type {boolean|undefined} */ (e.returnValue) == undefined) {\n e.returnValue = true;\n }\n};\n\n\n/**\n * This is used to check if an IE event has already been handled by the Closure\n * system so we do not do the Closure pass twice for a bubbling event.\n * @param {Event} e The IE browser event.\n * @return {boolean} True if the event object has been marked.\n * @private\n */\ngoog.events.isMarkedIeEvent_ = function(e) {\n 'use strict';\n return e.keyCode < 0 || e.returnValue != undefined;\n};\n\n\n/**\n * Counter to create unique event ids.\n * @private {number}\n */\ngoog.events.uniqueIdCounter_ = 0;\n\n\n/**\n * Creates a unique event id.\n *\n * @param {string} identifier The identifier.\n * @return {string} A unique identifier.\n * @idGenerator {unique}\n */\ngoog.events.getUniqueId = function(identifier) {\n 'use strict';\n return identifier + '_' + goog.events.uniqueIdCounter_++;\n};\n\n\n/**\n * @param {EventTarget} src The source object.\n * @return {goog.events.ListenerMap} A listener map for the given\n * source object, or null if none exists.\n * @private\n */\ngoog.events.getListenerMap_ = function(src) {\n 'use strict';\n var listenerMap = src[goog.events.LISTENER_MAP_PROP_];\n // IE serializes the property as well (e.g. when serializing outer\n // HTML). So we must check that the value is of the correct type.\n return listenerMap instanceof goog.events.ListenerMap ? listenerMap : null;\n};\n\n\n/**\n * Expando property for listener function wrapper for Object with\n * handleEvent.\n * @private @const {string}\n */\ngoog.events.LISTENER_WRAPPER_PROP_ =\n '__closure_events_fn_' + ((Math.random() * 1e9) >>> 0);\n\n\n/**\n * @param {Object|Function} listener The listener function or an\n * object that contains handleEvent method.\n * @return {!Function} Either the original function or a function that\n * calls obj.handleEvent. If the same listener is passed to this\n * function more than once, the same function is guaranteed to be\n * returned.\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.wrapListener = function(listener) {\n 'use strict';\n goog.asserts.assert(listener, 'Listener can not be null.');\n\n if (typeof listener === 'function') {\n return listener;\n }\n\n goog.asserts.assert(\n listener.handleEvent, 'An object listener must have handleEvent method.');\n if (!listener[goog.events.LISTENER_WRAPPER_PROP_]) {\n listener[goog.events.LISTENER_WRAPPER_PROP_] = function(e) {\n 'use strict';\n return /** @type {?} */ (listener).handleEvent(e);\n };\n }\n return listener[goog.events.LISTENER_WRAPPER_PROP_];\n};\n\n\n// Register the browser event handler as an entry point, so that\n// it can be monitored for exception handling, etc.\ngoog.debug.entryPointRegistry.register(\n /**\n * @param {function(!Function): !Function} transformer The transforming\n * function.\n */\n function(transformer) {\n 'use strict';\n goog.events.handleBrowserEvent_ =\n transformer(goog.events.handleBrowserEvent_);\n });\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A disposable implementation of a custom\n * listenable/event target. See also: documentation for\n * `goog.events.Listenable`.\n *\n * @see ../demos/eventtarget.html\n * @see goog.events.Listenable\n */\n\ngoog.provide('goog.events.EventTarget');\n\ngoog.require('goog.Disposable');\ngoog.require('goog.asserts');\ngoog.require('goog.events');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.Listenable');\ngoog.require('goog.events.ListenerMap');\ngoog.require('goog.object');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventLike');\ngoog.requireType('goog.events.ListenableKey');\n\n\n\n/**\n * An implementation of `goog.events.Listenable` with full W3C\n * EventTarget-like support (capture/bubble mechanism, stopping event\n * propagation, preventing default actions).\n *\n * You may subclass this class to turn your class into a Listenable.\n *\n * Unless propagation is stopped, an event dispatched by an\n * EventTarget will bubble to the parent returned by\n * `getParentEventTarget`. To set the parent, call\n * `setParentEventTarget`. Subclasses that don't support\n * changing the parent can override the setter to throw an error.\n *\n * Example usage:\n * <pre>\n * var source = new goog.events.EventTarget();\n * function handleEvent(e) {\n * alert('Type: ' + e.type + '; Target: ' + e.target);\n * }\n * source.listen('foo', handleEvent);\n * // Or: goog.events.listen(source, 'foo', handleEvent);\n * ...\n * source.dispatchEvent('foo'); // will call handleEvent\n * ...\n * source.unlisten('foo', handleEvent);\n * // Or: goog.events.unlisten(source, 'foo', handleEvent);\n * </pre>\n *\n * @constructor\n * @extends {goog.Disposable}\n * @implements {goog.events.Listenable}\n */\ngoog.events.EventTarget = function() {\n 'use strict';\n goog.Disposable.call(this);\n\n /**\n * Maps of event type to an array of listeners.\n * @private {!goog.events.ListenerMap}\n */\n this.eventTargetListeners_ = new goog.events.ListenerMap(this);\n\n /**\n * The object to use for event.target. Useful when mixing in an\n * EventTarget to another object.\n * @private {!Object}\n */\n this.actualEventTarget_ = this;\n\n /**\n * Parent event target, used during event bubbling.\n *\n * TODO(chrishenry): Change this to goog.events.Listenable. This\n * currently breaks people who expect getParentEventTarget to return\n * goog.events.EventTarget.\n *\n * @private {?goog.events.EventTarget}\n */\n this.parentEventTarget_ = null;\n};\ngoog.inherits(goog.events.EventTarget, goog.Disposable);\ngoog.events.Listenable.addImplementation(goog.events.EventTarget);\n\n\n/**\n * An artificial cap on the number of ancestors you can have. This is mainly\n * for loop detection.\n * @const {number}\n * @private\n */\ngoog.events.EventTarget.MAX_ANCESTORS_ = 1000;\n\n\n/**\n * Returns the parent of this event target to use for bubbling.\n *\n * @return {goog.events.EventTarget} The parent EventTarget or null if\n * there is no parent.\n * @override\n */\ngoog.events.EventTarget.prototype.getParentEventTarget = function() {\n 'use strict';\n return this.parentEventTarget_;\n};\n\n\n/**\n * Sets the parent of this event target to use for capture/bubble\n * mechanism.\n * @param {goog.events.EventTarget} parent Parent listenable (null if none).\n */\ngoog.events.EventTarget.prototype.setParentEventTarget = function(parent) {\n 'use strict';\n this.parentEventTarget_ = parent;\n};\n\n\n/**\n * Adds an event listener to the event target. The same handler can only be\n * added once per the type. Even if you add the same handler multiple times\n * using the same type then it will only be called once when the event is\n * dispatched.\n *\n * @param {string|!goog.events.EventId} type The type of the event to listen for\n * @param {function(?):?|{handleEvent:function(?):?}|null} handler The function\n * to handle the event. The handler can also be an object that implements\n * the handleEvent method which takes the event object as argument.\n * @param {boolean=} opt_capture In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase\n * of the event.\n * @param {Object=} opt_handlerScope Object in whose scope to call\n * the listener.\n * @deprecated Use `#listen` instead, when possible. Otherwise, use\n * `goog.events.listen` if you are passing Object\n * (instead of Function) as handler.\n */\ngoog.events.EventTarget.prototype.addEventListener = function(\n type, handler, opt_capture, opt_handlerScope) {\n 'use strict';\n goog.events.listen(this, type, handler, opt_capture, opt_handlerScope);\n};\n\n\n/**\n * Removes an event listener from the event target. The handler must be the\n * same object as the one added. If the handler has not been added then\n * nothing is done.\n *\n * @param {string|!goog.events.EventId} type The type of the event to listen for\n * @param {function(?):?|{handleEvent:function(?):?}|null} handler The function\n * to handle the event. The handler can also be an object that implements\n * the handleEvent method which takes the event object as argument.\n * @param {boolean=} opt_capture In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase\n * of the event.\n * @param {Object=} opt_handlerScope Object in whose scope to call\n * the listener.\n * @deprecated Use `#unlisten` instead, when possible. Otherwise, use\n * `goog.events.unlisten` if you are passing Object\n * (instead of Function) as handler.\n */\ngoog.events.EventTarget.prototype.removeEventListener = function(\n type, handler, opt_capture, opt_handlerScope) {\n 'use strict';\n goog.events.unlisten(this, type, handler, opt_capture, opt_handlerScope);\n};\n\n\n/**\n * @param {?goog.events.EventLike} e Event object.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the listeners returns false) this will also return false.\n * @override\n */\ngoog.events.EventTarget.prototype.dispatchEvent = function(e) {\n 'use strict';\n this.assertInitialized_();\n\n var ancestorsTree, ancestor = this.getParentEventTarget();\n if (ancestor) {\n ancestorsTree = [];\n var ancestorCount = 1;\n for (; ancestor; ancestor = ancestor.getParentEventTarget()) {\n ancestorsTree.push(ancestor);\n goog.asserts.assert(\n (++ancestorCount < goog.events.EventTarget.MAX_ANCESTORS_),\n 'infinite loop');\n }\n }\n\n return goog.events.EventTarget.dispatchEventInternal_(\n this.actualEventTarget_, e, ancestorsTree);\n};\n\n\n/**\n * Removes listeners from this object. Classes that extend EventTarget may\n * need to override this method in order to remove references to DOM Elements\n * and additional listeners.\n * @override\n * @protected\n */\ngoog.events.EventTarget.prototype.disposeInternal = function() {\n 'use strict';\n goog.events.EventTarget.superClass_.disposeInternal.call(this);\n\n this.removeAllListeners();\n this.parentEventTarget_ = null;\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.listen = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n this.assertInitialized_();\n return this.eventTargetListeners_.add(\n String(type), listener, false /* callOnce */, opt_useCapture,\n opt_listenerScope);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.listenOnce = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n return this.eventTargetListeners_.add(\n String(type), listener, true /* callOnce */, opt_useCapture,\n opt_listenerScope);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call\n * the listener.\n * @return {boolean} Whether any listener was removed.\n * @template SCOPE,EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.unlisten = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n return this.eventTargetListeners_.remove(\n String(type), listener, opt_useCapture, opt_listenerScope);\n};\n\n\n/**\n * @param {!goog.events.ListenableKey} key The key returned by\n * listen() or listenOnce().\n * @return {boolean} Whether any listener was removed.\n * @override\n */\ngoog.events.EventTarget.prototype.unlistenByKey = function(key) {\n 'use strict';\n return this.eventTargetListeners_.removeByKey(key);\n};\n\n\n/**\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove,\n * default is to remove all types.\n * @return {number} Number of listeners removed.\n * @override\n */\ngoog.events.EventTarget.prototype.removeAllListeners = function(opt_type) {\n 'use strict';\n // TODO(chrishenry): Previously, removeAllListeners can be called on\n // uninitialized EventTarget, so we preserve that behavior. We\n // should remove this when usages that rely on that fact are purged.\n if (!this.eventTargetListeners_) {\n return 0;\n }\n return this.eventTargetListeners_.removeAll(opt_type);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The type of the\n * listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @param {EVENTOBJ} eventObject The event object to fire.\n * @return {boolean} Whether all listeners succeeded without\n * attempting to prevent default behavior. If any listener returns\n * false or called goog.events.Event#preventDefault, this returns\n * false.\n * @template EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.fireListeners = function(\n type, capture, eventObject) {\n 'use strict';\n // TODO(chrishenry): Original code avoids array creation when there\n // is no listener, so we do the same. If this optimization turns\n // out to be not required, we can replace this with\n // getListeners(type, capture) instead, which is simpler.\n var listenerArray = this.eventTargetListeners_.listeners[String(type)];\n if (!listenerArray) {\n return true;\n }\n listenerArray = listenerArray.concat();\n\n var rv = true;\n for (var i = 0; i < listenerArray.length; ++i) {\n var listener = listenerArray[i];\n // We might not have a listener if the listener was removed.\n if (listener && !listener.removed && listener.capture == capture) {\n var listenerFn = listener.listener;\n var listenerHandler = listener.handler || listener.src;\n\n if (listener.callOnce) {\n this.unlistenByKey(listener);\n }\n rv = listenerFn.call(listenerHandler, eventObject) !== false && rv;\n }\n }\n\n return rv && !eventObject.defaultPrevented;\n};\n\n\n/**\n * @param {string|!goog.events.EventId} type The type of the listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @return {!Array<!goog.events.ListenableKey>} An array of registered\n * listeners.\n * @template EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.getListeners = function(type, capture) {\n 'use strict';\n return this.eventTargetListeners_.getListeners(String(type), capture);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The name of the event\n * without the 'on' prefix.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener The\n * listener function to get.\n * @param {boolean} capture Whether the listener is a capturing listener.\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {?goog.events.ListenableKey} the found listener or null if not found.\n * @template SCOPE,EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.getListener = function(\n type, listener, capture, opt_listenerScope) {\n 'use strict';\n return this.eventTargetListeners_.getListener(\n String(type), listener, capture, opt_listenerScope);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>=} opt_type Event type.\n * @param {boolean=} opt_capture Whether to check for capture or bubble\n * listeners.\n * @return {boolean} Whether there is any active listeners matching\n * the requested type and/or capture phase.\n * @template EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.hasListener = function(\n opt_type, opt_capture) {\n 'use strict';\n var id = (opt_type !== undefined) ? String(opt_type) : undefined;\n return this.eventTargetListeners_.hasListener(id, opt_capture);\n};\n\n\n/**\n * Sets the target to be used for `event.target` when firing\n * event. Mainly used for testing. For example, see\n * `goog.testing.events.mixinListenable`.\n * @param {!Object} target The target.\n */\ngoog.events.EventTarget.prototype.setTargetForTesting = function(target) {\n 'use strict';\n this.actualEventTarget_ = target;\n};\n\n\n/**\n * Asserts that the event target instance is initialized properly.\n * @private\n */\ngoog.events.EventTarget.prototype.assertInitialized_ = function() {\n 'use strict';\n goog.asserts.assert(\n this.eventTargetListeners_,\n 'Event target is not initialized. Did you call the superclass ' +\n '(goog.events.EventTarget) constructor?');\n};\n\n\n/**\n * Dispatches the given event on the ancestorsTree.\n *\n * @param {!Object} target The target to dispatch on.\n * @param {goog.events.Event|Object|string} e The event object.\n * @param {Array<goog.events.Listenable>=} opt_ancestorsTree The ancestors\n * tree of the target, in reverse order from the closest ancestor\n * to the root event target. May be null if the target has no ancestor.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the listeners returns false) this will also return false.\n * @private\n */\ngoog.events.EventTarget.dispatchEventInternal_ = function(\n target, e, opt_ancestorsTree) {\n 'use strict';\n /** @suppress {missingProperties} */\n var type = e.type || /** @type {string} */ (e);\n\n // If accepting a string or object, create a custom event object so that\n // preventDefault and stopPropagation work with the event.\n if (typeof e === 'string') {\n e = new goog.events.Event(e, target);\n } else if (!(e instanceof goog.events.Event)) {\n var oldEvent = e;\n e = new goog.events.Event(type, target);\n goog.object.extend(e, oldEvent);\n } else {\n e.target = e.target || target;\n }\n\n var rv = true, currentTarget;\n\n // Executes all capture listeners on the ancestors, if any.\n if (opt_ancestorsTree) {\n for (var i = opt_ancestorsTree.length - 1;\n !e.hasPropagationStopped() && i >= 0; i--) {\n currentTarget = e.currentTarget = opt_ancestorsTree[i];\n rv = currentTarget.fireListeners(type, true, e) && rv;\n }\n }\n\n // Executes capture and bubble listeners on the target.\n if (!e.hasPropagationStopped()) {\n currentTarget = /** @type {?} */ (e.currentTarget = target);\n rv = currentTarget.fireListeners(type, true, e) && rv;\n if (!e.hasPropagationStopped()) {\n rv = currentTarget.fireListeners(type, false, e) && rv;\n }\n }\n\n // Executes all bubble listeners on the ancestors, if any.\n if (opt_ancestorsTree) {\n for (i = 0; !e.hasPropagationStopped() && i < opt_ancestorsTree.length;\n i++) {\n currentTarget = e.currentTarget = opt_ancestorsTree[i];\n rv = currentTarget.fireListeners(type, false, e) && rv;\n }\n }\n\n return rv;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview JSON utility functions.\n */\n\n\ngoog.provide('goog.json');\ngoog.provide('goog.json.Replacer');\ngoog.provide('goog.json.Reviver');\ngoog.provide('goog.json.Serializer');\n\n\n/**\n * @define {boolean} If true, use the native JSON parsing API.\n * NOTE: The default `goog.json.parse` implementation is able to handle\n * invalid JSON. JSPB used to produce invalid JSON which is not the case\n * anymore so this is safe to enable for parsing JSPB. Using native JSON is\n * faster and safer than the default implementation using `eval`.\n */\ngoog.json.USE_NATIVE_JSON = goog.define('goog.json.USE_NATIVE_JSON', false);\n\n\n/**\n * Tests if a string is an invalid JSON string. This only ensures that we are\n * not using any invalid characters\n * @param {string} s The string to test.\n * @return {boolean} True if the input is a valid JSON string.\n */\ngoog.json.isValid = function(s) {\n 'use strict';\n // All empty whitespace is not valid.\n if (/^\\s*$/.test(s)) {\n return false;\n }\n\n // This is taken from http://www.json.org/json2.js which is released to the\n // public domain.\n // Changes: We dissallow \\u2028 Line separator and \\u2029 Paragraph separator\n // inside strings. We also treat \\u2028 and \\u2029 as whitespace which they\n // are in the RFC but IE and Safari does not match \\s to these so we need to\n // include them in the reg exps in all places where whitespace is allowed.\n // We allowed \\x7f inside strings because some tools don't escape it,\n // e.g. http://www.json.org/java/org/json/JSONObject.java\n\n // Parsing happens in three stages. In the first stage, we run the text\n // against regular expressions that look for non-JSON patterns. We are\n // especially concerned with '()' and 'new' because they can cause invocation,\n // and '=' because it can cause mutation. But just to be safe, we want to\n // reject all unexpected forms.\n\n // We split the first stage into 4 regexp operations in order to work around\n // crippling inefficiencies in IE's and Safari's regexp engines. First we\n // replace all backslash pairs with '@' (a non-JSON character). Second, we\n // replace all simple value tokens with ']' characters, but only when followed\n // by a colon, comma, closing bracket or end of string. Third, we delete all\n // open brackets that follow a colon or comma or that begin the text. Finally,\n // we look to see that the remaining characters are only whitespace or ']' or\n // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.\n\n // Don't make these static since they have the global flag.\n const backslashesRe = /\\\\[\"\\\\\\/bfnrtu]/g;\n const simpleValuesRe =\n /(?:\"[^\"\\\\\\n\\r\\u2028\\u2029\\x00-\\x08\\x0a-\\x1f]*\"|true|false|null|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)[\\s\\u2028\\u2029]*(?=:|,|]|}|$)/g;\n const openBracketsRe = /(?:^|:|,)(?:[\\s\\u2028\\u2029]*\\[)+/g;\n const remainderRe = /^[\\],:{}\\s\\u2028\\u2029]*$/;\n\n return remainderRe.test(\n s.replace(backslashesRe, '@')\n .replace(simpleValuesRe, ']')\n .replace(openBracketsRe, ''));\n};\n\n/**\n * Logs a parsing error in `JSON.parse` solvable by using `eval`.\n * @private {function(string, !Error)} The first parameter is the error message,\n * the second is the exception thrown by `JSON.parse`.\n */\ngoog.json.errorLogger_ = () => {};\n\n\n/**\n * Sets an error logger to use if there's a recoverable parsing error.\n * @param {function(string, !Error)} errorLogger The first parameter is the\n * error message, the second is the exception thrown by `JSON.parse`.\n */\ngoog.json.setErrorLogger = function(errorLogger) {\n 'use strict';\n goog.json.errorLogger_ = errorLogger;\n};\n\n\n/**\n * Parses a JSON string and returns the result. This throws an exception if\n * the string is an invalid JSON string.\n *\n * Note that this is very slow on large strings. Use JSON.parse if possible.\n *\n * @param {*} s The JSON string to parse.\n * @throws Error if s is invalid JSON.\n * @return {Object} The object generated from the JSON string, or null.\n * @deprecated Use JSON.parse.\n */\ngoog.json.parse = goog.json.USE_NATIVE_JSON ?\n /** @type {function(*):Object} */ (goog.global['JSON']['parse']) :\n function(s) {\n 'use strict';\n let error;\n try {\n return goog.global['JSON']['parse'](s);\n } catch (ex) {\n error = ex;\n }\n const o = String(s);\n if (goog.json.isValid(o)) {\n\n try {\n const result = /** @type {?Object} */ (eval('(' + o + ')'));\n if (error) {\n goog.json.errorLogger_('Invalid JSON: ' + o, error);\n }\n return result;\n } catch (ex) {\n }\n }\n throw new Error('Invalid JSON string: ' + o);\n };\n\n\n/**\n * JSON replacer, as defined in Section 15.12.3 of the ES5 spec.\n * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3\n *\n * TODO(nicksantos): Array should also be a valid replacer.\n *\n * @typedef {function(this:Object, string, *): *}\n */\ngoog.json.Replacer;\n\n\n/**\n * JSON reviver, as defined in Section 15.12.2 of the ES5 spec.\n * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3\n *\n * @typedef {function(this:Object, string, *): *}\n */\ngoog.json.Reviver;\n\n\n/**\n * Serializes an object or a value to a JSON string.\n *\n * @param {*} object The object to serialize.\n * @param {?goog.json.Replacer=} opt_replacer A replacer function\n * called for each (key, value) pair that determines how the value\n * should be serialized. By defult, this just returns the value\n * and allows default serialization to kick in.\n * @throws Error if there are loops in the object graph.\n * @return {string} A JSON string representation of the input.\n */\ngoog.json.serialize = goog.json.USE_NATIVE_JSON ?\n /** @type {function(*, ?goog.json.Replacer=):string} */\n (goog.global['JSON']['stringify']) :\n function(object, opt_replacer) {\n 'use strict';\n // NOTE(nicksantos): Currently, we never use JSON.stringify.\n //\n // The last time I evaluated this, JSON.stringify had subtle bugs and\n // behavior differences on all browsers, and the performance win was not\n // large enough to justify all the issues. This may change in the future\n // as browser implementations get better.\n //\n // assertSerialize in json_test contains if branches for the cases\n // that fail.\n return new goog.json.Serializer(opt_replacer).serialize(object);\n };\n\n\n\n/**\n * Class that is used to serialize JSON objects to a string.\n * @param {?goog.json.Replacer=} opt_replacer Replacer.\n * @constructor\n */\ngoog.json.Serializer = function(opt_replacer) {\n 'use strict';\n /**\n * @type {goog.json.Replacer|null|undefined}\n * @private\n */\n this.replacer_ = opt_replacer;\n};\n\n\n/**\n * Serializes an object or a value to a JSON string.\n *\n * @param {*} object The object to serialize.\n * @throws Error if there are loops in the object graph.\n * @return {string} A JSON string representation of the input.\n */\ngoog.json.Serializer.prototype.serialize = function(object) {\n 'use strict';\n const sb = [];\n this.serializeInternal(object, sb);\n return sb.join('');\n};\n\n\n/**\n * Serializes a generic value to a JSON string\n * @protected\n * @param {*} object The object to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n * @throws Error if there are loops in the object graph.\n */\ngoog.json.Serializer.prototype.serializeInternal = function(object, sb) {\n 'use strict';\n if (object == null) {\n // undefined == null so this branch covers undefined as well as null\n sb.push('null');\n return;\n }\n\n if (typeof object == 'object') {\n if (Array.isArray(object)) {\n this.serializeArray(object, sb);\n return;\n } else if (\n object instanceof String || object instanceof Number ||\n object instanceof Boolean) {\n object = object.valueOf();\n // Fall through to switch below.\n } else {\n this.serializeObject_(/** @type {!Object} */ (object), sb);\n return;\n }\n }\n\n switch (typeof object) {\n case 'string':\n this.serializeString_(object, sb);\n break;\n case 'number':\n this.serializeNumber_(object, sb);\n break;\n case 'boolean':\n sb.push(String(object));\n break;\n case 'function':\n sb.push('null');\n break;\n default:\n throw new Error('Unknown type: ' + typeof object);\n }\n};\n\n\n/**\n * Character mappings used internally for goog.string.quote\n * @private\n * @type {!Object}\n */\ngoog.json.Serializer.charToJsonCharCache_ = {\n '\\\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n '/': '\\\\/',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n\n '\\x0B': '\\\\u000b' // '\\v' is not supported in JScript\n};\n\n\n/**\n * Regular expression used to match characters that need to be replaced.\n * The S60 browser has a bug where unicode characters are not matched by\n * regular expressions. The condition below detects such behaviour and\n * adjusts the regular expression accordingly.\n * @private\n * @type {!RegExp}\n */\ngoog.json.Serializer.charsToReplace_ = /\\uffff/.test('\\uffff') ?\n /[\\\\\\\"\\x00-\\x1f\\x7f-\\uffff]/g :\n /[\\\\\\\"\\x00-\\x1f\\x7f-\\xff]/g;\n\n\n/**\n * Serializes a string to a JSON string\n * @private\n * @param {string} s The string to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n */\ngoog.json.Serializer.prototype.serializeString_ = function(s, sb) {\n 'use strict';\n // The official JSON implementation does not work with international\n // characters.\n sb.push('\"', s.replace(goog.json.Serializer.charsToReplace_, function(c) {\n 'use strict';\n // caching the result improves performance by a factor 2-3\n let rv = goog.json.Serializer.charToJsonCharCache_[c];\n if (!rv) {\n rv = '\\\\u' + (c.charCodeAt(0) | 0x10000).toString(16).slice(1);\n goog.json.Serializer.charToJsonCharCache_[c] = rv;\n }\n return rv;\n }), '\"');\n};\n\n\n/**\n * Serializes a number to a JSON string\n * @private\n * @param {number} n The number to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n */\ngoog.json.Serializer.prototype.serializeNumber_ = function(n, sb) {\n 'use strict';\n sb.push(isFinite(n) && !isNaN(n) ? String(n) : 'null');\n};\n\n\n/**\n * Serializes an array to a JSON string\n * @param {Array<string>} arr The array to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n * @protected\n */\ngoog.json.Serializer.prototype.serializeArray = function(arr, sb) {\n 'use strict';\n const l = arr.length;\n sb.push('[');\n let sep = '';\n for (let i = 0; i < l; i++) {\n sb.push(sep);\n\n const value = arr[i];\n this.serializeInternal(\n this.replacer_ ? this.replacer_.call(arr, String(i), value) : value,\n sb);\n\n sep = ',';\n }\n sb.push(']');\n};\n\n\n/**\n * Serializes an object to a JSON string\n * @private\n * @param {!Object} obj The object to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n */\ngoog.json.Serializer.prototype.serializeObject_ = function(obj, sb) {\n 'use strict';\n sb.push('{');\n let sep = '';\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = obj[key];\n // Skip functions.\n if (typeof value != 'function') {\n sb.push(sep);\n this.serializeString_(key, sb);\n sb.push(':');\n\n this.serializeInternal(\n this.replacer_ ? this.replacer_.call(obj, key, value) : value, sb);\n\n sep = ',';\n }\n }\n }\n sb.push('}');\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.module('goog.async.WorkQueue');\ngoog.module.declareLegacyNamespace();\n\nconst FreeList = goog.require('goog.async.FreeList');\nconst {assert} = goog.require('goog.asserts');\n\n// TODO(johnlenz): generalize the WorkQueue if this is used by more\n// than goog.async.run.\n\n\n/**\n * A low GC workqueue. The key elements of this design:\n * - avoids the need for goog.bind or equivalent by carrying scope\n * - avoids the need for array reallocation by using a linked list\n * - minimizes work entry objects allocation by recycling objects\n * @final\n * @struct\n */\nclass WorkQueue {\n constructor() {\n this.workHead_ = null;\n this.workTail_ = null;\n }\n\n /**\n * @param {function()} fn\n * @param {Object|null|undefined} scope\n */\n add(fn, scope) {\n const item = this.getUnusedItem_();\n item.set(fn, scope);\n\n if (this.workTail_) {\n this.workTail_.next = item;\n this.workTail_ = item;\n } else {\n assert(!this.workHead_);\n this.workHead_ = item;\n this.workTail_ = item;\n }\n }\n\n /**\n * @return {?WorkItem}\n */\n remove() {\n let item = null;\n\n if (this.workHead_) {\n item = this.workHead_;\n this.workHead_ = this.workHead_.next;\n if (!this.workHead_) {\n this.workTail_ = null;\n }\n item.next = null;\n }\n return item;\n }\n\n /**\n * @param {!WorkItem} item\n */\n returnUnused(item) {\n WorkQueue.freelist_.put(item);\n }\n\n /**\n * @return {!WorkItem}\n * @private\n */\n getUnusedItem_() {\n return WorkQueue.freelist_.get();\n }\n}\n\n/** @define {number} The maximum number of entries to keep for recycling. */\nWorkQueue.DEFAULT_MAX_UNUSED =\n goog.define('goog.async.WorkQueue.DEFAULT_MAX_UNUSED', 100);\n\n/** @const @private {!FreeList<!WorkItem>} */\nWorkQueue.freelist_ = new FreeList(\n () => new WorkItem(), item => item.reset(), WorkQueue.DEFAULT_MAX_UNUSED);\n\n/**\n * @final\n * @struct\n */\nclass WorkItem {\n constructor() {\n /** @type {?function()} */\n this.fn = null;\n /** @type {?Object|null|undefined} */\n this.scope = null;\n /** @type {?WorkItem} */\n this.next = null;\n }\n\n /**\n * @param {function()} fn\n * @param {Object|null|undefined} scope\n */\n set(fn, scope) {\n this.fn = fn;\n this.scope = scope;\n this.next = null;\n }\n\n /** Reset the work item so they don't prevent GC before reuse */\n reset() {\n this.fn = null;\n this.scope = null;\n this.next = null;\n }\n}\n\nexports = WorkQueue;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\ngoog.module('goog.async.run');\ngoog.module.declareLegacyNamespace();\n\nconst WorkQueue = goog.require('goog.async.WorkQueue');\nconst asyncStackTag = goog.require('goog.debug.asyncStackTag');\nconst nextTick = goog.require('goog.async.nextTick');\nconst throwException = goog.require('goog.async.throwException');\n\n/**\n * @define {boolean} If true, use the global Promise to implement run\n * assuming either the native, or polyfill version will be used. Does still\n * permit tests to use forceNextTick.\n */\ngoog.ASSUME_NATIVE_PROMISE = goog.define('goog.ASSUME_NATIVE_PROMISE', false);\n\n/**\n * The function used to schedule work asynchronousely.\n * @private {function()}\n */\nlet schedule;\n\n/** @private {boolean} */\nlet workQueueScheduled = false;\n\n/** @type {!WorkQueue} */\nlet workQueue = new WorkQueue();\n\n/**\n * Fires the provided callback just before the current callstack unwinds, or as\n * soon as possible after the current JS execution context.\n * @param {function(this:THIS)} callback\n * @param {THIS=} context Object to use as the \"this value\" when calling the\n * provided function.\n * @template THIS\n */\nlet run = (callback, context = undefined) => {\n if (!schedule) {\n initializeRunner();\n }\n if (!workQueueScheduled) {\n // Nothing is currently scheduled, schedule it now.\n schedule();\n workQueueScheduled = true;\n }\n callback = asyncStackTag.wrap(callback, 'goog.async.run');\n\n workQueue.add(callback, context);\n};\n\n/** Initializes the function to use to process the work queue. */\nlet initializeRunner = () => {\n if (goog.ASSUME_NATIVE_PROMISE ||\n (goog.global.Promise && goog.global.Promise.resolve)) {\n // Use goog.global.Promise instead of just Promise because the relevant\n // externs may be missing, and don't alias it because this could confuse the\n // compiler into thinking the polyfill is required when it should be treated\n // as optional.\n const promise = goog.global.Promise.resolve(undefined);\n schedule = () => {\n promise.then(run.processWorkQueue);\n };\n } else {\n schedule = () => {\n nextTick(run.processWorkQueue);\n };\n }\n};\n\n/**\n * Forces run to use nextTick instead of Promise.\n * This should only be done in unit tests. It's useful because MockClock\n * replaces nextTick, but not the browser Promise implementation, so it allows\n * Promise-based code to be tested with MockClock.\n * However, we also want to run promises if the MockClock is no longer in\n * control so we schedule a backup \"setTimeout\" to the unmocked timeout if\n * provided.\n * @param {function(function())=} realSetTimeout\n */\nrun.forceNextTick = (realSetTimeout = undefined) => {\n schedule = () => {\n nextTick(run.processWorkQueue);\n if (realSetTimeout) {\n realSetTimeout(run.processWorkQueue);\n }\n };\n};\n\nif (goog.DEBUG) {\n /** Reset the work queue. Only available for tests in debug mode. */\n run.resetQueue = () => {\n workQueueScheduled = false;\n workQueue = new WorkQueue();\n };\n\n /** Resets the scheduler. Only available for tests in debug mode. */\n run.resetSchedulerForTest = () => {\n initializeRunner();\n };\n}\n\n/**\n * Run any pending run work items. This function is not intended\n * for general use, but for use by entry point handlers to run items ahead of\n * nextTick.\n */\nrun.processWorkQueue = () => {\n // NOTE: additional work queue items may be added while processing.\n let item = null;\n while (item = workQueue.remove()) {\n try {\n item.fn.call(item.scope);\n } catch (e) {\n throwException(e);\n }\n workQueue.returnUnused(item);\n }\n\n // There are no more work items, allow processing to be scheduled again.\n workQueueScheduled = false;\n};\n\nexports = run;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Simple freelist.\n *\n * An anterative to goog.structs.SimplePool, it imposes the requirement that the\n * objects in the list contain a \"next\" property that can be used to maintain\n * the pool.\n */\ngoog.module('goog.async.FreeList');\ngoog.module.declareLegacyNamespace();\n\n/** @template ITEM */\nclass FreeList {\n /**\n * @param {function():ITEM} create\n * @param {function(ITEM):void} reset\n * @param {number} limit\n */\n constructor(create, reset, limit) {\n /** @private @const {number} */\n this.limit_ = limit;\n /** @private @const {function()} */\n this.create_ = create;\n /** @private @const {function(ITEM):void} */\n this.reset_ = reset;\n\n /** @private {number} */\n this.occupants_ = 0;\n /** @private {ITEM} */\n this.head_ = null;\n }\n\n /** @return {ITEM} */\n get() {\n let item;\n if (this.occupants_ > 0) {\n this.occupants_--;\n item = this.head_;\n this.head_ = item.next;\n item.next = null;\n } else {\n item = this.create_();\n }\n return item;\n }\n\n /** @param {ITEM} item An item available for possible future reuse. */\n put(item) {\n this.reset_(item);\n if (this.occupants_ < this.limit_) {\n this.occupants_++;\n item.next = this.head_;\n this.head_ = item;\n }\n }\n\n /**\n * Visible for testing.\n * @return {number}\n * @package\n */\n occupants() {\n return this.occupants_;\n }\n}\n\nexports = FreeList;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for string manipulation.\n */\n\n\n/**\n * Namespace for string utilities\n */\ngoog.provide('goog.string');\ngoog.provide('goog.string.Unicode');\n\ngoog.require('goog.dom.safe');\ngoog.require('goog.html.uncheckedconversions');\ngoog.require('goog.string.Const');\ngoog.require('goog.string.internal');\n\n\n/**\n * @define {boolean} Enables HTML escaping of lowercase letter \"e\" which helps\n * with detection of double-escaping as this letter is frequently used.\n */\ngoog.string.DETECT_DOUBLE_ESCAPING =\n goog.define('goog.string.DETECT_DOUBLE_ESCAPING', false);\n\n\n/**\n * @define {boolean} Whether to force non-dom html unescaping.\n */\ngoog.string.FORCE_NON_DOM_HTML_UNESCAPING =\n goog.define('goog.string.FORCE_NON_DOM_HTML_UNESCAPING', false);\n\n\n/**\n * Common Unicode string characters.\n * @enum {string}\n */\ngoog.string.Unicode = {\n NBSP: '\\xa0',\n ZERO_WIDTH_SPACE: '\\u200b' // This is equivalent to <wbr>.\n};\n\n\n/**\n * Fast prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the start of `str`.\n * @return {boolean} True if `str` begins with `prefix`.\n */\ngoog.string.startsWith = goog.string.internal.startsWith;\n\n\n/**\n * Fast suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix`.\n */\ngoog.string.endsWith = goog.string.internal.endsWith;\n\n\n/**\n * Case-insensitive prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the end of `str`.\n * @return {boolean} True if `str` begins with `prefix` (ignoring\n * case).\n */\ngoog.string.caseInsensitiveStartsWith =\n goog.string.internal.caseInsensitiveStartsWith;\n\n\n/**\n * Case-insensitive suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix` (ignoring\n * case).\n */\ngoog.string.caseInsensitiveEndsWith =\n goog.string.internal.caseInsensitiveEndsWith;\n\n\n/**\n * Case-insensitive equality checker.\n * @param {string} str1 First string to check.\n * @param {string} str2 Second string to check.\n * @return {boolean} True if `str1` and `str2` are the same string,\n * ignoring case.\n */\ngoog.string.caseInsensitiveEquals = goog.string.internal.caseInsensitiveEquals;\n\n\n/**\n * Does simple python-style string substitution.\n * subs(\"foo%s hot%s\", \"bar\", \"dog\") becomes \"foobar hotdog\".\n * @param {string} str The string containing the pattern.\n * @param {...*} var_args The items to substitute into the pattern.\n * @return {string} A copy of `str` in which each occurrence of\n * {@code %s} has been replaced an argument from `var_args`.\n */\ngoog.string.subs = function(str, var_args) {\n 'use strict';\n const splitParts = str.split('%s');\n let returnString = '';\n\n const subsArguments = Array.prototype.slice.call(arguments, 1);\n while (subsArguments.length &&\n // Replace up to the last split part. We are inserting in the\n // positions between split parts.\n splitParts.length > 1) {\n returnString += splitParts.shift() + subsArguments.shift();\n }\n\n return returnString + splitParts.join('%s'); // Join unused '%s'\n};\n\n\n/**\n * Converts multiple whitespace chars (spaces, non-breaking-spaces, new lines\n * and tabs) to a single space, and strips leading and trailing whitespace.\n * @param {string} str Input string.\n * @return {string} A copy of `str` with collapsed whitespace.\n */\ngoog.string.collapseWhitespace = function(str) {\n 'use strict';\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return str.replace(/[\\s\\xa0]+/g, ' ').replace(/^\\s+|\\s+$/g, '');\n};\n\n\n/**\n * Checks if a string is empty or contains only whitespaces.\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty or whitespace only.\n */\ngoog.string.isEmptyOrWhitespace = goog.string.internal.isEmptyOrWhitespace;\n\n\n/**\n * Checks if a string is empty.\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty.\n */\ngoog.string.isEmptyString = function(str) {\n 'use strict';\n return str.length == 0;\n};\n\n\n/**\n * Checks if a string is empty or contains only whitespaces.\n *\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty or whitespace only.\n * @deprecated Use goog.string.isEmptyOrWhitespace instead.\n */\ngoog.string.isEmpty = goog.string.isEmptyOrWhitespace;\n\n\n/**\n * Checks if a string is null, undefined, empty or contains only whitespaces.\n * @param {*} str The string to check.\n * @return {boolean} Whether `str` is null, undefined, empty, or\n * whitespace only.\n * @deprecated Use goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str))\n * instead.\n */\ngoog.string.isEmptyOrWhitespaceSafe = function(str) {\n 'use strict';\n return goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str));\n};\n\n\n/**\n * Checks if a string is null, undefined, empty or contains only whitespaces.\n *\n * @param {*} str The string to check.\n * @return {boolean} Whether `str` is null, undefined, empty, or\n * whitespace only.\n * @deprecated Use goog.string.isEmptyOrWhitespace instead.\n */\ngoog.string.isEmptySafe = goog.string.isEmptyOrWhitespaceSafe;\n\n\n/**\n * Checks if a string is all breaking whitespace.\n * @param {string} str The string to check.\n * @return {boolean} Whether the string is all breaking whitespace.\n */\ngoog.string.isBreakingWhitespace = function(str) {\n 'use strict';\n return !/[^\\t\\n\\r ]/.test(str);\n};\n\n\n/**\n * Checks if a string contains all letters.\n * @param {string} str string to check.\n * @return {boolean} True if `str` consists entirely of letters.\n */\ngoog.string.isAlpha = function(str) {\n 'use strict';\n return !/[^a-zA-Z]/.test(str);\n};\n\n\n/**\n * Checks if a string contains only numbers.\n * @param {*} str string to check. If not a string, it will be\n * casted to one.\n * @return {boolean} True if `str` is numeric.\n */\ngoog.string.isNumeric = function(str) {\n 'use strict';\n return !/[^0-9]/.test(str);\n};\n\n\n/**\n * Checks if a string contains only numbers or letters.\n * @param {string} str string to check.\n * @return {boolean} True if `str` is alphanumeric.\n */\ngoog.string.isAlphaNumeric = function(str) {\n 'use strict';\n return !/[^a-zA-Z0-9]/.test(str);\n};\n\n\n/**\n * Checks if a character is a space character.\n * @param {string} ch Character to check.\n * @return {boolean} True if `ch` is a space.\n */\ngoog.string.isSpace = function(ch) {\n 'use strict';\n return ch == ' ';\n};\n\n\n/**\n * Checks if a character is a valid unicode character.\n * @param {string} ch Character to check.\n * @return {boolean} True if `ch` is a valid unicode character.\n */\ngoog.string.isUnicodeChar = function(ch) {\n 'use strict';\n return ch.length == 1 && ch >= ' ' && ch <= '~' ||\n ch >= '\\u0080' && ch <= '\\uFFFD';\n};\n\n\n/**\n * Takes a string and replaces newlines with a space. Multiple lines are\n * replaced with a single space.\n * @param {string} str The string from which to strip newlines.\n * @return {string} A copy of `str` stripped of newlines.\n */\ngoog.string.stripNewlines = function(str) {\n 'use strict';\n return str.replace(/(\\r\\n|\\r|\\n)+/g, ' ');\n};\n\n\n/**\n * Replaces Windows and Mac new lines with unix style: \\r or \\r\\n with \\n.\n * @param {string} str The string to in which to canonicalize newlines.\n * @return {string} `str` A copy of {@code} with canonicalized newlines.\n */\ngoog.string.canonicalizeNewlines = function(str) {\n 'use strict';\n return str.replace(/(\\r\\n|\\r|\\n)/g, '\\n');\n};\n\n\n/**\n * Normalizes whitespace in a string, replacing all whitespace chars with\n * a space.\n * @param {string} str The string in which to normalize whitespace.\n * @return {string} A copy of `str` with all whitespace normalized.\n */\ngoog.string.normalizeWhitespace = function(str) {\n 'use strict';\n return str.replace(/\\xa0|\\s/g, ' ');\n};\n\n\n/**\n * Normalizes spaces in a string, replacing all consecutive spaces and tabs\n * with a single space. Replaces non-breaking space with a space.\n * @param {string} str The string in which to normalize spaces.\n * @return {string} A copy of `str` with all consecutive spaces and tabs\n * replaced with a single space.\n */\ngoog.string.normalizeSpaces = function(str) {\n 'use strict';\n return str.replace(/\\xa0|[ \\t]+/g, ' ');\n};\n\n\n/**\n * Removes the breaking spaces from the left and right of the string and\n * collapses the sequences of breaking spaces in the middle into single spaces.\n * The original and the result strings render the same way in HTML.\n * @param {string} str A string in which to collapse spaces.\n * @return {string} Copy of the string with normalized breaking spaces.\n */\ngoog.string.collapseBreakingSpaces = function(str) {\n 'use strict';\n return str.replace(/[\\t\\r\\n ]+/g, ' ')\n .replace(/^[\\t\\r\\n ]+|[\\t\\r\\n ]+$/g, '');\n};\n\n\n/**\n * Trims white spaces to the left and right of a string.\n * @param {string} str The string to trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.trim = goog.string.internal.trim;\n\n\n/**\n * Trims whitespaces at the left end of a string.\n * @param {string} str The string to left trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.trimLeft = function(str) {\n 'use strict';\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return str.replace(/^[\\s\\xa0]+/, '');\n};\n\n\n/**\n * Trims whitespaces at the right end of a string.\n * @param {string} str The string to right trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.trimRight = function(str) {\n 'use strict';\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return str.replace(/[\\s\\xa0]+$/, '');\n};\n\n\n/**\n * A string comparator that ignores case.\n * -1 = str1 less than str2\n * 0 = str1 equals str2\n * 1 = str1 greater than str2\n *\n * @param {string} str1 The string to compare.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} The comparator result, as described above.\n */\ngoog.string.caseInsensitiveCompare =\n goog.string.internal.caseInsensitiveCompare;\n\n\n/**\n * Compares two strings interpreting their numeric substrings as numbers.\n *\n * @param {string} str1 First string.\n * @param {string} str2 Second string.\n * @param {!RegExp} tokenizerRegExp Splits a string into substrings of\n * non-negative integers, non-numeric characters and optionally fractional\n * numbers starting with a decimal point.\n * @return {number} Negative if str1 < str2, 0 is str1 == str2, positive if\n * str1 > str2.\n * @private\n */\ngoog.string.numberAwareCompare_ = function(str1, str2, tokenizerRegExp) {\n 'use strict';\n if (str1 == str2) {\n return 0;\n }\n if (!str1) {\n return -1;\n }\n if (!str2) {\n return 1;\n }\n\n // Using match to split the entire string ahead of time turns out to be faster\n // for most inputs than using RegExp.exec or iterating over each character.\n const tokens1 = str1.toLowerCase().match(tokenizerRegExp);\n const tokens2 = str2.toLowerCase().match(tokenizerRegExp);\n\n const count = Math.min(tokens1.length, tokens2.length);\n\n for (let i = 0; i < count; i++) {\n const a = tokens1[i];\n const b = tokens2[i];\n\n // Compare pairs of tokens, returning if one token sorts before the other.\n if (a != b) {\n // Only if both tokens are integers is a special comparison required.\n // Decimal numbers are sorted as strings (e.g., '.09' < '.1').\n const num1 = parseInt(a, 10);\n if (!isNaN(num1)) {\n const num2 = parseInt(b, 10);\n if (!isNaN(num2) && num1 - num2) {\n return num1 - num2;\n }\n }\n return a < b ? -1 : 1;\n }\n }\n\n // If one string is a substring of the other, the shorter string sorts first.\n if (tokens1.length != tokens2.length) {\n return tokens1.length - tokens2.length;\n }\n\n // The two strings must be equivalent except for case (perfect equality is\n // tested at the head of the function.) Revert to default ASCII string\n // comparison to stabilize the sort.\n return str1 < str2 ? -1 : 1;\n};\n\n\n/**\n * String comparison function that handles non-negative integer numbers in a\n * way humans might expect. Using this function, the string 'File 2.jpg' sorts\n * before 'File 10.jpg', and 'Version 1.9' before 'Version 1.10'. The comparison\n * is mostly case-insensitive, though strings that are identical except for case\n * are sorted with the upper-case strings before lower-case.\n *\n * This comparison function is up to 50x slower than either the default or the\n * case-insensitive compare. It should not be used in time-critical code, but\n * should be fast enough to sort several hundred short strings (like filenames)\n * with a reasonable delay.\n *\n * @param {string} str1 The string to compare in a numerically sensitive way.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than\n * 0 if str1 > str2.\n */\ngoog.string.intAwareCompare = function(str1, str2) {\n 'use strict';\n return goog.string.numberAwareCompare_(str1, str2, /\\d+|\\D+/g);\n};\n\n\n/**\n * String comparison function that handles non-negative integer and fractional\n * numbers in a way humans might expect. Using this function, the string\n * 'File 2.jpg' sorts before 'File 10.jpg', and '3.14' before '3.2'. Equivalent\n * to {@link goog.string.intAwareCompare} apart from the way how it interprets\n * dots.\n *\n * @param {string} str1 The string to compare in a numerically sensitive way.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than\n * 0 if str1 > str2.\n */\ngoog.string.floatAwareCompare = function(str1, str2) {\n 'use strict';\n return goog.string.numberAwareCompare_(str1, str2, /\\d+|\\.\\d+|\\D+/g);\n};\n\n\n/**\n * Alias for {@link goog.string.floatAwareCompare}.\n *\n * @param {string} str1\n * @param {string} str2\n * @return {number}\n */\ngoog.string.numerateCompare = goog.string.floatAwareCompare;\n\n\n/**\n * URL-encodes a string\n * @param {*} str The string to url-encode.\n * @return {string} An encoded copy of `str` that is safe for urls.\n * Note that '#', ':', and other characters used to delimit portions\n * of URLs *will* be encoded.\n */\ngoog.string.urlEncode = function(str) {\n 'use strict';\n return encodeURIComponent(String(str));\n};\n\n\n/**\n * URL-decodes the string. We need to specially handle '+'s because\n * the javascript library doesn't convert them to spaces.\n * @param {string} str The string to url decode.\n * @return {string} The decoded `str`.\n */\ngoog.string.urlDecode = function(str) {\n 'use strict';\n return decodeURIComponent(str.replace(/\\+/g, ' '));\n};\n\n\n/**\n * Converts \\n to <br>s or <br />s.\n * @param {string} str The string in which to convert newlines.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} A copy of `str` with converted newlines.\n */\ngoog.string.newLineToBr = goog.string.internal.newLineToBr;\n\n\n/**\n * Escapes double quote '\"' and single quote '\\'' characters in addition to\n * '&', '<', and '>' so that a string can be included in an HTML tag attribute\n * value within double or single quotes.\n *\n * It should be noted that > doesn't need to be escaped for the HTML or XML to\n * be valid, but it has been decided to escape it for consistency with other\n * implementations.\n *\n * With goog.string.DETECT_DOUBLE_ESCAPING, this function escapes also the\n * lowercase letter \"e\".\n *\n * NOTE(user):\n * HtmlEscape is often called during the generation of large blocks of HTML.\n * Using statics for the regular expressions and strings is an optimization\n * that can more than half the amount of time IE spends in this function for\n * large apps, since strings and regexes both contribute to GC allocations.\n *\n * Testing for the presence of a character before escaping increases the number\n * of function calls, but actually provides a speed increase for the average\n * case -- since the average case often doesn't require the escaping of all 4\n * characters and indexOf() is much cheaper than replace().\n * The worst case does suffer slightly from the additional calls, therefore the\n * opt_isLikelyToContainHtmlChars option has been included for situations\n * where all 4 HTML entities are very likely to be present and need escaping.\n *\n * Some benchmarks (times tended to fluctuate +-0.05ms):\n * FireFox IE6\n * (no chars / average (mix of cases) / all 4 chars)\n * no checks 0.13 / 0.22 / 0.22 0.23 / 0.53 / 0.80\n * indexOf 0.08 / 0.17 / 0.26 0.22 / 0.54 / 0.84\n * indexOf + re test 0.07 / 0.17 / 0.28 0.19 / 0.50 / 0.85\n *\n * An additional advantage of checking if replace actually needs to be called\n * is a reduction in the number of object allocations, so as the size of the\n * application grows the difference between the various methods would increase.\n *\n * @param {string} str string to be escaped.\n * @param {boolean=} opt_isLikelyToContainHtmlChars Don't perform a check to see\n * if the character needs replacing - use this option if you expect each of\n * the characters to appear often. Leave false if you expect few html\n * characters to occur in your strings, such as if you are escaping HTML.\n * @return {string} An escaped copy of `str`.\n */\ngoog.string.htmlEscape = function(str, opt_isLikelyToContainHtmlChars) {\n 'use strict';\n str = goog.string.internal.htmlEscape(str, opt_isLikelyToContainHtmlChars);\n if (goog.string.DETECT_DOUBLE_ESCAPING) {\n str = str.replace(goog.string.E_RE_, 'e');\n }\n return str;\n};\n\n\n/**\n * Regular expression that matches a lowercase letter \"e\", for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.E_RE_ = /e/g;\n\n\n/**\n * Unescapes an HTML string.\n *\n * @param {string} str The string to unescape.\n * @return {string} An unescaped copy of `str`.\n */\ngoog.string.unescapeEntities = function(str) {\n 'use strict';\n if (goog.string.contains(str, '&')) {\n // We are careful not to use a DOM if we do not have one or we explicitly\n // requested non-DOM html unescaping.\n if (!goog.string.FORCE_NON_DOM_HTML_UNESCAPING &&\n 'document' in goog.global) {\n return goog.string.unescapeEntitiesUsingDom_(str);\n } else {\n // Fall back on pure XML entities\n return goog.string.unescapePureXmlEntities_(str);\n }\n }\n return str;\n};\n\n\n/**\n * Unescapes a HTML string using the provided document.\n *\n * @param {string} str The string to unescape.\n * @param {!Document} document A document to use in escaping the string.\n * @return {string} An unescaped copy of `str`.\n */\ngoog.string.unescapeEntitiesWithDocument = function(str, document) {\n 'use strict';\n if (goog.string.contains(str, '&')) {\n return goog.string.unescapeEntitiesUsingDom_(str, document);\n }\n return str;\n};\n\n\n/**\n * Unescapes an HTML string using a DOM to resolve non-XML, non-numeric\n * entities. This function is XSS-safe and whitespace-preserving.\n * @private\n * @param {string} str The string to unescape.\n * @param {Document=} opt_document An optional document to use for creating\n * elements. If this is not specified then the default window.document\n * will be used.\n * @return {string} The unescaped `str` string.\n */\ngoog.string.unescapeEntitiesUsingDom_ = function(str, opt_document) {\n 'use strict';\n /** @type {!Object<string, string>} */\n const seen = {'&': '&', '<': '<', '>': '>', '"': '\"'};\n /** @type {!Element} */\n let div;\n if (opt_document) {\n div = opt_document.createElement('div');\n } else {\n div = goog.global.document.createElement('div');\n }\n // Match as many valid entity characters as possible. If the actual entity\n // happens to be shorter, it will still work as innerHTML will return the\n // trailing characters unchanged. Since the entity characters do not include\n // open angle bracket, there is no chance of XSS from the innerHTML use.\n // Since no whitespace is passed to innerHTML, whitespace is preserved.\n return str.replace(goog.string.HTML_ENTITY_PATTERN_, function(s, entity) {\n 'use strict';\n // Check for cached entity.\n let value = seen[s];\n if (value) {\n return value;\n }\n // Check for numeric entity.\n if (entity.charAt(0) == '#') {\n // Prefix with 0 so that hex entities (e.g. ) parse as hex numbers.\n const n = Number('0' + entity.slice(1));\n if (!isNaN(n)) {\n value = String.fromCharCode(n);\n }\n }\n // Fall back to innerHTML otherwise.\n if (!value) {\n // Append a non-entity character to avoid a bug in Webkit that parses\n // an invalid entity at the end of innerHTML text as the empty string.\n goog.dom.safe.setInnerHtml(\n div,\n goog.html.uncheckedconversions\n .safeHtmlFromStringKnownToSatisfyTypeContract(\n goog.string.Const.from('Single HTML entity.'), s + ' '));\n // Then remove the trailing character from the result.\n value = div.firstChild.nodeValue.slice(0, -1);\n }\n // Cache and return.\n return seen[s] = value;\n });\n};\n\n\n/**\n * Unescapes XML entities.\n * @private\n * @param {string} str The string to unescape.\n * @return {string} An unescaped copy of `str`.\n */\ngoog.string.unescapePureXmlEntities_ = function(str) {\n 'use strict';\n return str.replace(/&([^;]+);/g, function(s, entity) {\n 'use strict';\n switch (entity) {\n case 'amp':\n return '&';\n case 'lt':\n return '<';\n case 'gt':\n return '>';\n case 'quot':\n return '\"';\n default:\n if (entity.charAt(0) == '#') {\n // Prefix with 0 so that hex entities (e.g. ) parse as hex.\n const n = Number('0' + entity.slice(1));\n if (!isNaN(n)) {\n return String.fromCharCode(n);\n }\n }\n // For invalid entities we just return the entity\n return s;\n }\n });\n};\n\n\n/**\n * Regular expression that matches an HTML entity.\n * See also HTML5: Tokenization / Tokenizing character references.\n * @private\n * @type {!RegExp}\n */\ngoog.string.HTML_ENTITY_PATTERN_ = /&([^;\\s<&]+);?/g;\n\n\n/**\n * Do escaping of whitespace to preserve spatial formatting. We use character\n * entity #160 to make it safer for xml.\n * @param {string} str The string in which to escape whitespace.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} An escaped copy of `str`.\n */\ngoog.string.whitespaceEscape = function(str, opt_xml) {\n 'use strict';\n // This doesn't use goog.string.preserveSpaces for backwards compatibility.\n return goog.string.newLineToBr(str.replace(/ /g, '  '), opt_xml);\n};\n\n\n/**\n * Preserve spaces that would be otherwise collapsed in HTML by replacing them\n * with non-breaking space Unicode characters.\n * @param {string} str The string in which to preserve whitespace.\n * @return {string} A copy of `str` with preserved whitespace.\n */\ngoog.string.preserveSpaces = function(str) {\n 'use strict';\n return str.replace(/(^|[\\n ]) /g, '$1' + goog.string.Unicode.NBSP);\n};\n\n\n/**\n * Strip quote characters around a string. The second argument is a string of\n * characters to treat as quotes. This can be a single character or a string of\n * multiple character and in that case each of those are treated as possible\n * quote characters. For example:\n *\n * <pre>\n * goog.string.stripQuotes('\"abc\"', '\"`') --> 'abc'\n * goog.string.stripQuotes('`abc`', '\"`') --> 'abc'\n * </pre>\n *\n * @param {string} str The string to strip.\n * @param {string} quoteChars The quote characters to strip.\n * @return {string} A copy of `str` without the quotes.\n */\ngoog.string.stripQuotes = function(str, quoteChars) {\n 'use strict';\n const length = quoteChars.length;\n for (let i = 0; i < length; i++) {\n const quoteChar = length == 1 ? quoteChars : quoteChars.charAt(i);\n if (str.charAt(0) == quoteChar && str.charAt(str.length - 1) == quoteChar) {\n return str.substring(1, str.length - 1);\n }\n }\n return str;\n};\n\n\n/**\n * Truncates a string to a certain length and adds '...' if necessary. The\n * length also accounts for the ellipsis, so a maximum length of 10 and a string\n * 'Hello World!' produces 'Hello W...'.\n * @param {string} str The string to truncate.\n * @param {number} chars Max number of characters.\n * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped\n * characters from being cut off in the middle.\n * @return {string} The truncated `str` string.\n */\ngoog.string.truncate = function(str, chars, opt_protectEscapedCharacters) {\n 'use strict';\n if (opt_protectEscapedCharacters) {\n str = goog.string.unescapeEntities(str);\n }\n\n if (str.length > chars) {\n str = str.substring(0, chars - 3) + '...';\n }\n\n if (opt_protectEscapedCharacters) {\n str = goog.string.htmlEscape(str);\n }\n\n return str;\n};\n\n\n/**\n * Truncate a string in the middle, adding \"...\" if necessary,\n * and favoring the beginning of the string.\n * @param {string} str The string to truncate the middle of.\n * @param {number} chars Max number of characters.\n * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped\n * characters from being cutoff in the middle.\n * @param {number=} opt_trailingChars Optional number of trailing characters to\n * leave at the end of the string, instead of truncating as close to the\n * middle as possible.\n * @return {string} A truncated copy of `str`.\n */\ngoog.string.truncateMiddle = function(\n str, chars, opt_protectEscapedCharacters, opt_trailingChars) {\n 'use strict';\n if (opt_protectEscapedCharacters) {\n str = goog.string.unescapeEntities(str);\n }\n\n if (opt_trailingChars && str.length > chars) {\n if (opt_trailingChars > chars) {\n opt_trailingChars = chars;\n }\n const endPoint = str.length - opt_trailingChars;\n const startPoint = chars - opt_trailingChars;\n str = str.substring(0, startPoint) + '...' + str.substring(endPoint);\n } else if (str.length > chars) {\n // Favor the beginning of the string:\n let half = Math.floor(chars / 2);\n const endPos = str.length - half;\n half += chars % 2;\n str = str.substring(0, half) + '...' + str.substring(endPos);\n }\n\n if (opt_protectEscapedCharacters) {\n str = goog.string.htmlEscape(str);\n }\n\n return str;\n};\n\n\n/**\n * Special chars that need to be escaped for goog.string.quote.\n * @private {!Object<string, string>}\n */\ngoog.string.specialEscapeChars_ = {\n '\\0': '\\\\0',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n '\\x0B': '\\\\x0B', // '\\v' is not supported in JScript\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n // To support the use case of embedding quoted strings inside of script\n // tags, we have to make sure HTML comments and opening/closing script tags do\n // not appear in the resulting string. The specific strings that must be\n // escaped are documented at:\n // https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements\n '<': '\\\\u003C' // NOTE: JSON.parse crashes on '\\\\x3c'.\n};\n\n\n/**\n * Character mappings used internally for goog.string.escapeChar.\n * @private {!Object<string, string>}\n */\ngoog.string.jsEscapeCache_ = {\n '\\'': '\\\\\\''\n};\n\n\n/**\n * Encloses a string in double quotes and escapes characters so that the\n * string is a valid JS string. The resulting string is safe to embed in\n * `<script>` tags as \"<\" is escaped.\n * @param {string} s The string to quote.\n * @return {string} A copy of `s` surrounded by double quotes.\n */\ngoog.string.quote = function(s) {\n 'use strict';\n s = String(s);\n const sb = ['\"'];\n for (let i = 0; i < s.length; i++) {\n const ch = s.charAt(i);\n const cc = ch.charCodeAt(0);\n sb[i + 1] = goog.string.specialEscapeChars_[ch] ||\n ((cc > 31 && cc < 127) ? ch : goog.string.escapeChar(ch));\n }\n sb.push('\"');\n return sb.join('');\n};\n\n\n/**\n * Takes a string and returns the escaped string for that input string.\n * @param {string} str The string to escape.\n * @return {string} An escaped string representing `str`.\n */\ngoog.string.escapeString = function(str) {\n 'use strict';\n const sb = [];\n for (let i = 0; i < str.length; i++) {\n sb[i] = goog.string.escapeChar(str.charAt(i));\n }\n return sb.join('');\n};\n\n\n/**\n * Takes a character and returns the escaped string for that character. For\n * example escapeChar(String.fromCharCode(15)) -> \"\\\\x0E\".\n * @param {string} c The character to escape.\n * @return {string} An escaped string representing `c`.\n */\ngoog.string.escapeChar = function(c) {\n 'use strict';\n if (c in goog.string.jsEscapeCache_) {\n return goog.string.jsEscapeCache_[c];\n }\n\n if (c in goog.string.specialEscapeChars_) {\n return goog.string.jsEscapeCache_[c] = goog.string.specialEscapeChars_[c];\n }\n\n let rv = c;\n const cc = c.charCodeAt(0);\n if (cc > 31 && cc < 127) {\n rv = c;\n } else {\n // tab is 9 but handled above\n if (cc < 256) {\n rv = '\\\\x';\n if (cc < 16 || cc > 256) {\n rv += '0';\n }\n } else {\n rv = '\\\\u';\n if (cc < 4096) { // \\u1000\n rv += '0';\n }\n }\n rv += cc.toString(16).toUpperCase();\n }\n\n return goog.string.jsEscapeCache_[c] = rv;\n};\n\n\n/**\n * Determines whether a string contains a substring.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n */\ngoog.string.contains = goog.string.internal.contains;\n\n\n/**\n * Determines whether a string contains a substring, ignoring case.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n */\ngoog.string.caseInsensitiveContains =\n goog.string.internal.caseInsensitiveContains;\n\n\n/**\n * Returns the non-overlapping occurrences of ss in s.\n * If either s or ss evalutes to false, then returns zero.\n * @param {string} s The string to look in.\n * @param {string} ss The string to look for.\n * @return {number} Number of occurrences of ss in s.\n */\ngoog.string.countOf = function(s, ss) {\n 'use strict';\n return s && ss ? s.split(ss).length - 1 : 0;\n};\n\n\n/**\n * Removes a substring of a specified length at a specific\n * index in a string.\n * @param {string} s The base string from which to remove.\n * @param {number} index The index at which to remove the substring.\n * @param {number} stringLength The length of the substring to remove.\n * @return {string} A copy of `s` with the substring removed or the full\n * string if nothing is removed or the input is invalid.\n */\ngoog.string.removeAt = function(s, index, stringLength) {\n 'use strict';\n let resultStr = s;\n // If the index is greater or equal to 0 then remove substring\n if (index >= 0 && index < s.length && stringLength > 0) {\n resultStr = s.slice(0, index) + s.slice(index + stringLength);\n }\n return resultStr;\n};\n\n\n/**\n * Removes the first occurrence of a substring from a string.\n * @param {string} str The base string from which to remove.\n * @param {string} substr The string to remove.\n * @return {string} A copy of `str` with `substr` removed or the\n * full string if nothing is removed.\n */\ngoog.string.remove = function(str, substr) {\n 'use strict';\n return str.replace(substr, '');\n};\n\n\n/**\n * Removes all occurrences of a substring from a string.\n * @param {string} s The base string from which to remove.\n * @param {string} ss The string to remove.\n * @return {string} A copy of `s` with `ss` removed or the full\n * string if nothing is removed.\n */\ngoog.string.removeAll = function(s, ss) {\n 'use strict';\n const re = new RegExp(goog.string.regExpEscape(ss), 'g');\n return s.replace(re, '');\n};\n\n\n/**\n * Replaces all occurrences of a substring of a string with a new substring.\n * @param {string} s The base string from which to remove.\n * @param {string} ss The string to replace.\n * @param {string} replacement The replacement string.\n * @return {string} A copy of `s` with `ss` replaced by\n * `replacement` or the original string if nothing is replaced.\n */\ngoog.string.replaceAll = function(s, ss, replacement) {\n 'use strict';\n const re = new RegExp(goog.string.regExpEscape(ss), 'g');\n return s.replace(re, replacement.replace(/\\$/g, '$$$$'));\n};\n\n\n/**\n * Escapes characters in the string that are not safe to use in a RegExp.\n * @param {*} s The string to escape. If not a string, it will be casted\n * to one.\n * @return {string} A RegExp safe, escaped copy of `s`.\n */\ngoog.string.regExpEscape = function(s) {\n 'use strict';\n return String(s)\n .replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g, '\\\\$1')\n .replace(/\\x08/g, '\\\\x08');\n};\n\n\n/**\n * Repeats a string n times.\n * @param {string} string The string to repeat.\n * @param {number} length The number of times to repeat.\n * @return {string} A string containing `length` repetitions of\n * `string`.\n */\ngoog.string.repeat = (String.prototype.repeat) ? function(string, length) {\n 'use strict';\n // The native method is over 100 times faster than the alternative.\n return string.repeat(length);\n} : function(string, length) {\n 'use strict';\n return new Array(length + 1).join(string);\n};\n\n\n/**\n * Pads number to given length and optionally rounds it to a given precision.\n * For example:\n * <pre>padNumber(1.25, 2, 3) -> '01.250'\n * padNumber(1.25, 2) -> '01.25'\n * padNumber(1.25, 2, 1) -> '01.3'\n * padNumber(1.25, 0) -> '1.25'</pre>\n *\n * @param {number} num The number to pad.\n * @param {number} length The desired length.\n * @param {number=} opt_precision The desired precision.\n * @return {string} `num` as a string with the given options.\n */\ngoog.string.padNumber = function(num, length, opt_precision) {\n 'use strict';\n if (!Number.isFinite(num)) return String(num);\n let s =\n (opt_precision !== undefined) ? num.toFixed(opt_precision) : String(num);\n let index = s.indexOf('.');\n if (index === -1) {\n index = s.length;\n }\n const sign = s[0] === '-' ? '-' : '';\n if (sign) {\n s = s.substring(1);\n }\n return sign + goog.string.repeat('0', Math.max(0, length - index)) + s;\n};\n\n\n/**\n * Returns a string representation of the given object, with\n * null and undefined being returned as the empty string.\n *\n * @param {*} obj The object to convert.\n * @return {string} A string representation of the `obj`.\n */\ngoog.string.makeSafe = function(obj) {\n 'use strict';\n return obj == null ? '' : String(obj);\n};\n\n/**\n * Returns a string with at least 64-bits of randomness.\n *\n * Doesn't trust JavaScript's random function entirely. Uses a combination of\n * random and current timestamp, and then encodes the string in base-36 to\n * make it shorter.\n *\n * @return {string} A random string, e.g. sn1s7vb4gcic.\n */\ngoog.string.getRandomString = function() {\n 'use strict';\n const x = 2147483648;\n return Math.floor(Math.random() * x).toString(36) +\n Math.abs(Math.floor(Math.random() * x) ^ goog.now()).toString(36);\n};\n\n\n/**\n * Compares two version numbers.\n *\n * @param {string|number} version1 Version of first item.\n * @param {string|number} version2 Version of second item.\n *\n * @return {number} 1 if `version1` is higher.\n * 0 if arguments are equal.\n * -1 if `version2` is higher.\n */\ngoog.string.compareVersions = goog.string.internal.compareVersions;\n\n\n/**\n * String hash function similar to java.lang.String.hashCode().\n * The hash code for a string is computed as\n * s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],\n * where s[i] is the ith character of the string and n is the length of\n * the string. We mod the result to make it between 0 (inclusive) and 2^32\n * (exclusive).\n * @param {string} str A string.\n * @return {number} Hash value for `str`, between 0 (inclusive) and 2^32\n * (exclusive). The empty string returns 0.\n */\ngoog.string.hashCode = function(str) {\n 'use strict';\n let result = 0;\n for (let i = 0; i < str.length; ++i) {\n // Normalize to 4 byte range, 0 ... 2^32.\n result = (31 * result + str.charCodeAt(i)) >>> 0;\n }\n return result;\n};\n\n\n/**\n * The most recent unique ID. |0 is equivalent to Math.floor in this case.\n * @type {number}\n * @private\n */\ngoog.string.uniqueStringCounter_ = Math.random() * 0x80000000 | 0;\n\n\n/**\n * Generates and returns a string which is unique in the current document.\n * This is useful, for example, to create unique IDs for DOM elements.\n * @return {string} A unique id.\n */\ngoog.string.createUniqueString = function() {\n 'use strict';\n return 'goog_' + goog.string.uniqueStringCounter_++;\n};\n\n\n/**\n * Converts the supplied string to a number, which may be Infinity or NaN.\n * This function strips whitespace: (toNumber(' 123') === 123)\n * This function accepts scientific notation: (toNumber('1e1') === 10)\n *\n * This is better than JavaScript's built-in conversions because, sadly:\n * (Number(' ') === 0) and (parseFloat('123a') === 123)\n *\n * @param {string} str The string to convert.\n * @return {number} The number the supplied string represents, or NaN.\n */\ngoog.string.toNumber = function(str) {\n 'use strict';\n const num = Number(str);\n if (num == 0 && goog.string.isEmptyOrWhitespace(str)) {\n return NaN;\n }\n return num;\n};\n\n\n/**\n * Returns whether the given string is lower camel case (e.g. \"isFooBar\").\n *\n * Note that this assumes the string is entirely letters.\n * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms\n *\n * @param {string} str String to test.\n * @return {boolean} Whether the string is lower camel case.\n */\ngoog.string.isLowerCamelCase = function(str) {\n 'use strict';\n return /^[a-z]+([A-Z][a-z]*)*$/.test(str);\n};\n\n\n/**\n * Returns whether the given string is upper camel case (e.g. \"FooBarBaz\").\n *\n * Note that this assumes the string is entirely letters.\n * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms\n *\n * @param {string} str String to test.\n * @return {boolean} Whether the string is upper camel case.\n */\ngoog.string.isUpperCamelCase = function(str) {\n 'use strict';\n return /^([A-Z][a-z]*)+$/.test(str);\n};\n\n\n/**\n * Converts a string from selector-case to camelCase (e.g. from\n * \"multi-part-string\" to \"multiPartString\"), useful for converting\n * CSS selectors and HTML dataset keys to their equivalent JS properties.\n * @param {string} str The string in selector-case form.\n * @return {string} The string in camelCase form.\n */\ngoog.string.toCamelCase = function(str) {\n 'use strict';\n return String(str).replace(/\\-([a-z])/g, function(all, match) {\n 'use strict';\n return match.toUpperCase();\n });\n};\n\n\n/**\n * Converts a string from camelCase to selector-case (e.g. from\n * \"multiPartString\" to \"multi-part-string\"), useful for converting JS\n * style and dataset properties to equivalent CSS selectors and HTML keys.\n * @param {string} str The string in camelCase form.\n * @return {string} The string in selector-case form.\n */\ngoog.string.toSelectorCase = function(str) {\n 'use strict';\n return String(str).replace(/([A-Z])/g, '-$1').toLowerCase();\n};\n\n\n/**\n * Converts a string into TitleCase. First character of the string is always\n * capitalized in addition to the first letter of every subsequent word.\n * Words are delimited by one or more whitespaces by default. Custom delimiters\n * can optionally be specified to replace the default, which doesn't preserve\n * whitespace delimiters and instead must be explicitly included if needed.\n *\n * Default delimiter => \" \":\n * goog.string.toTitleCase('oneTwoThree') => 'OneTwoThree'\n * goog.string.toTitleCase('one two three') => 'One Two Three'\n * goog.string.toTitleCase(' one two ') => ' One Two '\n * goog.string.toTitleCase('one_two_three') => 'One_two_three'\n * goog.string.toTitleCase('one-two-three') => 'One-two-three'\n *\n * Custom delimiter => \"_-.\":\n * goog.string.toTitleCase('oneTwoThree', '_-.') => 'OneTwoThree'\n * goog.string.toTitleCase('one two three', '_-.') => 'One two three'\n * goog.string.toTitleCase(' one two ', '_-.') => ' one two '\n * goog.string.toTitleCase('one_two_three', '_-.') => 'One_Two_Three'\n * goog.string.toTitleCase('one-two-three', '_-.') => 'One-Two-Three'\n * goog.string.toTitleCase('one...two...three', '_-.') => 'One...Two...Three'\n * goog.string.toTitleCase('one. two. three', '_-.') => 'One. two. three'\n * goog.string.toTitleCase('one-two.three', '_-.') => 'One-Two.Three'\n *\n * @param {string} str String value in camelCase form.\n * @param {string=} opt_delimiters Custom delimiter character set used to\n * distinguish words in the string value. Each character represents a\n * single delimiter. When provided, default whitespace delimiter is\n * overridden and must be explicitly included if needed.\n * @return {string} String value in TitleCase form.\n */\ngoog.string.toTitleCase = function(str, opt_delimiters) {\n 'use strict';\n let delimiters = (typeof opt_delimiters === 'string') ?\n goog.string.regExpEscape(opt_delimiters) :\n '\\\\s';\n\n // For IE8, we need to prevent using an empty character set. Otherwise,\n // incorrect matching will occur.\n delimiters = delimiters ? '|[' + delimiters + ']+' : '';\n\n const regexp = new RegExp('(^' + delimiters + ')([a-z])', 'g');\n return str.replace(regexp, function(all, p1, p2) {\n 'use strict';\n return p1 + p2.toUpperCase();\n });\n};\n\n\n/**\n * Capitalizes a string, i.e. converts the first letter to uppercase\n * and all other letters to lowercase, e.g.:\n *\n * goog.string.capitalize('one') => 'One'\n * goog.string.capitalize('ONE') => 'One'\n * goog.string.capitalize('one two') => 'One two'\n *\n * Note that this function does not trim initial whitespace.\n *\n * @param {string} str String value to capitalize.\n * @return {string} String value with first letter in uppercase.\n */\ngoog.string.capitalize = function(str) {\n 'use strict';\n return String(str.charAt(0)).toUpperCase() +\n String(str.slice(1)).toLowerCase();\n};\n\n\n/**\n * Parse a string in decimal or hexidecimal ('0xFFFF') form.\n *\n * To parse a particular radix, please use parseInt(string, radix) directly. See\n * https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt\n *\n * This is a wrapper for the built-in parseInt function that will only parse\n * numbers as base 10 or base 16. Some JS implementations assume strings\n * starting with \"0\" are intended to be octal. ES3 allowed but discouraged\n * this behavior. ES5 forbids it. This function emulates the ES5 behavior.\n *\n * For more information, see Mozilla JS Reference: http://goo.gl/8RiFj\n *\n * @param {string|number|null|undefined} value The value to be parsed.\n * @return {number} The number, parsed. If the string failed to parse, this\n * will be NaN.\n */\ngoog.string.parseInt = function(value) {\n 'use strict';\n // Force finite numbers to strings.\n if (isFinite(value)) {\n value = String(value);\n }\n\n if (typeof value === 'string') {\n // If the string starts with '0x' or '-0x', parse as hex.\n return /^\\s*-?0x/i.test(value) ? parseInt(value, 16) : parseInt(value, 10);\n }\n\n return NaN;\n};\n\n\n/**\n * Splits a string on a separator a limited number of times.\n *\n * This implementation is more similar to Python or Java, where the limit\n * parameter specifies the maximum number of splits rather than truncating\n * the number of results.\n *\n * See http://docs.python.org/2/library/stdtypes.html#str.split\n * See JavaDoc: http://goo.gl/F2AsY\n * See Mozilla reference: http://goo.gl/dZdZs\n *\n * @param {string} str String to split.\n * @param {string} separator The separator.\n * @param {number} limit The limit to the number of splits. The resulting array\n * will have a maximum length of limit+1. Negative numbers are the same\n * as zero.\n * @return {!Array<string>} The string, split.\n */\ngoog.string.splitLimit = function(str, separator, limit) {\n 'use strict';\n const parts = str.split(separator);\n const returnVal = [];\n\n // Only continue doing this while we haven't hit the limit and we have\n // parts left.\n while (limit > 0 && parts.length) {\n returnVal.push(parts.shift());\n limit--;\n }\n\n // If there are remaining parts, append them to the end.\n if (parts.length) {\n returnVal.push(parts.join(separator));\n }\n\n return returnVal;\n};\n\n\n/**\n * Finds the characters to the right of the last instance of any separator\n *\n * This function is similar to goog.string.path.baseName, except it can take a\n * list of characters to split the string on. It will return the rightmost\n * grouping of characters to the right of any separator as a left-to-right\n * oriented string.\n *\n * @see goog.string.path.baseName\n * @param {string} str The string\n * @param {string|!Array<string>} separators A list of separator characters\n * @return {string} The last part of the string with respect to the separators\n */\ngoog.string.lastComponent = function(str, separators) {\n 'use strict';\n if (!separators) {\n return str;\n } else if (typeof separators == 'string') {\n separators = [separators];\n }\n\n let lastSeparatorIndex = -1;\n for (let i = 0; i < separators.length; i++) {\n if (separators[i] == '') {\n continue;\n }\n const currentSeparatorIndex = str.lastIndexOf(separators[i]);\n if (currentSeparatorIndex > lastSeparatorIndex) {\n lastSeparatorIndex = currentSeparatorIndex;\n }\n }\n if (lastSeparatorIndex == -1) {\n return str;\n }\n return str.slice(lastSeparatorIndex + 1);\n};\n\n\n/**\n * Computes the Levenshtein edit distance between two strings.\n * @param {string} a\n * @param {string} b\n * @return {number} The edit distance between the two strings.\n */\ngoog.string.editDistance = function(a, b) {\n 'use strict';\n const v0 = [];\n const v1 = [];\n\n if (a == b) {\n return 0;\n }\n\n if (!a.length || !b.length) {\n return Math.max(a.length, b.length);\n }\n\n for (let i = 0; i < b.length + 1; i++) {\n v0[i] = i;\n }\n\n for (let i = 0; i < a.length; i++) {\n v1[0] = i + 1;\n\n for (let j = 0; j < b.length; j++) {\n const cost = Number(a[i] != b[j]);\n // Cost for the substring is the minimum of adding one character, removing\n // one character, or a swap.\n v1[j + 1] = Math.min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost);\n }\n\n for (let j = 0; j < v0.length; j++) {\n v0[j] = v1[j];\n }\n }\n\n return v1[b.length];\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Wrapper class for handling XmlHttpRequests.\n *\n * One off requests can be sent through goog.net.XhrIo.send() or an\n * instance can be created to send multiple requests. Each request uses its\n * own XmlHttpRequest object and handles clearing of the event callback to\n * ensure no leaks.\n *\n * XhrIo is event based, it dispatches events on success, failure, finishing,\n * ready-state change, or progress (download and upload).\n *\n * The ready-state or timeout event fires first, followed by\n * a generic completed event. Then the abort, error, or success event\n * is fired as appropriate. Progress events are fired as they are\n * received. Lastly, the ready event will fire to indicate that the\n * object may be used to make another request.\n *\n * The error event may also be called before completed and\n * ready-state-change if the XmlHttpRequest.open() or .send() methods throw.\n *\n * This class does not support multiple requests, queuing, or prioritization.\n *\n * When progress events are supported by the browser, and progress is\n * enabled via .setProgressEventsEnabled(true), the\n * goog.net.EventType.PROGRESS event will be the re-dispatched browser\n * progress event. Additionally, a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event\n * will be fired for download and upload progress respectively.\n */\n\n\ngoog.provide('goog.net.XhrIo');\ngoog.provide('goog.net.XhrIo.ResponseType');\n\ngoog.require('goog.Timer');\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.debug.entryPointRegistry');\ngoog.require('goog.events.EventTarget');\ngoog.require('goog.json.hybrid');\ngoog.require('goog.log');\ngoog.require('goog.net.ErrorCode');\ngoog.require('goog.net.EventType');\ngoog.require('goog.net.HttpStatus');\ngoog.require('goog.net.XmlHttp');\ngoog.require('goog.object');\ngoog.require('goog.string');\ngoog.require('goog.uri.utils');\ngoog.require('goog.userAgent');\ngoog.requireType('goog.Uri');\ngoog.requireType('goog.debug.ErrorHandler');\ngoog.requireType('goog.net.XhrLike');\ngoog.requireType('goog.net.XmlHttpFactory');\n\ngoog.scope(function() {\n\n'use strict';\n/**\n * Basic class for handling XMLHttpRequests.\n * @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when\n * creating XMLHttpRequest objects.\n * @constructor\n * @extends {goog.events.EventTarget}\n */\ngoog.net.XhrIo = function(opt_xmlHttpFactory) {\n 'use strict';\n XhrIo.base(this, 'constructor');\n\n /**\n * Map of default headers to add to every request, use:\n * XhrIo.headers.set(name, value)\n * @type {!Map<string,string>}\n */\n this.headers = new Map();\n\n /**\n * Optional XmlHttpFactory\n * @private {goog.net.XmlHttpFactory}\n */\n this.xmlHttpFactory_ = opt_xmlHttpFactory || null;\n\n /**\n * Whether XMLHttpRequest is active. A request is active from the time send()\n * is called until onReadyStateChange() is complete, or error() or abort()\n * is called.\n * @private {boolean}\n */\n this.active_ = false;\n\n /**\n * The XMLHttpRequest object that is being used for the transfer.\n * @private {?goog.net.XhrLike.OrNative}\n */\n this.xhr_ = null;\n\n /**\n * The options to use with the current XMLHttpRequest object.\n * @private {?Object}\n */\n this.xhrOptions_ = null;\n\n /**\n * Last URL that was requested.\n * @private {string|goog.Uri}\n */\n this.lastUri_ = '';\n\n /**\n * Method for the last request.\n * @private {string}\n */\n this.lastMethod_ = '';\n\n /**\n * Last error code.\n * @private {!goog.net.ErrorCode}\n */\n this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;\n\n /**\n * Last error message.\n * @private {Error|string}\n */\n this.lastError_ = '';\n\n /**\n * Used to ensure that we don't dispatch an multiple ERROR events. This can\n * happen in IE when it does a synchronous load and one error is handled in\n * the ready state change and one is handled due to send() throwing an\n * exception.\n * @private {boolean}\n */\n this.errorDispatched_ = false;\n\n /**\n * Used to make sure we don't fire the complete event from inside a send call.\n * @private {boolean}\n */\n this.inSend_ = false;\n\n /**\n * Used in determining if a call to {@link #onReadyStateChange_} is from\n * within a call to this.xhr_.open.\n * @private {boolean}\n */\n this.inOpen_ = false;\n\n /**\n * Used in determining if a call to {@link #onReadyStateChange_} is from\n * within a call to this.xhr_.abort.\n * @private {boolean}\n */\n this.inAbort_ = false;\n\n /**\n * Number of milliseconds after which an incomplete request will be aborted\n * and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout\n * is set.\n * @private {number}\n */\n this.timeoutInterval_ = 0;\n\n /**\n * Timer to track request timeout.\n * @private {?number}\n */\n this.timeoutId_ = null;\n\n /**\n * The requested type for the response. The empty string means use the default\n * XHR behavior.\n * @private {goog.net.XhrIo.ResponseType}\n */\n this.responseType_ = ResponseType.DEFAULT;\n\n /**\n * Whether a \"credentialed\" request is to be sent (one that is aware of\n * cookies and authentication). This is applicable only for cross-domain\n * requests and more recent browsers that support this part of the HTTP Access\n * Control standard.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute\n *\n * @private {boolean}\n */\n this.withCredentials_ = false;\n\n /**\n * Whether progress events are enabled for this request. This is\n * disabled by default because setting a progress event handler\n * causes pre-flight OPTIONS requests to be sent for CORS requests,\n * even in cases where a pre-flight request would not otherwise be\n * sent.\n *\n * @see http://xhr.spec.whatwg.org/#security-considerations\n *\n * Note that this can cause problems for Firefox 22 and below, as an\n * older \"LSProgressEvent\" will be dispatched by the browser. That\n * progress event is no longer supported, and can lead to failures,\n * including throwing exceptions.\n *\n * @see http://bugzilla.mozilla.org/show_bug.cgi?id=845631\n * @see b/23469793\n *\n * @private {boolean}\n */\n this.progressEventsEnabled_ = false;\n\n /**\n * True if we can use XMLHttpRequest's timeout directly.\n * @private {boolean}\n */\n this.useXhr2Timeout_ = false;\n\n /**\n * Specification for Trust Token operations (issuance, signing, and\n * redemption).\n * @private {?TrustTokenAttributeType}\n */\n this.trustToken_ = null;\n};\ngoog.inherits(goog.net.XhrIo, goog.events.EventTarget);\n\nconst XhrIo = goog.net.XhrIo;\n\n/**\n * Response types that may be requested for XMLHttpRequests.\n * @enum {string}\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute\n */\ngoog.net.XhrIo.ResponseType = {\n DEFAULT: '',\n TEXT: 'text',\n DOCUMENT: 'document',\n // Not supported as of Chrome 10.0.612.1 dev\n BLOB: 'blob',\n ARRAY_BUFFER: 'arraybuffer',\n};\n\nconst ResponseType = goog.net.XhrIo.ResponseType;\n\n\n/**\n * A reference to the XhrIo logger\n * @private {?goog.log.Logger}\n * @const\n */\ngoog.net.XhrIo.prototype.logger_ = goog.log.getLogger('goog.net.XhrIo');\n\n\n/**\n * The Content-Type HTTP header name\n * @type {string}\n */\ngoog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type';\n\n\n/**\n * The Content-Transfer-Encoding HTTP header name\n * @type {string}\n */\ngoog.net.XhrIo.CONTENT_TRANSFER_ENCODING = 'Content-Transfer-Encoding';\n\n\n/**\n * The pattern matching the 'http' and 'https' URI schemes\n * @type {!RegExp}\n */\ngoog.net.XhrIo.HTTP_SCHEME_PATTERN = /^https?$/i;\n\nconst HTTP_SCHEME_PATTERN = goog.net.XhrIo.HTTP_SCHEME_PATTERN;\n\n\n/**\n * The methods that typically come along with form data. We set different\n * headers depending on whether the HTTP action is one of these.\n * @type {!Array<string>}\n */\ngoog.net.XhrIo.METHODS_WITH_FORM_DATA = ['POST', 'PUT'];\n\n\n/**\n * The Content-Type HTTP header value for a url-encoded form\n * @type {string}\n */\ngoog.net.XhrIo.FORM_CONTENT_TYPE =\n 'application/x-www-form-urlencoded;charset=utf-8';\n\n\n/**\n * The XMLHttpRequest Level two timeout delay ms property name.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\n *\n * @private {string}\n * @const\n */\ngoog.net.XhrIo.XHR2_TIMEOUT_ = 'timeout';\n\n\n/**\n * The XMLHttpRequest Level two ontimeout handler property name.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\n *\n * @private {string}\n * @const\n */\ngoog.net.XhrIo.XHR2_ON_TIMEOUT_ = 'ontimeout';\n\n\n/**\n * All non-disposed instances of goog.net.XhrIo created\n * by {@link goog.net.XhrIo.send} are in this Array.\n * @see goog.net.XhrIo.cleanup\n * @private {!Array<!goog.net.XhrIo>}\n */\ngoog.net.XhrIo.sendInstances_ = [];\n\n\n/**\n * Static send that creates a short lived instance of XhrIo to send the\n * request.\n * @see goog.net.XhrIo.cleanup\n * @param {string|goog.Uri} url Uri to make request to.\n * @param {?function(this:goog.net.XhrIo, ?)=} opt_callback Callback function\n * for when request is complete.\n * @param {string=} opt_method Send method, default: GET.\n * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}\n * opt_content Body data.\n * @param {(?Object|?goog.collections.maps.MapLike<string, string>)=}\n * opt_headers Map of headers to add to the request.\n * @param {number=} opt_timeoutInterval Number of milliseconds after which an\n * incomplete request will be aborted; 0 means no timeout is set.\n * @param {boolean=} opt_withCredentials Whether to send credentials with the\n * request. Default to false. See {@link goog.net.XhrIo#setWithCredentials}.\n * @return {!goog.net.XhrIo} The sent XhrIo.\n */\ngoog.net.XhrIo.send = function(\n url, opt_callback, opt_method, opt_content, opt_headers,\n opt_timeoutInterval, opt_withCredentials) {\n 'use strict';\n const x = new goog.net.XhrIo();\n goog.net.XhrIo.sendInstances_.push(x);\n if (opt_callback) {\n x.listen(goog.net.EventType.COMPLETE, opt_callback);\n }\n x.listenOnce(goog.net.EventType.READY, x.cleanupSend_);\n if (opt_timeoutInterval) {\n x.setTimeoutInterval(opt_timeoutInterval);\n }\n if (opt_withCredentials) {\n x.setWithCredentials(opt_withCredentials);\n }\n x.send(url, opt_method, opt_content, opt_headers);\n return x;\n};\n\n\n/**\n * Disposes all non-disposed instances of goog.net.XhrIo created by\n * {@link goog.net.XhrIo.send}.\n * {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance\n * it creates when the request completes or fails. However, if\n * the request never completes, then the goog.net.XhrIo is not disposed.\n * This can occur if the window is unloaded before the request completes.\n * We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo\n * it creates and make the client of {@link goog.net.XhrIo.send} be\n * responsible for disposing it in this case. However, this makes things\n * significantly more complicated for the client, and the whole point\n * of {@link goog.net.XhrIo.send} is that it's simple and easy to use.\n * Clients of {@link goog.net.XhrIo.send} should call\n * {@link goog.net.XhrIo.cleanup} when doing final\n * cleanup on window unload.\n */\ngoog.net.XhrIo.cleanup = function() {\n 'use strict';\n const instances = goog.net.XhrIo.sendInstances_;\n while (instances.length) {\n instances.pop().dispose();\n }\n};\n\n\n/**\n * Installs exception protection for all entry point introduced by\n * goog.net.XhrIo instances which are not protected by\n * {@link goog.debug.ErrorHandler#protectWindowSetTimeout},\n * {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or\n * {@link goog.events.protectBrowserEventEntryPoint}.\n *\n * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to\n * protect the entry point(s).\n */\ngoog.net.XhrIo.protectEntryPoints = function(errorHandler) {\n 'use strict';\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =\n errorHandler.protectEntryPoint(\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);\n};\n\n\n/**\n * Disposes of the specified goog.net.XhrIo created by\n * {@link goog.net.XhrIo.send} and removes it from\n * {@link goog.net.XhrIo.pendingStaticSendInstances_}.\n * @private\n */\ngoog.net.XhrIo.prototype.cleanupSend_ = function() {\n 'use strict';\n this.dispose();\n goog.array.remove(goog.net.XhrIo.sendInstances_, this);\n};\n\n\n/**\n * Returns the number of milliseconds after which an incomplete request will be\n * aborted, or 0 if no timeout is set.\n * @return {number} Timeout interval in milliseconds.\n */\ngoog.net.XhrIo.prototype.getTimeoutInterval = function() {\n 'use strict';\n return this.timeoutInterval_;\n};\n\n\n/**\n * Sets the number of milliseconds after which an incomplete request will be\n * aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no\n * timeout is set.\n * @param {number} ms Timeout interval in milliseconds; 0 means none.\n */\ngoog.net.XhrIo.prototype.setTimeoutInterval = function(ms) {\n 'use strict';\n this.timeoutInterval_ = Math.max(0, ms);\n};\n\n\n/**\n * Sets the desired type for the response. At time of writing, this is only\n * supported in very recent versions of WebKit (10.0.612.1 dev and later).\n *\n * If this is used, the response may only be accessed via {@link #getResponse}.\n *\n * @param {goog.net.XhrIo.ResponseType} type The desired type for the response.\n */\ngoog.net.XhrIo.prototype.setResponseType = function(type) {\n 'use strict';\n this.responseType_ = type;\n};\n\n\n/**\n * Gets the desired type for the response.\n * @return {goog.net.XhrIo.ResponseType} The desired type for the response.\n */\ngoog.net.XhrIo.prototype.getResponseType = function() {\n 'use strict';\n return this.responseType_;\n};\n\n\n/**\n * Sets whether a \"credentialed\" request that is aware of cookie and\n * authentication information should be made. This option is only supported by\n * browsers that support HTTP Access Control. As of this writing, this option\n * is not supported in IE.\n *\n * @param {boolean} withCredentials Whether this should be a \"credentialed\"\n * request.\n */\ngoog.net.XhrIo.prototype.setWithCredentials = function(withCredentials) {\n 'use strict';\n this.withCredentials_ = withCredentials;\n};\n\n\n/**\n * Gets whether a \"credentialed\" request is to be sent.\n * @return {boolean} The desired type for the response.\n */\ngoog.net.XhrIo.prototype.getWithCredentials = function() {\n 'use strict';\n return this.withCredentials_;\n};\n\n\n/**\n * Sets whether progress events are enabled for this request. Note\n * that progress events require pre-flight OPTIONS request handling\n * for CORS requests, and may cause trouble with older browsers. See\n * progressEventsEnabled_ for details.\n * @param {boolean} enabled Whether progress events should be enabled.\n */\ngoog.net.XhrIo.prototype.setProgressEventsEnabled = function(enabled) {\n 'use strict';\n this.progressEventsEnabled_ = enabled;\n};\n\n\n/**\n * Gets whether progress events are enabled.\n * @return {boolean} Whether progress events are enabled for this request.\n */\ngoog.net.XhrIo.prototype.getProgressEventsEnabled = function() {\n 'use strict';\n return this.progressEventsEnabled_;\n};\n\n/**\n * Specify a Trust Tokens operation to execute alongside the request.\n * @param {!TrustTokenAttributeType} trustToken a Trust Tokens operation to\n * execute.\n */\ngoog.net.XhrIo.prototype.setTrustToken = function(trustToken) {\n 'use strict';\n this.trustToken_ = trustToken;\n};\n\n/**\n * Instance send that actually uses XMLHttpRequest to make a server call.\n * @param {string|goog.Uri} url Uri to make request to.\n * @param {string=} opt_method Send method, default: GET.\n * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}\n * opt_content Body data.\n * @param {(?Object|?goog.collections.maps.MapLike<string, string>)=}\n * opt_headers Map of headers to add to the request.\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different\n * types of parameters for opt_headers.\n */\ngoog.net.XhrIo.prototype.send = function(\n url, opt_method, opt_content, opt_headers) {\n 'use strict';\n if (this.xhr_) {\n throw new Error(\n '[goog.net.XhrIo] Object is active with another request=' +\n this.lastUri_ + '; newUri=' + url);\n }\n\n const method = opt_method ? opt_method.toUpperCase() : 'GET';\n\n this.lastUri_ = url;\n this.lastError_ = '';\n this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;\n this.lastMethod_ = method;\n this.errorDispatched_ = false;\n this.active_ = true;\n\n // Use the factory to create the XHR object and options\n this.xhr_ = this.createXhr();\n this.xhrOptions_ = this.xmlHttpFactory_ ? this.xmlHttpFactory_.getOptions() :\n goog.net.XmlHttp.getOptions();\n\n // Set up the onreadystatechange callback\n this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this);\n\n // Set up upload/download progress events, if progress events are supported.\n if (this.getProgressEventsEnabled() && 'onprogress' in this.xhr_) {\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n this.xhr_.onprogress = goog.bind(function(e) {\n 'use strict';\n this.onProgressHandler_(e, true);\n }, this);\n if (this.xhr_.upload) {\n /**\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\n this.xhr_.upload.onprogress = goog.bind(this.onProgressHandler_, this);\n }\n }\n\n /**\n * Try to open the XMLHttpRequest (always async), if an error occurs here it\n * is generally permission denied\n */\n try {\n goog.log.fine(this.logger_, this.formatMsg_('Opening Xhr'));\n this.inOpen_ = true;\n this.xhr_.open(method, String(url), true); // Always async!\n this.inOpen_ = false;\n } catch (err) {\n goog.log.fine(\n this.logger_, this.formatMsg_('Error opening Xhr: ' + err.message));\n this.error_(goog.net.ErrorCode.EXCEPTION, err);\n return;\n }\n\n // We can't use null since this won't allow requests with form data to have a\n // content length specified which will cause some proxies to return a 411\n // error.\n const content = opt_content || '';\n\n const headers = new Map(this.headers);\n\n // Add headers specific to this request\n if (opt_headers) {\n if (Object.getPrototypeOf(opt_headers) === Object.prototype) {\n for (let key in opt_headers) {\n headers.set(key, opt_headers[key]);\n }\n } else if (\n typeof opt_headers.keys === 'function' &&\n typeof opt_headers.get === 'function') {\n for (const key of opt_headers.keys()) {\n headers.set(key, opt_headers.get(key));\n }\n } else {\n throw new Error(\n 'Unknown input type for opt_headers: ' + String(opt_headers));\n }\n }\n\n // Find whether a content type header is set, ignoring case.\n // HTTP header names are case-insensitive. See:\n // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2\n const contentTypeKey =\n Array.from(headers.keys())\n .find(\n header => goog.string.caseInsensitiveEquals(\n goog.net.XhrIo.CONTENT_TYPE_HEADER, header));\n\n const contentIsFormData =\n (goog.global['FormData'] && (content instanceof goog.global['FormData']));\n if (goog.array.contains(goog.net.XhrIo.METHODS_WITH_FORM_DATA, method) &&\n !contentTypeKey && !contentIsFormData) {\n // For requests typically with form data, default to the url-encoded form\n // content type unless this is a FormData request. For FormData,\n // the browser will automatically add a multipart/form-data content type\n // with an appropriate multipart boundary.\n headers.set(\n goog.net.XhrIo.CONTENT_TYPE_HEADER, goog.net.XhrIo.FORM_CONTENT_TYPE);\n }\n\n // Add the headers to the Xhr object\n for (const [key, value] of headers) {\n this.xhr_.setRequestHeader(key, value);\n }\n\n if (this.responseType_) {\n this.xhr_.responseType = this.responseType_;\n }\n // Set xhr_.withCredentials only when the value is different, or else in\n // synchronous XMLHtppRequest.open Firefox will throw an exception.\n // https://bugzilla.mozilla.org/show_bug.cgi?id=736340\n if ('withCredentials' in this.xhr_ &&\n this.xhr_.withCredentials !== this.withCredentials_) {\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n this.xhr_.withCredentials = this.withCredentials_;\n }\n\n if ('setTrustToken' in this.xhr_ && this.trustToken_) {\n try {\n this.xhr_.setTrustToken(this.trustToken_);\n } catch (err) {\n goog.log.fine(\n this.logger_, this.formatMsg_('Error SetTrustToken: ' + err.message));\n }\n }\n /**\n * Try to send the request, or other wise report an error (404 not found).\n */\n try {\n this.cleanUpTimeoutTimer_(); // Paranoid, should never be running.\n if (this.timeoutInterval_ > 0) {\n this.useXhr2Timeout_ = goog.net.XhrIo.shouldUseXhr2Timeout_(this.xhr_);\n goog.log.fine(\n this.logger_,\n this.formatMsg_(\n 'Will abort after ' + this.timeoutInterval_ +\n 'ms if incomplete, xhr2 ' + this.useXhr2Timeout_));\n if (this.useXhr2Timeout_) {\n this.xhr_[goog.net.XhrIo.XHR2_TIMEOUT_] = this.timeoutInterval_;\n this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] =\n goog.bind(this.timeout_, this);\n } else {\n this.timeoutId_ =\n goog.Timer.callOnce(this.timeout_, this.timeoutInterval_, this);\n }\n }\n goog.log.fine(this.logger_, this.formatMsg_('Sending request'));\n this.inSend_ = true;\n this.xhr_.send(content);\n this.inSend_ = false;\n\n } catch (err) {\n goog.log.fine(this.logger_, this.formatMsg_('Send error: ' + err.message));\n this.error_(goog.net.ErrorCode.EXCEPTION, err);\n }\n};\n\n\n/**\n * Determines if the argument is an XMLHttpRequest that supports the level 2\n * timeout value and event.\n *\n * Currently, FF 21.0 OS X has the fields but won't actually call the timeout\n * handler. Perhaps the confusion in the bug referenced below hasn't\n * entirely been resolved.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\n * @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816\n *\n * @param {!goog.net.XhrLike.OrNative} xhr The request.\n * @return {boolean} True if the request supports level 2 timeout.\n * @private\n */\ngoog.net.XhrIo.shouldUseXhr2Timeout_ = function(xhr) {\n 'use strict';\n return goog.userAgent.IE &&\n typeof xhr[goog.net.XhrIo.XHR2_TIMEOUT_] === 'number' &&\n xhr[goog.net.XhrIo.XHR2_ON_TIMEOUT_] !== undefined;\n};\n\n\n/**\n * Creates a new XHR object.\n * @return {!goog.net.XhrLike.OrNative} The newly created XHR object.\n * @protected\n */\ngoog.net.XhrIo.prototype.createXhr = function() {\n 'use strict';\n return this.xmlHttpFactory_ ? this.xmlHttpFactory_.createInstance() :\n goog.net.XmlHttp();\n};\n\n\n/**\n * The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_}\n * milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts\n * the request.\n * @private\n */\ngoog.net.XhrIo.prototype.timeout_ = function() {\n 'use strict';\n if (typeof goog == 'undefined') {\n // If goog is undefined then the callback has occurred as the application\n // is unloading and will error. Thus we let it silently fail.\n } else if (this.xhr_) {\n this.lastError_ =\n 'Timed out after ' + this.timeoutInterval_ + 'ms, aborting';\n this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT;\n goog.log.fine(this.logger_, this.formatMsg_(this.lastError_));\n this.dispatchEvent(goog.net.EventType.TIMEOUT);\n this.abort(goog.net.ErrorCode.TIMEOUT);\n }\n};\n\n\n/**\n * Something errorred, so inactivate, fire error callback and clean up\n * @param {goog.net.ErrorCode} errorCode The error code.\n * @param {Error} err The error object.\n * @private\n */\ngoog.net.XhrIo.prototype.error_ = function(errorCode, err) {\n 'use strict';\n this.active_ = false;\n if (this.xhr_) {\n this.inAbort_ = true;\n this.xhr_.abort(); // Ensures XHR isn't hung (FF)\n this.inAbort_ = false;\n }\n this.lastError_ = err;\n this.lastErrorCode_ = errorCode;\n this.dispatchErrors_();\n this.cleanUpXhr_();\n};\n\n\n/**\n * Dispatches COMPLETE and ERROR in case of an error. This ensures that we do\n * not dispatch multiple error events.\n * @private\n */\ngoog.net.XhrIo.prototype.dispatchErrors_ = function() {\n 'use strict';\n if (!this.errorDispatched_) {\n this.errorDispatched_ = true;\n this.dispatchEvent(goog.net.EventType.COMPLETE);\n this.dispatchEvent(goog.net.EventType.ERROR);\n }\n};\n\n\n/**\n * Abort the current XMLHttpRequest\n * @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use -\n * defaults to ABORT.\n */\ngoog.net.XhrIo.prototype.abort = function(opt_failureCode) {\n 'use strict';\n if (this.xhr_ && this.active_) {\n goog.log.fine(this.logger_, this.formatMsg_('Aborting'));\n this.active_ = false;\n this.inAbort_ = true;\n this.xhr_.abort();\n this.inAbort_ = false;\n this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT;\n this.dispatchEvent(goog.net.EventType.COMPLETE);\n this.dispatchEvent(goog.net.EventType.ABORT);\n this.cleanUpXhr_();\n }\n};\n\n\n/**\n * Nullifies all callbacks to reduce risks of leaks.\n * @override\n * @protected\n */\ngoog.net.XhrIo.prototype.disposeInternal = function() {\n 'use strict';\n if (this.xhr_) {\n // We explicitly do not call xhr_.abort() unless active_ is still true.\n // This is to avoid unnecessarily aborting a successful request when\n // dispose() is called in a callback triggered by a complete response, but\n // in which browser cleanup has not yet finished.\n // (See http://b/issue?id=1684217.)\n if (this.active_) {\n this.active_ = false;\n this.inAbort_ = true;\n this.xhr_.abort();\n this.inAbort_ = false;\n }\n this.cleanUpXhr_(true);\n }\n\n XhrIo.base(this, 'disposeInternal');\n};\n\n\n/**\n * Internal handler for the XHR object's readystatechange event. This method\n * checks the status and the readystate and fires the correct callbacks.\n * If the request has ended, the handlers are cleaned up and the XHR object is\n * nullified.\n * @private\n */\ngoog.net.XhrIo.prototype.onReadyStateChange_ = function() {\n 'use strict';\n if (this.isDisposed()) {\n // This method is the target of an untracked goog.Timer.callOnce().\n return;\n }\n if (!this.inOpen_ && !this.inSend_ && !this.inAbort_) {\n // Were not being called from within a call to this.xhr_.send\n // this.xhr_.abort, or this.xhr_.open, so this is an entry point\n this.onReadyStateChangeEntryPoint_();\n } else {\n this.onReadyStateChangeHelper_();\n }\n};\n\n\n/**\n * Used to protect the onreadystatechange handler entry point. Necessary\n * as {#onReadyStateChange_} maybe called from within send or abort, this\n * method is only called when {#onReadyStateChange_} is called as an\n * entry point.\n * {@see #protectEntryPoints}\n * @private\n */\ngoog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() {\n 'use strict';\n this.onReadyStateChangeHelper_();\n};\n\n\n/**\n * Helper for {@link #onReadyStateChange_}. This is used so that\n * entry point calls to {@link #onReadyStateChange_} can be routed through\n * {@link #onReadyStateChangeEntryPoint_}.\n * @private\n */\ngoog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() {\n 'use strict';\n if (!this.active_) {\n // can get called inside abort call\n return;\n }\n\n if (typeof goog == 'undefined') {\n // NOTE(user): If goog is undefined then the callback has occurred as the\n // application is unloading and will error. Thus we let it silently fail.\n\n } else if (\n this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] &&\n this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE &&\n this.getStatus() == 2) {\n // NOTE(user): In IE if send() errors on a *local* request the readystate\n // is still changed to COMPLETE. We need to ignore it and allow the\n // try/catch around send() to pick up the error.\n goog.log.fine(\n this.logger_,\n this.formatMsg_('Local request error detected and ignored'));\n\n } else {\n // In IE when the response has been cached we sometimes get the callback\n // from inside the send call and this usually breaks code that assumes that\n // XhrIo is asynchronous. If that is the case we delay the callback\n // using a timer.\n if (this.inSend_ &&\n this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) {\n goog.Timer.callOnce(this.onReadyStateChange_, 0, this);\n return;\n }\n\n this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE);\n\n // readyState indicates the transfer has finished\n if (this.isComplete()) {\n goog.log.fine(this.logger_, this.formatMsg_('Request complete'));\n\n this.active_ = false;\n\n try {\n // Call the specific callbacks for success or failure. Only call the\n // success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED)\n if (this.isSuccess()) {\n this.dispatchEvent(goog.net.EventType.COMPLETE);\n this.dispatchEvent(goog.net.EventType.SUCCESS);\n } else {\n this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR;\n this.lastError_ =\n this.getStatusText() + ' [' + this.getStatus() + ']';\n this.dispatchErrors_();\n }\n } finally {\n this.cleanUpXhr_();\n }\n }\n }\n};\n\n\n/**\n * Internal handler for the XHR object's onprogress event. Fires both a generic\n * PROGRESS event and either a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event to\n * allow specific binding for each XHR progress event.\n * @param {!ProgressEvent} e XHR progress event.\n * @param {boolean=} opt_isDownload Whether the current progress event is from a\n * download. Used to determine whether DOWNLOAD_PROGRESS or UPLOAD_PROGRESS\n * event should be dispatched.\n * @private\n */\ngoog.net.XhrIo.prototype.onProgressHandler_ = function(e, opt_isDownload) {\n 'use strict';\n goog.asserts.assert(\n e.type === goog.net.EventType.PROGRESS,\n 'goog.net.EventType.PROGRESS is of the same type as raw XHR progress.');\n this.dispatchEvent(\n goog.net.XhrIo.buildProgressEvent_(e, goog.net.EventType.PROGRESS));\n this.dispatchEvent(goog.net.XhrIo.buildProgressEvent_(\n e,\n opt_isDownload ? goog.net.EventType.DOWNLOAD_PROGRESS :\n goog.net.EventType.UPLOAD_PROGRESS));\n};\n\n\n/**\n * Creates a representation of the native ProgressEvent. IE doesn't support\n * constructing ProgressEvent via \"new\", and the alternatives (e.g.,\n * ProgressEvent.initProgressEvent) are non-standard or deprecated.\n * @param {!ProgressEvent} e XHR progress event.\n * @param {!goog.net.EventType} eventType The type of the event.\n * @return {!ProgressEvent} The progress event.\n * @private\n */\ngoog.net.XhrIo.buildProgressEvent_ = function(e, eventType) {\n 'use strict';\n return /** @type {!ProgressEvent} */ ({\n type: eventType,\n lengthComputable: e.lengthComputable,\n loaded: e.loaded,\n total: e.total,\n });\n};\n\n\n/**\n * Remove the listener to protect against leaks, and nullify the XMLHttpRequest\n * object.\n * @param {boolean=} opt_fromDispose If this is from the dispose (don't want to\n * fire any events).\n * @private\n */\ngoog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) {\n 'use strict';\n if (this.xhr_) {\n // Cancel any pending timeout event handler.\n this.cleanUpTimeoutTimer_();\n\n // Save reference so we can mark it as closed after the READY event. The\n // READY event may trigger another request, thus we must nullify this.xhr_\n const xhr = this.xhr_;\n const clearedOnReadyStateChange =\n this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ?\n () => {} :\n null;\n this.xhr_ = null;\n this.xhrOptions_ = null;\n\n if (!opt_fromDispose) {\n this.dispatchEvent(goog.net.EventType.READY);\n }\n\n try {\n // NOTE(user): Not nullifying in FireFox can still leak if the callbacks\n // are defined in the same scope as the instance of XhrIo. But, IE doesn't\n // allow you to set the onreadystatechange to NULL so nullFunction is\n // used.\n xhr.onreadystatechange = clearedOnReadyStateChange;\n } catch (e) {\n // This seems to occur with a Gears HTTP request. Delayed the setting of\n // this onreadystatechange until after READY is sent out and catching the\n // error to see if we can track down the problem.\n goog.log.error(\n this.logger_,\n 'Problem encountered resetting onreadystatechange: ' + e.message);\n }\n }\n};\n\n\n/**\n * Make sure the timeout timer isn't running.\n * @private\n */\ngoog.net.XhrIo.prototype.cleanUpTimeoutTimer_ = function() {\n 'use strict';\n if (this.xhr_ && this.useXhr2Timeout_) {\n this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] = null;\n }\n if (this.timeoutId_) {\n goog.Timer.clear(this.timeoutId_);\n this.timeoutId_ = null;\n }\n};\n\n\n/**\n * @return {boolean} Whether there is an active request.\n */\ngoog.net.XhrIo.prototype.isActive = function() {\n 'use strict';\n return !!this.xhr_;\n};\n\n\n/**\n * @return {boolean} Whether the request has completed.\n */\ngoog.net.XhrIo.prototype.isComplete = function() {\n 'use strict';\n return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;\n};\n\n\n/**\n * @return {boolean} Whether the request completed with a success.\n */\ngoog.net.XhrIo.prototype.isSuccess = function() {\n 'use strict';\n const status = this.getStatus();\n // A zero status code is considered successful for local files.\n return goog.net.HttpStatus.isSuccess(status) ||\n status === 0 && !this.isLastUriEffectiveSchemeHttp_();\n};\n\n\n/**\n * @return {boolean} whether the effective scheme of the last URI that was\n * fetched was 'http' or 'https'.\n * @private\n */\ngoog.net.XhrIo.prototype.isLastUriEffectiveSchemeHttp_ = function() {\n 'use strict';\n const scheme = goog.uri.utils.getEffectiveScheme(String(this.lastUri_));\n return HTTP_SCHEME_PATTERN.test(scheme);\n};\n\n\n/**\n * Get the readystate from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*.\n */\ngoog.net.XhrIo.prototype.getReadyState = function() {\n 'use strict';\n return this.xhr_ ?\n /** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) :\n goog.net.XmlHttp.ReadyState.UNINITIALIZED;\n};\n\n\n/**\n * Get the status from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @return {number} Http status.\n */\ngoog.net.XhrIo.prototype.getStatus = function() {\n 'use strict';\n /**\n * IE doesn't like you checking status until the readystate is greater than 2\n * (i.e. it is receiving or complete). The try/catch is used for when the\n * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.\n */\n try {\n return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?\n this.xhr_.status :\n -1;\n } catch (e) {\n return -1;\n }\n};\n\n\n/**\n * Get the status text from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @return {string} Status text.\n */\ngoog.net.XhrIo.prototype.getStatusText = function() {\n 'use strict';\n /**\n * IE doesn't like you checking status until the readystate is greater than 2\n * (i.e. it is receiving or complete). The try/catch is used for when the\n * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.\n */\n try {\n return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?\n this.xhr_.statusText :\n '';\n } catch (e) {\n goog.log.fine(this.logger_, 'Can not get status: ' + e.message);\n return '';\n }\n};\n\n\n/**\n * Get the last Uri that was requested\n * @return {string} Last Uri.\n */\ngoog.net.XhrIo.prototype.getLastUri = function() {\n 'use strict';\n return String(this.lastUri_);\n};\n\n\n/**\n * Get the response text from the Xhr object\n * Will only return correct result when called from the context of a callback.\n * @return {string} Result from the server, or '' if no result available.\n */\ngoog.net.XhrIo.prototype.getResponseText = function() {\n 'use strict';\n try {\n return this.xhr_ ? this.xhr_.responseText : '';\n } catch (e) {\n // http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute\n // states that responseText should return '' (and responseXML null)\n // when the state is not LOADING or DONE. Instead, IE can\n // throw unexpected exceptions, for example when a request is aborted\n // or no data is available yet.\n goog.log.fine(this.logger_, 'Can not get responseText: ' + e.message);\n return '';\n }\n};\n\n\n/**\n * Get the response body from the Xhr object. This property is only available\n * in IE since version 7 according to MSDN:\n * http://msdn.microsoft.com/en-us/library/ie/ms534368(v=vs.85).aspx\n * Will only return correct result when called from the context of a callback.\n *\n * One option is to construct a VBArray from the returned object and convert\n * it to a JavaScript array using the toArray method:\n * `(new window['VBArray'](xhrIo.getResponseBody())).toArray()`\n * This will result in an array of numbers in the range of [0..255]\n *\n * Another option is to use the VBScript CStr method to convert it into a\n * string as outlined in http://stackoverflow.com/questions/1919972\n *\n * @return {Object} Binary result from the server or null if not available.\n */\ngoog.net.XhrIo.prototype.getResponseBody = function() {\n 'use strict';\n try {\n if (this.xhr_ && 'responseBody' in this.xhr_) {\n return this.xhr_['responseBody'];\n }\n } catch (e) {\n // IE can throw unexpected exceptions, for example when a request is aborted\n // or no data is yet available.\n goog.log.fine(this.logger_, 'Can not get responseBody: ' + e.message);\n }\n return null;\n};\n\n\n/**\n * Get the response XML from the Xhr object\n * Will only return correct result when called from the context of a callback.\n * @return {Document} The DOM Document representing the XML file, or null\n * if no result available.\n */\ngoog.net.XhrIo.prototype.getResponseXml = function() {\n 'use strict';\n try {\n return this.xhr_ ? this.xhr_.responseXML : null;\n } catch (e) {\n goog.log.fine(this.logger_, 'Can not get responseXML: ' + e.message);\n return null;\n }\n};\n\n\n/**\n * Get the response and evaluates it as JSON from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for\n * stripping of the response before parsing. This needs to be set only if\n * your backend server prepends the same prefix string to the JSON response.\n * @throws Error if the response text is invalid JSON.\n * @return {Object|undefined} JavaScript object.\n */\ngoog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) {\n 'use strict';\n if (!this.xhr_) {\n return undefined;\n }\n\n let responseText = this.xhr_.responseText;\n if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) {\n responseText = responseText.substring(opt_xssiPrefix.length);\n }\n\n return goog.json.hybrid.parse(responseText);\n};\n\n\n/**\n * Get the response as the type specificed by {@link #setResponseType}. At time\n * of writing, this is only directly supported in very recent versions of WebKit\n * (10.0.612.1 dev and later). If the field is not supported directly, we will\n * try to emulate it.\n *\n * Emulating the response means following the rules laid out at\n * http://www.w3.org/TR/XMLHttpRequest/#the-response-attribute\n *\n * On browsers with no support for this (Chrome < 10, Firefox < 4, etc), only\n * response types of DEFAULT or TEXT may be used, and the response returned will\n * be the text response.\n *\n * On browsers with Mozilla's draft support for array buffers (Firefox 4, 5),\n * only response types of DEFAULT, TEXT, and ARRAY_BUFFER may be used, and the\n * response returned will be either the text response or the Mozilla\n * implementation of the array buffer response.\n *\n * On browsers will full support, any valid response type supported by the\n * browser may be used, and the response provided by the browser will be\n * returned.\n *\n * @return {*} The response.\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.net.XhrIo.prototype.getResponse = function() {\n 'use strict';\n try {\n if (!this.xhr_) {\n return null;\n }\n if ('response' in this.xhr_) {\n return this.xhr_.response;\n }\n switch (this.responseType_) {\n case ResponseType.DEFAULT:\n case ResponseType.TEXT:\n return this.xhr_.responseText;\n // DOCUMENT and BLOB don't need to be handled here because they are\n // introduced in the same spec that adds the .response field, and would\n // have been caught above.\n // ARRAY_BUFFER needs an implementation for Firefox 4, where it was\n // implemented using a draft spec rather than the final spec.\n case ResponseType.ARRAY_BUFFER:\n if ('mozResponseArrayBuffer' in this.xhr_) {\n return this.xhr_.mozResponseArrayBuffer;\n }\n }\n // Fell through to a response type that is not supported on this browser.\n goog.log.error(\n this.logger_,\n 'Response type ' + this.responseType_ + ' is not ' +\n 'supported on this browser');\n return null;\n } catch (e) {\n goog.log.fine(this.logger_, 'Can not get response: ' + e.message);\n return null;\n }\n};\n\n\n/**\n * Get the value of the response-header with the given name from the Xhr object\n * Will only return correct result when called from the context of a callback\n * and the request has completed\n * @param {string} key The name of the response-header to retrieve.\n * @return {string|undefined} The value of the response-header named key.\n */\ngoog.net.XhrIo.prototype.getResponseHeader = function(key) {\n 'use strict';\n if (!this.xhr_ || !this.isComplete()) {\n return undefined;\n }\n\n const value = this.xhr_.getResponseHeader(key);\n return value === null ? undefined : value;\n};\n\n\n/**\n * Gets the text of all the headers in the response.\n * Will only return correct result after ready state reaches `LOADED` (i.e.\n * `HEADERS_RECEIVED` as per MDN).\n * @return {string} The value of the response headers or empty string.\n */\ngoog.net.XhrIo.prototype.getAllResponseHeaders = function() {\n 'use strict';\n // getAllResponseHeaders can return null if no response has been received,\n // ensure we always return an empty string.\n return this.xhr_ &&\n this.getReadyState() >= goog.net.XmlHttp.ReadyState.LOADED ?\n (this.xhr_.getAllResponseHeaders() || '') :\n '';\n};\n\n\n/**\n * Returns all response headers as a key-value map.\n * Multiple values for the same header key can be combined into one,\n * separated by a comma and a space.\n * Note that the native getResponseHeader method for retrieving a single header\n * does a case insensitive match on the header name. This method does not\n * include any case normalization logic, it will just return a key-value\n * representation of the headers.\n * See: http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method\n * @return {!Object<string, string>} An object with the header keys as keys\n * and header values as values.\n */\ngoog.net.XhrIo.prototype.getResponseHeaders = function() {\n 'use strict';\n // TODO(user): Make this function parse headers as per the spec\n // (https://tools.ietf.org/html/rfc2616#section-4.2).\n\n const headersObject = {};\n const headersArray = this.getAllResponseHeaders().split('\\r\\n');\n for (let i = 0; i < headersArray.length; i++) {\n if (goog.string.isEmptyOrWhitespace(headersArray[i])) {\n continue;\n }\n const keyValue =\n goog.string.splitLimit(headersArray[i], ':', /* maxSplitCount= */ 1);\n const key = keyValue[0];\n let value = keyValue[1];\n\n if (typeof value !== 'string') {\n // There must be a value but it can be the empty string.\n continue;\n }\n\n // Whitespace at the start and end of the value is meaningless.\n value = value.trim();\n // The key should not contain whitespace but we currently ignore that.\n\n const values = headersObject[key] || [];\n headersObject[key] = values;\n values.push(value);\n }\n\n return goog.object.map(headersObject, function(values) {\n 'use strict';\n return values.join(', ');\n });\n};\n\n\n/**\n * Get the value of the response-header with the given name from the Xhr object.\n * As opposed to {@link #getResponseHeader}, this method does not require that\n * the request has completed.\n * @param {string} key The name of the response-header to retrieve.\n * @return {?string} The value of the response-header, or null if it is\n * unavailable.\n */\ngoog.net.XhrIo.prototype.getStreamingResponseHeader = function(key) {\n 'use strict';\n return this.xhr_ ? this.xhr_.getResponseHeader(key) : null;\n};\n\n\n/**\n * Gets the text of all the headers in the response. As opposed to\n * {@link #getAllResponseHeaders}, this method does not require that the request\n * has completed.\n * @return {string} The value of the response headers or empty string.\n */\ngoog.net.XhrIo.prototype.getAllStreamingResponseHeaders = function() {\n 'use strict';\n return this.xhr_ ? this.xhr_.getAllResponseHeaders() : '';\n};\n\n\n/**\n * Get the last error message\n * @return {!goog.net.ErrorCode} Last error code.\n */\ngoog.net.XhrIo.prototype.getLastErrorCode = function() {\n 'use strict';\n return this.lastErrorCode_;\n};\n\n\n/**\n * Get the last error message\n * @return {string} Last error message.\n */\ngoog.net.XhrIo.prototype.getLastError = function() {\n 'use strict';\n return typeof this.lastError_ === 'string' ? this.lastError_ :\n String(this.lastError_);\n};\n\n\n/**\n * Adds the last method, status and URI to the message. This is used to add\n * this information to the logging calls.\n * @param {string} msg The message text that we want to add the extra text to.\n * @return {string} The message with the extra text appended.\n * @private\n */\ngoog.net.XhrIo.prototype.formatMsg_ = function(msg) {\n 'use strict';\n return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' +\n this.getStatus() + ']';\n};\n\n\n// Register the xhr handler as an entry point, so that\n// it can be monitored for exception handling, etc.\ngoog.debug.entryPointRegistry.register(\n /**\n * @param {function(!Function): !Function} transformer The transforming\n * function.\n */\n function(transformer) {\n 'use strict';\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =\n transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);\n });\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Provides a function to throw an error without interrupting\n * the current execution context.\n */\n\ngoog.module('goog.async.throwException');\ngoog.module.declareLegacyNamespace();\n\n/**\n * Throw an item without interrupting the current execution context. For\n * example, if processing a group of items in a loop, sometimes it is useful\n * to report an error while still allowing the rest of the batch to be\n * processed.\n * @param {*} exception\n */\nfunction throwException(exception) {\n // Each throw needs to be in its own context.\n goog.global.setTimeout(() => {\n throw exception;\n }, 0);\n}\nexports = throwException;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A timer class to which other classes and objects can listen on.\n * This is only an abstraction above `setInterval`.\n *\n * @see ../demos/timers.html\n */\n\ngoog.provide('goog.Timer');\n\ngoog.require('goog.Promise');\ngoog.require('goog.events.EventTarget');\ngoog.requireType('goog.Thenable');\n\n\n\n/**\n * Class for handling timing events.\n *\n * @param {number=} opt_interval Number of ms between ticks (default: 1ms).\n * @param {Object=} opt_timerObject An object that has `setTimeout`,\n * `setInterval`, `clearTimeout` and `clearInterval`\n * (e.g., `window`).\n * @constructor\n * @extends {goog.events.EventTarget}\n */\ngoog.Timer = function(opt_interval, opt_timerObject) {\n 'use strict';\n goog.events.EventTarget.call(this);\n\n /**\n * Number of ms between ticks\n * @private {number}\n */\n this.interval_ = opt_interval || 1;\n\n /**\n * An object that implements `setTimeout`, `setInterval`,\n * `clearTimeout` and `clearInterval`. We default to the window\n * object. Changing this on {@link goog.Timer.prototype} changes the object\n * for all timer instances which can be useful if your environment has some\n * other implementation of timers than the `window` object.\n * @private {{setTimeout:!Function, clearTimeout:!Function}}\n */\n this.timerObject_ = /** @type {{setTimeout, clearTimeout}} */ (\n opt_timerObject || goog.Timer.defaultTimerObject);\n\n /**\n * Cached `tick_` bound to the object for later use in the timer.\n * @private {Function}\n * @const\n */\n this.boundTick_ = goog.bind(this.tick_, this);\n\n /**\n * Firefox browser often fires the timer event sooner (sometimes MUCH sooner)\n * than the requested timeout. So we compare the time to when the event was\n * last fired, and reschedule if appropriate. See also\n * {@link goog.Timer.intervalScale}.\n * @private {number}\n */\n this.last_ = goog.now();\n};\ngoog.inherits(goog.Timer, goog.events.EventTarget);\n\n\n/**\n * Maximum timeout value.\n *\n * Timeout values too big to fit into a signed 32-bit integer may cause overflow\n * in FF, Safari, and Chrome, resulting in the timeout being scheduled\n * immediately. It makes more sense simply not to schedule these timeouts, since\n * 24.8 days is beyond a reasonable expectation for the browser to stay open.\n *\n * @private {number}\n * @const\n */\ngoog.Timer.MAX_TIMEOUT_ = 2147483647;\n\n\n/**\n * A timer ID that cannot be returned by any known implementation of\n * `window.setTimeout`. Passing this value to `window.clearTimeout`\n * should therefore be a no-op.\n *\n * @private {number}\n * @const\n */\ngoog.Timer.INVALID_TIMEOUT_ID_ = -1;\n\n\n/**\n * Whether this timer is enabled\n * @type {boolean}\n */\ngoog.Timer.prototype.enabled = false;\n\n\n/**\n * An object that implements `setTimeout`, `setInterval`,\n * `clearTimeout` and `clearInterval`. We default to the global\n * object. Changing `goog.Timer.defaultTimerObject` changes the object for\n * all timer instances which can be useful if your environment has some other\n * implementation of timers you'd like to use.\n * @type {{setTimeout, clearTimeout}}\n */\ngoog.Timer.defaultTimerObject = goog.global;\n\n\n/**\n * Variable that controls the timer error correction. If the timer is called\n * before the requested interval times `intervalScale`, which often\n * happens on Mozilla, the timer is rescheduled.\n * @see {@link #last_}\n * @type {number}\n */\ngoog.Timer.intervalScale = 0.8;\n\n\n/**\n * Variable for storing the result of `setInterval`.\n * @private {?number}\n */\ngoog.Timer.prototype.timer_ = null;\n\n\n/**\n * Gets the interval of the timer.\n * @return {number} interval Number of ms between ticks.\n */\ngoog.Timer.prototype.getInterval = function() {\n 'use strict';\n return this.interval_;\n};\n\n\n/**\n * Sets the interval of the timer.\n * @param {number} interval Number of ms between ticks.\n */\ngoog.Timer.prototype.setInterval = function(interval) {\n 'use strict';\n this.interval_ = interval;\n if (this.timer_ && this.enabled) {\n // Stop and then start the timer to reset the interval.\n this.stop();\n this.start();\n } else if (this.timer_) {\n this.stop();\n }\n};\n\n\n/**\n * Callback for the `setTimeout` used by the timer.\n * @private\n */\ngoog.Timer.prototype.tick_ = function() {\n 'use strict';\n if (this.enabled) {\n var elapsed = goog.now() - this.last_;\n if (elapsed > 0 && elapsed < this.interval_ * goog.Timer.intervalScale) {\n this.timer_ = this.timerObject_.setTimeout(\n this.boundTick_, this.interval_ - elapsed);\n return;\n }\n\n // Prevents setInterval from registering a duplicate timeout when called\n // in the timer event handler.\n if (this.timer_) {\n this.timerObject_.clearTimeout(this.timer_);\n this.timer_ = null;\n }\n\n this.dispatchTick();\n // The timer could be stopped in the timer event handler.\n if (this.enabled) {\n // Stop and start to ensure there is always only one timeout even if\n // start is called in the timer event handler.\n this.stop();\n this.start();\n }\n }\n};\n\n\n/**\n * Dispatches the TICK event. This is its own method so subclasses can override.\n */\ngoog.Timer.prototype.dispatchTick = function() {\n 'use strict';\n this.dispatchEvent(goog.Timer.TICK);\n};\n\n\n/**\n * Starts the timer.\n */\ngoog.Timer.prototype.start = function() {\n 'use strict';\n this.enabled = true;\n\n // If there is no interval already registered, start it now\n if (!this.timer_) {\n // IMPORTANT!\n // window.setInterval in FireFox has a bug - it fires based on\n // absolute time, rather than on relative time. What this means\n // is that if a computer is sleeping/hibernating for 24 hours\n // and the timer interval was configured to fire every 1000ms,\n // then after the PC wakes up the timer will fire, in rapid\n // succession, 3600*24 times.\n // This bug is described here and is already fixed, but it will\n // take time to propagate, so for now I am switching this over\n // to setTimeout logic.\n // https://bugzilla.mozilla.org/show_bug.cgi?id=376643\n //\n this.timer_ = this.timerObject_.setTimeout(this.boundTick_, this.interval_);\n this.last_ = goog.now();\n }\n};\n\n\n/**\n * Stops the timer.\n */\ngoog.Timer.prototype.stop = function() {\n 'use strict';\n this.enabled = false;\n if (this.timer_) {\n this.timerObject_.clearTimeout(this.timer_);\n this.timer_ = null;\n }\n};\n\n\n/** @override */\ngoog.Timer.prototype.disposeInternal = function() {\n 'use strict';\n goog.Timer.superClass_.disposeInternal.call(this);\n this.stop();\n delete this.timerObject_;\n};\n\n\n/**\n * Constant for the timer's event type.\n * @const\n */\ngoog.Timer.TICK = 'tick';\n\n\n/**\n * Calls the given function once, after the optional pause.\n * <p>\n * The function is always called asynchronously, even if the delay is 0. This\n * is a common trick to schedule a function to run after a batch of browser\n * event processing.\n *\n * @param {function(this:SCOPE)|{handleEvent:function()}|null} listener Function\n * or object that has a handleEvent method.\n * @param {number=} opt_delay Milliseconds to wait; default is 0.\n * @param {SCOPE=} opt_handler Object in whose scope to call the listener.\n * @return {number} A handle to the timer ID.\n * @template SCOPE\n */\ngoog.Timer.callOnce = function(listener, opt_delay, opt_handler) {\n 'use strict';\n if (typeof listener === 'function') {\n if (opt_handler) {\n listener = goog.bind(listener, opt_handler);\n }\n } else if (listener && typeof listener.handleEvent == 'function') {\n // using typeof to prevent strict js warning\n listener = goog.bind(listener.handleEvent, listener);\n } else {\n throw new Error('Invalid listener argument');\n }\n\n if (Number(opt_delay) > goog.Timer.MAX_TIMEOUT_) {\n // Timeouts greater than MAX_INT return immediately due to integer\n // overflow in many browsers. Since MAX_INT is 24.8 days, just don't\n // schedule anything at all.\n return goog.Timer.INVALID_TIMEOUT_ID_;\n } else {\n return goog.Timer.defaultTimerObject.setTimeout(listener, opt_delay || 0);\n }\n};\n\n\n/**\n * Clears a timeout initiated by {@link #callOnce}.\n * @param {?number} timerId A timer ID.\n */\ngoog.Timer.clear = function(timerId) {\n 'use strict';\n goog.Timer.defaultTimerObject.clearTimeout(timerId);\n};\n\n\n/**\n * @param {number} delay Milliseconds to wait.\n * @param {(RESULT|goog.Thenable<RESULT>|Thenable)=} opt_result The value\n * with which the promise will be resolved.\n * @return {!goog.Promise<RESULT>} A promise that will be resolved after\n * the specified delay, unless it is canceled first.\n * @template RESULT\n */\ngoog.Timer.promise = function(delay, opt_result) {\n 'use strict';\n var timerKey = null;\n return new goog\n .Promise(function(resolve, reject) {\n 'use strict';\n timerKey = goog.Timer.callOnce(function() {\n 'use strict';\n resolve(opt_result);\n }, delay);\n if (timerKey == goog.Timer.INVALID_TIMEOUT_ID_) {\n reject(new Error('Failed to schedule timer.'));\n }\n })\n .thenCatch(function(error) {\n 'use strict';\n // Clear the timer. The most likely reason is \"cancel\" signal.\n goog.Timer.clear(timerKey);\n throw error;\n });\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Definition of the goog.async.Throttle class.\n *\n * @see ../demos/timers.html\n */\n\ngoog.module('goog.async.Throttle');\ngoog.module.declareLegacyNamespace();\n\nconst Disposable = goog.require('goog.Disposable');\nconst Timer = goog.require('goog.Timer');\n\n\n/**\n * Throttle will perform an action that is passed in no more than once\n * per interval (specified in milliseconds). If it gets multiple signals\n * to perform the action while it is waiting, it will only perform the action\n * once at the end of the interval.\n * @final\n * @template T\n */\nclass Throttle extends Disposable {\n /**\n * @param {function(this: T, ...?)} listener Function to callback when the\n * action is triggered.\n * @param {number} interval Interval over which to throttle. The listener can\n * only be called once per interval.\n * @param {T=} handler Object in whose scope to call the listener.\n */\n constructor(listener, interval, handler) {\n super();\n /**\n * Function to callback\n * @type {function(this: T, ...?)}\n * @private\n */\n this.listener_ = handler != null ? listener.bind(handler) : listener;\n\n /**\n * Interval for the throttle time\n * @type {number}\n * @private\n */\n this.interval_ = interval;\n\n /**\n * The last arguments passed into `fire`, or null if there is no pending\n * call.\n * @private {?IArrayLike}\n */\n this.args_ = null;\n\n /**\n * Indicates that the action is pending and needs to be fired.\n * @type {boolean}\n * @private\n */\n this.shouldFire_ = false;\n\n /**\n * Indicates the count of nested pauses currently in effect on the throttle.\n * When this count is not zero, fired actions will be postponed until the\n * throttle is resumed enough times to drop the pause count to zero.\n * @type {number}\n * @private\n */\n this.pauseCount_ = 0;\n\n /**\n * Timer for scheduling the next callback\n * @type {?number}\n * @private\n */\n this.timer_ = null;\n }\n\n /**\n * Notifies the throttle that the action has happened. It will throttle\n * the call so that the callback is not called too often according to the\n * interval parameter passed to the constructor, passing the arguments\n * from the last call of this function into the throttled function.\n * @param {...?} var_args Arguments to pass on to the throttled function.\n */\n fire(var_args) {\n this.args_ = arguments;\n if (!this.timer_ && !this.pauseCount_) {\n this.doAction_();\n } else {\n this.shouldFire_ = true;\n }\n }\n\n /**\n * Cancels any pending action callback. The throttle can be restarted by\n * calling {@link #fire}.\n */\n stop() {\n if (this.timer_) {\n Timer.clear(this.timer_);\n this.timer_ = null;\n this.shouldFire_ = false;\n this.args_ = null;\n }\n }\n\n /**\n * Pauses the throttle. All pending and future action callbacks will be\n * delayed until the throttle is resumed. Pauses can be nested.\n */\n pause() {\n this.pauseCount_++;\n }\n\n /**\n * Resumes the throttle. If doing so drops the pausing count to zero,\n * pending action callbacks will be executed as soon as possible, but\n * still no sooner than an interval's delay after the previous call.\n * Future action callbacks will be executed as normal.\n */\n resume() {\n this.pauseCount_--;\n if (!this.pauseCount_ && this.shouldFire_ && !this.timer_) {\n this.shouldFire_ = false;\n this.doAction_();\n }\n }\n\n /** @override */\n disposeInternal() {\n super.disposeInternal();\n this.stop();\n }\n\n /**\n * Handler for the timer to fire the throttle\n * @private\n */\n onTimer_() {\n this.timer_ = null;\n\n if (this.shouldFire_ && !this.pauseCount_) {\n this.shouldFire_ = false;\n this.doAction_();\n }\n }\n\n /**\n * Calls the callback\n * @private\n */\n doAction_() {\n this.timer_ = Timer.callOnce(() => this.onTimer_(), this.interval_);\n const args = this.args_;\n // release memory first so it always happens even if listener throws\n this.args_ = null;\n this.listener_.apply(null, args);\n }\n}\n\nexports = Throttle;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Class to create objects which want to handle multiple events\n * and have their listeners easily cleaned up via a dispose method.\n *\n * Example:\n * <pre>\n * function Something() {\n * Something.base(this);\n *\n * ... set up object ...\n *\n * // Add event listeners\n * this.listen(this.starEl, goog.events.EventType.CLICK, this.handleStar);\n * this.listen(this.headerEl, goog.events.EventType.CLICK, this.expand);\n * this.listen(this.collapseEl, goog.events.EventType.CLICK, this.collapse);\n * this.listen(this.infoEl, goog.events.EventType.MOUSEOVER, this.showHover);\n * this.listen(this.infoEl, goog.events.EventType.MOUSEOUT, this.hideHover);\n * }\n * goog.inherits(Something, goog.events.EventHandler);\n *\n * Something.prototype.disposeInternal = function() {\n * Something.base(this, 'disposeInternal');\n * goog.dom.removeNode(this.container);\n * };\n *\n *\n * // Then elsewhere:\n *\n * var activeSomething = null;\n * function openSomething() {\n * activeSomething = new Something();\n * }\n *\n * function closeSomething() {\n * if (activeSomething) {\n * activeSomething.dispose(); // Remove event listeners\n * activeSomething = null;\n * }\n * }\n * </pre>\n */\n\ngoog.provide('goog.events.EventHandler');\n\ngoog.require('goog.Disposable');\ngoog.require('goog.events');\ngoog.require('goog.object');\ngoog.requireType('goog.events.Event');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventTarget');\ngoog.requireType('goog.events.EventWrapper');\n\n\n\n/**\n * Super class for objects that want to easily manage a number of event\n * listeners. It allows a short cut to listen and also provides a quick way\n * to remove all events listeners belonging to this object.\n * @param {SCOPE=} opt_scope Object in whose scope to call the listeners.\n * @constructor\n * @extends {goog.Disposable}\n * @template SCOPE\n */\ngoog.events.EventHandler = function(opt_scope) {\n 'use strict';\n goog.Disposable.call(this);\n // TODO(mknichel): Rename this to this.scope_ and fix the classes in google3\n // that access this private variable. :(\n this.handler_ = opt_scope;\n\n /**\n * Keys for events that are being listened to.\n * @type {!Object<!goog.events.Key>}\n * @private\n */\n this.keys_ = {};\n};\ngoog.inherits(goog.events.EventHandler, goog.Disposable);\n\n\n/**\n * Utility array used to unify the cases of listening for an array of types\n * and listening for a single event, without using recursion or allocating\n * an array each time.\n * @type {!Array<string>}\n * @const\n * @private\n */\ngoog.events.EventHandler.typeArray_ = [];\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted then the\n * EventHandler's handleEvent method will be used.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\n * opt_fn Optional callback function to be used as the listener or an object\n * with handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listen = function(\n src, type, opt_fn, opt_options) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n return self.listen_(src, type, opt_fn, opt_options);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted then the\n * EventHandler's handleEvent method will be used.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}|\n * null|undefined} fn Optional callback function to be used as the\n * listener or an object with handleEvent function.\n * @param {boolean|!AddEventListenerOptions|undefined} options\n * @param {T} scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template T, EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listenWithScope = function(\n src, type, fn, options, scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Deprecate this function.\n return self.listen_(src, type, fn, options, scope);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted then the\n * EventHandler's handleEvent method will be used.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn\n * Optional callback function to be used as the listener or an object with\n * handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {Object=} opt_scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n * @private\n */\ngoog.events.EventHandler.prototype.listen_ = function(\n src, type, opt_fn, opt_options, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n if (!Array.isArray(type)) {\n if (type) {\n goog.events.EventHandler.typeArray_[0] = type.toString();\n }\n type = goog.events.EventHandler.typeArray_;\n }\n for (var i = 0; i < type.length; i++) {\n var listenerObj = goog.events.listen(\n src, type[i], opt_fn || self.handleEvent, opt_options || false,\n opt_scope || self.handler_ || self);\n\n if (!listenerObj) {\n // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT\n // (goog.events.CaptureSimulationMode) in IE8-, it will return null\n // value.\n return self;\n }\n\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n var key = listenerObj.key;\n self.keys_[key] = listenerObj;\n }\n\n return self;\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted, then the\n * EventHandler's handleEvent method will be used. After the event has fired the\n * event listener is removed from the target. If an array of event types is\n * provided, each event type will be listened to once.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\n * opt_fn\n * Optional callback function to be used as the listener or an object with\n * handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listenOnce = function(\n src, type, opt_fn, opt_options) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n return self.listenOnce_(src, type, opt_fn, opt_options);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted, then the\n * EventHandler's handleEvent method will be used. After the event has fired the\n * event listener is removed from the target. If an array of event types is\n * provided, each event type will be listened to once.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}|\n * null|undefined} fn Optional callback function to be used as the\n * listener or an object with handleEvent function.\n * @param {boolean|undefined} capture Optional whether to use capture phase.\n * @param {T} scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template T, EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listenOnceWithScope = function(\n src, type, fn, capture, scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Deprecate this function.\n return self.listenOnce_(src, type, fn, capture, scope);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted, then the\n * EventHandler's handleEvent method will be used. After the event has fired\n * the event listener is removed from the target. If an array of event types is\n * provided, each event type will be listened to once.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn\n * Optional callback function to be used as the listener or an object with\n * handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {Object=} opt_scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n * @private\n */\ngoog.events.EventHandler.prototype.listenOnce_ = function(\n src, type, opt_fn, opt_options, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n self.listenOnce_(src, type[i], opt_fn, opt_options, opt_scope);\n }\n } else {\n var listenerObj = goog.events.listenOnce(\n src, type, opt_fn || self.handleEvent, opt_options,\n opt_scope || self.handler_ || self);\n if (!listenerObj) {\n // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT\n // (goog.events.CaptureSimulationMode) in IE8-, it will return null\n // value.\n return self;\n }\n\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n var key = listenerObj.key;\n self.keys_[key] = listenerObj;\n }\n\n return self;\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.EventTarget}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\n * events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(this:SCOPE, ?):?|{handleEvent:function(?):?}|null} listener\n * Callback method, or an object with a handleEvent function.\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\n * false).\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template THIS\n */\ngoog.events.EventHandler.prototype.listenWithWrapper = function(\n src, wrapper, listener, opt_capt) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Remove the opt_scope from this function and then\n // templatize it.\n return self.listenWithWrapper_(src, wrapper, listener, opt_capt);\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.EventTarget}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\n * events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(this:T, ?):?|{handleEvent:function(this:T, ?):?}|null}\n * listener Optional callback function to be used as the\n * listener or an object with handleEvent function.\n * @param {boolean|undefined} capture Optional whether to use capture phase.\n * @param {T} scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template T, THIS\n */\ngoog.events.EventHandler.prototype.listenWithWrapperAndScope = function(\n src, wrapper, listener, capture, scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Deprecate this function.\n return self.listenWithWrapper_(src, wrapper, listener, capture, scope);\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.EventTarget}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\n * events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener Callback\n * method, or an object with a handleEvent function.\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\n * false).\n * @param {Object=} opt_scope Element in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template THIS\n * @private\n */\ngoog.events.EventHandler.prototype.listenWithWrapper_ = function(\n src, wrapper, listener, opt_capt, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n wrapper.listen(\n src, listener, opt_capt, opt_scope || self.handler_ || self, self);\n return self;\n};\n\n\n/**\n * @return {number} Number of listeners registered by this handler.\n */\ngoog.events.EventHandler.prototype.getListenerCount = function() {\n 'use strict';\n var count = 0;\n for (var key in this.keys_) {\n if (Object.prototype.hasOwnProperty.call(this.keys_, key)) {\n count++;\n }\n }\n return count;\n};\n\n\n/**\n * Unlistens on an event.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types to unlisten to.\n * @param {function(this:?, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\n * opt_fn Optional callback function to be used as the listener or an object\n * with handleEvent function.\n * @param {(boolean|!EventListenerOptions)=} opt_options\n * @param {Object=} opt_scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.unlisten = function(\n src, type, opt_fn, opt_options, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n self.unlisten(src, type[i], opt_fn, opt_options, opt_scope);\n }\n } else {\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n var listener = goog.events.getListener(\n src, type, opt_fn || self.handleEvent, capture,\n opt_scope || self.handler_ || self);\n\n if (listener) {\n goog.events.unlistenByKey(listener);\n delete self.keys_[listener.key];\n }\n }\n\n return self;\n};\n\n\n/**\n * Removes an event listener which was added with listenWithWrapper().\n *\n * @param {EventTarget|goog.events.EventTarget} src The target to stop\n * listening to events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\n * listener function to remove.\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase of the\n * event.\n * @param {Object=} opt_scope Element in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template THIS\n */\ngoog.events.EventHandler.prototype.unlistenWithWrapper = function(\n src, wrapper, listener, opt_capt, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n wrapper.unlisten(\n src, listener, opt_capt, opt_scope || self.handler_ || self, self);\n return self;\n};\n\n\n/**\n * Unlistens to all events.\n */\ngoog.events.EventHandler.prototype.removeAll = function() {\n 'use strict';\n goog.object.forEach(this.keys_, function(listenerObj, key) {\n 'use strict';\n if (this.keys_.hasOwnProperty(key)) {\n goog.events.unlistenByKey(listenerObj);\n }\n }, this);\n\n this.keys_ = {};\n};\n\n\n/**\n * Disposes of this EventHandler and removes all listeners that it registered.\n * @override\n * @protected\n */\ngoog.events.EventHandler.prototype.disposeInternal = function() {\n 'use strict';\n goog.events.EventHandler.superClass_.disposeInternal.call(this);\n this.removeAll();\n};\n\n\n/**\n * Default event handler\n * @param {goog.events.Event} e Event object.\n */\ngoog.events.EventHandler.prototype.handleEvent = function(e) {\n 'use strict';\n throw new Error('EventHandler.handleEvent not implemented');\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Provides a utility for tracing and debugging WebChannel\n * requests.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.WebChannelDebug');\n\ngoog.require('goog.json');\ngoog.require('goog.log');\ngoog.requireType('goog.Uri');\ngoog.requireType('goog.net.XmlHttp.ReadyState');\n\n\n\n/**\n * Logs and keeps a buffer of debugging info for the Channel.\n *\n * @constructor\n * @struct\n * @final\n */\ngoog.labs.net.webChannel.WebChannelDebug = function() {\n 'use strict';\n /**\n * The logger instance.\n * @const\n * @private {?goog.log.Logger}\n */\n this.logger_ = goog.log.getLogger('goog.labs.net.webChannel.WebChannelDebug');\n\n /**\n * Whether to enable redact. Defaults to true.\n * @private {boolean}\n */\n this.redactEnabled_ = true;\n};\n\n\ngoog.scope(function() {\n'use strict';\nvar WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\n\n\n/**\n * Turns off redact.\n */\nWebChannelDebug.prototype.disableRedact = function() {\n 'use strict';\n this.redactEnabled_ = false;\n};\n\n\n/**\n * Logs that the browser went offline during the lifetime of a request.\n * @param {goog.Uri} url The URL being requested.\n */\nWebChannelDebug.prototype.browserOfflineResponse = function(url) {\n 'use strict';\n this.info(function() {\n 'use strict';\n return 'BROWSER_OFFLINE: ' + url;\n });\n};\n\n\n/**\n * Logs an XmlHttp request..\n * @param {string} verb The request type (GET/POST).\n * @param {goog.Uri} uri The request destination.\n * @param {string|number|undefined} id The request id.\n * @param {number} attempt Which attempt # the request was.\n * @param {?string} postData The data posted in the request.\n */\nWebChannelDebug.prototype.xmlHttpChannelRequest = function(\n verb, uri, id, attempt, postData) {\n 'use strict';\n var self = this;\n this.info(function() {\n 'use strict';\n return 'XMLHTTP REQ (' + id + ') [attempt ' + attempt + ']: ' + verb +\n '\\n' + uri + '\\n' + self.maybeRedactPostData_(postData);\n });\n};\n\n\n/**\n * Logs the meta data received from an XmlHttp request.\n * @param {string} verb The request type (GET/POST).\n * @param {goog.Uri} uri The request destination.\n * @param {string|number|undefined} id The request id.\n * @param {number} attempt Which attempt # the request was.\n * @param {goog.net.XmlHttp.ReadyState} readyState The ready state.\n * @param {number} statusCode The HTTP status code.\n */\nWebChannelDebug.prototype.xmlHttpChannelResponseMetaData = function(\n verb, uri, id, attempt, readyState, statusCode) {\n 'use strict';\n this.info(function() {\n 'use strict';\n return 'XMLHTTP RESP (' + id + ') [ attempt ' + attempt + ']: ' + verb +\n '\\n' + uri + '\\n' + readyState + ' ' + statusCode;\n });\n};\n\n\n/**\n * Logs the response data received from an XmlHttp request.\n * @param {string|number|undefined} id The request id.\n * @param {?string} responseText The response text.\n * @param {?string=} opt_desc Optional request description.\n */\nWebChannelDebug.prototype.xmlHttpChannelResponseText = function(\n id, responseText, opt_desc) {\n 'use strict';\n var self = this;\n this.info(function() {\n 'use strict';\n return 'XMLHTTP TEXT (' + id + '): ' + self.redactResponse_(responseText) +\n (opt_desc ? ' ' + opt_desc : '');\n });\n};\n\n\n/**\n * Logs a request timeout.\n * @param {goog.Uri} uri The uri that timed out.\n */\nWebChannelDebug.prototype.timeoutResponse = function(uri) {\n 'use strict';\n this.info(function() {\n 'use strict';\n return 'TIMEOUT: ' + uri;\n });\n};\n\n\n/**\n * Logs a debug message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.debug = function(text) {\n 'use strict';\n goog.log.fine(this.logger_, text);\n};\n\n\n/**\n * Logs an exception\n * @param {Error} e The error or error event.\n * @param {goog.log.Loggable=} opt_msg The optional message,\n * defaults to 'Exception'.\n */\nWebChannelDebug.prototype.dumpException = function(e, opt_msg) {\n 'use strict';\n goog.log.error(this.logger_, opt_msg || 'Exception', e);\n};\n\n\n/**\n * Logs an info message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.info = function(text) {\n 'use strict';\n goog.log.info(this.logger_, text);\n};\n\n\n/**\n * Logs a warning message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.warning = function(text) {\n 'use strict';\n goog.log.warning(this.logger_, text);\n};\n\n\n/**\n * Logs a severe message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.severe = function(text) {\n 'use strict';\n goog.log.error(this.logger_, text);\n};\n\n\n/**\n * Removes potentially private data from a response so that we don't\n * accidentally save private and personal data to the server logs.\n * @param {?string} responseText A JSON response to clean.\n * @return {?string} The cleaned response.\n * @private\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\nWebChannelDebug.prototype.redactResponse_ = function(responseText) {\n 'use strict';\n if (!this.redactEnabled_) {\n return responseText;\n }\n\n if (!responseText) {\n return null;\n }\n\n try {\n var responseArray = JSON.parse(responseText);\n if (responseArray) {\n for (var i = 0; i < responseArray.length; i++) {\n if (Array.isArray(responseArray[i])) {\n this.maybeRedactArray_(responseArray[i]);\n }\n }\n }\n\n return goog.json.serialize(responseArray);\n } catch (e) {\n this.debug('Exception parsing expected JS array - probably was not JS');\n return responseText;\n }\n};\n\n\n/**\n * Removes data from a response array that may be sensitive.\n * @param {!Array<?>} array The array to clean.\n * @private\n */\nWebChannelDebug.prototype.maybeRedactArray_ = function(array) {\n 'use strict';\n if (array.length < 2) {\n return;\n }\n var dataPart = array[1];\n if (!Array.isArray(dataPart)) {\n return;\n }\n if (dataPart.length < 1) {\n return;\n }\n\n var type = dataPart[0];\n if (type != 'noop' && type != 'stop' && type != 'close') {\n // redact all fields in the array\n for (var i = 1; i < dataPart.length; i++) {\n dataPart[i] = '';\n }\n }\n};\n\n\n/**\n * Removes potentially private data from a request POST body so that we don't\n * accidentally save private and personal data to the server logs.\n * @param {?string} data The data string to clean.\n * @return {?string} The data string with sensitive data replaced by 'redacted'.\n * @private\n */\nWebChannelDebug.prototype.maybeRedactPostData_ = function(data) {\n 'use strict';\n if (!this.redactEnabled_) {\n return data;\n }\n\n if (!data) {\n return null;\n }\n var out = '';\n var params = data.split('&');\n for (var i = 0; i < params.length; i++) {\n var param = params[i];\n var keyValue = param.split('=');\n if (keyValue.length > 1) {\n var key = keyValue[0];\n var value = keyValue[1];\n\n var keyParts = key.split('_');\n if (keyParts.length >= 2 && keyParts[1] == 'type') {\n out += key + '=' + value + '&';\n } else {\n out += key + '=' +\n 'redacted' +\n '&';\n }\n }\n }\n return out;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Static utilities for collecting stats associated with\n * ChannelRequest.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.requestStats');\ngoog.provide('goog.labs.net.webChannel.requestStats.Event');\ngoog.provide('goog.labs.net.webChannel.requestStats.ServerReachability');\ngoog.provide('goog.labs.net.webChannel.requestStats.ServerReachabilityEvent');\ngoog.provide('goog.labs.net.webChannel.requestStats.Stat');\ngoog.provide('goog.labs.net.webChannel.requestStats.StatEvent');\ngoog.provide('goog.labs.net.webChannel.requestStats.TimingEvent');\n\ngoog.require('goog.events.Event');\ngoog.require('goog.events.EventTarget');\n\n\ngoog.scope(function() {\n'use strict';\nconst requestStats = goog.labs.net.webChannel.requestStats;\n\n\n/**\n * Events fired.\n * @const\n */\nrequestStats.Event = {};\n\n\n/**\n * Singleton event target for firing stat events\n * @type {?goog.events.EventTarget}\n * @private\n */\nrequestStats.eventTarget_ = null;\n\n/**\n * Singleton event target for firing stat events\n * @return {!goog.events.EventTarget}\n * @private\n */\nrequestStats.getStatEventTarget_ = function() {\n 'use strict';\n requestStats.eventTarget_ =\n requestStats.eventTarget_ || new goog.events.EventTarget();\n return requestStats.eventTarget_;\n};\n\n/**\n * The type of event that occurs every time some information about how reachable\n * the server is is discovered.\n */\nrequestStats.Event.SERVER_REACHABILITY_EVENT = 'serverreachability';\n\n\n/**\n * Types of events which reveal information about the reachability of the\n * server.\n * @enum {number}\n */\nrequestStats.ServerReachability = {\n REQUEST_MADE: 1,\n REQUEST_SUCCEEDED: 2,\n REQUEST_FAILED: 3,\n BACK_CHANNEL_ACTIVITY: 4 // any response data received\n};\n\n\n\n/**\n * Event class for SERVER_REACHABILITY_EVENT.\n *\n * @param {goog.events.EventTarget} target The stat event target for\n the channel.\n * @param {requestStats.ServerReachability} reachabilityType\n * The reachability event type.\n * @constructor\n * @extends {goog.events.Event}\n */\nrequestStats.ServerReachabilityEvent = function(target, reachabilityType) {\n 'use strict';\n goog.events.Event.call(\n this, requestStats.Event.SERVER_REACHABILITY_EVENT, target);\n\n /**\n * @type {requestStats.ServerReachability}\n */\n this.reachabilityType = reachabilityType;\n};\ngoog.inherits(requestStats.ServerReachabilityEvent, goog.events.Event);\n\n\n/**\n * Notify the channel that a particular fine grained network event has occurred.\n * Should be considered package-private.\n * @param {requestStats.ServerReachability} reachabilityType\n * The reachability event type.\n */\nrequestStats.notifyServerReachabilityEvent = function(reachabilityType) {\n 'use strict';\n const target = requestStats.getStatEventTarget_();\n target.dispatchEvent(\n new requestStats.ServerReachabilityEvent(target, reachabilityType));\n};\n\n\n/**\n * Stat Event that fires when things of interest happen that may be useful for\n * applications to know about for stats or debugging purposes.\n */\nrequestStats.Event.STAT_EVENT = 'statevent';\n\n\n/**\n * Enum that identifies events for statistics that are interesting to track.\n * @enum {number}\n */\nrequestStats.Stat = {\n /** Event indicating a new connection attempt. */\n CONNECT_ATTEMPT: 0,\n\n /** Event indicating a connection error due to a general network problem. */\n ERROR_NETWORK: 1,\n\n /**\n * Event indicating a connection error that isn't due to a general network\n * problem.\n */\n ERROR_OTHER: 2,\n\n /** Event indicating the start of test stage one. */\n TEST_STAGE_ONE_START: 3,\n\n /** Event indicating the start of test stage two. */\n TEST_STAGE_TWO_START: 4,\n\n /** Event indicating the first piece of test data was received. */\n TEST_STAGE_TWO_DATA_ONE: 5,\n\n /**\n * Event indicating that the second piece of test data was received and it was\n * received separately from the first.\n */\n TEST_STAGE_TWO_DATA_TWO: 6,\n\n /** Event indicating both pieces of test data were received simultaneously. */\n TEST_STAGE_TWO_DATA_BOTH: 7,\n\n /** Event indicating stage one of the test request failed. */\n TEST_STAGE_ONE_FAILED: 8,\n\n /** Event indicating stage two of the test request failed. */\n TEST_STAGE_TWO_FAILED: 9,\n\n /**\n * Event indicating that a buffering proxy is likely between the client and\n * the server.\n */\n PROXY: 10,\n\n /**\n * Event indicating that no buffering proxy is likely between the client and\n * the server.\n */\n NOPROXY: 11,\n\n /** Event indicating an unknown SID error. */\n REQUEST_UNKNOWN_SESSION_ID: 12,\n\n /** Event indicating a bad status code was received. */\n REQUEST_BAD_STATUS: 13,\n\n /** Event indicating incomplete data was received */\n REQUEST_INCOMPLETE_DATA: 14,\n\n /** Event indicating bad data was received */\n REQUEST_BAD_DATA: 15,\n\n /** Event indicating no data was received when data was expected. */\n REQUEST_NO_DATA: 16,\n\n /** Event indicating a request timeout. */\n REQUEST_TIMEOUT: 17,\n\n /**\n * Event indicating that the server never received our hanging GET and so it\n * is being retried.\n */\n BACKCHANNEL_MISSING: 18,\n\n /**\n * Event indicating that we have determined that our hanging GET is not\n * receiving data when it should be. Thus it is dead dead and will be retried.\n */\n BACKCHANNEL_DEAD: 19,\n\n /**\n * The browser declared itself offline during the lifetime of a request, or\n * was offline when a request was initially made.\n */\n BROWSER_OFFLINE: 20\n};\n\n\n\n/**\n * Event class for STAT_EVENT.\n *\n * @param {goog.events.EventTarget} eventTarget The stat event target for\n the channel.\n * @param {requestStats.Stat} stat The stat.\n * @constructor\n * @extends {goog.events.Event}\n */\nrequestStats.StatEvent = function(eventTarget, stat) {\n 'use strict';\n goog.events.Event.call(this, requestStats.Event.STAT_EVENT, eventTarget);\n\n /**\n * The stat\n * @type {requestStats.Stat}\n */\n this.stat = stat;\n};\ngoog.inherits(requestStats.StatEvent, goog.events.Event);\n\n\n/**\n * Returns the singleton event target for stat events.\n * @return {!goog.events.EventTarget} The event target for stat events.\n */\nrequestStats.getStatEventTarget = function() {\n 'use strict';\n return requestStats.getStatEventTarget_();\n};\n\n\n/**\n * Helper function to call the stat event callback.\n * @param {requestStats.Stat} stat The stat.\n */\nrequestStats.notifyStatEvent = function(stat) {\n 'use strict';\n const target = requestStats.getStatEventTarget_();\n target.dispatchEvent(new requestStats.StatEvent(target, stat));\n};\n\n\n/**\n * An event that fires when POST requests complete successfully, indicating\n * the size of the POST and the round trip time.\n */\nrequestStats.Event.TIMING_EVENT = 'timingevent';\n\n\n\n/**\n * Event class for requestStats.Event.TIMING_EVENT\n *\n * @param {goog.events.EventTarget} target The stat event target for\n the channel.\n * @param {number} size The number of characters in the POST data.\n * @param {number} rtt The total round trip time from POST to response in MS.\n * @param {number} retries The number of times the POST had to be retried.\n * @constructor\n * @extends {goog.events.Event}\n */\nrequestStats.TimingEvent = function(target, size, rtt, retries) {\n 'use strict';\n goog.events.Event.call(this, requestStats.Event.TIMING_EVENT, target);\n\n /**\n * @type {number}\n */\n this.size = size;\n\n /**\n * @type {number}\n */\n this.rtt = rtt;\n\n /**\n * @type {number}\n */\n this.retries = retries;\n};\ngoog.inherits(requestStats.TimingEvent, goog.events.Event);\n\n\n/**\n * Helper function to notify listeners about POST request performance.\n *\n * @param {number} size Number of characters in the POST data.\n * @param {number} rtt The amount of time from POST start to response.\n * @param {number} retries The number of times the POST had to be retried.\n */\nrequestStats.notifyTimingEvent = function(size, rtt, retries) {\n 'use strict';\n const target = requestStats.getStatEventTarget_();\n target.dispatchEvent(\n new requestStats.TimingEvent(target, size, rtt, retries));\n};\n\n\n/**\n * Allows the application to set an execution hooks for when a channel\n * starts processing requests. This is useful to track timing or logging\n * special information. The function takes no parameters and return void.\n * @param {Function} startHook The function for the start hook.\n */\nrequestStats.setStartThreadExecutionHook = function(startHook) {\n 'use strict';\n requestStats.startExecutionHook_ = startHook;\n};\n\n\n/**\n * Allows the application to set an execution hooks for when a channel\n * stops processing requests. This is useful to track timing or logging\n * special information. The function takes no parameters and return void.\n * @param {Function} endHook The function for the end hook.\n */\nrequestStats.setEndThreadExecutionHook = function(endHook) {\n 'use strict';\n requestStats.endExecutionHook_ = endHook;\n};\n\n\n/**\n * Application provided execution hook for the start hook.\n *\n * @type {Function}\n * @private\n */\nrequestStats.startExecutionHook_ = function() {};\n\n\n/**\n * Application provided execution hook for the end hook.\n *\n * @type {Function}\n * @private\n */\nrequestStats.endExecutionHook_ = function() {};\n\n\n/**\n * Helper function to call the start hook\n */\nrequestStats.onStartExecution = function() {\n 'use strict';\n requestStats.startExecutionHook_();\n};\n\n\n/**\n * Helper function to call the end hook\n */\nrequestStats.onEndExecution = function() {\n 'use strict';\n requestStats.endExecutionHook_();\n};\n\n\n/**\n * Wrapper around SafeTimeout which calls the start and end execution hooks\n * with a try...finally block.\n * @param {Function} fn The callback function.\n * @param {number} ms The time in MS for the timer.\n * @return {number} The ID of the timer.\n */\nrequestStats.setTimeout = function(fn, ms) {\n 'use strict';\n if (typeof fn !== 'function') {\n throw new Error('Fn must not be null and must be a function');\n }\n return goog.global.setTimeout(function() {\n 'use strict';\n requestStats.onStartExecution();\n try {\n fn();\n } finally {\n requestStats.onEndExecution();\n }\n }, ms);\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Error codes shared between goog.net.IframeIo and\n * goog.net.XhrIo.\n */\n\ngoog.provide('goog.net.ErrorCode');\n\n\n/**\n * Error codes\n * @enum {number}\n */\ngoog.net.ErrorCode = {\n\n /**\n * There is no error condition.\n */\n NO_ERROR: 0,\n\n /**\n * The most common error from iframeio, unfortunately, is that the browser\n * responded with an error page that is classed as a different domain. The\n * situations, are when a browser error page is shown -- 404, access denied,\n * DNS failure, connection reset etc.)\n *\n */\n ACCESS_DENIED: 1,\n\n /**\n * Currently the only case where file not found will be caused is when the\n * code is running on the local file system and a non-IE browser makes a\n * request to a file that doesn't exist.\n */\n FILE_NOT_FOUND: 2,\n\n /**\n * If Firefox shows a browser error page, such as a connection reset by\n * server or access denied, then it will fail silently without the error or\n * load handlers firing.\n */\n FF_SILENT_ERROR: 3,\n\n /**\n * Custom error provided by the client through the error check hook.\n */\n CUSTOM_ERROR: 4,\n\n /**\n * Exception was thrown while processing the request.\n */\n EXCEPTION: 5,\n\n /**\n * The Http response returned a non-successful http status code.\n */\n HTTP_ERROR: 6,\n\n /**\n * The request was aborted.\n */\n ABORT: 7,\n\n /**\n * The request timed out.\n */\n TIMEOUT: 8,\n\n /**\n * The resource is not available offline.\n */\n OFFLINE: 9,\n};\n\n\n/**\n * Returns a friendly error message for an error code. These messages are for\n * debugging and are not localized.\n * @param {goog.net.ErrorCode} errorCode An error code.\n * @return {string} A message for debugging.\n */\ngoog.net.ErrorCode.getDebugMessage = function(errorCode) {\n 'use strict';\n switch (errorCode) {\n case goog.net.ErrorCode.NO_ERROR:\n return 'No Error';\n\n case goog.net.ErrorCode.ACCESS_DENIED:\n return 'Access denied to content document';\n\n case goog.net.ErrorCode.FILE_NOT_FOUND:\n return 'File not found';\n\n case goog.net.ErrorCode.FF_SILENT_ERROR:\n return 'Firefox silently errored';\n\n case goog.net.ErrorCode.CUSTOM_ERROR:\n return 'Application custom error';\n\n case goog.net.ErrorCode.EXCEPTION:\n return 'An exception occurred';\n\n case goog.net.ErrorCode.HTTP_ERROR:\n return 'Http response at 400 or 500 level';\n\n case goog.net.ErrorCode.ABORT:\n return 'Request was aborted';\n\n case goog.net.ErrorCode.TIMEOUT:\n return 'Request timed out';\n\n case goog.net.ErrorCode.OFFLINE:\n return 'The resource is not available offline';\n\n default:\n return 'Unrecognized error code';\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Common events for the network classes.\n */\n\n\ngoog.provide('goog.net.EventType');\n\n\n/**\n * Event names for network events\n * @enum {string}\n */\ngoog.net.EventType = {\n COMPLETE: 'complete',\n SUCCESS: 'success',\n ERROR: 'error',\n ABORT: 'abort',\n READY: 'ready',\n READY_STATE_CHANGE: 'readystatechange',\n TIMEOUT: 'timeout',\n INCREMENTAL_DATA: 'incrementaldata',\n PROGRESS: 'progress',\n // DOWNLOAD_PROGRESS and UPLOAD_PROGRESS are special events dispatched by\n // goog.net.XhrIo to allow binding listeners specific to each type of\n // progress.\n DOWNLOAD_PROGRESS: 'downloadprogress',\n UPLOAD_PROGRESS: 'uploadprogress',\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Interface for a factory for creating XMLHttpRequest objects\n * and metadata about them.\n */\n\ngoog.provide('goog.net.XmlHttpFactory');\n\n/** @suppress {extraRequire} Typedef. */\ngoog.require('goog.net.XhrLike');\n\n\n\n/**\n * Abstract base class for an XmlHttpRequest factory.\n * @constructor\n */\ngoog.net.XmlHttpFactory = function() {};\n\n\n/**\n * Cache of options - we only actually call internalGetOptions once.\n * @type {?Object}\n * @private\n */\ngoog.net.XmlHttpFactory.prototype.cachedOptions_ = null;\n\n\n/**\n * @return {!goog.net.XhrLike.OrNative} A new XhrLike instance.\n */\ngoog.net.XmlHttpFactory.prototype.createInstance = goog.abstractMethod;\n\n\n/**\n * @return {Object} Options describing how xhr objects obtained from this\n * factory should be used.\n */\ngoog.net.XmlHttpFactory.prototype.getOptions = function() {\n 'use strict';\n return this.cachedOptions_ ||\n (this.cachedOptions_ = this.internalGetOptions());\n};\n\n\n/**\n * Override this method in subclasses to preserve the caching offered by\n * getOptions().\n * @return {Object} Options describing how xhr objects obtained from this\n * factory should be used.\n * @protected\n */\ngoog.net.XmlHttpFactory.prototype.internalGetOptions = goog.abstractMethod;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview The API spec for the WebChannel messaging library.\n *\n * Similar to HTML5 WebSocket, WebChannel offers an abstraction for\n * point-to-point socket-like communication between a browser client and\n * a remote origin.\n *\n * WebChannels are created via <code>WebChannel</code>. Multiple WebChannels\n * may be multiplexed over the same WebChannelTransport, which encapsulates\n * the underlying physical connectivity over standard wire protocols\n * such as HTTP.\n *\n * A WebChannel in turn represents a logical communication channel between\n * the client and server endpoint. A WebChannel remains open for as long\n * as the client or server endpoint allows.\n *\n * Messages are delivered in-order and reliably over the same WebChannel,\n * and the choice of the underlying wire protocols is completely transparent\n * to the API users.\n *\n * Note that we have no immediate plan to move this API out of labs. While\n * the implementation is production ready, the API is subject to change.\n */\n\ngoog.provide('goog.net.WebChannel');\ngoog.provide('goog.net.WebChannel.Options');\n\ngoog.require('goog.events');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.Listenable');\ngoog.require('goog.net.XmlHttpFactory');\n\n\n\n/**\n * A WebChannel represents a logical bi-directional channel over which the\n * client communicates with a remote server that holds the other endpoint\n * of the channel. A WebChannel is always created in the context of a shared\n * {@link WebChannelTransport} instance. It is up to the underlying client-side\n * and server-side implementations to decide how or when multiplexing is\n * to be enabled.\n *\n * @interface\n * @extends {goog.events.Listenable}\n */\ngoog.net.WebChannel = function() {};\n\n\n\n/**\n * This interface defines a pluggable API to allow WebChannel runtime to support\n * customized algorithms in order to recover from transient failures such as\n * those failures caused by network or proxies (intermediaries).\n *\n * The algorithm may also choose to fail-fast, e.g. switch the client to some\n * offline mode.\n *\n * Extra measurements and logging could also be implemented in the custom\n * module, which has the full knowledge of all the state transitions\n * (due to failures).\n *\n * A default algorithm will be provided by the webchannel library itself. Custom\n * algorithms are expected to be tailored to specific client platforms or\n * networking environments, e.g. mobile, cellular network.\n *\n * @interface\n */\ngoog.net.WebChannel.FailureRecovery = function() {};\n\n\n/**\n * Configuration spec for newly created WebChannel instances.\n *\n * WebChannels are configured in the context of the containing\n * {@link WebChannelTransport}. The configuration parameters are specified\n * when a new instance of WebChannel is created via {@link WebChannelTransport}.\n * @record\n */\ngoog.net.WebChannel.Options = function() {};\n\n/**\n * Transport-metadata support.\n *\n * Custom HTTP headers to be added to every message sent to the server. This\n * object is mutable, and custom headers may be changed, removed, or added\n * during the runtime after a channel has been opened.\n *\n * Custom headers may trigger CORS preflight. See other related options.\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.messageHeaders;\n\n/**\n * Transport-metadata support.\n *\n * Similar to messageHeaders, but any custom HTTP headers will be sent only once\n * when the channel is opened as part of the handshake request. Typical usage is\n * to send an auth header to the server, which only checks the auth header at\n * the time during the handshake when the channel is opened.\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.initMessageHeaders;\n\n/**\n * Sent as initMessageHeaders via X-WebChannel-Content-Type,\n * to inform the server the MIME type of WebChannel messages.\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.messageContentType;\n\n/**\n * Transport-metadata support.\n *\n * Custom url query parameters to be added to every message sent to the server.\n * This object is mutable, and custom parameters may be changed, removed or\n * added during the runtime after a channel has been opened.\n *\n * TODO: initMessageUrlParams\n * TODO: closeMessageUrlParams (custom url query params to be added to the\n * channel-close message. Custom headers are not supported due to the use of\n * SendBeacon)\n *\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.messageUrlParams;\n\n/**\n * Whether a special header should be added to\n * each message so that the server can dispatch webchannel messages without\n * knowing the URL path prefix. Defaults to false.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.clientProtocolHeaderRequired;\n\n/**\n * The maximum number of in-flight HTTP requests allowed\n * when SPDY is enabled. Currently we only detect SPDY in Chrome.\n * This parameter defaults to 10. When SPDY is not enabled, this parameter\n * will have no effect.\n * @type {number|undefined}\n */\ngoog.net.WebChannel.Options.prototype.concurrentRequestLimit;\n\n/**\n * Setting this to true to allow the use of sub-domains\n * (as configured by the server) to send XHRs with the CORS withCredentials\n * bit set to true.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.supportsCrossDomainXhr;\n\n/**\n * Whether to bypass v8 encoding of client-sent messages.\n * This defaults to false now due to legacy servers. New applications should\n * always configure this option to true.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.sendRawJson;\n\n/**\n * The URL parameter name that contains the session id (for sticky routing of\n * HTTP requests). When this param is specified, a server that supports this\n * option will respond with an opaque session id as part of the initial\n * handshake (via the X-HTTP-Session-Id header); and all the subsequent requests\n * will contain the httpSessionIdParam. This option will take precedence over\n * any duplicated parameter specified with messageUrlParams, whose value will be\n * ignored.\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.httpSessionIdParam;\n\n/**\n * The URL parameter name to allow custom HTTP\n * headers to be overwritten as a URL param to bypass CORS preflight.\n *\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.httpHeadersOverwriteParam;\n\n/**\n * Whether to encode Options.initMessageHeaders in the HTTP request body.\n * This option defaults to false. If true, Options.httpHeadersOverwriteParam\n * will be ignored.\n *\n * This option should not be set if Options.fastHandshake is set (which\n * uses GET for handshake).\n *\n * Web-only feature.\n *\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.encodeInitMessageHeaders;\n\n/**\n * Whether to force long-polling from client to server.\n * This defaults to false. Long-polling may be necessary when a (MITM) proxy\n * is buffering data sent by the server.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.forceLongPolling;\n\n/**\n * Whether to enable automatic detection of buffering proxies. In the presence\n * of any buffering proxy, webchannel will use long-polling to send messages\n * from the server to the client. This option defaults to false.\n * Currently when fastHandshake is enabled, this option will be ignored.\n * Compared to \"forceLongPolling\", this option may introduce up to 2-RTT\n * extra latency for delivering messages generated immediately after the\n * handshake.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.detectBufferingProxy;\n\n/**\n * This option informs the server the desired maximum timeout interval (in\n * Milliseconds) to complete a long-polling GET response, e.g. to accommodate\n * the timeout enforced by a proxy. The WebChannel server may adjust the\n * specified timeout or may ignore this client-configured timeout.\n * @type {number|undefined}\n */\ngoog.net.WebChannel.Options.prototype.longPollingTimeout;\n\n/**\n * Enable true 0-RTT message delivery, including\n * leveraging QUIC 0-RTT (which requires GET to be used). This option\n * defaults to false. Note it is allowed to send messages before Open event is\n * received, after a channel has been opened. In order to enable 0-RTT,\n * messages will be encoded as part of URL and therefore there needs be a size\n * limit for those initial messages that are sent immediately as part of the\n * GET handshake request. With sendRawJson=true, this limit is currently set\n * to 4K chars and data beyond this limit will be buffered till the handshake\n * (1-RTT) finishes. With sendRawJson=false, it's up to the application\n * to limit the amount of data that is sent as part of the handshake.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.fastHandshake;\n\n/**\n * Enable the blocking RPC semantics for the handshake:\n * 1) the completion of handshake is blocked by the server-side application\n * logic for handling the handshake (HTTP) request; 2) the client application\n * will inspect the handshake (HTTP) response headers as generated\n * by the server application (v.s. by only the webchannel runtime). This option\n * defaults to false.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.blockingHandshake;\n\n/**\n * Whether to disable logging redact. By default, redact is\n * enabled to remove any message payload or user-provided info\n * from closure logs.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.disableRedact;\n\n/**\n * Inform the server about the client profile to enable\n * customized configs that are optimized for certain clients or environments.\n * Currently this information is sent via X-WebChannel-Client-Profile header.\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.clientProfile;\n\n/**\n * The internal channel parameter name to allow\n * experimental channel configurations. Supported options include fastfail,\n * baseRetryDelayMs, retryDelaySeedMs, forwardChannelMaxRetries and\n * forwardChannelRequestTimeoutMs. Note that these options are subject to\n * change.\n * @type {!Object<string, boolean|number>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.internalChannelParams;\n\n/**\n * Allows the caller to override the factory used to create\n * XMLHttpRequest objects. This is introduced to disable CORS on firefox OS.\n * @type {!goog.net.XmlHttpFactory|undefined}\n */\ngoog.net.WebChannel.Options.prototype.xmlHttpFactory;\n\n/**\n * Client-side thresholds that decide when to refresh\n * an underlying HTTP request, to limit memory consumption due to XHR buffering\n * or compression context. The client-side thresholds should be significantly\n * smaller than the server-side thresholds. This allows the client to eliminate\n * any latency introduced by request refreshing, i.e. an RTT window during which\n * messages may be buffered on the server-side. Supported params include\n * totalBytesReceived, totalDurationMs.\n * @type {!Object<string, number>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.requestRefreshThresholds;\n\n/**\n * This is an experimental feature to use WHATWG Fetch/streams (when supported)\n * for the backchannel. If a custom 'xmlHttpFactory' is speficied, this option\n * will not be effective. This option defaults to false now and will eventually\n * be turned on by default.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.useFetchStreams;\n\n/**\n * Opt-in to enable Chrome origin trials from the WebChannel client. See\n * https://github.com/GoogleChrome/OriginTrials\n *\n * Origin trial history:\n * - fetch upload (11/2020 - 07/2021)\n * https://developers.chrome.com/origintrials/#/view_trial/3524066708417413121\n *\n * Participating in the origin trials will help Chrome to release new Web\n * platform features sooner, which will in turn help improve WebChannel\n * performance.\n *\n * Origin trials are not expected to interfere with WebChannel wire messages\n * and should not introduce any noticeable overhead.\n *\n * This is enabled by default with any on-going origin-trial.\n *\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.enableOriginTrials;\n\n\n/**\n * Types that are allowed as message data.\n *\n * Note that JS objects (sent by the client) can only have string encoded\n * values due to the limitation of the current wire protocol.\n *\n * Unicode strings (sent by the server) may or may not need be escaped, as\n * decided by the server.\n *\n * @typedef {(!ArrayBuffer|!Blob|!Object<string, !Object|string>|!Array|string)}\n */\ngoog.net.WebChannel.MessageData;\n\n\n/**\n * Open the WebChannel against the URI specified in the constructor.\n */\ngoog.net.WebChannel.prototype.open = goog.abstractMethod;\n\n\n/**\n * Close the WebChannel.\n *\n * This is a full close (shutdown) with no guarantee of FIFO delivery in respect\n * to any in-flight messages sent to the server.\n *\n * If you need such a guarantee, see the Half the halfClose() method.\n */\ngoog.net.WebChannel.prototype.close = goog.abstractMethod;\n\n\n/**\n * Half-close the WebChannel.\n *\n * Half-close semantics:\n * 1. delivered as a regular message in FIFO programming order\n * 2. the server is expected to return a half-close too (with or without\n * application involved), which will trigger a full close (shutdown)\n * on the client side\n * 3. for now, the half-close event defined for server-initiated\n * half-close is not exposed to the client application\n * 4. a client-side half-close may be triggered internally when the client\n * receives a half-close from the server; and the client is expected to\n * do a full close after the half-close is acked and delivered\n * on the server-side.\n * 5. Full close is always a forced one. See the close() method.\n *\n * New messages sent after halfClose() will be dropped.\n *\n * NOTE: This is not yet implemented, and will throw an exception if called.\n */\ngoog.net.WebChannel.prototype.halfClose = goog.abstractMethod;\n\n\n/**\n * Sends a message to the server that maintains the other endpoint of\n * the WebChannel.\n *\n * O-RTT behavior:\n * 1. messages sent before open() is called will always be delivered as\n * part of the handshake, i.e. with 0-RTT\n * 2. messages sent after open() is called but before the OPEN event\n * is received will be delivered as part of the handshake if\n * send() is called from the same execution context as open().\n * 3. otherwise, those messages will be buffered till the handshake\n * is completed (which will fire the OPEN event).\n *\n * @param {!goog.net.WebChannel.MessageData} message The message to send.\n */\ngoog.net.WebChannel.prototype.send = goog.abstractMethod;\n\n\n/**\n * Common events fired by WebChannels.\n * @enum {string}\n */\ngoog.net.WebChannel.EventType = {\n /** Dispatched when the channel is opened. */\n OPEN: goog.events.getUniqueId('open'),\n\n /** Dispatched when the channel is closed. */\n CLOSE: goog.events.getUniqueId('close'),\n\n /**\n * Dispatched when the channel is aborted due to errors.\n *\n * For backward compatibility reasons, a CLOSE event will also be\n * dispatched, following the ERROR event, which indicates that the channel\n * has been completely shutdown .\n */\n ERROR: goog.events.getUniqueId('error'),\n\n /** Dispatched when the channel has received a new message. */\n MESSAGE: goog.events.getUniqueId('message')\n};\n\n\n\n/**\n * The event interface for the MESSAGE event.\n *\n * @constructor\n * @extends {goog.events.Event}\n */\ngoog.net.WebChannel.MessageEvent = function() {\n 'use strict';\n goog.net.WebChannel.MessageEvent.base(\n this, 'constructor', goog.net.WebChannel.EventType.MESSAGE);\n};\ngoog.inherits(goog.net.WebChannel.MessageEvent, goog.events.Event);\n\n\n/**\n * The content of the message received from the server.\n *\n * @type {!goog.net.WebChannel.MessageData}\n */\ngoog.net.WebChannel.MessageEvent.prototype.data;\n\n\n/**\n * The metadata key when the MESSAGE event represents a metadata message.\n *\n * @type {string|undefined}\n */\ngoog.net.WebChannel.MessageEvent.prototype.metadataKey;\n\n\n/**\n * Metadata as HTTP status code. Typically sent before the channel is\n * half-closed by the server.\n *\n * @type {number|undefined}\n */\ngoog.net.WebChannel.MessageEvent.prototype.statusCode;\n\n\n/**\n * Metadata as HTTP headers. Typically sent before the channel is\n * half-closed by the server.\n *\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.MessageEvent.prototype.headers;\n\n\n/**\n * WebChannel level error conditions.\n *\n * Summary of error debugging and reporting in WebChannel:\n *\n * Network Error\n * 1. By default the webchannel library will set the error status to\n * NETWORK_ERROR when a channel has to be aborted or closed. NETWORK_ERROR\n * may be recovered by the application by retrying and opening a new channel.\n * 2. There may be lost messages (not acked by the server) when a channel is\n * aborted. Currently we don't have a public API to retrieve messages that\n * are waiting to be acked on the client side. File a bug if you think it\n * is useful to expose such an API.\n * 3. Details of why a channel fails are available via closure debug logs,\n * and stats events (see webchannel/requeststats.js). Those are internal\n * stats and are subject to change. File a bug if you think it's useful to\n * version and expose such stats as part of the WebChannel API.\n *\n * Server Error\n * 1. SERVER_ERROR is intended to indicate a non-recoverable condition, e.g.\n * when auth fails.\n * 2. We don't currently generate any such errors, because most of the time\n * it's the responsibility of upper-layer frameworks or the application\n * itself to indicate to the client why a webchannel has been failed\n * by the server.\n * 3. When a channel is failed by the server explicitly, we still signal\n * NETWORK_ERROR to the client. Explicit server failure may happen when the\n * server does a fail-over, or becomes overloaded, or conducts a forced\n * shutdown etc.\n * 4. We use some heuristic to decide if the network (aka cloud) is down\n * v.s. the actual server is down.\n *\n * RuntimeProperties.getLastStatusCode is a useful state that we expose to\n * the client to indicate the HTTP response status code of the last HTTP\n * request initiated by the WebChannel client library, for debugging\n * purposes only.\n *\n * See WebChannel.Options.backChannelFailureRecovery and\n * WebChannel.FailureRecovery to install a custom failure-recovery algorithm.\n *\n * @enum {number}\n */\ngoog.net.WebChannel.ErrorStatus = {\n /** No error has occurred. */\n OK: 0,\n\n /** Communication to the server has failed. */\n NETWORK_ERROR: 1,\n\n /** The server fails to accept or process the WebChannel. */\n SERVER_ERROR: 2\n};\n\n\n\n/**\n * The event interface for the ERROR event.\n *\n * @constructor\n * @extends {goog.events.Event}\n */\ngoog.net.WebChannel.ErrorEvent = function() {\n 'use strict';\n goog.net.WebChannel.ErrorEvent.base(\n this, 'constructor', goog.net.WebChannel.EventType.ERROR);\n};\ngoog.inherits(goog.net.WebChannel.ErrorEvent, goog.events.Event);\n\n\n/**\n * The error status.\n *\n * @type {!goog.net.WebChannel.ErrorStatus}\n */\ngoog.net.WebChannel.ErrorEvent.prototype.status;\n\n\n/**\n * @return {!goog.net.WebChannel.RuntimeProperties} The runtime properties\n * of the WebChannel instance.\n */\ngoog.net.WebChannel.prototype.getRuntimeProperties = goog.abstractMethod;\n\n\n\n/**\n * The runtime properties of the WebChannel instance.\n *\n * This class is defined for debugging and monitoring purposes, as well as for\n * runtime functions that the application may choose to manage by itself.\n *\n * @interface\n */\ngoog.net.WebChannel.RuntimeProperties = function() {};\n\n\n/**\n * @return {number} The effective limit for the number of concurrent HTTP\n * requests that are allowed to be made for sending messages from the client\n * to the server. When SPDY is not enabled, this limit will be one.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getConcurrentRequestLimit =\n goog.abstractMethod;\n\n\n/**\n * For applications that need support multiple channels (e.g. from\n * different tabs) to the same origin, use this method to decide if SPDY is\n * enabled and therefore it is safe to open multiple channels.\n *\n * If SPDY is disabled, the application may choose to limit the number of active\n * channels to one or use other means such as sub-domains to work around\n * the browser connection limit.\n *\n * @return {boolean} Whether SPDY is enabled for the origin against which\n * the channel is created.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.isSpdyEnabled =\n goog.abstractMethod;\n\n\n/**\n * @return {number} The number of requests (for sending messages to the server)\n * that are pending. If this number is approaching the value of\n * getConcurrentRequestLimit(), client-to-server message delivery may experience\n * a higher latency.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getPendingRequestCount =\n goog.abstractMethod;\n\n\n/**\n * For applications to query the current HTTP session id, sent by the server\n * during the initial handshake.\n *\n * @return {?string} the HTTP session id or null if no HTTP session is in use.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getHttpSessionId =\n goog.abstractMethod;\n\n\n/**\n * Experimental API.\n *\n * This method generates an in-band commit request to the server, which will\n * ack the commit request as soon as all messages sent prior to this commit\n * request have been committed by the application.\n *\n * Committing a message has a stronger semantics than delivering a message\n * to the application. Detail spec:\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * Timeout or cancellation is not supported and the application is expected to\n * abort the channel if the commit-ack fails to arrive in time.\n *\n * ===\n *\n * This is currently implemented only in the client layer and the commit\n * callback will be invoked after all the pending client-sent messages have been\n * delivered by the server-side webchannel endpoint. This semantics is\n * different and weaker than what's required for end-to-end ack which requires\n * the server application to ack the in-order delivery of messages that are sent\n * before the commit request is issued.\n *\n * Commit should only be called after the channel open event is received.\n * Duplicated commits are allowed and only the last callback is guaranteed.\n * Commit called after the channel has been closed will be ignored.\n *\n * @param {function()} callback The callback will be invoked once an\n * ack has been received for the current commit or any newly issued commit.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.commit = goog.abstractMethod;\n\n\n/**\n * This method may be used by the application to recover from a peer failure\n * or to enable sender-initiated flow-control.\n *\n * Detail spec: https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * Note that the caller should NOT modify the list of returned messages.\n *\n * @return {!Array<!goog.net.WebChannel.MessageData>} The list of messages that\n * have not received commit-ack from the server; or if no commit has been\n * issued, the list of messages that have not been delivered to the server\n * application.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getNonAckedMessages =\n goog.abstractMethod;\n\n\n/**\n * A low water-mark message count to notify the application when the\n * flow-control condition is cleared, that is, when the application is\n * able to send more messages.\n *\n * We expect the application to configure a high water-mark message count,\n * which is checked via getNonAckedMessageCount(). When the high water-mark\n * is exceeded, the application should install a callback via this method\n * to be notified when to start to send new messages.\n *\n * This is not yet implemented.\n *\n * @param {number} count The low water-mark count. It is an error to pass\n * a non-positive value.\n * @param {function()} callback The call back to notify the application\n * when NonAckedMessageCount is below the specified low water-mark count.\n * Any previously registered callback is cleared. This new callback will\n * be cleared once it has been fired, or when the channel is closed or aborted.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.notifyNonAckedMessageCount =\n goog.abstractMethod;\n\n\n/**\n * Experimental API.\n *\n * This method registers a callback to handle the commit request sent\n * by the server. Commit protocol spec:\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * This is not yet implemented.\n *\n * @param {function(!Object)} callback The callback will take an opaque\n * commitId which needs be passed back to the server when an ack-commit\n * response is generated by the client application, via ackCommit().\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.onCommit = goog.abstractMethod;\n\n\n/**\n * Experimental API.\n *\n * This method is used by the application to generate an ack-commit response\n * for the given commitId. Commit protocol spec:\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * This is not yet implemented.\n *\n * @param {!Object} commitId The commitId which denotes the commit request\n * from the server that needs be ack'ed.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.ackCommit = goog.abstractMethod;\n\n\n/**\n * Transport-metadata support.\n *\n * Responses from the channel-close (abort) message are not available.\n *\n * In future when client-side half-close is supported, its response headers\n * will be available via this API too.\n * @return {!Object<string, string>|undefined} The response headers received\n * with the non-200 HTTP status code that causes the channel to be aborted.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getLastResponseHeaders =\n goog.abstractMethod;\n\n/**\n * Transport-metadata support.\n *\n * TODO: getInitStatusCode (handshake)\n * TODO: getInitResponseHeaders (handshake)\n *\n * Note that response headers from client-initiated close (abort) are not\n * available.\n *\n * In future when client-initiated half-close is supported, its response status\n * will be available via this API.\n *\n * @return {number} The non-200 HTTP status code received that causes the\n * channel to be aborted.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getLastStatusCode =\n goog.abstractMethod;\n\n\n/**\n * Enum to indicate the current recovery state.\n *\n * @enum {string}\n */\ngoog.net.WebChannel.FailureRecovery.State = {\n /** Initial state. */\n INIT: 'init',\n\n /** Once a failure has been detected. */\n FAILED: 'failed',\n\n /**\n * Once a recovery operation has been issued, e.g. a new request to resume\n * communication.\n */\n RECOVERING: 'recovering',\n\n /** The channel has been closed. */\n CLOSED: 'closed'\n};\n\n\n/**\n * Enum to indicate different failure conditions as detected by the webchannel\n * runtime.\n *\n * This enum is to be used only between the runtime and FailureRecovery module,\n * and new states are expected to be introduced in future.\n *\n * @enum {string}\n */\ngoog.net.WebChannel.FailureRecovery.FailureCondition = {\n /**\n * The HTTP response returned a non-successful http status code.\n */\n HTTP_ERROR: 'http_error',\n\n /**\n * The request was aborted.\n */\n ABORT: 'abort',\n\n /**\n * The request timed out.\n */\n TIMEOUT: 'timeout',\n\n /**\n * Exception was thrown while processing the request/response.\n */\n EXCEPTION: 'exception'\n};\n\n\n/**\n * @return {!goog.net.WebChannel.FailureRecovery.State} the current state,\n * mainly for debugging use.\n */\ngoog.net.WebChannel.FailureRecovery.prototype.getState = goog.abstractMethod;\n\n\n/**\n * This method is for WebChannel runtime to set the current failure condition\n * and to provide a callback for the algorithm to signal to the runtime\n * when it is time to issue a recovery operation, e.g. a new request to the\n * server.\n *\n * Supported transitions include:\n * INIT->FAILED\n * FAILED->FAILED (re-entry ok)\n * RECOVERY->FAILED.\n *\n * Ignored if state == CLOSED.\n *\n * Advanced implementations are expected to track all the state transitions\n * and their timestamps for monitoring purposes.\n *\n * @param {!goog.net.WebChannel.FailureRecovery.FailureCondition} failure The\n * new failure condition generated by the WebChannel runtime.\n * @param {!Function} operation The callback function to the WebChannel\n * runtime to issue a recovery operation, e.g. a new request. E.g. the default\n * recovery algorithm will issue timeout-based recovery operations.\n * Post-condition for the callback: state transition to RECOVERING.\n *\n * @return {!goog.net.WebChannel.FailureRecovery.State} The updated state\n * as decided by the failure recovery module. Upon a recoverable failure event,\n * the state is transitioned to RECOVERING; or the state is transitioned to\n * FAILED which indicates a fail-fast decision for the runtime to execute.\n */\ngoog.net.WebChannel.FailureRecovery.prototype.setFailure = goog.abstractMethod;\n\n\n/**\n * The Webchannel runtime needs call this method when webchannel is closed or\n * aborted.\n *\n * Once the instance is closed, any access to the instance will be a no-op.\n */\ngoog.net.WebChannel.FailureRecovery.prototype.close = goog.abstractMethod;\n\n\n/**\n * A request header to indicate to the server the messaging protocol\n * each HTTP message is speaking.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_CLIENT_PROTOCOL = 'X-Client-Protocol';\n\n\n/**\n * The value for x-client-protocol when the messaging protocol is WebChannel.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL = 'webchannel';\n\n\n/**\n * A response header for the server to signal the wire-protocol that\n * the browser establishes with the server (or proxy), e.g. \"spdy\" (aka http/2)\n * \"quic\". This information avoids the need to use private APIs to decide if\n * HTTP requests are multiplexed etc.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_CLIENT_WIRE_PROTOCOL = 'X-Client-Wire-Protocol';\n\n\n/**\n * A response header for the server to send back the HTTP session id as part of\n * the initial handshake. The value of the HTTP session id is opaque to the\n * WebChannel protocol.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_HTTP_SESSION_ID = 'X-HTTP-Session-Id';\n\n\n/**\n * A response header for the server to send back any initial response data as a\n * header to avoid any possible buffering by an intermediary, which may\n * be undesired during the handshake.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_HTTP_INITIAL_RESPONSE = 'X-HTTP-Initial-Response';\n\n\n/**\n * A request header for specifying the content-type of WebChannel messages,\n * e.g. application-defined JSON encoding styles. Currently this header\n * is sent by the client via initMessageHeaders when the channel is opened.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE = 'X-WebChannel-Content-Type';\n\n\n/**\n * A request header for specifying the client profile in order to apply\n * customized config params on the server side, e.g. timeouts.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE = 'X-WebChannel-Client-Profile';\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Low level handling of XMLHttpRequest.\n */\n\ngoog.provide('goog.net.DefaultXmlHttpFactory');\ngoog.provide('goog.net.XmlHttp');\ngoog.provide('goog.net.XmlHttp.OptionType');\ngoog.provide('goog.net.XmlHttp.ReadyState');\ngoog.provide('goog.net.XmlHttpDefines');\n\ngoog.require('goog.asserts');\ngoog.require('goog.net.WrapperXmlHttpFactory');\ngoog.require('goog.net.XmlHttpFactory');\ngoog.requireType('goog.net.XhrLike');\n\n\n/**\n * Static class for creating XMLHttpRequest objects.\n * @return {!goog.net.XhrLike.OrNative} A new XMLHttpRequest object.\n */\ngoog.net.XmlHttp = function() {\n 'use strict';\n return goog.net.XmlHttp.factory_.createInstance();\n};\n\n\n/**\n * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to\n * true bypasses the ActiveX probing code.\n * NOTE(ruilopes): Due to the way JSCompiler works, this define *will not* strip\n * out the ActiveX probing code from binaries. To achieve this, use\n * `goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR` instead.\n * TODO(ruilopes): Collapse both defines.\n */\ngoog.net.XmlHttp.ASSUME_NATIVE_XHR =\n goog.define('goog.net.XmlHttp.ASSUME_NATIVE_XHR', false);\n\n\n/** @const */\ngoog.net.XmlHttpDefines = {};\n\n\n/**\n * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to\n * true eliminates the ActiveX probing code.\n */\ngoog.net.XmlHttpDefines.ASSUME_NATIVE_XHR =\n goog.define('goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR', false);\n\n\n/**\n * Gets the options to use with the XMLHttpRequest objects obtained using\n * the static methods.\n * @return {Object} The options.\n */\ngoog.net.XmlHttp.getOptions = function() {\n 'use strict';\n return goog.net.XmlHttp.factory_.getOptions();\n};\n\n\n/**\n * Type of options that an XmlHttp object can have.\n * @enum {number}\n */\ngoog.net.XmlHttp.OptionType = {\n /**\n * Whether a no-op function should be used to clear the onreadystatechange\n * handler instead of null.\n */\n USE_NULL_FUNCTION: 0,\n\n /**\n * NOTE(user): In IE if send() errors on a *local* request the readystate\n * is still changed to COMPLETE. We need to ignore it and allow the\n * try/catch around send() to pick up the error.\n */\n LOCAL_REQUEST_ERROR: 1,\n};\n\n\n/**\n * Status constants for XMLHTTP, matches:\n * https://msdn.microsoft.com/en-us/library/ms534361(v=vs.85).aspx\n * @enum {number}\n */\ngoog.net.XmlHttp.ReadyState = {\n /**\n * Constant for when xmlhttprequest.readyState is uninitialized\n */\n UNINITIALIZED: 0,\n\n /**\n * Constant for when xmlhttprequest.readyState is loading.\n */\n LOADING: 1,\n\n /**\n * Constant for when xmlhttprequest.readyState is loaded.\n */\n LOADED: 2,\n\n /**\n * Constant for when xmlhttprequest.readyState is in an interactive state.\n */\n INTERACTIVE: 3,\n\n /**\n * Constant for when xmlhttprequest.readyState is completed\n */\n COMPLETE: 4,\n};\n\n\n/**\n * The global factory instance for creating XMLHttpRequest objects.\n * @type {goog.net.XmlHttpFactory}\n * @private\n */\ngoog.net.XmlHttp.factory_;\n\n\n/**\n * Sets the factories for creating XMLHttpRequest objects and their options.\n * @param {Function} factory The factory for XMLHttpRequest objects.\n * @param {Function} optionsFactory The factory for options.\n * @deprecated Use setGlobalFactory instead.\n */\ngoog.net.XmlHttp.setFactory = function(factory, optionsFactory) {\n 'use strict';\n goog.net.XmlHttp.setGlobalFactory(new goog.net.WrapperXmlHttpFactory(\n goog.asserts.assert(factory), goog.asserts.assert(optionsFactory)));\n};\n\n\n/**\n * Sets the global factory object.\n * @param {!goog.net.XmlHttpFactory} factory New global factory object.\n */\ngoog.net.XmlHttp.setGlobalFactory = function(factory) {\n 'use strict';\n goog.net.XmlHttp.factory_ = factory;\n};\n\n\n\n/**\n * Default factory to use when creating xhr objects. You probably shouldn't be\n * instantiating this directly, but rather using it via goog.net.XmlHttp.\n * @extends {goog.net.XmlHttpFactory}\n * @constructor\n */\ngoog.net.DefaultXmlHttpFactory = function() {\n 'use strict';\n goog.net.XmlHttpFactory.call(this);\n};\ngoog.inherits(goog.net.DefaultXmlHttpFactory, goog.net.XmlHttpFactory);\n\n\n/** @override */\ngoog.net.DefaultXmlHttpFactory.prototype.createInstance = function() {\n 'use strict';\n const progId = this.getProgId_();\n if (progId) {\n return new ActiveXObject(progId);\n } else {\n return new XMLHttpRequest();\n }\n};\n\n\n/** @override */\ngoog.net.DefaultXmlHttpFactory.prototype.internalGetOptions = function() {\n 'use strict';\n const progId = this.getProgId_();\n const options = {};\n if (progId) {\n options[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] = true;\n options[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] = true;\n }\n return options;\n};\n\n\n/**\n * The ActiveX PROG ID string to use to create xhr's in IE. Lazily initialized.\n * @type {string|undefined}\n * @private\n */\ngoog.net.DefaultXmlHttpFactory.prototype.ieProgId_;\n\n\n/**\n * Initialize the private state used by other functions.\n * @return {string} The ActiveX PROG ID string to use to create xhr's in IE.\n * @private\n */\ngoog.net.DefaultXmlHttpFactory.prototype.getProgId_ = function() {\n 'use strict';\n if (goog.net.XmlHttp.ASSUME_NATIVE_XHR ||\n goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR) {\n return '';\n }\n\n // The following blog post describes what PROG IDs to use to create the\n // XMLHTTP object in Internet Explorer:\n // http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx\n // However we do not (yet) fully trust that this will be OK for old versions\n // of IE on Win9x so we therefore keep the last 2.\n if (!this.ieProgId_ && typeof XMLHttpRequest == 'undefined' &&\n typeof ActiveXObject != 'undefined') {\n // Candidate Active X types.\n const ACTIVE_X_IDENTS = [\n 'MSXML2.XMLHTTP.6.0',\n 'MSXML2.XMLHTTP.3.0',\n 'MSXML2.XMLHTTP',\n 'Microsoft.XMLHTTP',\n ];\n for (let i = 0; i < ACTIVE_X_IDENTS.length; i++) {\n const candidate = ACTIVE_X_IDENTS[i];\n\n try {\n new ActiveXObject(candidate);\n // NOTE(user): cannot assign progid and return candidate in one line\n // because JSCompiler complaings: BUG 658126\n this.ieProgId_ = candidate;\n return candidate;\n } catch (e) {\n // do nothing; try next choice\n }\n }\n\n // couldn't find any matches\n throw new Error(\n 'Could not create ActiveXObject. ActiveX might be disabled,' +\n ' or MSXML might not be installed');\n }\n\n return /** @type {string} */ (this.ieProgId_);\n};\n\n\n// Set the global factory to an instance of the default factory.\ngoog.net.XmlHttp.setGlobalFactory(new goog.net.DefaultXmlHttpFactory());\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Definition of the ChannelRequest class. The request\n * object encapsulates the logic for making a single request, either for the\n * forward channel, back channel, or test channel, to the server. It contains\n * the logic for the two types of transports we use:\n * XMLHTTP and Image request. It provides timeout detection. More transports\n * to be added in future, such as Fetch, WebSocket.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.ChannelRequest');\n\ngoog.require('goog.Timer');\ngoog.require('goog.asserts');\ngoog.require('goog.async.Throttle');\ngoog.require('goog.dispose');\ngoog.require('goog.events.EventHandler');\ngoog.require('goog.labs.net.webChannel.Channel');\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\ngoog.require('goog.labs.net.webChannel.environment');\ngoog.require('goog.labs.net.webChannel.requestStats');\ngoog.require('goog.net.ErrorCode');\ngoog.require('goog.net.EventType');\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.net.XmlHttp');\ngoog.require('goog.object');\ngoog.require('goog.string');\ngoog.require('goog.userAgent');\ngoog.requireType('goog.Uri');\ngoog.requireType('goog.events.Event');\ngoog.requireType('goog.labs.net.webChannel.Wire.QueuedMap');\ngoog.requireType('goog.net.XhrIo');\n\n\n\n/**\n * A new ChannelRequest is created for each request to the server.\n *\n * @param {goog.labs.net.webChannel.Channel} channel\n * The channel that owns this request.\n * @param {goog.labs.net.webChannel.WebChannelDebug} channelDebug A\n * WebChannelDebug to use for logging.\n * @param {string=} opt_sessionId The session id for the channel.\n * @param {string|number=} opt_requestId The request id for this request.\n * @param {number=} opt_retryId The retry id for this request.\n * @constructor\n * @struct\n * @final\n */\ngoog.labs.net.webChannel.ChannelRequest = function(\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {\n 'use strict';\n /**\n * The channel object that owns the request.\n * @private {goog.labs.net.webChannel.Channel}\n */\n this.channel_ = channel;\n\n /**\n * The channel debug to use for logging\n * @private {goog.labs.net.webChannel.WebChannelDebug}\n */\n this.channelDebug_ = channelDebug;\n\n /**\n * The Session ID for the channel.\n * @private {string|undefined}\n */\n this.sid_ = opt_sessionId;\n\n /**\n * The RID (request ID) for the request.\n * @private {string|number|undefined}\n */\n this.rid_ = opt_requestId;\n\n /**\n * The attempt number of the current request.\n * @private {number}\n */\n this.retryId_ = opt_retryId || 1;\n\n /**\n * An object to keep track of the channel request event listeners.\n * @private {!goog.events.EventHandler<\n * !goog.labs.net.webChannel.ChannelRequest>}\n */\n this.eventHandler_ = new goog.events.EventHandler(this);\n\n /**\n * The timeout in ms before failing the request.\n * @private {number}\n */\n this.timeout_ = goog.labs.net.webChannel.ChannelRequest.TIMEOUT_MS_;\n\n /**\n * A timer for polling responseText in browsers that don't fire\n * onreadystatechange during incremental loading of responseText.\n * @private {goog.Timer}\n */\n this.pollingTimer_ =\n new goog.Timer(goog.labs.net.webChannel.environment.getPollingInterval());\n\n /**\n * Extra HTTP headers to add to all the requests sent to the server.\n * @private {?Object}\n */\n this.extraHeaders_ = null;\n\n\n /**\n * Whether the request was successful. This is only set to true after the\n * request successfully completes.\n * @private {boolean}\n */\n this.successful_ = false;\n\n\n /**\n * The TimerID of the timer used to detect if the request has timed-out.\n * @type {?number}\n * @private\n */\n this.watchDogTimerId_ = null;\n\n /**\n * The time in the future when the request will timeout.\n * @private {?number}\n */\n this.watchDogTimeoutTime_ = null;\n\n /**\n * The time the request started.\n * @private {?number}\n */\n this.requestStartTime_ = null;\n\n /**\n * The type of request (XMLHTTP, IMG)\n * @private {?number}\n */\n this.type_ = null;\n\n /**\n * The base Uri for the request. The includes all the parameters except the\n * one that indicates the retry number.\n * @private {?goog.Uri}\n */\n this.baseUri_ = null;\n\n /**\n * The request Uri that was actually used for the most recent request attempt.\n * @private {?goog.Uri}\n */\n this.requestUri_ = null;\n\n /**\n * The post data, if the request is a post.\n * @private {?string}\n */\n this.postData_ = null;\n\n /**\n * An array of pending messages that we have either received a non-successful\n * response for, or no response at all, and which therefore may or may not\n * have been received by the server.\n * @private {!Array<goog.labs.net.webChannel.Wire.QueuedMap>}\n */\n this.pendingMessages_ = [];\n\n /**\n * The XhrLte request if the request is using XMLHTTP\n * @private {?goog.net.XhrIo}\n */\n this.xmlHttp_ = null;\n\n /**\n * The position of where the next unprocessed chunk starts in the response\n * text.\n * @private {number}\n */\n this.xmlHttpChunkStart_ = 0;\n\n /**\n * The verb (Get or Post) for the request.\n * @private {?string}\n */\n this.verb_ = null;\n\n /**\n * The last error if the request failed.\n * @private {?goog.labs.net.webChannel.ChannelRequest.Error}\n */\n this.lastError_ = null;\n\n /**\n * The response headers received along with the non-200 status.\n *\n * @private {!Object<string, string>|undefined}\n */\n this.errorResponseHeaders_ = undefined;\n\n /**\n * The last status code received.\n * @private {number}\n */\n this.lastStatusCode_ = -1;\n\n /**\n * Whether the request has been cancelled due to a call to cancel.\n * @private {boolean}\n */\n this.cancelled_ = false;\n\n /**\n * A throttle time in ms for readystatechange events for the backchannel.\n * Useful for throttling when ready state is INTERACTIVE (partial data).\n * If set to zero no throttle is used.\n *\n * See WebChannelBase.prototype.readyStateChangeThrottleMs_\n *\n * @private {number}\n */\n this.readyStateChangeThrottleMs_ = 0;\n\n /**\n * The throttle for readystatechange events for the current request, or null\n * if there is none.\n * @private {?goog.async.Throttle}\n */\n this.readyStateChangeThrottle_ = null;\n\n /**\n * Whether to the result is expected to be encoded for chunking and thus\n * requires decoding.\n * @private {boolean}\n */\n this.decodeChunks_ = false;\n\n /**\n * Whether to decode x-http-initial-response.\n * @private {boolean}\n */\n this.decodeInitialResponse_ = false;\n\n /**\n * Whether x-http-initial-response has been decoded (dispatched).\n * @private {boolean}\n */\n this.initialResponseDecoded_ = false;\n\n /**\n * Whether the first byte of response body has arrived, for a successful\n * response.\n * @private {boolean}\n */\n this.firstByteReceived_ = false;\n\n /**\n * The current state of fetch responses if webchannel is using WHATWG\n * fetch/streams.\n * @private {!goog.labs.net.webChannel.FetchResponseState}\n */\n this.fetchResponseState_ = new goog.labs.net.webChannel.FetchResponseState();\n};\n\n/**\n * A collection of fetch/stream properties.\n * @struct\n * @constructor\n */\ngoog.labs.net.webChannel.FetchResponseState = function() {\n 'use strict';\n /**\n * The TextDecoder for decoding Uint8Array responses from fetch request.\n * @type {?goog.global.TextDecoder}\n */\n this.textDecoder = null;\n\n /**\n * The unconsumed response text from the fetch requests.\n * @type {string}\n */\n this.responseBuffer = '';\n\n /**\n * Whether or not the response body has arrived.\n * @type {boolean}\n */\n this.responseArrivedForFetch = false;\n};\n\n\ngoog.scope(function() {\n'use strict';\nconst WebChannel = goog.net.WebChannel;\nconst Channel = goog.labs.net.webChannel.Channel;\nconst ChannelRequest = goog.labs.net.webChannel.ChannelRequest;\nconst FetchResponseState = goog.labs.net.webChannel.FetchResponseState;\nconst requestStats = goog.labs.net.webChannel.requestStats;\nconst WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\nconst environment = goog.labs.net.webChannel.environment;\n\n/**\n * Default timeout in MS for a request. The server must return data within this\n * time limit for the request to not timeout.\n * @private {number}\n */\nChannelRequest.TIMEOUT_MS_ = 45 * 1000;\n\n\n/**\n * Enum for channel requests type\n * @enum {number}\n * @private\n */\nChannelRequest.Type_ = {\n /**\n * XMLHTTP requests.\n */\n XML_HTTP: 1,\n\n /**\n * IMG requests.\n */\n CLOSE_REQUEST: 2\n};\n\n\n/**\n * Enum type for identifying an error.\n * @enum {number}\n */\nChannelRequest.Error = {\n /**\n * Errors due to a non-200 status code.\n */\n STATUS: 0,\n\n /**\n * Errors due to no data being returned.\n */\n NO_DATA: 1,\n\n /**\n * Errors due to a timeout.\n */\n TIMEOUT: 2,\n\n /**\n * Errors due to the server returning an unknown.\n */\n UNKNOWN_SESSION_ID: 3,\n\n /**\n * Errors due to bad data being received.\n */\n BAD_DATA: 4,\n\n /**\n * Errors due to the handler throwing an exception.\n */\n HANDLER_EXCEPTION: 5,\n\n /**\n * The browser declared itself offline during the request.\n */\n BROWSER_OFFLINE: 6\n};\n\n\n/**\n * Returns a useful error string for debugging based on the specified error\n * code.\n * @param {?ChannelRequest.Error} errorCode The error code.\n * @param {number} statusCode The HTTP status code.\n * @return {string} The error string for the given code combination.\n */\nChannelRequest.errorStringFromCode = function(errorCode, statusCode) {\n 'use strict';\n switch (errorCode) {\n case ChannelRequest.Error.STATUS:\n return 'Non-200 return code (' + statusCode + ')';\n case ChannelRequest.Error.NO_DATA:\n return 'XMLHTTP failure (no data)';\n case ChannelRequest.Error.TIMEOUT:\n return 'HttpConnection timeout';\n default:\n return 'Unknown error';\n }\n};\n\n\n/**\n * Sentinel value used to indicate an invalid chunk in a multi-chunk response.\n * @private {!Object}\n */\nChannelRequest.INVALID_CHUNK_ = {};\n\n\n/**\n * Sentinel value used to indicate an incomplete chunk in a multi-chunk\n * response.\n * @private {!Object}\n */\nChannelRequest.INCOMPLETE_CHUNK_ = {};\n\n\n/**\n * Returns whether XHR streaming is supported on this browser.\n *\n * @return {boolean} Whether XHR streaming is supported.\n * @see http://code.google.com/p/closure-library/issues/detail?id=346\n */\nChannelRequest.supportsXhrStreaming = function() {\n 'use strict';\n return !goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(10);\n};\n\n\n/**\n * Sets extra HTTP headers to add to all the requests sent to the server.\n *\n * @param {Object} extraHeaders The HTTP headers.\n */\nChannelRequest.prototype.setExtraHeaders = function(extraHeaders) {\n 'use strict';\n this.extraHeaders_ = extraHeaders;\n};\n\n\n/**\n * Overrides the default HTTP method.\n *\n * @param {string} verb The HTTP method\n */\nChannelRequest.prototype.setVerb = function(verb) {\n 'use strict';\n this.verb_ = verb;\n};\n\n\n/**\n * Sets the timeout for a request\n *\n * @param {number} timeout The timeout in MS for when we fail the request.\n */\nChannelRequest.prototype.setTimeout = function(timeout) {\n 'use strict';\n this.timeout_ = timeout;\n};\n\n\n/**\n * Sets the throttle for handling onreadystatechange events for the request.\n *\n * @param {number} throttle The throttle in ms. A value of zero indicates\n * no throttle.\n */\nChannelRequest.prototype.setReadyStateChangeThrottle = function(throttle) {\n 'use strict';\n this.readyStateChangeThrottleMs_ = throttle;\n};\n\n\n/**\n * Sets the pending messages that this request is handling.\n *\n * @param {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} pendingMessages\n * The pending messages for this request.\n */\nChannelRequest.prototype.setPendingMessages = function(pendingMessages) {\n 'use strict';\n this.pendingMessages_ = pendingMessages;\n};\n\n\n/**\n * Gets the pending messages that this request is handling, in case of a retry.\n *\n * @return {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} The pending\n * messages for this request.\n */\nChannelRequest.prototype.getPendingMessages = function() {\n 'use strict';\n return this.pendingMessages_;\n};\n\n\n/**\n * Uses XMLHTTP to send an HTTP POST to the server.\n *\n * @param {goog.Uri} uri The uri of the request.\n * @param {?string} postData The data for the post body.\n * @param {boolean} decodeChunks Whether to the result is expected to be\n * encoded for chunking and thus requires decoding.\n */\nChannelRequest.prototype.xmlHttpPost = function(uri, postData, decodeChunks) {\n 'use strict';\n this.type_ = ChannelRequest.Type_.XML_HTTP;\n this.baseUri_ = uri.clone().makeUnique();\n this.postData_ = postData;\n this.decodeChunks_ = decodeChunks;\n this.sendXmlHttp_(null /* hostPrefix */);\n};\n\n\n/**\n * Uses XMLHTTP to send an HTTP GET to the server.\n *\n * @param {goog.Uri} uri The uri of the request.\n * @param {boolean} decodeChunks Whether to the result is expected to be\n * encoded for chunking and thus requires decoding.\n * @param {?string} hostPrefix The host prefix, if we might be using a\n * secondary domain. Note that it should also be in the URL, adding this\n * won't cause it to be added to the URL.\n */\nChannelRequest.prototype.xmlHttpGet = function(uri, decodeChunks, hostPrefix) {\n 'use strict';\n this.type_ = ChannelRequest.Type_.XML_HTTP;\n this.baseUri_ = uri.clone().makeUnique();\n this.postData_ = null;\n this.decodeChunks_ = decodeChunks;\n\n this.sendXmlHttp_(hostPrefix);\n};\n\n\n/**\n * Sends a request via XMLHTTP according to the current state of the request\n * object.\n *\n * @param {?string} hostPrefix The host prefix, if we might be using a secondary\n * domain.\n * @private\n */\nChannelRequest.prototype.sendXmlHttp_ = function(hostPrefix) {\n 'use strict';\n this.requestStartTime_ = Date.now();\n this.ensureWatchDogTimer_();\n\n // clone the base URI to create the request URI. The request uri has the\n // attempt number as a parameter which helps in debugging.\n this.requestUri_ = this.baseUri_.clone();\n this.requestUri_.setParameterValues('t', this.retryId_);\n\n // send the request either as a POST or GET\n this.xmlHttpChunkStart_ = 0;\n const useSecondaryDomains = this.channel_.shouldUseSecondaryDomains();\n this.fetchResponseState_ = new FetchResponseState();\n // If the request is a GET request, start a backchannel to transfer streaming\n // data. Note that WebChannel GET request can also be used for closing the\n // channel as in method ChannelRequest#sendCloseRequest.\n // The second parameter of Channel#createXhrIo is JS only.\n this.xmlHttp_ = this.channel_.createXhrIo(\n useSecondaryDomains ? hostPrefix : null, !this.postData_);\n\n if (this.readyStateChangeThrottleMs_ > 0) {\n this.readyStateChangeThrottle_ = new goog.async.Throttle(\n goog.bind(this.xmlHttpHandler_, this, this.xmlHttp_),\n this.readyStateChangeThrottleMs_);\n }\n\n this.eventHandler_.listen(\n this.xmlHttp_, goog.net.EventType.READY_STATE_CHANGE,\n this.readyStateChangeHandler_);\n\n const headers =\n this.extraHeaders_ ? goog.object.clone(this.extraHeaders_) : {};\n if (this.postData_) {\n if (!this.verb_) {\n this.verb_ = 'POST';\n }\n headers['Content-Type'] = 'application/x-www-form-urlencoded';\n this.xmlHttp_.send(this.requestUri_, this.verb_, this.postData_, headers);\n } else {\n this.verb_ = 'GET';\n this.xmlHttp_.send(this.requestUri_, this.verb_, null, headers);\n }\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_MADE);\n this.channelDebug_.xmlHttpChannelRequest(\n this.verb_, this.requestUri_, this.rid_, this.retryId_, this.postData_);\n};\n\n\n/**\n * Handles a readystatechange event.\n * @param {goog.events.Event} evt The event.\n * @private\n */\nChannelRequest.prototype.readyStateChangeHandler_ = function(evt) {\n 'use strict';\n const xhr = /** @type {goog.net.XhrIo} */ (evt.target);\n const throttle = this.readyStateChangeThrottle_;\n if (throttle &&\n xhr.getReadyState() == goog.net.XmlHttp.ReadyState.INTERACTIVE) {\n // Only throttle in the partial data case.\n this.channelDebug_.debug('Throttling readystatechange.');\n throttle.fire();\n } else {\n // If we haven't throttled, just handle response directly.\n this.xmlHttpHandler_(xhr);\n }\n};\n\n\n/**\n * XmlHttp handler\n * @param {goog.net.XhrIo} xmlhttp The XhrIo object for the current request.\n * @private\n */\nChannelRequest.prototype.xmlHttpHandler_ = function(xmlhttp) {\n 'use strict';\n requestStats.onStartExecution();\n\n try {\n if (xmlhttp == this.xmlHttp_) {\n this.onXmlHttpReadyStateChanged_();\n } else {\n this.channelDebug_.warning(\n 'Called back with an ' +\n 'unexpected xmlhttp');\n }\n } catch (ex) {\n this.channelDebug_.debug('Failed call to OnXmlHttpReadyStateChanged_');\n if (this.hasResponseBody_()) {\n const channelRequest = this;\n this.channelDebug_.dumpException(ex, function() {\n 'use strict';\n return 'ResponseText: ' + channelRequest.xmlHttp_.getResponseText();\n });\n } else {\n this.channelDebug_.dumpException(ex, 'No response text');\n }\n } finally {\n requestStats.onEndExecution();\n }\n};\n\n\n/**\n * Called by the readystate handler for XMLHTTP requests.\n *\n * @private\n */\nChannelRequest.prototype.onXmlHttpReadyStateChanged_ = function() {\n 'use strict';\n const readyState = this.xmlHttp_.getReadyState();\n const errorCode = this.xmlHttp_.getLastErrorCode();\n const statusCode = this.xmlHttp_.getStatus();\n\n // we get partial results in browsers that support ready state interactive.\n // We also make sure that getResponseText is not null in interactive mode\n // before we continue.\n if (readyState < goog.net.XmlHttp.ReadyState.INTERACTIVE ||\n (readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE &&\n !environment.isPollingRequired() && // otherwise, go on to startPolling\n !this.hasResponseBody_())) {\n return; // not yet ready\n }\n\n // Dispatch any appropriate network events.\n if (!this.cancelled_ && readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&\n errorCode != goog.net.ErrorCode.ABORT) {\n // Pretty conservative, these are the only known scenarios which we'd\n // consider indicative of a truly non-functional network connection.\n if (errorCode == goog.net.ErrorCode.TIMEOUT || statusCode <= 0) {\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_FAILED);\n } else {\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_SUCCEEDED);\n }\n }\n\n // got some data so cancel the watchdog timer\n this.cancelWatchDogTimer_();\n\n const status = this.xmlHttp_.getStatus();\n this.lastStatusCode_ = status;\n const responseText = this.decodeXmlHttpResponse_();\n\n if (!this.hasResponseBody_()) {\n const channelRequest = this;\n this.channelDebug_.debug(function() {\n 'use strict';\n return 'No response text for uri ' + channelRequest.requestUri_ +\n ' status ' + status;\n });\n }\n this.successful_ = (status == 200);\n\n this.channelDebug_.xmlHttpChannelResponseMetaData(\n /** @type {string} */ (this.verb_), this.requestUri_, this.rid_,\n this.retryId_, readyState, status);\n\n if (!this.successful_) {\n this.errorResponseHeaders_ = this.xmlHttp_.getResponseHeaders();\n if (status == 400 && responseText.indexOf('Unknown SID') > 0) {\n // the server error string will include 'Unknown SID' which indicates the\n // server doesn't know about the session (maybe it got restarted, maybe\n // the user got moved to another server, etc.,). Handlers can special\n // case this error\n this.lastError_ = ChannelRequest.Error.UNKNOWN_SESSION_ID;\n requestStats.notifyStatEvent(\n requestStats.Stat.REQUEST_UNKNOWN_SESSION_ID);\n this.channelDebug_.warning('XMLHTTP Unknown SID (' + this.rid_ + ')');\n } else {\n this.lastError_ = ChannelRequest.Error.STATUS;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_STATUS);\n this.channelDebug_.warning(\n 'XMLHTTP Bad status ' + status + ' (' + this.rid_ + ')');\n }\n this.cleanup_();\n this.dispatchFailure_();\n return;\n }\n\n if (this.shouldCheckInitialResponse_()) {\n const initialResponse = this.getInitialResponse_();\n if (initialResponse) {\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, initialResponse,\n 'Initial handshake response via ' +\n WebChannel.X_HTTP_INITIAL_RESPONSE);\n this.initialResponseDecoded_ = true;\n this.safeOnRequestData_(initialResponse);\n } else {\n this.successful_ = false;\n this.lastError_ = ChannelRequest.Error.UNKNOWN_SESSION_ID; // fail-fast\n requestStats.notifyStatEvent(\n requestStats.Stat.REQUEST_UNKNOWN_SESSION_ID);\n this.channelDebug_.warning(\n 'XMLHTTP Missing X_HTTP_INITIAL_RESPONSE' +\n ' (' + this.rid_ + ')');\n this.cleanup_();\n this.dispatchFailure_();\n return;\n }\n }\n\n if (this.decodeChunks_) {\n this.decodeNextChunks_(readyState, responseText);\n if (environment.isPollingRequired() && this.successful_ &&\n readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE) {\n this.startPolling_();\n }\n } else {\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, responseText, null);\n this.safeOnRequestData_(responseText);\n }\n\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\n this.cleanup_();\n }\n\n if (!this.successful_) {\n return;\n }\n\n if (!this.cancelled_) {\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\n this.channel_.onRequestComplete(this);\n } else {\n // The default is false, the result from this callback shouldn't carry\n // over to the next callback, otherwise the request looks successful if\n // the watchdog timer gets called\n this.successful_ = false;\n this.ensureWatchDogTimer_();\n }\n }\n};\n\n\n/**\n * Whether we need check the initial-response header that is sent during the\n * fast handshake.\n *\n * @return {boolean} true if the initial-response header is yet to be processed.\n * @private\n */\nChannelRequest.prototype.shouldCheckInitialResponse_ = function() {\n 'use strict';\n return this.decodeInitialResponse_ && !this.initialResponseDecoded_;\n};\n\n\n/**\n * Queries the initial response header that is sent during the handshake.\n *\n * @return {?string} The non-empty header value or null.\n * @private\n */\nChannelRequest.prototype.getInitialResponse_ = function() {\n 'use strict';\n if (this.xmlHttp_) {\n const value = this.xmlHttp_.getStreamingResponseHeader(\n WebChannel.X_HTTP_INITIAL_RESPONSE);\n if (value && !goog.string.isEmptyOrWhitespace(value)) {\n return value;\n }\n }\n\n return null;\n};\n\n\n/**\n * Check if the initial response header has been handled.\n *\n * @return {boolean} true if X_HTTP_INITIAL_RESPONSE has been handled.\n */\nChannelRequest.prototype.isInitialResponseDecoded = function() {\n 'use strict';\n return this.initialResponseDecoded_;\n};\n\n\n/**\n * Decodes X_HTTP_INITIAL_RESPONSE if present.\n */\nChannelRequest.prototype.setDecodeInitialResponse = function() {\n 'use strict';\n this.decodeInitialResponse_ = true;\n};\n\n\n\n/**\n * Decodes the responses from XhrIo object.\n * @returns {string} responseText\n * @private\n */\nChannelRequest.prototype.decodeXmlHttpResponse_ = function() {\n 'use strict';\n if (!this.useFetchStreamsForResponse_()) {\n return this.xmlHttp_.getResponseText();\n }\n const responseChunks =\n /** @type {!Array<!Uint8Array>} */ (this.xmlHttp_.getResponse());\n let responseText = '';\n const responseLength = responseChunks.length;\n const requestCompleted =\n this.xmlHttp_.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;\n if (!this.fetchResponseState_.textDecoder) {\n if (typeof TextDecoder === 'undefined') {\n this.channelDebug_.severe(\n 'TextDecoder is not supported by this browser.');\n this.cleanup_();\n this.dispatchFailure_();\n return '';\n }\n this.fetchResponseState_.textDecoder = new goog.global.TextDecoder();\n }\n for (let i = 0; i < responseLength; i++) {\n this.fetchResponseState_.responseArrivedForFetch = true;\n const isLastChunk = requestCompleted && i == responseLength - 1;\n responseText += this.fetchResponseState_.textDecoder.decode(\n responseChunks[i], {stream: isLastChunk});\n }\n responseChunks.splice(0, responseLength);\n this.fetchResponseState_.responseBuffer += responseText;\n this.xmlHttpChunkStart_ = 0;\n return this.fetchResponseState_.responseBuffer;\n};\n\n\n/**\n * Whether or not the response has response body.\n * @private\n * @returns {boolean}\n */\nChannelRequest.prototype.hasResponseBody_ = function() {\n 'use strict';\n if (!this.xmlHttp_) {\n return false;\n }\n if (this.fetchResponseState_.responseArrivedForFetch) {\n return true;\n }\n return !(!this.xmlHttp_.getResponseText() && !this.xmlHttp_.getResponse());\n};\n\n/**\n * Whether or not the response body is streamed.\n * @private\n * @returns {boolean}\n */\nChannelRequest.prototype.useFetchStreamsForResponse_ = function() {\n 'use strict';\n if (!this.xmlHttp_) {\n return false;\n }\n return (\n this.verb_ == 'GET' && this.type_ != ChannelRequest.Type_.CLOSE_REQUEST &&\n this.channel_.usesFetchStreams());\n};\n\n\n/**\n * Resets the response buffer if the saved chunk has been processed.\n * @private\n * @param {string|!Object|undefined} chunkText\n */\nChannelRequest.prototype.maybeResetBuffer_ = function(chunkText) {\n 'use strict';\n if (this.useFetchStreamsForResponse_() &&\n chunkText != ChannelRequest.INCOMPLETE_CHUNK_ &&\n chunkText != ChannelRequest.INVALID_CHUNK_) {\n this.fetchResponseState_.responseBuffer = '';\n this.xmlHttpChunkStart_ = 0;\n }\n};\n\n\n/**\n * Decodes the next set of available chunks in the response.\n * @param {number} readyState The value of readyState.\n * @param {string} responseText The value of responseText.\n * @private\n */\nChannelRequest.prototype.decodeNextChunks_ = function(\n readyState, responseText) {\n 'use strict';\n let decodeNextChunksSuccessful = true;\n\n let chunkText;\n while (!this.cancelled_ && this.xmlHttpChunkStart_ < responseText.length) {\n chunkText = this.getNextChunk_(responseText);\n if (chunkText == ChannelRequest.INCOMPLETE_CHUNK_) {\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\n // should have consumed entire response when the request is done\n this.lastError_ = ChannelRequest.Error.BAD_DATA;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_INCOMPLETE_DATA);\n decodeNextChunksSuccessful = false;\n }\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, null, '[Incomplete Response]');\n break;\n } else if (chunkText == ChannelRequest.INVALID_CHUNK_) {\n this.lastError_ = ChannelRequest.Error.BAD_DATA;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_DATA);\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, responseText, '[Invalid Chunk]');\n decodeNextChunksSuccessful = false;\n break;\n } else {\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, /** @type {string} */ (chunkText), null);\n this.safeOnRequestData_(/** @type {string} */ (chunkText));\n }\n }\n\n this.maybeResetBuffer_(chunkText);\n\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&\n responseText.length == 0 &&\n !this.fetchResponseState_.responseArrivedForFetch) {\n // also an error if we didn't get any response\n this.lastError_ = ChannelRequest.Error.NO_DATA;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_NO_DATA);\n decodeNextChunksSuccessful = false;\n }\n\n this.successful_ = this.successful_ && decodeNextChunksSuccessful;\n\n if (!decodeNextChunksSuccessful) {\n // malformed response - we make this trigger retry logic\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, responseText, '[Invalid Chunked Response]');\n this.cleanup_();\n this.dispatchFailure_();\n } else {\n if (responseText.length > 0 && !this.firstByteReceived_) {\n this.firstByteReceived_ = true;\n this.channel_.onFirstByteReceived(this, responseText);\n }\n }\n};\n\n\n/**\n * Polls the response for new data.\n * @private\n */\nChannelRequest.prototype.pollResponse_ = function() {\n 'use strict';\n if (!this.xmlHttp_) {\n return; // already closed\n }\n const readyState = this.xmlHttp_.getReadyState();\n const responseText = this.xmlHttp_.getResponseText();\n if (this.xmlHttpChunkStart_ < responseText.length) {\n this.cancelWatchDogTimer_();\n this.decodeNextChunks_(readyState, responseText);\n if (this.successful_ &&\n readyState != goog.net.XmlHttp.ReadyState.COMPLETE) {\n this.ensureWatchDogTimer_();\n }\n }\n};\n\n\n/**\n * Starts a polling interval for changes to responseText of the\n * XMLHttpRequest, for browsers that don't fire onreadystatechange\n * as data comes in incrementally. This timer is disabled in\n * cleanup_().\n * @private\n */\nChannelRequest.prototype.startPolling_ = function() {\n 'use strict';\n this.eventHandler_.listen(\n this.pollingTimer_, goog.Timer.TICK, this.pollResponse_);\n this.pollingTimer_.start();\n};\n\n\n/**\n * Returns the next chunk of a chunk-encoded response. This is not standard\n * HTTP chunked encoding because browsers don't expose the chunk boundaries to\n * the application through XMLHTTP. So we have an additional chunk encoding at\n * the application level that lets us tell where the beginning and end of\n * individual responses are so that we can only try to eval a complete JS array.\n *\n * The encoding is the size of the chunk encoded as a decimal string followed\n * by a newline followed by the data.\n *\n * @param {string} responseText The response text from the XMLHTTP response.\n * @return {string|!Object} The next chunk string or a sentinel object\n * indicating a special condition.\n * @private\n */\nChannelRequest.prototype.getNextChunk_ = function(responseText) {\n 'use strict';\n const sizeStartIndex = this.xmlHttpChunkStart_;\n const sizeEndIndex = responseText.indexOf('\\n', sizeStartIndex);\n if (sizeEndIndex == -1) {\n return ChannelRequest.INCOMPLETE_CHUNK_;\n }\n\n const sizeAsString = responseText.substring(sizeStartIndex, sizeEndIndex);\n const size = Number(sizeAsString);\n if (isNaN(size)) {\n return ChannelRequest.INVALID_CHUNK_;\n }\n\n const chunkStartIndex = sizeEndIndex + 1;\n if (chunkStartIndex + size > responseText.length) {\n return ChannelRequest.INCOMPLETE_CHUNK_;\n }\n\n const chunkText = responseText.slice(chunkStartIndex, chunkStartIndex + size);\n this.xmlHttpChunkStart_ = chunkStartIndex + size;\n return chunkText;\n};\n\n\n/**\n * Uses an IMG tag or navigator.sendBeacon to send an HTTP get to the server.\n *\n * This is only currently used to terminate the connection, as an IMG tag is\n * the most reliable way to send something to the server while the page\n * is getting torn down.\n *\n * Navigator.sendBeacon is available on Chrome and Firefox as a formal\n * solution to ensure delivery without blocking window close. See\n * https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon\n *\n * For Chrome Apps, sendBeacon is always necessary due to Content Security\n * Policy (CSP) violation of using an IMG tag.\n *\n * For react-native, we use xhr to send the actual close request, and assume\n * there is no page-close issue with react-native.\n *\n * @param {goog.Uri} uri The uri to send a request to.\n */\nChannelRequest.prototype.sendCloseRequest = function(uri) {\n 'use strict';\n this.type_ = ChannelRequest.Type_.CLOSE_REQUEST;\n this.baseUri_ = uri.clone().makeUnique();\n\n let requestSent = false;\n\n if (goog.global.navigator && goog.global.navigator.sendBeacon) {\n try {\n // empty string body to avoid 413 error on chrome < 41\n requestSent =\n goog.global.navigator.sendBeacon(this.baseUri_.toString(), '');\n } catch {\n // Intentionally left empty; sendBeacon might throw TypeError in certain\n // unexpected cases.\n }\n }\n\n if (!requestSent && goog.global.Image) {\n const eltImg = new Image();\n eltImg.src = this.baseUri_;\n requestSent = true;\n }\n\n if (!requestSent) {\n // no handler is set to match the sendBeacon/Image behavior\n this.xmlHttp_ = this.channel_.createXhrIo(null);\n this.xmlHttp_.send(this.baseUri_);\n }\n\n this.requestStartTime_ = Date.now();\n this.ensureWatchDogTimer_();\n};\n\n\n/**\n * Cancels the request no matter what the underlying transport is.\n */\nChannelRequest.prototype.cancel = function() {\n 'use strict';\n this.cancelled_ = true;\n this.cleanup_();\n};\n\n\n/**\n * Resets the timeout.\n *\n * @param {number=} opt_timeout The new timeout\n */\nChannelRequest.prototype.resetTimeout = function(opt_timeout) {\n 'use strict';\n if (opt_timeout) {\n this.setTimeout(opt_timeout);\n }\n // restart only if a timer is currently set\n if (this.watchDogTimerId_) {\n this.cancelWatchDogTimer_();\n this.ensureWatchDogTimer_();\n }\n};\n\n\n/**\n * Ensures that there is watchdog timeout which is used to ensure that\n * the connection completes in time.\n *\n * @private\n */\nChannelRequest.prototype.ensureWatchDogTimer_ = function() {\n 'use strict';\n this.watchDogTimeoutTime_ = Date.now() + this.timeout_;\n this.startWatchDogTimer_(this.timeout_);\n};\n\n\n/**\n * Starts the watchdog timer which is used to ensure that the connection\n * completes in time.\n * @param {number} time The number of milliseconds to wait.\n * @private\n */\nChannelRequest.prototype.startWatchDogTimer_ = function(time) {\n 'use strict';\n if (this.watchDogTimerId_ != null) {\n // assertion\n throw new Error('WatchDog timer not null');\n }\n this.watchDogTimerId_ =\n requestStats.setTimeout(goog.bind(this.onWatchDogTimeout_, this), time);\n};\n\n\n/**\n * Cancels the watchdog timer if it has been started.\n *\n * @private\n */\nChannelRequest.prototype.cancelWatchDogTimer_ = function() {\n 'use strict';\n if (this.watchDogTimerId_) {\n goog.global.clearTimeout(this.watchDogTimerId_);\n this.watchDogTimerId_ = null;\n }\n};\n\n\n/**\n * Called when the watchdog timer is triggered. It also handles a case where it\n * is called too early which we suspect may be happening sometimes\n * (not sure why)\n *\n * @private\n */\nChannelRequest.prototype.onWatchDogTimeout_ = function() {\n 'use strict';\n this.watchDogTimerId_ = null;\n const now = Date.now();\n goog.asserts.assert(\n this.watchDogTimeoutTime_, 'WatchDog timeout time missing?');\n if (now - this.watchDogTimeoutTime_ >= 0) {\n this.handleTimeout_();\n } else {\n // got called too early for some reason\n this.channelDebug_.warning('WatchDog timer called too early');\n this.startWatchDogTimer_(this.watchDogTimeoutTime_ - now);\n }\n};\n\n\n/**\n * Called when the request has actually timed out. Will cleanup and notify the\n * channel of the failure.\n *\n * @private\n */\nChannelRequest.prototype.handleTimeout_ = function() {\n 'use strict';\n if (this.successful_) {\n // Should never happen.\n this.channelDebug_.severe(\n 'Received watchdog timeout even though request loaded successfully');\n }\n\n this.channelDebug_.timeoutResponse(this.requestUri_);\n\n // IMG or SendBeacon requests never notice if they were successful,\n // and always 'time out'. This fact says nothing about reachability.\n if (this.type_ != ChannelRequest.Type_.CLOSE_REQUEST) {\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_FAILED);\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_TIMEOUT);\n }\n\n this.cleanup_();\n\n // Set error and dispatch failure.\n // This is called for CLOSE_REQUEST too to ensure channel_.onRequestComplete.\n this.lastError_ = ChannelRequest.Error.TIMEOUT;\n this.dispatchFailure_();\n};\n\n\n/**\n * Notifies the channel that this request failed.\n * @private\n */\nChannelRequest.prototype.dispatchFailure_ = function() {\n 'use strict';\n if (this.channel_.isClosed() || this.cancelled_) {\n return;\n }\n\n this.channel_.onRequestComplete(this);\n};\n\n\n/**\n * Cleans up the objects used to make the request. This function is\n * idempotent.\n *\n * @private\n */\nChannelRequest.prototype.cleanup_ = function() {\n 'use strict';\n this.cancelWatchDogTimer_();\n\n goog.dispose(this.readyStateChangeThrottle_);\n this.readyStateChangeThrottle_ = null;\n\n // Stop the polling timer, if necessary.\n this.pollingTimer_.stop();\n\n // Unhook all event handlers.\n this.eventHandler_.removeAll();\n\n if (this.xmlHttp_) {\n // clear out this.xmlHttp_ before aborting so we handle getting reentered\n // inside abort\n const xmlhttp = this.xmlHttp_;\n this.xmlHttp_ = null;\n xmlhttp.abort();\n xmlhttp.dispose();\n }\n};\n\n\n/**\n * Indicates whether the request was successful. Only valid after the handler\n * is called to indicate completion of the request.\n *\n * @return {boolean} True if the request succeeded.\n */\nChannelRequest.prototype.getSuccess = function() {\n 'use strict';\n return this.successful_;\n};\n\n\n/**\n * If the request was not successful, returns the reason.\n *\n * @return {?ChannelRequest.Error} The last error.\n */\nChannelRequest.prototype.getLastError = function() {\n 'use strict';\n return this.lastError_;\n};\n\n\n/**\n * @return {!Object<string, string>|undefined} Response headers received\n * along with the non-200 status, as a key-value map.\n */\nChannelRequest.prototype.getErrorResponseHeaders = function() {\n 'use strict';\n return this.errorResponseHeaders_;\n};\n\n\n/**\n * Returns the status code of the last request.\n *\n * @return {number} The status code of the last request.\n */\nChannelRequest.prototype.getLastStatusCode = function() {\n 'use strict';\n return this.lastStatusCode_;\n};\n\n\n/**\n * Returns the session id for this channel.\n *\n * @return {string|undefined} The session ID.\n */\nChannelRequest.prototype.getSessionId = function() {\n 'use strict';\n return this.sid_;\n};\n\n\n/**\n * Returns the request id for this request. Each request has a unique request\n * id and the request IDs are a sequential increasing count.\n *\n * @return {string|number|undefined} The request ID.\n */\nChannelRequest.prototype.getRequestId = function() {\n 'use strict';\n return this.rid_;\n};\n\n\n/**\n * Returns the data for a post, if this request is a post.\n *\n * @return {?string} The POST data provided by the request initiator.\n */\nChannelRequest.prototype.getPostData = function() {\n 'use strict';\n return this.postData_;\n};\n\n\n/**\n * Returns the XhrIo request object.\n *\n * @return {?goog.net.XhrIo} Any XhrIo request created for this object.\n */\nChannelRequest.prototype.getXhr = function() {\n 'use strict';\n return this.xmlHttp_;\n};\n\n\n/**\n * Returns the time that the request started, if it has started.\n *\n * @return {?number} The time the request started, as returned by Date.now().\n */\nChannelRequest.prototype.getRequestStartTime = function() {\n 'use strict';\n return this.requestStartTime_;\n};\n\n\n/**\n * Helper to call the callback's onRequestData, which catches any\n * exception.\n * @param {string} data The request data.\n * @private\n */\nChannelRequest.prototype.safeOnRequestData_ = function(data) {\n 'use strict';\n try {\n this.channel_.onRequestData(this, data);\n const stats = requestStats.ServerReachability;\n requestStats.notifyServerReachabilityEvent(stats.BACK_CHANNEL_ACTIVITY);\n } catch (e) {\n // Dump debug info, but keep going without closing the channel.\n this.channelDebug_.dumpException(e, 'Error in httprequest callback');\n }\n};\n\n\n/**\n * Convenience factory method.\n *\n * @param {Channel} channel The channel object that owns this request.\n * @param {WebChannelDebug} channelDebug A WebChannelDebug to use for logging.\n * @param {string=} opt_sessionId The session id for the channel.\n * @param {string|number=} opt_requestId The request id for this request.\n * @param {number=} opt_retryId The retry id for this request.\n * @return {!ChannelRequest} The created channel request.\n */\nChannelRequest.createChannelRequest = function(\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {\n 'use strict';\n return new ChannelRequest(\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId);\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A single module to define user-agent specific environment\n * details.\n *\n */\n\ngoog.module('goog.labs.net.webChannel.environment');\n\ngoog.module.declareLegacyNamespace();\n\nvar userAgent = goog.require('goog.userAgent');\n\n\n/**\n * The default polling interval in millis for Edge.\n *\n * Currently on edge, new-chunk events may be not be fired (at all) if a new\n * chunk arrives within 50ms following the previous chunk. This may be fixed\n * in future, which requires changes to the whatwg spec too.\n *\n * @private @const {number}\n */\nvar EDGE_POLLING_INTERVAL_ = 125;\n\n\n/**\n * History:\n *\n * IE11 is still using Trident, the traditional engine for IE.\n * Edge is using EdgeHTML, a fork of Trident. We are seeing the same issue\n * on IE-11 (reported in 2017), so treat IE the same as Edge for now.\n *\n * We used to do polling for Opera (only) with an 250ms interval, because Opera\n * only fires readyState == INTERACTIVE once. Opera switched to WebKit in 2013,\n * and then to Blink (chrome).\n *\n * TODO(user): check the raw UA string to keep polling for old, mobile operas\n * that may still be affected. For old Opera, double the polling interval\n * to 250ms.\n *\n * @return {boolean} True if polling is required with XHR.\n */\nexports.isPollingRequired = function() {\n return userAgent.EDGE_OR_IE;\n};\n\n\n/**\n * How often to poll (in MS) for changes to responseText in browsers that don't\n * fire onreadystatechange during incremental loading of the response body.\n *\n * @return {number|undefined} The polling interval (MS) for the current U-A;\n * or undefined if polling is not supposed to be enabled.\n */\nexports.getPollingInterval = function() {\n if (userAgent.EDGE_OR_IE) {\n return EDGE_POLLING_INTERVAL_;\n }\n\n return undefined;\n};\n\n/**\n * Origin trial token for google.com\n *\n * https://developers.chrome.com/origintrials/#/trials\n *\n * http://googlechrome.github.io/OriginTrials/check-token.html\n * Origin: https://google.com:443\n * Matches Subdomains? Yes\n * Matches Third-party? Yes\n * Feature: FetchUploadStreaming\n * Up to Chrome 95 (ends with the rollout of next Chrome release), no later\n * than Nov 9, 2021\n *\n * Token for googleapis.com will be registered after google.com's is deployed.\n *\n */\nconst OT_TOKEN_GOOGLE_COM =\n 'A0eNbltY1nd4MP7XTHXnTxWogDL6mWTdgIIKfKOTJoUHNbFFMZQBoiHHjJ9UK9lgYndWFaxOWR7ld8uUjcWmcwIAAAB/eyJvcmlnaW4iOiJodHRwczovL2dvb2dsZS5jb206NDQzIiwiZmVhdHVyZSI6IkZldGNoVXBsb2FkU3RyZWFtaW5nIiwiZXhwaXJ5IjoxNjM2NTAyMzk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlfQ==';\n\n\n/**\n * Creates ReadableStream to upload\n * @return {!ReadableStream} ReadableStream to upload\n */\nfunction createStream() {\n const encoder = new goog.global.TextEncoder();\n return new goog.global.ReadableStream({\n start: controller => {\n for (const obj of ['test\\r\\n', 'test\\r\\n']) {\n controller.enqueue(encoder.encode(obj));\n }\n controller.close();\n }\n });\n}\n\n/**\n * Detect the user agent is chrome and its version is higher than M90.\n * This code is hard-coded from goog.labs.userAgent.browser to avoid file size\n * increasing.\n * @return {boolean} Whether the above is true.\n */\nfunction isChromeM90OrHigher() {\n const userAgentStr = function() {\n const navigator = goog.global.navigator;\n if (navigator) {\n const userAgent = navigator.userAgent;\n if (userAgent) {\n return userAgent;\n }\n }\n return '';\n }();\n\n const matchUserAgent = function(str) {\n return userAgentStr.indexOf(str) != -1;\n };\n\n if (!matchUserAgent('Chrome') || matchUserAgent('Edg')) {\n return false;\n }\n\n const match = /Chrome\\/(\\d+)/.exec(userAgentStr);\n const chromeVersion = parseInt(match[1], 10);\n return chromeVersion >= 90;\n}\n\n/**\n * Detect the URL origin is *.google.com.\n * @param {string} url The target URL.\n * @return {boolean} Whether the above is true.\n */\nfunction isUrlGoogle(url) {\n const match = /\\/\\/([^\\/]+)\\//.exec(url);\n if (!match) {\n return false;\n }\n const origin = match[1];\n return origin.endsWith('google.com');\n}\n\n/**\n * The flag to run the origin trials code only once.\n */\nlet isStartOriginTrialsCalled = false;\n\n/**\n * For Fetch/upload OT, make three requests against the server endpoint.\n * POST requests contain only dummy payload.\n *\n * https://developers.chrome.com/origintrials/#/view_trial/3524066708417413121\n *\n * This function is expected to be called from background during the handshake.\n * Exceptions will be logged by the caller.\n *\n * No stats or logs are collected on the client-side. To be disabled once the\n * OT is expired.\n *\n * @param {string} path The base URL path for the requests\n * @param {function(*)} logError A function to execute when exceptions are\n * caught.\n */\nexports.startOriginTrials = function(path, logError) {\n if (isStartOriginTrialsCalled) {\n return;\n }\n isStartOriginTrialsCalled = true;\n // NE: may need check if path has already contains query params?\n\n // Accept only Chrome M90 or later due to service worker support.\n if (!isChromeM90OrHigher()) {\n return;\n }\n\n // Accept only only google.com and subdoamins.\n if (!isUrlGoogle(path)) {\n return;\n }\n // Since 3P OT is not supported yet, we should check the current page matches\n // the path (absolute one?) to disable this OT for cross-origin calls\n if (!window || !window.document || !isUrlGoogle(window.document.URL)) {\n return;\n }\n\n // Enable origin trial by injecting OT <meta> tag\n const tokenElement =\n /** @type {! HTMLMetaElement} */ (document.createElement('meta'));\n tokenElement.httpEquiv = 'origin-trial';\n tokenElement.content = OT_TOKEN_GOOGLE_COM;\n // appendChild() synchronously enables OT.\n document.head.appendChild(tokenElement);\n\n // Check if fetch upload stream is actually enabled.\n // By the spec, Streaming request doesn't has the Content-Type header:\n // https://fetch.spec.whatwg.org/#concept-bodyinit-extract\n // If Chrome doesn't support Streaming, the body stream is converted to a\n // string \"[object ReadableStream]\" for fallback then it has \"Content-Type:\n // text/plain;charset=UTF-8\".\n const supportsRequestStreams = !new Request('', {\n body: new ReadableStream(),\n method: 'POST',\n }).headers.has('Content-Type');\n\n if (supportsRequestStreams) {\n logError('OriginTrial unexpected.');\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Base WebChannel implementation.\n */\n\n\ngoog.provide('goog.labs.net.webChannel.WebChannelBase');\n\ngoog.require('goog.Uri');\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.async.run');\ngoog.require('goog.collections.maps');\ngoog.require('goog.json');\ngoog.require('goog.labs.net.webChannel.Channel');\ngoog.require('goog.labs.net.webChannel.ChannelRequest');\ngoog.require('goog.labs.net.webChannel.ConnectionState');\ngoog.require('goog.labs.net.webChannel.ForwardChannelRequestPool');\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\ngoog.require('goog.labs.net.webChannel.Wire');\ngoog.require('goog.labs.net.webChannel.WireV8');\ngoog.require('goog.labs.net.webChannel.environment');\ngoog.require('goog.labs.net.webChannel.netUtils');\ngoog.require('goog.labs.net.webChannel.requestStats');\ngoog.require('goog.net.FetchXmlHttpFactory');\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.net.XhrIo');\ngoog.require('goog.net.XmlHttpFactory');\ngoog.require('goog.net.rpc.HttpCors');\ngoog.require('goog.object');\ngoog.require('goog.string');\ngoog.require('goog.structs');\n\ngoog.scope(function() {\n'use strict';\nconst WebChannel = goog.net.WebChannel;\nconst ChannelRequest = goog.labs.net.webChannel.ChannelRequest;\nconst ConnectionState = goog.labs.net.webChannel.ConnectionState;\nconst ForwardChannelRequestPool =\n goog.labs.net.webChannel.ForwardChannelRequestPool;\nconst WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\nconst Wire = goog.labs.net.webChannel.Wire;\nconst WireV8 = goog.labs.net.webChannel.WireV8;\nconst environment = goog.labs.net.webChannel.environment;\nconst netUtils = goog.labs.net.webChannel.netUtils;\nconst requestStats = goog.labs.net.webChannel.requestStats;\n\nconst httpCors = goog.module.get('goog.net.rpc.HttpCors');\n\n/**\n * @define {boolean} If WebChannel should compile with Origin Trial features.\n */\nconst ALLOW_ORIGIN_TRIAL_FEATURES =\n goog.define('goog.net.webChannel.ALLOW_ORIGIN_TRIAL_FEATURES', false);\n\n/**\n * Gets an internal channel parameter in a type-safe way.\n *\n * @param {string} paramName the key of the parameter to fetch.\n * @param {!T} defaultValue the default value to return\n * @param {!goog.net.WebChannel.Options=} options Configuration for the\n * WebChannel instance.\n * @return {T}\n * @template T\n */\nfunction getInternalChannelParam(paramName, defaultValue, options) {\n if (!options || !options.internalChannelParams) {\n return defaultValue;\n }\n return /** @type {T} */ (options.internalChannelParams[paramName]) ||\n defaultValue;\n}\n\n/**\n * This WebChannel implementation is branched off goog.net.BrowserChannel\n * for now. Ongoing changes to goog.net.BrowserChannel will be back\n * ported to this implementation as needed.\n *\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\n * WebChannel instance.\n * @param {number=} opt_clientVersion An application-specific version number\n * that is sent to the server when connected.\n * @param {!ConnectionState=} opt_conn Previously determined connection\n * conditions.\n * @constructor\n * @struct\n * @implements {goog.labs.net.webChannel.Channel}\n */\ngoog.labs.net.webChannel.WebChannelBase = function(\n opt_options, opt_clientVersion, opt_conn) {\n 'use strict';\n /**\n * The client library version (capabilities).\n * @private {number}\n */\n this.clientVersion_ = opt_clientVersion || 0;\n\n /**\n * The server library version (capabilities).\n * @private {number}\n */\n this.serverVersion_ = 0;\n\n\n /**\n * An array of queued maps that need to be sent to the server.\n * @private {!Array<Wire.QueuedMap>}\n */\n this.outgoingMaps_ = [];\n\n /**\n * The channel debug used for logging\n * @private {!WebChannelDebug}\n */\n this.channelDebug_ = new WebChannelDebug();\n\n /**\n * Connectivity state.\n * @private {!ConnectionState}\n */\n this.connState_ = opt_conn || new ConnectionState();\n\n /**\n * Extra HTTP headers to add to all the requests sent to the server.\n * @private {?Object}\n */\n this.extraHeaders_ = null;\n\n /**\n * Extra HTTP headers to add to the init request(s) sent to the server.\n * @private {?Object}\n */\n this.initHeaders_ = null;\n\n /**\n * @private {?string} The URL param name to overwrite custom HTTP headers\n * to bypass CORS preflight.\n */\n this.httpHeadersOverwriteParam_ = null;\n\n /**\n * Extra parameters to add to all the requests sent to the server.\n * @private {?Object}\n */\n this.extraParams_ = null;\n\n /**\n * Parameter name for the http session id.\n * @private {?string}\n */\n this.httpSessionIdParam_ = null;\n\n /**\n * The http session id, to be sent with httpSessionIdParam_ with each\n * request after the initial handshake.\n * @private {?string}\n */\n this.httpSessionId_ = null;\n\n /**\n * The ChannelRequest object for the backchannel.\n * @private {?ChannelRequest}\n */\n this.backChannelRequest_ = null;\n\n /**\n * The relative path (in the context of the page hosting the browser channel)\n * for making requests to the server.\n * @private {?string}\n */\n this.path_ = null;\n\n /**\n * The absolute URI for the forwardchannel request.\n * @private {?goog.Uri}\n */\n this.forwardChannelUri_ = null;\n\n /**\n * The absolute URI for the backchannel request.\n * @private {?goog.Uri}\n */\n this.backChannelUri_ = null;\n\n /**\n * A subdomain prefix for using a subdomain in IE for the backchannel\n * requests.\n * @private {?string}\n */\n this.hostPrefix_ = null;\n\n /**\n * Whether we allow the use of a subdomain in IE for the backchannel requests.\n * @private {boolean}\n */\n this.allowHostPrefix_ = true;\n\n /**\n * The next id to use for the RID (request identifier) parameter. This\n * identifier uniquely identifies the forward channel request.\n * @private {number}\n */\n this.nextRid_ = 0;\n\n /**\n * The id to use for the next outgoing map. This identifier uniquely\n * identifies a sent map.\n * @private {number}\n */\n this.nextMapId_ = 0;\n\n /**\n * Whether to fail forward-channel requests after one try or a few tries.\n * @private {boolean}\n */\n this.failFast_ = getInternalChannelParam('failFast', false, opt_options);\n\n /**\n * The handler that receive callbacks for state changes and data.\n * @private {?goog.labs.net.webChannel.WebChannelBase.Handler}\n */\n this.handler_ = null;\n\n /**\n * Timer identifier for asynchronously making a forward channel request.\n * This is set to true if the func is scheduled with async.run, which\n * is equivalent to setTimeout(0).\n * @private {?number|?boolean}\n */\n this.forwardChannelTimerId_ = null;\n\n /**\n * Timer identifier for asynchronously making a back channel request.\n * @private {?number}\n */\n this.backChannelTimerId_ = null;\n\n /**\n * Timer identifier for the timer that waits for us to retry the backchannel\n * in the case where it is dead and no longer receiving data.\n * @private {?number}\n */\n this.deadBackChannelTimerId_ = null;\n\n /**\n * Whether the client's network conditions can support streamed responses.\n * @private {?boolean}\n */\n this.enableStreaming_ = null;\n\n /**\n * Whether streaming mode is allowed. In certain debugging situations, it's\n * useful to disable this.\n * @private {boolean}\n */\n this.allowStreamingMode_ = true;\n\n /**\n * The array identifier of the last array received from the server for the\n * backchannel request.\n * @private {number}\n */\n this.lastArrayId_ = -1;\n\n /**\n * The array id of the last array sent by the server that we know about.\n * @private {number}\n */\n this.lastPostResponseArrayId_ = -1;\n\n /**\n * The non-200 status code received that causes the channel to be aborted.\n * @private {number}\n */\n this.errorResponseStatusCode_ = -1;\n\n /**\n * The response headers received along with the non-200 status.\n * @private {!Object<string, string>|undefined}\n */\n this.errorResponseHeaders_ = undefined;\n\n /**\n * Number of times we have retried the current forward channel request.\n * @private {number}\n */\n this.forwardChannelRetryCount_ = 0;\n\n /**\n * Number of times in a row that we have retried the current back channel\n * request and received no data.\n * @private {number}\n */\n this.backChannelRetryCount_ = 0;\n\n /**\n * The attempt id for the current back channel request. Starts at 1 and\n * increments for each reconnect. The server uses this to log if our\n * connection is flaky or not.\n * @private {number}\n */\n this.backChannelAttemptId_ = 0;\n\n /**\n * The base part of the time before firing next retry request. Default is 5\n * seconds. Note that a random delay is added (see {@link retryDelaySeedMs_})\n * for all retries, and linear backoff is applied to the sum for subsequent\n * retries.\n * @private {number}\n */\n this.baseRetryDelayMs_ =\n getInternalChannelParam('baseRetryDelayMs', 5 * 1000, opt_options);\n\n /**\n * A random time between 0 and this number of MS is added to the\n * {@link baseRetryDelayMs_}. Default is 10 seconds.\n * @private {number}\n */\n this.retryDelaySeedMs_ =\n getInternalChannelParam('retryDelaySeedMs', 10 * 1000, opt_options);\n\n /**\n * Maximum number of attempts to connect to the server for forward channel\n * requests. Defaults to 2.\n * @private {number}\n */\n this.forwardChannelMaxRetries_ =\n getInternalChannelParam('forwardChannelMaxRetries', 2, opt_options);\n\n /**\n * The timeout in milliseconds for a forward channel request. Defaults to 20\n * seconds. Note that part of this timeout can be randomized.\n * @private {number}\n */\n this.forwardChannelRequestTimeoutMs_ = getInternalChannelParam(\n 'forwardChannelRequestTimeoutMs', 20 * 1000, opt_options);\n\n /**\n * The custom factory used to create XMLHttpRequest objects.\n * @private {!goog.net.XmlHttpFactory | undefined}\n */\n this.xmlHttpFactory_ =\n (opt_options && opt_options.xmlHttpFactory) || undefined;\n\n /**\n * Whether or not this channel uses WHATWG Fetch/streams.\n * @private {boolean}\n */\n this.usesFetchStreams_ =\n (opt_options && opt_options.useFetchStreams) || false;\n\n /**\n * The timeout in milliseconds for a back channel request. Defaults to using\n * the timeout configured in ChannelRequest (45s). If server-side\n * keepaliveInterval is known to the client, set the backchannel request\n * timeout to 1.5 * keepaliveInterval (ms).\n *\n * @private {number|undefined}\n */\n this.backChannelRequestTimeoutMs_ = undefined;\n\n /**\n * A throttle time in ms for readystatechange events for the backchannel.\n * Useful for throttling when ready state is INTERACTIVE (partial data).\n *\n * This throttle is useful if the server sends large data chunks down the\n * backchannel. It prevents examining XHR partial data on every readystate\n * change event. This is useful because large chunks can trigger hundreds\n * of readystatechange events, each of which takes ~5ms or so to handle,\n * in turn making the UI unresponsive for a significant period.\n *\n * If set to zero no throttle is used.\n * @private {number}\n */\n this.readyStateChangeThrottleMs_ = 0;\n\n /**\n * Whether cross origin requests are supported for the channel.\n *\n * See {@link goog.net.XhrIo#setWithCredentials}.\n * @private {boolean}\n */\n this.supportsCrossDomainXhrs_ =\n (opt_options && opt_options.supportsCrossDomainXhr) || false;\n\n /**\n * The current session id.\n * @private {string}\n */\n this.sid_ = '';\n\n /**\n * The current ChannelRequest pool for the forward channel.\n * @private {!ForwardChannelRequestPool}\n */\n this.forwardChannelRequestPool_ = new ForwardChannelRequestPool(\n opt_options && opt_options.concurrentRequestLimit);\n\n /**\n * The V8 codec.\n * @private {!WireV8}\n */\n this.wireCodec_ = new WireV8();\n\n /**\n * Whether to turn on the fast handshake behavior.\n *\n * @private {boolean}\n */\n this.fastHandshake_ = (opt_options && opt_options.fastHandshake) || false;\n\n /**\n * Whether to encode initMessageHeaders in the body.\n *\n * @private {boolean}\n */\n this.encodeInitMessageHeaders_ =\n (opt_options && opt_options.encodeInitMessageHeaders) || false;\n\n if (this.fastHandshake_ && this.encodeInitMessageHeaders_) {\n this.channelDebug_.warning(\n 'Ignore encodeInitMessageHeaders because fastHandshake is set.');\n this.encodeInitMessageHeaders_ = false;\n }\n\n /**\n * Whether to signal to the server to enable blocking handshake.\n *\n * @private {boolean}\n */\n this.blockingHandshake_ =\n (opt_options && opt_options.blockingHandshake) || false;\n\n\n if (opt_options && opt_options.disableRedact) {\n this.channelDebug_.disableRedact();\n }\n\n if (opt_options && opt_options.forceLongPolling) {\n this.allowStreamingMode_ = false;\n }\n\n /**\n * Whether to detect buffering proxies.\n *\n * fastHandshake + detectBufferingProxy are yet to be implemented.\n *\n * @private {boolean}\n */\n this.detectBufferingProxy_ =\n (!this.fastHandshake_ && this.allowStreamingMode_ && opt_options &&\n opt_options.detectBufferingProxy) ||\n false;\n\n /**\n * Long polling timeout interval for the server to complete the handing GET.\n *\n * @private {number|undefined}\n */\n this.longPollingTimeout_ = undefined;\n\n if (opt_options && opt_options.longPollingTimeout &&\n opt_options.longPollingTimeout > 0) {\n this.longPollingTimeout_ = opt_options.longPollingTimeout;\n }\n\n /**\n * Callback when all the pending client-sent messages have been flushed.\n *\n * @private {function()|undefined}\n */\n this.forwardChannelFlushedCallback_ = undefined;\n\n /**\n * TODO(user): move all backchannel states to its own class similar to\n * forwardchannelrequestpool.js and log more stats.\n *\n * The estimated handshake RTT (ms) as measured from when the handshake\n * request is sent and when the handshake response headers are received.\n * If the value is 0, the RTT is unknown.\n *\n * @private {number}\n */\n this.handshakeRttMs_ = 0;\n\n /**\n * If BP detection is done or still in progress.\n * Should only be checked when detectBufferingProxy is turned on.\n * @private {boolean}\n */\n this.bpDetectionDone_ = false;\n\n /**\n * The timer for detecting buffering proxy. This needs be reset with each\n * backchannel request. If this is not null, bpDetectionDone_ == false.\n * @private {?number}\n */\n this.bpDetectionTimerId_ = null;\n\n /***\n * Whether to attempt Chrome Origin Trials as part of the handshake.\n * @private @const {boolean}\n */\n this.enableOriginTrials_ = ALLOW_ORIGIN_TRIAL_FEATURES &&\n (!opt_options || opt_options.enableOriginTrials !== false);\n\n /**\n * The array of non-acked maps at the time of channel close. Refer to\n * `getNonAckedMessagesWithClosedChannel()` API for definitions of non-acked\n * messages.\n *\n * @private {?Array<!Wire.QueuedMap>}\n */\n this.nonAckedMapsAtChannelClose_ = null;\n};\n\nconst WebChannelBase = goog.labs.net.webChannel.WebChannelBase;\n\n\n/**\n * The channel version that we negotiated with the server for this session.\n * Starts out as the version we request, and then is changed to the negotiated\n * version after the initial open.\n * @private {number}\n */\nWebChannelBase.prototype.channelVersion_ = Wire.LATEST_CHANNEL_VERSION;\n\n\n/**\n * Enum type for the channel state machine.\n * @enum {number}\n */\nWebChannelBase.State = {\n /** The channel is closed. */\n CLOSED: 0,\n\n /** The channel has been initialized but hasn't yet initiated a connection. */\n INIT: 1,\n\n /** The channel is in the process of opening a connection to the server. */\n OPENING: 2,\n\n /** The channel is open. */\n OPENED: 3\n};\n\n\n/**\n * The current state of the WebChannel.\n * @private {!WebChannelBase.State}\n */\nWebChannelBase.prototype.state_ = WebChannelBase.State.INIT;\n\n\n/**\n * The timeout in milliseconds for a forward channel request.\n * @type {number}\n */\nWebChannelBase.FORWARD_CHANNEL_RETRY_TIMEOUT = 20 * 1000;\n\n\n/**\n * Maximum number of attempts to connect to the server for back channel\n * requests.\n * @type {number}\n */\nWebChannelBase.BACK_CHANNEL_MAX_RETRIES = 3;\n\n\n/**\n * A number in MS of how long we guess the maxmium amount of time a round trip\n * to the server should take. In the future this could be substituted with a\n * real measurement of the RTT.\n * @type {number}\n */\nWebChannelBase.RTT_ESTIMATE = 3 * 1000;\n\n\n/**\n * When retrying for an inactive channel, we will multiply the total delay by\n * this number.\n * @type {number}\n */\nWebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR = 2;\n\n\n/**\n * Enum type for identifying an error.\n * @enum {number}\n */\nWebChannelBase.Error = {\n /** Value that indicates no error has occurred. */\n OK: 0,\n\n /** An error due to a request failing. */\n REQUEST_FAILED: 2,\n\n /** An error due to the user being logged out. */\n LOGGED_OUT: 4,\n\n /** An error due to server response which contains no data. */\n NO_DATA: 5,\n\n /** An error due to a server response indicating an unknown session id */\n UNKNOWN_SESSION_ID: 6,\n\n /** An error due to a server response requesting to stop the channel. */\n STOP: 7,\n\n /** A general network error. */\n NETWORK: 8,\n\n /** An error due to bad data being returned from the server. */\n BAD_DATA: 10,\n\n /** An error due to a response that is not parsable. */\n BAD_RESPONSE: 11\n};\n\n\n/**\n * Internal enum type for the two channel types.\n * @enum {number}\n * @private\n */\nWebChannelBase.ChannelType_ = {\n FORWARD_CHANNEL: 1,\n\n BACK_CHANNEL: 2\n};\n\n\n/**\n * The maximum number of maps that can be sent in one POST. Should match\n * MAX_MAPS_PER_REQUEST on the server code.\n * @type {number}\n * @private\n */\nWebChannelBase.MAX_MAPS_PER_REQUEST_ = 1000;\n\n\n/**\n * The maximum number of utf-8 chars that can be sent in one GET to enable 0-RTT\n * handshake.\n *\n * @const @private {number}\n */\nWebChannelBase.MAX_CHARS_PER_GET_ = 4 * 1024;\n\n\n/**\n * A guess at a cutoff at which to no longer assume the backchannel is dead\n * when we are slow to receive data. Number in bytes.\n *\n * Assumption: The worst bandwidth we work on is 50 kilobits/sec\n * 50kbits/sec * (1 byte / 8 bits) * 6 sec dead backchannel timeout\n * @type {number}\n */\nWebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF = 37500;\n\n\n/**\n * @return {number} The server version or 0 if undefined\n */\nWebChannelBase.prototype.getServerVersion = function() {\n 'use strict';\n return this.serverVersion_;\n};\n\n\n/**\n * @return {!ForwardChannelRequestPool} The forward channel request pool.\n */\nWebChannelBase.prototype.getForwardChannelRequestPool = function() {\n 'use strict';\n return this.forwardChannelRequestPool_;\n};\n\n\n/**\n * @return {!Object} The codec object.\n */\nWebChannelBase.prototype.getWireCodec = function() {\n 'use strict';\n return this.wireCodec_;\n};\n\n\n/**\n * Returns the logger.\n *\n * @return {!WebChannelDebug} The channel debug object.\n */\nWebChannelBase.prototype.getChannelDebug = function() {\n 'use strict';\n return this.channelDebug_;\n};\n\n\n/**\n * Sets the logger.\n *\n * @param {!WebChannelDebug} channelDebug The channel debug object.\n */\nWebChannelBase.prototype.setChannelDebug = function(channelDebug) {\n 'use strict';\n this.channelDebug_ = channelDebug;\n};\n\n\n/**\n * Starts the channel. This initiates connections to the server.\n *\n * @param {string} channelPath The path for the channel connection.\n * @param {!Object=} opt_extraParams Extra parameter keys and values to add to\n * the requests.\n * @param {string=} opt_oldSessionId Session ID from a previous session.\n * @param {number=} opt_oldArrayId The last array ID from a previous session.\n */\nWebChannelBase.prototype.connect = function(\n channelPath, opt_extraParams, opt_oldSessionId, opt_oldArrayId) {\n 'use strict';\n this.channelDebug_.debug('connect()');\n\n this.startOriginTrials_(channelPath);\n\n requestStats.notifyStatEvent(requestStats.Stat.CONNECT_ATTEMPT);\n\n this.path_ = channelPath;\n this.extraParams_ = opt_extraParams || {};\n\n // Attach parameters about the previous session if reconnecting.\n if (opt_oldSessionId && opt_oldArrayId !== undefined) {\n this.extraParams_['OSID'] = opt_oldSessionId;\n this.extraParams_['OAID'] = opt_oldArrayId;\n }\n\n this.enableStreaming_ = this.allowStreamingMode_;\n this.connectChannel_();\n};\n\n\n/**\n * Disconnects and closes the channel.\n */\nWebChannelBase.prototype.disconnect = function() {\n 'use strict';\n this.channelDebug_.debug('disconnect()');\n\n this.cancelRequests_();\n\n if (this.state_ == WebChannelBase.State.OPENED) {\n const rid = this.nextRid_++;\n const uri = this.forwardChannelUri_.clone();\n uri.setParameterValue('SID', this.sid_);\n uri.setParameterValue('RID', rid);\n uri.setParameterValue('TYPE', 'terminate');\n\n this.addAdditionalParams_(uri);\n\n const request = ChannelRequest.createChannelRequest(\n this, this.channelDebug_, this.sid_, rid);\n request.sendCloseRequest(uri);\n }\n\n this.onClose_();\n};\n\n\n/**\n * Returns the session id of the channel. Only available after the\n * channel has been opened.\n * @return {string} Session ID.\n */\nWebChannelBase.prototype.getSessionId = function() {\n 'use strict';\n return this.sid_;\n};\n\n\n/**\n * Starts the connection.\n * @private\n */\nWebChannelBase.prototype.connectChannel_ = function() {\n 'use strict';\n this.channelDebug_.debug('connectChannel_()');\n this.ensureInState_(WebChannelBase.State.INIT, WebChannelBase.State.CLOSED);\n this.forwardChannelUri_ =\n this.getForwardChannelUri(/** @type {string} */ (this.path_));\n this.ensureForwardChannel_();\n};\n\n\n/**\n * Starts the Origin Trials.\n * @param {string} channelPath The path for the channel connection.\n * @private\n */\nWebChannelBase.prototype.startOriginTrials_ = function(channelPath) {\n 'use strict';\n\n if (!this.enableOriginTrials_) {\n return;\n }\n\n this.channelDebug_.info('Origin Trials enabled.');\n goog.async.run(goog.bind(this.runOriginTrials_, this, channelPath));\n};\n\n\n/**\n * Runs the Origin Trials.\n * @param {string} channelPath The path for the channel connection.\n * @private\n */\nWebChannelBase.prototype.runOriginTrials_ = function(channelPath) {\n 'use strict';\n\n try {\n // Since startOriginTrials might throw exceptions asynchronously, we should\n // capture it in promise-catch.\n environment.startOriginTrials(channelPath, e => {\n this.channelDebug_.dumpException(\n /** @type {?Error} */ (e), 'Error in running origin trials');\n });\n this.channelDebug_.info('Origin Trials invoked: ' + channelPath);\n } catch (e) {\n this.channelDebug_.dumpException(e, 'Error in running origin trials');\n }\n};\n\n\n/**\n * Cancels backchannel request.\n * @private\n */\nWebChannelBase.prototype.cancelBackChannelRequest_ = function() {\n 'use strict';\n if (this.backChannelRequest_) {\n this.clearBpDetectionTimer_();\n this.backChannelRequest_.cancel();\n this.backChannelRequest_ = null;\n }\n};\n\n\n/**\n * Cancels all outstanding requests.\n * @private\n */\nWebChannelBase.prototype.cancelRequests_ = function() {\n 'use strict';\n this.cancelBackChannelRequest_();\n\n if (this.backChannelTimerId_) {\n goog.global.clearTimeout(this.backChannelTimerId_);\n this.backChannelTimerId_ = null;\n }\n\n this.clearDeadBackchannelTimer_();\n\n this.forwardChannelRequestPool_.cancel();\n\n if (this.forwardChannelTimerId_) {\n this.clearForwardChannelTimer_();\n }\n};\n\n\n/**\n * Clears the forward channel timer.\n * @private\n */\nWebChannelBase.prototype.clearForwardChannelTimer_ = function() {\n 'use strict';\n if (typeof this.forwardChannelTimerId_ === 'number') {\n goog.global.clearTimeout(this.forwardChannelTimerId_);\n }\n\n this.forwardChannelTimerId_ = null;\n};\n\n\n/**\n * Returns the extra HTTP headers to add to all the requests sent to the server.\n *\n * @return {Object} The HTTP headers, or null.\n */\nWebChannelBase.prototype.getExtraHeaders = function() {\n 'use strict';\n return this.extraHeaders_;\n};\n\n\n/**\n * Sets extra HTTP headers to add to all the requests sent to the server.\n *\n * @param {Object} extraHeaders The HTTP headers, or null.\n */\nWebChannelBase.prototype.setExtraHeaders = function(extraHeaders) {\n 'use strict';\n this.extraHeaders_ = extraHeaders;\n};\n\n\n/**\n * Returns the extra HTTP headers to add to the init requests\n * sent to the server.\n *\n * @return {Object} The HTTP headers, or null.\n */\nWebChannelBase.prototype.getInitHeaders = function() {\n 'use strict';\n return this.initHeaders_;\n};\n\n\n/**\n * Sets extra HTTP headers to add to the init requests sent to the server.\n *\n * @param {Object} initHeaders The HTTP headers, or null.\n */\nWebChannelBase.prototype.setInitHeaders = function(initHeaders) {\n 'use strict';\n this.initHeaders_ = initHeaders;\n};\n\n\n/**\n * Sets the URL param name to overwrite custom HTTP headers.\n *\n * @param {string} httpHeadersOverwriteParam The URL param name.\n */\nWebChannelBase.prototype.setHttpHeadersOverwriteParam = function(\n httpHeadersOverwriteParam) {\n 'use strict';\n this.httpHeadersOverwriteParam_ = httpHeadersOverwriteParam;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.setHttpSessionIdParam = function(httpSessionIdParam) {\n 'use strict';\n this.httpSessionIdParam_ = httpSessionIdParam;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getHttpSessionIdParam = function() {\n 'use strict';\n return this.httpSessionIdParam_;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.setHttpSessionId = function(httpSessionId) {\n 'use strict';\n this.httpSessionId_ = httpSessionId;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getHttpSessionId = function() {\n 'use strict';\n return this.httpSessionId_;\n};\n\n\n/**\n * Sets the throttle for handling onreadystatechange events for the request.\n *\n * @param {number} throttle The throttle in ms. A value of zero indicates\n * no throttle.\n */\nWebChannelBase.prototype.setReadyStateChangeThrottle = function(throttle) {\n 'use strict';\n this.readyStateChangeThrottleMs_ = throttle;\n};\n\n\n/**\n * Sets whether cross origin requests are supported for the channel.\n *\n * Setting this allows the creation of requests to secondary domains and\n * sends XHRs with the CORS withCredentials bit set to true.\n *\n * In order for cross-origin requests to work, the server will also need to set\n * CORS response headers as per:\n * https://developer.mozilla.org/en-US/docs/HTTP_access_control\n *\n * See {@link goog.net.XhrIo#setWithCredentials}.\n * @param {boolean} supportCrossDomain Whether cross domain XHRs are supported.\n */\nWebChannelBase.prototype.setSupportsCrossDomainXhrs = function(\n supportCrossDomain) {\n 'use strict';\n this.supportsCrossDomainXhrs_ = supportCrossDomain;\n};\n\n\n/**\n * Returns the handler used for channel callback events.\n *\n * @return {WebChannelBase.Handler} The handler.\n */\nWebChannelBase.prototype.getHandler = function() {\n 'use strict';\n return this.handler_;\n};\n\n\n/**\n * Sets the handler used for channel callback events.\n * @param {WebChannelBase.Handler} handler The handler to set.\n */\nWebChannelBase.prototype.setHandler = function(handler) {\n 'use strict';\n this.handler_ = handler;\n};\n\n\n/**\n * Returns whether the channel allows the use of a subdomain. There may be\n * cases where this isn't allowed.\n * @return {boolean} Whether a host prefix is allowed.\n */\nWebChannelBase.prototype.getAllowHostPrefix = function() {\n 'use strict';\n return this.allowHostPrefix_;\n};\n\n\n/**\n * Sets whether the channel allows the use of a subdomain. There may be cases\n * where this isn't allowed, for example, logging in with troutboard where\n * using a subdomain causes Apache to force the user to authenticate twice.\n * @param {boolean} allowHostPrefix Whether a host prefix is allowed.\n */\nWebChannelBase.prototype.setAllowHostPrefix = function(allowHostPrefix) {\n 'use strict';\n this.allowHostPrefix_ = allowHostPrefix;\n};\n\n\n/**\n * Returns whether the channel is buffered or not. This may be\n * queried in the WebChannelBase.okToMakeRequest() callback.\n *\n * @return {boolean} Whether the channel is buffered.\n */\nWebChannelBase.prototype.isBuffered = function() {\n 'use strict';\n return !this.enableStreaming_;\n};\n\n\n/**\n * Returns whether streaming mode is allowed. In certain debugging situations,\n * it's useful for the application to have a way to disable streaming mode for a\n * user.\n\n * @return {boolean} Whether streaming mode is allowed.\n */\nWebChannelBase.prototype.getAllowStreamingMode = function() {\n 'use strict';\n return this.allowStreamingMode_;\n};\n\n\n/**\n * Sets whether streaming mode is allowed. In certain debugging situations, it's\n * useful for the application to have a way to disable streaming mode for a\n * user.\n * @param {boolean} allowStreamingMode Whether streaming mode is allowed.\n */\nWebChannelBase.prototype.setAllowStreamingMode = function(allowStreamingMode) {\n 'use strict';\n this.allowStreamingMode_ = allowStreamingMode;\n};\n\n\n/**\n * Sends a request to the server. The format of the request is a Map data\n * structure of key/value pairs. These maps are then encoded in a format\n * suitable for the wire and then reconstituted as a Map data structure that\n * the server can process.\n * @param {!Object|!goog.collections.maps.MapLike} map The map to send.\n * @param {!Object=} opt_context The context associated with the map.\n */\nWebChannelBase.prototype.sendMap = function(map, opt_context) {\n 'use strict';\n goog.asserts.assert(\n this.state_ != WebChannelBase.State.CLOSED,\n 'Invalid operation: sending map when state is closed');\n\n // We can only send 1000 maps per POST, but typically we should never have\n // that much to send, so warn if we exceed that (we still send all the maps).\n if (this.outgoingMaps_.length == WebChannelBase.MAX_MAPS_PER_REQUEST_) {\n // severe() is temporary so that we get these uploaded and can figure out\n // what's causing them. Afterwards can change to warning().\n this.channelDebug_.severe(function() {\n 'use strict';\n return 'Already have ' + WebChannelBase.MAX_MAPS_PER_REQUEST_ +\n ' queued maps upon queueing ' + goog.json.serialize(map);\n });\n }\n\n this.outgoingMaps_.push(\n new Wire.QueuedMap(this.nextMapId_++, map, opt_context));\n\n // Messages need be buffered during OPENING to avoid server-side race\n if (this.state_ == WebChannelBase.State.OPENED) {\n this.ensureForwardChannel_();\n }\n};\n\n\n/**\n * When set to true, this changes the behavior of the forward channel so it\n * will not retry requests; it will fail after one network failure, and if\n * there was already one network failure, the request will fail immediately.\n * @param {boolean} failFast Whether or not to fail fast.\n */\nWebChannelBase.prototype.setFailFast = function(failFast) {\n 'use strict';\n this.failFast_ = failFast;\n this.channelDebug_.info('setFailFast: ' + failFast);\n if ((this.forwardChannelRequestPool_.hasPendingRequest() ||\n this.forwardChannelTimerId_) &&\n this.forwardChannelRetryCount_ > this.getForwardChannelMaxRetries()) {\n const self = this;\n this.channelDebug_.info(function() {\n 'use strict';\n return 'Retry count ' + self.forwardChannelRetryCount_ +\n ' > new maxRetries ' + self.getForwardChannelMaxRetries() +\n '. Fail immediately!';\n });\n\n if (!this.forwardChannelRequestPool_.forceComplete(\n goog.bind(this.onRequestComplete, this))) {\n // i.e., this.forwardChannelTimerId_\n this.clearForwardChannelTimer_();\n // The error code from the last failed request is gone, so just use a\n // generic one.\n this.signalError_(WebChannelBase.Error.REQUEST_FAILED);\n }\n }\n};\n\n\n/**\n * @return {number} The max number of forward-channel retries, which will be 0\n * in fail-fast mode.\n */\nWebChannelBase.prototype.getForwardChannelMaxRetries = function() {\n 'use strict';\n return this.failFast_ ? 0 : this.forwardChannelMaxRetries_;\n};\n\n\n/**\n * Sets the maximum number of attempts to connect to the server for forward\n * channel requests.\n * @param {number} retries The maximum number of attempts.\n */\nWebChannelBase.prototype.setForwardChannelMaxRetries = function(retries) {\n 'use strict';\n this.forwardChannelMaxRetries_ = retries;\n};\n\n\n/**\n * Sets the timeout for a forward channel request.\n * @param {number} timeoutMs The timeout in milliseconds.\n */\nWebChannelBase.prototype.setForwardChannelRequestTimeout = function(timeoutMs) {\n 'use strict';\n this.forwardChannelRequestTimeoutMs_ = timeoutMs;\n};\n\n\n/**\n * @return {number} The max number of back-channel retries, which is a constant.\n */\nWebChannelBase.prototype.getBackChannelMaxRetries = function() {\n 'use strict';\n // Back-channel retries is a constant.\n return WebChannelBase.BACK_CHANNEL_MAX_RETRIES;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.isClosed = function() {\n 'use strict';\n return this.state_ == WebChannelBase.State.CLOSED;\n};\n\n\n/**\n * Returns the channel state.\n * @return {WebChannelBase.State} The current state of the channel.\n */\nWebChannelBase.prototype.getState = function() {\n 'use strict';\n return this.state_;\n};\n\n\n/**\n * @return {!Object<string, string>|undefined} The response headers received\n * along with the non-200 status.\n */\nWebChannelBase.prototype.getLastResponseHeaders = function() {\n 'use strict';\n return this.errorResponseHeaders_;\n};\n\n\n/**\n * @return {number} The non-200 status code received that causes the channel to\n * be aborted.\n */\nWebChannelBase.prototype.getLastStatusCode = function() {\n 'use strict';\n return this.errorResponseStatusCode_;\n};\n\n\n/**\n * @return {number} The last array id received.\n */\nWebChannelBase.prototype.getLastArrayId = function() {\n 'use strict';\n return this.lastArrayId_;\n};\n\n\n/**\n * Returns whether there are outstanding requests servicing the channel.\n * @return {boolean} true if there are outstanding requests.\n */\nWebChannelBase.prototype.hasOutstandingRequests = function() {\n 'use strict';\n return this.getOutstandingRequests_() != 0;\n};\n\n\n/**\n * Returns the number of outstanding requests.\n * @return {number} The number of outstanding requests to the server.\n * @private\n */\nWebChannelBase.prototype.getOutstandingRequests_ = function() {\n 'use strict';\n let count = 0;\n if (this.backChannelRequest_) {\n count++;\n }\n count += this.forwardChannelRequestPool_.getRequestCount();\n return count;\n};\n\n\n/**\n * Ensures that a forward channel request is scheduled.\n * @private\n */\nWebChannelBase.prototype.ensureForwardChannel_ = function() {\n 'use strict';\n if (this.forwardChannelRequestPool_.isFull()) {\n // enough connection in process - no need to start a new request\n return;\n }\n\n if (this.forwardChannelTimerId_) {\n // no need to start a new request - one is already scheduled\n return;\n }\n\n // Use async.run instead of setTimeout(0) to avoid the 1s message delay\n // from chrome/firefox background tabs\n this.forwardChannelTimerId_ = true;\n goog.async.run(this.onStartForwardChannelTimer_, this);\n\n this.forwardChannelRetryCount_ = 0;\n};\n\n\n/**\n * Schedules a forward-channel retry for the specified request, unless the max\n * retries has been reached.\n * @param {!ChannelRequest} request The failed request to retry.\n * @return {boolean} true iff a retry was scheduled.\n * @private\n */\nWebChannelBase.prototype.maybeRetryForwardChannel_ = function(request) {\n 'use strict';\n if (this.forwardChannelRequestPool_.getRequestCount() >=\n this.forwardChannelRequestPool_.getMaxSize() -\n (this.forwardChannelTimerId_ ? 1 : 0)) {\n // Should be impossible to be called in this state.\n this.channelDebug_.severe('Unexpected retry request is scheduled.');\n return false;\n }\n\n if (this.forwardChannelTimerId_) {\n this.channelDebug_.debug(\n 'Use the retry request that is already scheduled.');\n this.outgoingMaps_ =\n request.getPendingMessages().concat(this.outgoingMaps_);\n return true;\n }\n\n // No retry for open_() and fail-fast\n if (this.state_ == WebChannelBase.State.INIT ||\n this.state_ == WebChannelBase.State.OPENING ||\n (this.forwardChannelRetryCount_ >= this.getForwardChannelMaxRetries())) {\n return false;\n }\n\n this.channelDebug_.debug('Going to retry POST');\n\n this.forwardChannelTimerId_ = requestStats.setTimeout(\n goog.bind(this.onStartForwardChannelTimer_, this, request),\n this.getRetryTime_(this.forwardChannelRetryCount_));\n this.forwardChannelRetryCount_++;\n return true;\n};\n\n\n/**\n * Timer callback for ensureForwardChannel\n * @param {ChannelRequest=} opt_retryRequest A failed request\n * to retry.\n * @private\n */\nWebChannelBase.prototype.onStartForwardChannelTimer_ = function(\n opt_retryRequest) {\n 'use strict';\n // null is possible if scheduled with async.run\n if (this.forwardChannelTimerId_) {\n this.forwardChannelTimerId_ = null;\n this.startForwardChannel_(opt_retryRequest);\n }\n};\n\n\n/**\n * Begins a new forward channel operation to the server.\n * @param {ChannelRequest=} opt_retryRequest A failed request to retry.\n * @private\n */\nWebChannelBase.prototype.startForwardChannel_ = function(opt_retryRequest) {\n 'use strict';\n this.channelDebug_.debug('startForwardChannel_');\n if (!this.okToMakeRequest_()) {\n return; // channel is cancelled\n } else if (this.state_ == WebChannelBase.State.INIT) {\n if (opt_retryRequest) {\n this.channelDebug_.severe('Not supposed to retry the open');\n return;\n }\n this.open_();\n this.state_ = WebChannelBase.State.OPENING;\n } else if (this.state_ == WebChannelBase.State.OPENED) {\n if (opt_retryRequest) {\n this.makeForwardChannelRequest_(opt_retryRequest);\n return;\n }\n\n if (this.outgoingMaps_.length == 0) {\n this.channelDebug_.debug(\n 'startForwardChannel_ returned: ' +\n 'nothing to send');\n // no need to start a new forward channel request\n return;\n }\n\n if (this.forwardChannelRequestPool_.isFull()) {\n // Should be impossible to be called in this state.\n this.channelDebug_.severe(\n 'startForwardChannel_ returned: ' +\n 'connection already in progress');\n return;\n }\n\n this.makeForwardChannelRequest_();\n this.channelDebug_.debug('startForwardChannel_ finished, sent request');\n }\n};\n\n\n/**\n * Establishes a new channel session with the server.\n * @private\n */\nWebChannelBase.prototype.open_ = function() {\n 'use strict';\n this.channelDebug_.debug('open_()');\n this.nextRid_ = Math.floor(Math.random() * 100000);\n\n const rid = this.nextRid_++;\n const request =\n ChannelRequest.createChannelRequest(this, this.channelDebug_, '', rid);\n\n // mix the init headers\n let extraHeaders = this.extraHeaders_;\n if (this.initHeaders_) {\n if (extraHeaders) {\n extraHeaders = goog.object.clone(extraHeaders);\n goog.object.extend(extraHeaders, this.initHeaders_);\n } else {\n extraHeaders = this.initHeaders_;\n }\n }\n\n if (this.httpHeadersOverwriteParam_ === null &&\n !this.encodeInitMessageHeaders_) {\n request.setExtraHeaders(extraHeaders);\n extraHeaders = null;\n }\n\n let requestText = this.dequeueOutgoingMaps_(\n request,\n this.fastHandshake_ ? this.getMaxNumMessagesForFastHandshake_() :\n WebChannelBase.MAX_MAPS_PER_REQUEST_);\n\n const uri = this.forwardChannelUri_.clone();\n uri.setParameterValue('RID', rid);\n\n if (this.clientVersion_ > 0) {\n uri.setParameterValue('CVER', this.clientVersion_);\n }\n\n // http-session-id to be generated as the response\n if (this.getHttpSessionIdParam()) {\n uri.setParameterValue(\n WebChannel.X_HTTP_SESSION_ID, this.getHttpSessionIdParam());\n }\n\n this.addAdditionalParams_(uri);\n\n if (extraHeaders) {\n if (this.encodeInitMessageHeaders_) {\n let encodedHeaders =\n httpCors.generateEncodedHttpHeadersOverwriteParam(extraHeaders);\n requestText = 'headers=' + encodedHeaders + '&' + requestText;\n } else if (this.httpHeadersOverwriteParam_) {\n httpCors.setHttpHeadersWithOverwriteParam(\n uri, this.httpHeadersOverwriteParam_, extraHeaders);\n } // else - should not happen\n }\n\n this.forwardChannelRequestPool_.addRequest(request);\n\n if (this.blockingHandshake_) {\n uri.setParameterValue('TYPE', 'init'); // default to blocking in future\n }\n\n // Check the option and use GET to enable QUIC 0-RTT\n if (this.fastHandshake_) {\n uri.setParameterValue('$req', requestText);\n\n // enable handshake upgrade\n uri.setParameterValue('SID', 'null');\n request.setDecodeInitialResponse();\n\n request.xmlHttpPost(uri, null, true); // Send as a GET\n } else {\n request.xmlHttpPost(uri, requestText, true);\n }\n};\n\n\n/**\n * @return {number} The number of raw JSON messages to be encoded\n * with the fast-handshake (GET) request, including zero. If messages are not\n * encoded as raw JSON data, return WebChannelBase.MAX_MAPS_PER_REQUEST_\n * @private\n */\nWebChannelBase.prototype.getMaxNumMessagesForFastHandshake_ = function() {\n 'use strict';\n let total = 0;\n for (let i = 0; i < this.outgoingMaps_.length; i++) {\n const map = this.outgoingMaps_[i];\n const size = map.getRawDataSize();\n if (size === undefined) {\n break;\n }\n total += size;\n\n if (total > WebChannelBase.MAX_CHARS_PER_GET_) {\n return i;\n }\n\n if (total === WebChannelBase.MAX_CHARS_PER_GET_ ||\n i === this.outgoingMaps_.length - 1) {\n return i + 1;\n }\n }\n\n return WebChannelBase.MAX_MAPS_PER_REQUEST_;\n};\n\n\n\n/**\n * Makes a forward channel request using XMLHTTP.\n * @param {!ChannelRequest=} opt_retryRequest A failed request to retry.\n * @private\n */\nWebChannelBase.prototype.makeForwardChannelRequest_ = function(\n opt_retryRequest) {\n 'use strict';\n let rid;\n if (opt_retryRequest) {\n rid = opt_retryRequest.getRequestId(); // Reuse the same RID for a retry\n } else {\n rid = this.nextRid_++;\n }\n\n const uri = this.forwardChannelUri_.clone();\n uri.setParameterValue('SID', this.sid_);\n uri.setParameterValue('RID', rid);\n uri.setParameterValue('AID', this.lastArrayId_);\n\n this.addAdditionalParams_(uri);\n\n if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {\n httpCors.setHttpHeadersWithOverwriteParam(\n uri, this.httpHeadersOverwriteParam_, this.extraHeaders_);\n }\n\n const request = ChannelRequest.createChannelRequest(\n this, this.channelDebug_, this.sid_, rid,\n this.forwardChannelRetryCount_ + 1);\n\n if (this.httpHeadersOverwriteParam_ === null) {\n request.setExtraHeaders(this.extraHeaders_);\n }\n\n let requestText;\n if (opt_retryRequest) {\n this.requeuePendingMaps_(opt_retryRequest);\n }\n requestText =\n this.dequeueOutgoingMaps_(request, WebChannelBase.MAX_MAPS_PER_REQUEST_);\n\n // Randomize from 50%-100% of the forward channel timeout to avoid\n // a big hit if servers happen to die at once.\n request.setTimeout(\n Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50) +\n Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50 * Math.random()));\n this.forwardChannelRequestPool_.addRequest(request);\n request.xmlHttpPost(uri, requestText, true);\n};\n\n\n/**\n * Adds additional query parameters from `extraParams_` and `handler_` to the\n * given URI.\n * @param {!goog.Uri} uri The URI to add the parameters to.\n * @private\n */\nWebChannelBase.prototype.addAdditionalParams_ = function(uri) {\n 'use strict';\n if (this.extraParams_) {\n goog.object.forEach(this.extraParams_, function(value, key) {\n 'use strict';\n uri.setParameterValue(key, value);\n });\n }\n\n if (this.handler_) {\n const params = this.handler_.getAdditionalParams(this);\n if (params) {\n goog.structs.forEach(params, function(value, key, coll) {\n 'use strict';\n uri.setParameterValue(key, value);\n });\n }\n }\n};\n\n\n/**\n * Returns the request text from the outgoing maps and resets it.\n * @param {!ChannelRequest} request The new request for sending the messages.\n * @param {number} maxNum The maximum number of messages to be encoded\n * @return {string} The encoded request text created from all the currently\n * queued outgoing maps.\n * @private\n */\nWebChannelBase.prototype.dequeueOutgoingMaps_ = function(request, maxNum) {\n 'use strict';\n const count = Math.min(this.outgoingMaps_.length, maxNum);\n\n const badMapHandler = this.handler_ ?\n goog.bind(this.handler_.badMapError, this.handler_, this) :\n null;\n const result = this.wireCodec_.encodeMessageQueue(\n this.outgoingMaps_, count, badMapHandler);\n\n request.setPendingMessages(this.outgoingMaps_.splice(0, count));\n\n return result;\n};\n\n\n/**\n * Requeues unacknowledged sent arrays for retransmission in the next forward\n * channel request.\n * @param {!ChannelRequest} retryRequest A failed request to retry.\n * @private\n */\nWebChannelBase.prototype.requeuePendingMaps_ = function(retryRequest) {\n 'use strict';\n this.outgoingMaps_ =\n retryRequest.getPendingMessages().concat(this.outgoingMaps_);\n};\n\n\n/**\n * Ensures there is a backchannel request for receiving data from the server.\n * @private\n */\nWebChannelBase.prototype.ensureBackChannel_ = function() {\n 'use strict';\n if (this.backChannelRequest_) {\n // already have one\n return;\n }\n\n if (this.backChannelTimerId_) {\n // no need to start a new request - one is already scheduled\n return;\n }\n\n this.backChannelAttemptId_ = 1;\n\n // Use async.run instead of setTimeout(0) to avoid the 1s message delay\n // from chrome/firefox background tabs\n // backChannelTimerId_ stays unset, as with setTimeout(0)\n goog.async.run(this.onStartBackChannelTimer_, this);\n\n this.backChannelRetryCount_ = 0;\n};\n\n\n/**\n * Schedules a back-channel retry, unless the max retries has been reached.\n * @return {boolean} true iff a retry was scheduled.\n * @private\n */\nWebChannelBase.prototype.maybeRetryBackChannel_ = function() {\n 'use strict';\n if (this.backChannelRequest_ || this.backChannelTimerId_) {\n // Should be impossible to be called in this state.\n this.channelDebug_.severe('Request already in progress');\n return false;\n }\n\n if (this.backChannelRetryCount_ >= this.getBackChannelMaxRetries()) {\n return false;\n }\n\n this.channelDebug_.debug('Going to retry GET');\n\n this.backChannelAttemptId_++;\n this.backChannelTimerId_ = requestStats.setTimeout(\n goog.bind(this.onStartBackChannelTimer_, this),\n this.getRetryTime_(this.backChannelRetryCount_));\n this.backChannelRetryCount_++;\n return true;\n};\n\n\n/**\n * Timer callback for ensureBackChannel_.\n * @private\n */\nWebChannelBase.prototype.onStartBackChannelTimer_ = function() {\n 'use strict';\n this.backChannelTimerId_ = null;\n this.startBackChannel_();\n\n if (!this.detectBufferingProxy_) {\n return;\n }\n\n if (this.bpDetectionDone_) {\n return;\n }\n\n if (this.backChannelRequest_ == null || this.handshakeRttMs_ <= 0) {\n this.channelDebug_.warning(\n 'Skip bpDetectionTimerId_ ' + this.backChannelRequest_ + ' ' +\n this.handshakeRttMs_);\n return;\n }\n\n // This goes with each new request until bpDetectionDone_\n const bpDetectionTimeout = 2 * this.handshakeRttMs_;\n this.channelDebug_.info('BP detection timer enabled: ' + bpDetectionTimeout);\n\n this.bpDetectionTimerId_ = requestStats.setTimeout(\n goog.bind(this.onBpDetectionTimer_, this), bpDetectionTimeout);\n};\n\n\n/**\n * Timer callback for bpDetection.\n * @private\n */\nWebChannelBase.prototype.onBpDetectionTimer_ = function() {\n 'use strict';\n if (!this.bpDetectionTimerId_) {\n this.channelDebug_.warning('Invalid operation.');\n return;\n }\n\n this.bpDetectionTimerId_ = null;\n this.channelDebug_.info('BP detection timeout reached.');\n\n goog.asserts.assert(\n this.backChannelRequest_ != null,\n 'Invalid state: no backchannel request');\n\n // We wait for extra response payload in addition to just headers to\n // cancel the timer.\n if (this.backChannelRequest_.getXhr() != null) {\n const responseData = this.backChannelRequest_.getXhr().getResponseText();\n if (responseData) {\n this.channelDebug_.warning(\n 'Timer should have been cancelled : ' + responseData);\n }\n }\n\n // Enable long-polling\n this.channelDebug_.info(\n 'Buffering proxy detected and switch to long-polling!');\n this.enableStreaming_ = false;\n\n this.bpDetectionDone_ = true;\n requestStats.notifyStatEvent(requestStats.Stat.PROXY);\n\n // Cancel the request and start a new one immediately\n this.cancelBackChannelRequest_();\n this.startBackChannel_();\n};\n\n\n/**\n * Clears the timer for BP detection.\n * @private\n */\nWebChannelBase.prototype.clearBpDetectionTimer_ = function() {\n 'use strict';\n if (this.bpDetectionTimerId_ != null) {\n this.channelDebug_.debug('Cancel the BP detection timer.');\n goog.global.clearTimeout(this.bpDetectionTimerId_);\n this.bpDetectionTimerId_ = null;\n }\n};\n\n\n/**\n * Begins a new back channel operation to the server.\n * @private\n */\nWebChannelBase.prototype.startBackChannel_ = function() {\n 'use strict';\n if (!this.okToMakeRequest_()) {\n // channel is cancelled\n return;\n }\n\n this.channelDebug_.debug('Creating new HttpRequest');\n this.backChannelRequest_ = ChannelRequest.createChannelRequest(\n this, this.channelDebug_, this.sid_, 'rpc', this.backChannelAttemptId_);\n\n if (this.httpHeadersOverwriteParam_ === null) {\n this.backChannelRequest_.setExtraHeaders(this.extraHeaders_);\n }\n\n this.backChannelRequest_.setReadyStateChangeThrottle(\n this.readyStateChangeThrottleMs_);\n const uri = this.backChannelUri_.clone();\n uri.setParameterValue('RID', 'rpc');\n uri.setParameterValue('SID', this.sid_);\n uri.setParameterValue('AID', this.lastArrayId_);\n\n uri.setParameterValue('CI', this.enableStreaming_ ? '0' : '1');\n if (!this.enableStreaming_ && this.longPollingTimeout_) {\n uri.setParameterValue('TO', this.longPollingTimeout_);\n }\n\n uri.setParameterValue('TYPE', 'xmlhttp');\n\n this.addAdditionalParams_(uri);\n\n if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {\n httpCors.setHttpHeadersWithOverwriteParam(\n uri, this.httpHeadersOverwriteParam_, this.extraHeaders_);\n }\n\n if (this.backChannelRequestTimeoutMs_) {\n this.backChannelRequest_.setTimeout(this.backChannelRequestTimeoutMs_);\n }\n\n this.backChannelRequest_.xmlHttpGet(\n uri, true /* decodeChunks */, this.hostPrefix_);\n\n this.channelDebug_.debug('New Request created');\n};\n\n\n/**\n * Gives the handler a chance to return an error code and stop channel\n * execution. A handler might want to do this to check that the user is still\n * logged in, for example.\n * @private\n * @return {boolean} If it's OK to make a request.\n */\nWebChannelBase.prototype.okToMakeRequest_ = function() {\n 'use strict';\n if (this.handler_) {\n const result = this.handler_.okToMakeRequest(this);\n if (result != WebChannelBase.Error.OK) {\n this.channelDebug_.debug(\n 'Handler returned error code from okToMakeRequest');\n this.signalError_(result);\n return false;\n }\n }\n return true;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.onFirstByteReceived = function(request, responseText) {\n 'use strict';\n if (this.backChannelRequest_ == request && this.detectBufferingProxy_) {\n if (!this.bpDetectionDone_) {\n this.channelDebug_.info(\n 'Great, no buffering proxy detected. Bytes received: ' +\n responseText.length);\n goog.asserts.assert(\n this.bpDetectionTimerId_, 'Timer should not have been cancelled.');\n this.clearBpDetectionTimer_();\n this.bpDetectionDone_ = true;\n requestStats.notifyStatEvent(requestStats.Stat.NOPROXY);\n }\n }\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.onRequestData = function(request, responseText) {\n 'use strict';\n if (this.state_ == WebChannelBase.State.CLOSED ||\n (this.backChannelRequest_ != request &&\n !this.forwardChannelRequestPool_.hasRequest(request))) {\n // either CLOSED or a request we don't know about (perhaps an old request)\n return;\n }\n\n // first to check if request has been upgraded to backchannel\n if (!request.isInitialResponseDecoded() &&\n this.forwardChannelRequestPool_.hasRequest(request) &&\n this.state_ == WebChannelBase.State.OPENED) {\n let response;\n try {\n response = this.wireCodec_.decodeMessage(responseText);\n } catch (ex) {\n response = null;\n }\n if (Array.isArray(response) && response.length == 3) {\n this.handlePostResponse_(/** @type {!Array<?>} */ (response), request);\n this.onForwardChannelFlushed_();\n } else {\n this.channelDebug_.debug('Bad POST response data returned');\n this.signalError_(WebChannelBase.Error.BAD_RESPONSE);\n }\n } else {\n if (request.isInitialResponseDecoded() ||\n this.backChannelRequest_ == request) {\n this.clearDeadBackchannelTimer_();\n }\n\n if (!goog.string.isEmptyOrWhitespace(responseText)) {\n let response = this.wireCodec_.decodeMessage(responseText);\n this.onInput_(/** @type {!Array<?>} */ (response), request);\n }\n }\n};\n\n\n/**\n * Checks if we need call the flush callback.\n *\n * @private\n */\nWebChannelBase.prototype.onForwardChannelFlushed_ = function() {\n 'use strict';\n if (this.forwardChannelRequestPool_.getRequestCount() <= 1) {\n if (this.forwardChannelFlushedCallback_) {\n try {\n this.forwardChannelFlushedCallback_();\n } catch (ex) {\n this.channelDebug_.dumpException(\n ex, 'Exception from forwardChannelFlushedCallback_ ');\n }\n // reset\n this.forwardChannelFlushedCallback_ = undefined;\n }\n }\n};\n\n\n/**\n * Handles a POST response from the server.\n * @param {Array<number>} responseValues The key value pairs in\n * the POST response.\n * @param {!ChannelRequest} forwardReq The forward channel request that\n * triggers this function call.\n * @private\n */\nWebChannelBase.prototype.handlePostResponse_ = function(\n responseValues, forwardReq) {\n 'use strict';\n // The first response value is set to 0 if server is missing backchannel.\n if (responseValues[0] == 0) {\n this.handleBackchannelMissing_(forwardReq);\n return;\n }\n this.lastPostResponseArrayId_ = responseValues[1];\n const outstandingArrays = this.lastPostResponseArrayId_ - this.lastArrayId_;\n if (0 < outstandingArrays) {\n const numOutstandingBackchannelBytes = responseValues[2];\n this.channelDebug_.debug(\n numOutstandingBackchannelBytes + ' bytes (in ' + outstandingArrays +\n ' arrays) are outstanding on the BackChannel');\n if (!this.shouldRetryBackChannel_(numOutstandingBackchannelBytes)) {\n return;\n }\n if (!this.deadBackChannelTimerId_) {\n // We expect to receive data within 2 RTTs or we retry the backchannel.\n this.deadBackChannelTimerId_ = requestStats.setTimeout(\n goog.bind(this.onBackChannelDead_, this),\n 2 * WebChannelBase.RTT_ESTIMATE);\n }\n }\n};\n\n\n/**\n * Handles a POST response from the server telling us that it has detected that\n * we have no hanging GET connection.\n * @param {!ChannelRequest} forwardReq The forward channel request that\n * triggers this function call.\n * @private\n * @suppress {strictPrimitiveOperators}\n */\nWebChannelBase.prototype.handleBackchannelMissing_ = function(forwardReq) {\n 'use strict';\n // As long as the back channel was started before the POST was sent,\n // we should retry the backchannel. We give a slight buffer of RTT_ESTIMATE\n // so as not to excessively retry the backchannel\n this.channelDebug_.debug('Server claims our backchannel is missing.');\n if (this.backChannelTimerId_) {\n this.channelDebug_.debug('But we are currently starting the request.');\n return;\n } else if (!this.backChannelRequest_) {\n this.channelDebug_.warning('We do not have a BackChannel established');\n } else if (\n this.backChannelRequest_.getRequestStartTime() +\n WebChannelBase.RTT_ESTIMATE <\n forwardReq.getRequestStartTime()) {\n this.clearDeadBackchannelTimer_();\n this.cancelBackChannelRequest_();\n } else {\n return;\n }\n this.maybeRetryBackChannel_();\n requestStats.notifyStatEvent(requestStats.Stat.BACKCHANNEL_MISSING);\n};\n\n\n/**\n * Determines whether we should start the process of retrying a possibly\n * dead backchannel.\n * @param {number} outstandingBytes The number of bytes for which the server has\n * not yet received acknowledgement.\n * @return {boolean} Whether to start the backchannel retry timer.\n * @private\n */\nWebChannelBase.prototype.shouldRetryBackChannel_ = function(outstandingBytes) {\n 'use strict';\n // Not too many outstanding bytes, not buffered and not after a retry.\n return outstandingBytes <\n WebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF &&\n !this.isBuffered() && this.backChannelRetryCount_ == 0;\n};\n\n\n/**\n * Decides which host prefix should be used, if any. If there is a handler,\n * allows the handler to validate a host prefix provided by the server, and\n * optionally override it.\n * @param {?string} serverHostPrefix The host prefix provided by the server.\n * @return {?string} The host prefix to actually use, if any. Will return null\n * if the use of host prefixes was disabled via setAllowHostPrefix().\n * @override\n */\nWebChannelBase.prototype.correctHostPrefix = function(serverHostPrefix) {\n 'use strict';\n if (this.allowHostPrefix_) {\n if (this.handler_) {\n return this.handler_.correctHostPrefix(serverHostPrefix);\n }\n return serverHostPrefix;\n }\n return null;\n};\n\n\n/**\n * Handles the timer that indicates that our backchannel is no longer able to\n * successfully receive data from the server.\n * @private\n */\nWebChannelBase.prototype.onBackChannelDead_ = function() {\n 'use strict';\n if (this.deadBackChannelTimerId_ != null) {\n this.deadBackChannelTimerId_ = null;\n this.cancelBackChannelRequest_();\n this.maybeRetryBackChannel_();\n requestStats.notifyStatEvent(requestStats.Stat.BACKCHANNEL_DEAD);\n }\n};\n\n\n/**\n * Clears the timer that indicates that our backchannel is no longer able to\n * successfully receive data from the server.\n * @private\n */\nWebChannelBase.prototype.clearDeadBackchannelTimer_ = function() {\n 'use strict';\n if (this.deadBackChannelTimerId_ != null) {\n goog.global.clearTimeout(this.deadBackChannelTimerId_);\n this.deadBackChannelTimerId_ = null;\n }\n};\n\n\n/**\n * Returns whether or not the given error/status combination is fatal or not.\n * On fatal errors we immediately close the session rather than retrying the\n * failed request.\n * @param {?ChannelRequest.Error} error The error code for the\n * failed request.\n * @param {number} statusCode The last HTTP status code.\n * @return {boolean} Whether or not the error is fatal.\n * @private\n */\nWebChannelBase.isFatalError_ = function(error, statusCode) {\n 'use strict';\n return error == ChannelRequest.Error.UNKNOWN_SESSION_ID ||\n (error == ChannelRequest.Error.STATUS && statusCode > 0);\n};\n\n\n/**\n * @override\n * @suppress {strictPrimitiveOperators}\n */\nWebChannelBase.prototype.onRequestComplete = function(request) {\n 'use strict';\n this.channelDebug_.debug('Request complete');\n let type;\n let pendingMessages = null;\n if (this.backChannelRequest_ == request) {\n this.clearDeadBackchannelTimer_();\n this.clearBpDetectionTimer_();\n this.backChannelRequest_ = null;\n type = WebChannelBase.ChannelType_.BACK_CHANNEL;\n } else if (this.forwardChannelRequestPool_.hasRequest(request)) {\n pendingMessages = request.getPendingMessages();\n this.forwardChannelRequestPool_.removeRequest(request);\n type = WebChannelBase.ChannelType_.FORWARD_CHANNEL;\n } else {\n // return if it was an old request from a previous session\n return;\n }\n\n if (this.state_ == WebChannelBase.State.CLOSED) {\n return;\n }\n\n if (request.getSuccess()) {\n if (type == WebChannelBase.ChannelType_.FORWARD_CHANNEL) {\n const size = request.getPostData() ? request.getPostData().length : 0;\n requestStats.notifyTimingEvent(\n size, Date.now() - request.getRequestStartTime(),\n this.forwardChannelRetryCount_);\n this.ensureForwardChannel_();\n this.onSuccess_(request);\n } else { // i.e., back-channel\n this.ensureBackChannel_();\n }\n return;\n }\n // Else unsuccessful. Fall through.\n\n const lastStatusCode = request.getLastStatusCode();\n const lastError = request.getLastError();\n if (!WebChannelBase.isFatalError_(lastError, lastStatusCode)) {\n // Maybe retry.\n const self = this;\n this.channelDebug_.debug(function() {\n 'use strict';\n return 'Maybe retrying, last error: ' +\n ChannelRequest.errorStringFromCode(\n lastError, self.errorResponseStatusCode_);\n });\n if (type == WebChannelBase.ChannelType_.FORWARD_CHANNEL) {\n if (this.maybeRetryForwardChannel_(request)) {\n return;\n }\n }\n if (type == WebChannelBase.ChannelType_.BACK_CHANNEL) {\n if (this.maybeRetryBackChannel_()) {\n return;\n }\n }\n // Else exceeded max retries. Fall through.\n this.channelDebug_.debug('Exceeded max number of retries');\n } else {\n // Else fatal error. Fall through and mark the pending maps as failed.\n this.channelDebug_.debug('Not retrying due to error type');\n\n if (lastStatusCode > 200) {\n this.errorResponseStatusCode_ = request.getLastStatusCode();\n this.errorResponseHeaders_ = request.getErrorResponseHeaders();\n }\n }\n\n // Abort the channel now\n\n // Record pending messages from the failed request\n if (pendingMessages && pendingMessages.length > 0) {\n this.forwardChannelRequestPool_.addPendingMessages(pendingMessages);\n }\n\n this.channelDebug_.debug('Error: HTTP request failed');\n switch (lastError) {\n case ChannelRequest.Error.NO_DATA:\n this.signalError_(WebChannelBase.Error.NO_DATA);\n break;\n case ChannelRequest.Error.BAD_DATA:\n this.signalError_(WebChannelBase.Error.BAD_DATA);\n break;\n case ChannelRequest.Error.UNKNOWN_SESSION_ID:\n this.signalError_(WebChannelBase.Error.UNKNOWN_SESSION_ID);\n break;\n default:\n this.signalError_(WebChannelBase.Error.REQUEST_FAILED);\n break;\n }\n};\n\n\n/**\n * @param {number} retryCount Number of retries so far.\n * @return {number} Time in ms before firing next retry request.\n * @private\n */\nWebChannelBase.prototype.getRetryTime_ = function(retryCount) {\n 'use strict';\n let retryTime = this.baseRetryDelayMs_ +\n Math.floor(Math.random() * this.retryDelaySeedMs_);\n if (!this.isActive()) {\n this.channelDebug_.debug('Inactive channel');\n retryTime = retryTime * WebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR;\n }\n // Backoff for subsequent retries\n retryTime *= retryCount;\n return retryTime;\n};\n\n\n/**\n * @param {number} baseDelayMs The base part of the retry delay, in ms.\n * @param {number} delaySeedMs A random delay between 0 and this is added to\n * the base part.\n */\nWebChannelBase.prototype.setRetryDelay = function(baseDelayMs, delaySeedMs) {\n 'use strict';\n this.baseRetryDelayMs_ = baseDelayMs;\n this.retryDelaySeedMs_ = delaySeedMs;\n};\n\n\n/**\n * Apply any handshake control headers.\n * @param {!ChannelRequest} request The underlying request object\n * @private\n */\nWebChannelBase.prototype.applyControlHeaders_ = function(request) {\n 'use strict';\n const xhr = request.getXhr();\n if (xhr) {\n const clientProtocol =\n xhr.getStreamingResponseHeader(WebChannel.X_CLIENT_WIRE_PROTOCOL);\n if (clientProtocol) {\n this.forwardChannelRequestPool_.applyClientProtocol(clientProtocol);\n }\n\n if (this.getHttpSessionIdParam()) {\n const httpSessionIdHeader =\n xhr.getStreamingResponseHeader(WebChannel.X_HTTP_SESSION_ID);\n if (httpSessionIdHeader) {\n this.setHttpSessionId(httpSessionIdHeader);\n // update the cached uri\n const httpSessionIdParam = this.getHttpSessionIdParam();\n\n this.forwardChannelUri_.setParameterValue(\n /** @type {string} */ (httpSessionIdParam), // never null\n httpSessionIdHeader);\n } else {\n this.channelDebug_.warning(\n 'Missing X_HTTP_SESSION_ID in the handshake response');\n }\n }\n }\n};\n\n\n/**\n * Processes the data returned by the server.\n * @param {!Array<!Array<?>>} respArray The response array returned\n * by the server.\n * @param {!ChannelRequest} request The underlying request object\n * @private\n * @suppress {strictPrimitiveOperators}\n */\nWebChannelBase.prototype.onInput_ = function(respArray, request) {\n 'use strict';\n const batch =\n this.handler_ && this.handler_.channelHandleMultipleArrays ? [] : null;\n for (let i = 0; i < respArray.length; i++) {\n let nextArray = respArray[i];\n this.lastArrayId_ = nextArray[0];\n nextArray = nextArray[1];\n if (this.state_ == WebChannelBase.State.OPENING) {\n if (nextArray[0] == 'c') {\n this.sid_ = nextArray[1];\n this.hostPrefix_ = this.correctHostPrefix(nextArray[2]);\n\n const negotiatedVersion = nextArray[3];\n if (negotiatedVersion != null) {\n this.channelVersion_ = negotiatedVersion;\n this.channelDebug_.info('VER=' + this.channelVersion_);\n }\n\n const negotiatedServerVersion = nextArray[4];\n if (negotiatedServerVersion != null) {\n this.serverVersion_ = negotiatedServerVersion;\n this.channelDebug_.info('SVER=' + this.serverVersion_);\n }\n\n // CVER=22\n const serverKeepaliveMs = nextArray[5];\n if (serverKeepaliveMs != null &&\n typeof serverKeepaliveMs === 'number' && serverKeepaliveMs > 0) {\n const timeout = 1.5 * serverKeepaliveMs;\n this.backChannelRequestTimeoutMs_ = timeout;\n this.channelDebug_.info('backChannelRequestTimeoutMs_=' + timeout);\n }\n\n this.applyControlHeaders_(request);\n\n this.state_ = WebChannelBase.State.OPENED;\n if (this.handler_) {\n this.handler_.channelOpened(this);\n }\n\n if (this.detectBufferingProxy_) {\n this.handshakeRttMs_ = Date.now() - request.getRequestStartTime();\n this.channelDebug_.info(\n 'Handshake RTT: ' + this.handshakeRttMs_ + 'ms');\n }\n\n this.startBackchannelAfterHandshake_(request);\n\n if (this.outgoingMaps_.length > 0) {\n this.ensureForwardChannel_();\n }\n } else if (nextArray[0] == 'stop' || nextArray[0] == 'close') {\n // treat close also as an abort\n this.signalError_(WebChannelBase.Error.STOP);\n }\n } else if (this.state_ == WebChannelBase.State.OPENED) {\n if (nextArray[0] == 'stop' || nextArray[0] == 'close') {\n if (batch && !(batch.length === 0)) {\n this.handler_.channelHandleMultipleArrays(this, batch);\n batch.length = 0;\n }\n if (nextArray[0] == 'stop') {\n this.signalError_(WebChannelBase.Error.STOP);\n } else {\n this.disconnect();\n }\n } else if (nextArray[0] == 'noop') {\n // ignore - noop to keep connection happy\n } else {\n if (batch) {\n batch.push(nextArray);\n } else if (this.handler_) {\n this.handler_.channelHandleArray(this, nextArray);\n }\n }\n // We have received useful data on the back-channel, so clear its retry\n // count. We do this because back-channels by design do not complete\n // quickly, so on a flaky connection we could have many fail to complete\n // fully but still deliver a lot of data before they fail. We don't want\n // to count such failures towards the retry limit, because we don't want\n // to give up on a session if we can still receive data.\n this.backChannelRetryCount_ = 0;\n }\n }\n if (batch && !(batch.length === 0)) {\n this.handler_.channelHandleMultipleArrays(this, batch);\n }\n};\n\n\n/**\n * Starts the backchannel after the handshake.\n *\n * @param {!ChannelRequest} request The underlying request object\n * @private\n */\nWebChannelBase.prototype.startBackchannelAfterHandshake_ = function(request) {\n 'use strict';\n this.backChannelUri_ = this.getBackChannelUri(\n this.hostPrefix_, /** @type {string} */ (this.path_));\n\n if (request.isInitialResponseDecoded()) {\n this.channelDebug_.debug('Upgrade the handshake request to a backchannel.');\n this.forwardChannelRequestPool_.removeRequest(request);\n request.resetTimeout(this.backChannelRequestTimeoutMs_);\n this.backChannelRequest_ = request;\n } else {\n this.ensureBackChannel_();\n }\n};\n\n\n/**\n * Helper to ensure the channel is in the expected state.\n * @param {...number} var_args The channel must be in one of the indicated\n * states.\n * @private\n */\nWebChannelBase.prototype.ensureInState_ = function(var_args) {\n 'use strict';\n goog.asserts.assert(\n goog.array.contains(arguments, this.state_),\n 'Unexpected channel state: %s', this.state_);\n};\n\n\n/**\n * Signals an error has occurred.\n * @param {WebChannelBase.Error} error The error code for the failure.\n * @private\n */\nWebChannelBase.prototype.signalError_ = function(error) {\n 'use strict';\n this.channelDebug_.info('Error code ' + error);\n if (error == WebChannelBase.Error.REQUEST_FAILED) {\n // Create a separate Internet connection to check\n // if it's a server error or user's network error.\n let imageUri = null;\n if (this.handler_) {\n imageUri = this.handler_.getNetworkTestImageUri(this);\n }\n netUtils.testNetwork(goog.bind(this.testNetworkCallback_, this), imageUri);\n } else {\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_OTHER);\n }\n this.onError_(error);\n};\n\n\n/**\n * Callback for netUtils.testNetwork during error handling.\n * @param {boolean} networkUp Whether the network is up.\n * @private\n */\nWebChannelBase.prototype.testNetworkCallback_ = function(networkUp) {\n 'use strict';\n if (networkUp) {\n this.channelDebug_.info('Successfully pinged google.com');\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_OTHER);\n } else {\n this.channelDebug_.info('Failed to ping google.com');\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_NETWORK);\n // Do not call onError_ again to eliminate duplicated Error events.\n }\n};\n\n\n/**\n * Called when messages have been successfully sent from the queue.\n * @param {!ChannelRequest} request The request object\n * @private\n */\nWebChannelBase.prototype.onSuccess_ = function(request) {\n 'use strict';\n if (this.handler_) {\n this.handler_.channelSuccess(this, request);\n }\n};\n\n\n/**\n * Called when we've determined the final error for a channel. It closes the\n * notifiers the handler of the error and closes the channel.\n * @param {WebChannelBase.Error} error The error code for the failure.\n * @private\n */\nWebChannelBase.prototype.onError_ = function(error) {\n 'use strict';\n this.channelDebug_.debug('HttpChannel: error - ' + error);\n this.state_ = WebChannelBase.State.CLOSED;\n if (this.handler_) {\n this.handler_.channelError(this, error);\n }\n this.onClose_();\n this.cancelRequests_();\n};\n\n\n/**\n * Called when the channel has been closed. It notifiers the handler of the\n * event, and reports any pending or undelivered maps.\n * @private\n */\nWebChannelBase.prototype.onClose_ = function() {\n 'use strict';\n this.state_ = WebChannelBase.State.CLOSED;\n this.nonAckedMapsAtChannelClose_ = [];\n if (this.handler_) {\n const pendingMessages =\n this.forwardChannelRequestPool_.getPendingMessages();\n\n if (pendingMessages.length == 0 && this.outgoingMaps_.length == 0) {\n this.handler_.channelClosed(this);\n } else {\n this.channelDebug_.debug(\n () => 'Number of undelivered maps' +\n ', pending: ' + pendingMessages.length +\n ', outgoing: ' + this.outgoingMaps_.length);\n\n goog.array.extend(this.nonAckedMapsAtChannelClose_, pendingMessages);\n goog.array.extend(this.nonAckedMapsAtChannelClose_, this.outgoingMaps_);\n\n this.forwardChannelRequestPool_.clearPendingMessages();\n\n const copyOfUndeliveredMaps = goog.array.clone(this.outgoingMaps_);\n this.outgoingMaps_.length = 0;\n\n this.handler_.channelClosed(this, pendingMessages, copyOfUndeliveredMaps);\n }\n }\n};\n\n/**\n * @return {!Array<!Wire.QueuedMap>} Returns the list of non-acked maps, both\n * during an active channel or after the channel is closed. Refer to the\n * `getNonAckedMessages()` API for definitions of non-acked messages.\n */\nWebChannelBase.prototype.getNonAckedMaps = function() {\n if (this.state_ == WebChannelBase.State.CLOSED) {\n goog.asserts.assert(\n this.nonAckedMapsAtChannelClose_ != null,\n 'nonAckedMapsAtChannelClose_ is not set after channel close.');\n return this.nonAckedMapsAtChannelClose_;\n }\n\n // The underlying message objects are not cloned and thus exposes a mutability\n // risk, but is chosen to make strict equality (i.e. ===) checks possible for\n // callers.\n let unAckedMaps = [];\n goog.array.extend(\n unAckedMaps, this.forwardChannelRequestPool_.getPendingMessages());\n goog.array.extend(unAckedMaps, this.outgoingMaps_);\n\n return unAckedMaps;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getForwardChannelUri = function(path) {\n 'use strict';\n const uri = this.createDataUri(null, path);\n this.channelDebug_.debug('GetForwardChannelUri: ' + uri);\n return uri;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getConnectionState = function() {\n 'use strict';\n return this.connState_;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getBackChannelUri = function(hostPrefix, path) {\n 'use strict';\n const uri = this.createDataUri(\n this.shouldUseSecondaryDomains() ? hostPrefix : null, path);\n this.channelDebug_.debug('GetBackChannelUri: ' + uri);\n return uri;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.createDataUri = function(\n hostPrefix, path, opt_overridePort) {\n 'use strict';\n let uri = goog.Uri.parse(path);\n const uriAbsolute = (uri.getDomain() != '');\n if (uriAbsolute) {\n if (hostPrefix) {\n uri.setDomain(hostPrefix + '.' + uri.getDomain());\n }\n\n uri.setPort(opt_overridePort || uri.getPort());\n } else {\n const locationPage = goog.global.location;\n let hostName;\n if (hostPrefix) {\n hostName = hostPrefix + '.' + locationPage.hostname;\n } else {\n hostName = locationPage.hostname;\n }\n\n const port = opt_overridePort || +locationPage.port;\n\n uri = goog.Uri.create(locationPage.protocol, null, hostName, port, path);\n }\n\n const param = this.getHttpSessionIdParam();\n const value = this.getHttpSessionId();\n if (param && value) {\n uri.setParameterValue(param, value);\n }\n\n // Add the protocol version to the URI.\n uri.setParameterValue('VER', this.channelVersion_);\n\n this.addAdditionalParams_(uri);\n\n return uri;\n};\n\n/**\n * @override\n * @param {?string} hostPrefix The host prefix, if we need an XhrIo object\n * capable of calling a secondary domain.\n * @param {boolean=} isStreaming Whether or not fetch/streams are enabled for\n * the underlying HTTP request.\n * @return {!goog.net.XhrIo} A new XhrIo object.\n */\nWebChannelBase.prototype.createXhrIo = function(hostPrefix, isStreaming) {\n 'use strict';\n if (hostPrefix && !this.supportsCrossDomainXhrs_) {\n throw new Error('Can\\'t create secondary domain capable XhrIo object.');\n }\n let xhr;\n if (isStreaming && this.usesFetchStreams_ && !this.xmlHttpFactory_) {\n xhr = new goog.net.XhrIo(\n new goog.net.FetchXmlHttpFactory({streamBinaryChunks: true}));\n } else {\n xhr = new goog.net.XhrIo(this.xmlHttpFactory_);\n }\n xhr.setWithCredentials(this.supportsCrossDomainXhrs_);\n return xhr;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.isActive = function() {\n 'use strict';\n return !!this.handler_ && this.handler_.isActive(this);\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.shouldUseSecondaryDomains = function() {\n 'use strict';\n return this.supportsCrossDomainXhrs_;\n};\n\n\n/**\n * Sets (overwrites) the forward channel flush callback.\n *\n * @param {function()} callback The callback to be invoked.\n */\nWebChannelBase.prototype.setForwardChannelFlushCallback = function(callback) {\n 'use strict';\n this.forwardChannelFlushedCallback_ = callback;\n};\n\n\n/**\n * Abstract base class for the channel handler\n * @constructor\n * @struct\n */\nWebChannelBase.Handler = function() {};\n\n\n/**\n * Callback handler for when a batch of response arrays is received from the\n * server. When null, batched dispatching is disabled.\n * @type {?function(!WebChannelBase, !Array<!Array<?>>)}\n */\nWebChannelBase.Handler.prototype.channelHandleMultipleArrays = null;\n\n\n/**\n * Whether it's okay to make a request to the server. A handler can return\n * false if the channel should fail. For example, if the user has logged out,\n * the handler may want all requests to fail immediately.\n * @param {WebChannelBase} channel The channel.\n * @return {WebChannelBase.Error} An error code. The code should\n * return WebChannelBase.Error.OK to indicate it's okay. Any other\n * error code will cause a failure.\n */\nWebChannelBase.Handler.prototype.okToMakeRequest = function(channel) {\n 'use strict';\n return WebChannelBase.Error.OK;\n};\n\n\n/**\n * Indicates the WebChannel has successfully negotiated with the server\n * and can now send and receive data.\n * @param {WebChannelBase} channel The channel.\n */\nWebChannelBase.Handler.prototype.channelOpened = function(channel) {};\n\n\n/**\n * New input is available for the application to process.\n *\n * @param {WebChannelBase} channel The channel.\n * @param {!Array<?>|!Object} array The data array.\n */\nWebChannelBase.Handler.prototype.channelHandleArray = function(\n channel, array) {};\n\n\n/**\n * Indicates messages that have been successfully sent on the channel.\n *\n * @param {WebChannelBase} channel The channel.\n * @param {!ChannelRequest} request The request object that contains\n * the pending messages that have been successfully delivered to the server.\n */\nWebChannelBase.Handler.prototype.channelSuccess = function(channel, request) {};\n\n\n/**\n * Indicates an error occurred on the WebChannel.\n *\n * @param {WebChannelBase} channel The channel.\n * @param {WebChannelBase.Error} error The error code.\n */\nWebChannelBase.Handler.prototype.channelError = function(channel, error) {};\n\n\n/**\n * Indicates the WebChannel is closed. Also notifies about which maps,\n * if any, that may not have been delivered to the server.\n * @param {WebChannelBase} channel The channel.\n * @param {Array<Wire.QueuedMap>=} opt_pendingMaps The\n * array of pending maps, which may or may not have been delivered to the\n * server.\n * @param {Array<Wire.QueuedMap>=} opt_undeliveredMaps\n * The array of undelivered maps, which have definitely not been delivered\n * to the server.\n */\nWebChannelBase.Handler.prototype.channelClosed = function(\n channel, opt_pendingMaps, opt_undeliveredMaps) {};\n\n\n/**\n * Gets any parameters that should be added at the time another connection is\n * made to the server.\n * @param {WebChannelBase} channel The channel.\n * @return {!Object} Extra parameter keys and values to add to the requests.\n */\nWebChannelBase.Handler.prototype.getAdditionalParams = function(channel) {\n 'use strict';\n return {};\n};\n\n\n/**\n * Gets the URI of an image that can be used to test network connectivity.\n * @param {WebChannelBase} channel The channel.\n * @return {goog.Uri?} A custom URI to load for the network test.\n */\nWebChannelBase.Handler.prototype.getNetworkTestImageUri = function(channel) {\n 'use strict';\n return null;\n};\n\n\n/**\n * Gets whether this channel is currently active. This is used to determine the\n * length of time to wait before retrying.\n * @param {WebChannelBase} channel The channel.\n * @return {boolean} Whether the channel is currently active.\n */\nWebChannelBase.Handler.prototype.isActive = function(channel) {\n 'use strict';\n return true;\n};\n\n/**\n * Whether or not this channel uses WHATWG Fetch/streams.\n * @override\n * @return {boolean}\n */\nWebChannelBase.prototype.usesFetchStreams = function() {\n 'use strict';\n return this.usesFetchStreams_;\n};\n\n\n/**\n * Called by the channel if enumeration of the map throws an exception.\n * @param {WebChannelBase} channel The channel.\n * @param {Object} map The map that can't be enumerated.\n */\nWebChannelBase.Handler.prototype.badMapError = function(channel, map) {};\n\n\n/**\n * Allows the handler to override a host prefix provided by the server. Will\n * be called whenever the channel has received such a prefix and is considering\n * its use.\n * @param {?string} serverHostPrefix The host prefix provided by the server.\n * @return {?string} The host prefix the client should use.\n */\nWebChannelBase.Handler.prototype.correctHostPrefix = function(\n serverHostPrefix) {\n 'use strict';\n return serverHostPrefix;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Class for parsing and formatting URIs.\n *\n * This package is deprecated in favour of the Closure URL package (goog.url)\n * when manipulating URIs for use by a browser. This package uses regular\n * expressions to parse a potential URI which can fall out of sync with how a\n * browser will actually interpret the URI. See\n * `goog.uri.utils.setUrlPackageSupportLoggingHandler` for one way to identify\n * URIs that should instead be parsed using the URL package.\n *\n * Use goog.Uri(string) to parse a URI string. Use goog.Uri.create(...) to\n * create a new instance of the goog.Uri object from Uri parts.\n *\n * e.g: <code>var myUri = new goog.Uri(window.location);</code>\n *\n * Implements RFC 3986 for parsing/formatting URIs.\n * http://www.ietf.org/rfc/rfc3986.txt\n *\n * Some changes have been made to the interface (more like .NETs), though the\n * internal representation is now of un-encoded parts, this will change the\n * behavior slightly.\n */\n\ngoog.provide('goog.Uri');\ngoog.provide('goog.Uri.QueryData');\n\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.string');\ngoog.require('goog.structs');\ngoog.require('goog.uri.utils');\ngoog.require('goog.uri.utils.ComponentIndex');\ngoog.require('goog.uri.utils.StandardQueryParam');\n\n\n\n/**\n * This class contains setters and getters for the parts of the URI.\n * The <code>getXyz</code>/<code>setXyz</code> methods return the decoded part\n * -- so<code>goog.Uri.parse('/foo%20bar').getPath()</code> will return the\n * decoded path, <code>/foo bar</code>.\n *\n * Reserved characters (see RFC 3986 section 2.2) can be present in\n * their percent-encoded form in scheme, domain, and path URI components and\n * will not be auto-decoded. For example:\n * <code>goog.Uri.parse('rel%61tive/path%2fto/resource').getPath()</code> will\n * return <code>relative/path%2fto/resource</code>.\n *\n * The constructor accepts an optional unparsed, raw URI string. The parser\n * is relaxed, so special characters that aren't escaped but don't cause\n * ambiguities will not cause parse failures.\n *\n * All setters return <code>this</code> and so may be chained, a la\n * <code>goog.Uri.parse('/foo').setFragment('part').toString()</code>.\n *\n * @param {*=} opt_uri Optional string URI to parse\n * (use goog.Uri.create() to create a URI from parts), or if\n * a goog.Uri is passed, a clone is created.\n * @param {boolean=} opt_ignoreCase If true, #getParameterValue will ignore\n * the case of the parameter name.\n *\n * @throws URIError If opt_uri is provided and URI is malformed (that is,\n * if decodeURIComponent fails on any of the URI components).\n * @constructor\n * @struct\n */\ngoog.Uri = function(opt_uri, opt_ignoreCase) {\n 'use strict';\n /**\n * Scheme such as \"http\".\n * @private {string}\n */\n this.scheme_ = '';\n\n /**\n * User credentials in the form \"username:password\".\n * @private {string}\n */\n this.userInfo_ = '';\n\n /**\n * Domain part, e.g. \"www.google.com\".\n * @private {string}\n */\n this.domain_ = '';\n\n /**\n * Port, e.g. 8080.\n * @private {?number}\n */\n this.port_ = null;\n\n /**\n * Path, e.g. \"/tests/img.png\".\n * @private {string}\n */\n this.path_ = '';\n\n /**\n * The fragment without the #.\n * @private {string}\n */\n this.fragment_ = '';\n\n /**\n * Whether or not this Uri should be treated as Read Only.\n * @private {boolean}\n */\n this.isReadOnly_ = false;\n\n /**\n * Whether or not to ignore case when comparing query params.\n * @private {boolean}\n */\n this.ignoreCase_ = false;\n\n /**\n * Object representing query data.\n * @private {!goog.Uri.QueryData}\n */\n this.queryData_;\n\n // Parse in the uri string\n var m;\n if (opt_uri instanceof goog.Uri) {\n this.ignoreCase_ = (opt_ignoreCase !== undefined) ? opt_ignoreCase :\n opt_uri.getIgnoreCase();\n this.setScheme(opt_uri.getScheme());\n this.setUserInfo(opt_uri.getUserInfo());\n this.setDomain(opt_uri.getDomain());\n this.setPort(opt_uri.getPort());\n this.setPath(opt_uri.getPath());\n this.setQueryData(opt_uri.getQueryData().clone());\n this.setFragment(opt_uri.getFragment());\n } else if (opt_uri && (m = goog.uri.utils.split(String(opt_uri)))) {\n this.ignoreCase_ = !!opt_ignoreCase;\n\n // Set the parts -- decoding as we do so.\n // COMPATIBILITY NOTE - In IE, unmatched fields may be empty strings,\n // whereas in other browsers they will be undefined.\n this.setScheme(m[goog.uri.utils.ComponentIndex.SCHEME] || '', true);\n this.setUserInfo(m[goog.uri.utils.ComponentIndex.USER_INFO] || '', true);\n this.setDomain(m[goog.uri.utils.ComponentIndex.DOMAIN] || '', true);\n this.setPort(m[goog.uri.utils.ComponentIndex.PORT]);\n this.setPath(m[goog.uri.utils.ComponentIndex.PATH] || '', true);\n this.setQueryData(m[goog.uri.utils.ComponentIndex.QUERY_DATA] || '', true);\n this.setFragment(m[goog.uri.utils.ComponentIndex.FRAGMENT] || '', true);\n\n } else {\n this.ignoreCase_ = !!opt_ignoreCase;\n this.queryData_ = new goog.Uri.QueryData(null, this.ignoreCase_);\n }\n};\n\n\n/**\n * Parameter name added to stop caching.\n * @type {string}\n */\ngoog.Uri.RANDOM_PARAM = goog.uri.utils.StandardQueryParam.RANDOM;\n\n\n/**\n * @return {string} The string form of the url.\n * @override\n */\ngoog.Uri.prototype.toString = function() {\n 'use strict';\n var out = [];\n\n var scheme = this.getScheme();\n if (scheme) {\n out.push(\n goog.Uri.encodeSpecialChars_(\n scheme, goog.Uri.reDisallowedInSchemeOrUserInfo_, true),\n ':');\n }\n\n var domain = this.getDomain();\n if (domain || scheme == 'file') {\n out.push('//');\n\n var userInfo = this.getUserInfo();\n if (userInfo) {\n out.push(\n goog.Uri.encodeSpecialChars_(\n userInfo, goog.Uri.reDisallowedInSchemeOrUserInfo_, true),\n '@');\n }\n\n out.push(goog.Uri.removeDoubleEncoding_(goog.string.urlEncode(domain)));\n\n var port = this.getPort();\n if (port != null) {\n out.push(':', String(port));\n }\n }\n\n var path = this.getPath();\n if (path) {\n if (this.hasDomain() && path.charAt(0) != '/') {\n out.push('/');\n }\n out.push(goog.Uri.encodeSpecialChars_(\n path,\n path.charAt(0) == '/' ? goog.Uri.reDisallowedInAbsolutePath_ :\n goog.Uri.reDisallowedInRelativePath_,\n true));\n }\n\n var query = this.getEncodedQuery();\n if (query) {\n out.push('?', query);\n }\n\n var fragment = this.getFragment();\n if (fragment) {\n out.push(\n '#',\n goog.Uri.encodeSpecialChars_(\n fragment, goog.Uri.reDisallowedInFragment_));\n }\n return out.join('');\n};\n\n\n/**\n * Resolves the given relative URI (a goog.Uri object), using the URI\n * represented by this instance as the base URI.\n *\n * There are several kinds of relative URIs:<br>\n * 1. foo - replaces the last part of the path, the whole query and fragment<br>\n * 2. /foo - replaces the path, the query and fragment<br>\n * 3. //foo - replaces everything from the domain on. foo is a domain name<br>\n * 4. ?foo - replace the query and fragment<br>\n * 5. #foo - replace the fragment only\n *\n * Additionally, if relative URI has a non-empty path, all \"..\" and \".\"\n * segments will be resolved, as described in RFC 3986.\n *\n * @param {!goog.Uri} relativeUri The relative URI to resolve.\n * @return {!goog.Uri} The resolved URI.\n */\ngoog.Uri.prototype.resolve = function(relativeUri) {\n 'use strict';\n var absoluteUri = this.clone();\n\n // we satisfy these conditions by looking for the first part of relativeUri\n // that is not blank and applying defaults to the rest\n\n var overridden = relativeUri.hasScheme();\n\n if (overridden) {\n absoluteUri.setScheme(relativeUri.getScheme());\n } else {\n overridden = relativeUri.hasUserInfo();\n }\n\n if (overridden) {\n absoluteUri.setUserInfo(relativeUri.getUserInfo());\n } else {\n overridden = relativeUri.hasDomain();\n }\n\n if (overridden) {\n absoluteUri.setDomain(relativeUri.getDomain());\n } else {\n overridden = relativeUri.hasPort();\n }\n\n var path = relativeUri.getPath();\n if (overridden) {\n absoluteUri.setPort(relativeUri.getPort());\n } else {\n overridden = relativeUri.hasPath();\n if (overridden) {\n // resolve path properly\n if (path.charAt(0) != '/') {\n // path is relative\n if (this.hasDomain() && !this.hasPath()) {\n // RFC 3986, section 5.2.3, case 1\n path = '/' + path;\n } else {\n // RFC 3986, section 5.2.3, case 2\n var lastSlashIndex = absoluteUri.getPath().lastIndexOf('/');\n if (lastSlashIndex != -1) {\n path = absoluteUri.getPath().slice(0, lastSlashIndex + 1) + path;\n }\n }\n }\n path = goog.Uri.removeDotSegments(path);\n }\n }\n\n if (overridden) {\n absoluteUri.setPath(path);\n } else {\n overridden = relativeUri.hasQuery();\n }\n\n if (overridden) {\n absoluteUri.setQueryData(relativeUri.getQueryData().clone());\n } else {\n overridden = relativeUri.hasFragment();\n }\n\n if (overridden) {\n absoluteUri.setFragment(relativeUri.getFragment());\n }\n\n return absoluteUri;\n};\n\n\n/**\n * Clones the URI instance.\n * @return {!goog.Uri} New instance of the URI object.\n */\ngoog.Uri.prototype.clone = function() {\n 'use strict';\n return new goog.Uri(this);\n};\n\n\n/**\n * @return {string} The encoded scheme/protocol for the URI.\n */\ngoog.Uri.prototype.getScheme = function() {\n 'use strict';\n return this.scheme_;\n};\n\n\n/**\n * Sets the scheme/protocol.\n * @throws URIError If opt_decode is true and newScheme is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newScheme New scheme value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setScheme = function(newScheme, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.scheme_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newScheme, true) : newScheme;\n\n // remove an : at the end of the scheme so somebody can pass in\n // window.location.protocol\n if (this.scheme_) {\n this.scheme_ = this.scheme_.replace(/:$/, '');\n }\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the scheme has been set.\n */\ngoog.Uri.prototype.hasScheme = function() {\n 'use strict';\n return !!this.scheme_;\n};\n\n\n/**\n * @return {string} The decoded user info.\n */\ngoog.Uri.prototype.getUserInfo = function() {\n 'use strict';\n return this.userInfo_;\n};\n\n\n/**\n * Sets the userInfo.\n * @throws URIError If opt_decode is true and newUserInfo is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newUserInfo New userInfo value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setUserInfo = function(newUserInfo, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.userInfo_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newUserInfo) : newUserInfo;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the user info has been set.\n */\ngoog.Uri.prototype.hasUserInfo = function() {\n 'use strict';\n return !!this.userInfo_;\n};\n\n\n/**\n * @return {string} The decoded domain.\n */\ngoog.Uri.prototype.getDomain = function() {\n 'use strict';\n return this.domain_;\n};\n\n\n/**\n * Sets the domain.\n * @throws URIError If opt_decode is true and newDomain is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newDomain New domain value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setDomain = function(newDomain, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.domain_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newDomain, true) : newDomain;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the domain has been set.\n */\ngoog.Uri.prototype.hasDomain = function() {\n 'use strict';\n return !!this.domain_;\n};\n\n\n/**\n * @return {?number} The port number.\n */\ngoog.Uri.prototype.getPort = function() {\n 'use strict';\n return this.port_;\n};\n\n\n/**\n * Sets the port number.\n * @param {*} newPort Port number. Will be explicitly casted to a number.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setPort = function(newPort) {\n 'use strict';\n this.enforceReadOnly();\n\n if (newPort) {\n newPort = Number(newPort);\n if (isNaN(newPort) || newPort < 0) {\n throw new Error('Bad port number ' + newPort);\n }\n this.port_ = newPort;\n } else {\n this.port_ = null;\n }\n\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the port has been set.\n */\ngoog.Uri.prototype.hasPort = function() {\n 'use strict';\n return this.port_ != null;\n};\n\n\n/**\n * @return {string} The decoded path.\n */\ngoog.Uri.prototype.getPath = function() {\n 'use strict';\n return this.path_;\n};\n\n\n/**\n * Sets the path.\n * @throws URIError If opt_decode is true and newPath is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newPath New path value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setPath = function(newPath, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.path_ = opt_decode ? goog.Uri.decodeOrEmpty_(newPath, true) : newPath;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the path has been set.\n */\ngoog.Uri.prototype.hasPath = function() {\n 'use strict';\n return !!this.path_;\n};\n\n\n/**\n * @return {boolean} Whether the query string has been set.\n */\ngoog.Uri.prototype.hasQuery = function() {\n 'use strict';\n return this.queryData_.toString() !== '';\n};\n\n\n/**\n * Sets the query data.\n * @param {goog.Uri.QueryData|string|undefined} queryData QueryData object.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * Applies only if queryData is a string.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setQueryData = function(queryData, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n\n if (queryData instanceof goog.Uri.QueryData) {\n this.queryData_ = queryData;\n this.queryData_.setIgnoreCase(this.ignoreCase_);\n } else {\n if (!opt_decode) {\n // QueryData accepts encoded query string, so encode it if\n // opt_decode flag is not true.\n queryData = goog.Uri.encodeSpecialChars_(\n queryData, goog.Uri.reDisallowedInQuery_);\n }\n this.queryData_ = new goog.Uri.QueryData(queryData, this.ignoreCase_);\n }\n\n return this;\n};\n\n\n/**\n * Sets the URI query.\n * @param {string} newQuery New query value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setQuery = function(newQuery, opt_decode) {\n 'use strict';\n return this.setQueryData(newQuery, opt_decode);\n};\n\n\n/**\n * @return {string} The encoded URI query, not including the ?.\n */\ngoog.Uri.prototype.getEncodedQuery = function() {\n 'use strict';\n return this.queryData_.toString();\n};\n\n\n/**\n * @return {string} The decoded URI query, not including the ?.\n */\ngoog.Uri.prototype.getDecodedQuery = function() {\n 'use strict';\n return this.queryData_.toDecodedString();\n};\n\n\n/**\n * Returns the query data.\n * @return {!goog.Uri.QueryData} QueryData object.\n */\ngoog.Uri.prototype.getQueryData = function() {\n 'use strict';\n return this.queryData_;\n};\n\n\n/**\n * @return {string} The encoded URI query, not including the ?.\n *\n * Warning: This method, unlike other getter methods, returns encoded\n * value, instead of decoded one.\n */\ngoog.Uri.prototype.getQuery = function() {\n 'use strict';\n return this.getEncodedQuery();\n};\n\n\n/**\n * Sets the value of the named query parameters, clearing previous values for\n * that key.\n *\n * @param {string} key The parameter to set.\n * @param {*} value The new value. Value does not need to be encoded.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setParameterValue = function(key, value) {\n 'use strict';\n this.enforceReadOnly();\n this.queryData_.set(key, value);\n return this;\n};\n\n\n/**\n * Sets the values of the named query parameters, clearing previous values for\n * that key. Not new values will currently be moved to the end of the query\n * string.\n *\n * So, <code>goog.Uri.parse('foo?a=b&c=d&e=f').setParameterValues('c', ['new'])\n * </code> yields <tt>foo?a=b&e=f&c=new</tt>.</p>\n *\n * @param {string} key The parameter to set.\n * @param {*} values The new values. If values is a single\n * string then it will be treated as the sole value. Values do not need to\n * be encoded.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setParameterValues = function(key, values) {\n 'use strict';\n this.enforceReadOnly();\n\n if (!Array.isArray(values)) {\n values = [String(values)];\n }\n\n this.queryData_.setValues(key, values);\n\n return this;\n};\n\n\n/**\n * Returns the value<b>s</b> for a given cgi parameter as a list of decoded\n * query parameter values.\n * @param {string} name The parameter to get values for.\n * @return {!Array<?>} The values for a given cgi parameter as a list of\n * decoded query parameter values.\n */\ngoog.Uri.prototype.getParameterValues = function(name) {\n 'use strict';\n return this.queryData_.getValues(name);\n};\n\n\n/**\n * Returns the first value for a given cgi parameter or undefined if the given\n * parameter name does not appear in the query string.\n * @param {string} paramName Unescaped parameter name.\n * @return {string|undefined} The first value for a given cgi parameter or\n * undefined if the given parameter name does not appear in the query\n * string.\n */\ngoog.Uri.prototype.getParameterValue = function(paramName) {\n 'use strict';\n return /** @type {string|undefined} */ (this.queryData_.get(paramName));\n};\n\n\n/**\n * @return {string} The URI fragment, not including the #.\n */\ngoog.Uri.prototype.getFragment = function() {\n 'use strict';\n return this.fragment_;\n};\n\n\n/**\n * Sets the URI fragment.\n * @throws URIError If opt_decode is true and newFragment is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newFragment New fragment value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setFragment = function(newFragment, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.fragment_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newFragment) : newFragment;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the URI has a fragment set.\n */\ngoog.Uri.prototype.hasFragment = function() {\n 'use strict';\n return !!this.fragment_;\n};\n\n\n/**\n * Returns true if this has the same domain as that of uri2.\n * @param {!goog.Uri} uri2 The URI object to compare to.\n * @return {boolean} true if same domain; false otherwise.\n */\ngoog.Uri.prototype.hasSameDomainAs = function(uri2) {\n 'use strict';\n return ((!this.hasDomain() && !uri2.hasDomain()) ||\n this.getDomain() == uri2.getDomain()) &&\n ((!this.hasPort() && !uri2.hasPort()) ||\n this.getPort() == uri2.getPort());\n};\n\n\n/**\n * Adds a random parameter to the Uri.\n * @return {!goog.Uri} Reference to this Uri object.\n */\ngoog.Uri.prototype.makeUnique = function() {\n 'use strict';\n this.enforceReadOnly();\n this.setParameterValue(goog.Uri.RANDOM_PARAM, goog.string.getRandomString());\n\n return this;\n};\n\n\n/**\n * Removes the named query parameter.\n *\n * @param {string} key The parameter to remove.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.removeParameter = function(key) {\n 'use strict';\n this.enforceReadOnly();\n this.queryData_.remove(key);\n return this;\n};\n\n\n/**\n * Sets whether Uri is read only. If this goog.Uri is read-only,\n * enforceReadOnly_ will be called at the start of any function that may modify\n * this Uri.\n * @param {boolean} isReadOnly whether this goog.Uri should be read only.\n * @return {!goog.Uri} Reference to this Uri object.\n */\ngoog.Uri.prototype.setReadOnly = function(isReadOnly) {\n 'use strict';\n this.isReadOnly_ = isReadOnly;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the URI is read only.\n */\ngoog.Uri.prototype.isReadOnly = function() {\n 'use strict';\n return this.isReadOnly_;\n};\n\n\n/**\n * Checks if this Uri has been marked as read only, and if so, throws an error.\n * This should be called whenever any modifying function is called.\n */\ngoog.Uri.prototype.enforceReadOnly = function() {\n 'use strict';\n if (this.isReadOnly_) {\n throw new Error('Tried to modify a read-only Uri');\n }\n};\n\n\n/**\n * Sets whether to ignore case.\n * NOTE: If there are already key/value pairs in the QueryData, and\n * ignoreCase_ is set to false, the keys will all be lower-cased.\n * @param {boolean} ignoreCase whether this goog.Uri should ignore case.\n * @return {!goog.Uri} Reference to this Uri object.\n */\ngoog.Uri.prototype.setIgnoreCase = function(ignoreCase) {\n 'use strict';\n this.ignoreCase_ = ignoreCase;\n if (this.queryData_) {\n this.queryData_.setIgnoreCase(ignoreCase);\n }\n return this;\n};\n\n\n/**\n * @return {boolean} Whether to ignore case.\n */\ngoog.Uri.prototype.getIgnoreCase = function() {\n 'use strict';\n return this.ignoreCase_;\n};\n\n\n//==============================================================================\n// Static members\n//==============================================================================\n\n\n/**\n * Creates a uri from the string form. Basically an alias of new goog.Uri().\n * If a Uri object is passed to parse then it will return a clone of the object.\n *\n * @throws URIError If parsing the URI is malformed. The passed URI components\n * should all be parseable by decodeURIComponent.\n * @param {*} uri Raw URI string or instance of Uri\n * object.\n * @param {boolean=} opt_ignoreCase Whether to ignore the case of parameter\n * names in #getParameterValue.\n * @return {!goog.Uri} The new URI object.\n */\ngoog.Uri.parse = function(uri, opt_ignoreCase) {\n 'use strict';\n return uri instanceof goog.Uri ? uri.clone() :\n new goog.Uri(uri, opt_ignoreCase);\n};\n\n\n/**\n * Creates a new goog.Uri object from unencoded parts.\n *\n * @param {?string=} opt_scheme Scheme/protocol or full URI to parse.\n * @param {?string=} opt_userInfo username:password.\n * @param {?string=} opt_domain www.google.com.\n * @param {?number=} opt_port 9830.\n * @param {?string=} opt_path /some/path/to/a/file.html.\n * @param {string|goog.Uri.QueryData=} opt_query a=1&b=2.\n * @param {?string=} opt_fragment The fragment without the #.\n * @param {boolean=} opt_ignoreCase Whether to ignore parameter name case in\n * #getParameterValue.\n *\n * @return {!goog.Uri} The new URI object.\n */\ngoog.Uri.create = function(\n opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_query,\n opt_fragment, opt_ignoreCase) {\n 'use strict';\n var uri = new goog.Uri(null, opt_ignoreCase);\n\n // Only set the parts if they are defined and not empty strings.\n opt_scheme && uri.setScheme(opt_scheme);\n opt_userInfo && uri.setUserInfo(opt_userInfo);\n opt_domain && uri.setDomain(opt_domain);\n opt_port && uri.setPort(opt_port);\n opt_path && uri.setPath(opt_path);\n opt_query && uri.setQueryData(opt_query);\n opt_fragment && uri.setFragment(opt_fragment);\n\n return uri;\n};\n\n\n/**\n * Resolves a relative Uri against a base Uri, accepting both strings and\n * Uri objects.\n *\n * @param {*} base Base Uri.\n * @param {*} rel Relative Uri.\n * @return {!goog.Uri} Resolved uri.\n */\ngoog.Uri.resolve = function(base, rel) {\n 'use strict';\n if (!(base instanceof goog.Uri)) {\n base = goog.Uri.parse(base);\n }\n\n if (!(rel instanceof goog.Uri)) {\n rel = goog.Uri.parse(rel);\n }\n\n return base.resolve(rel);\n};\n\n\n/**\n * Removes dot segments in given path component, as described in\n * RFC 3986, section 5.2.4.\n *\n * @param {string} path A non-empty path component.\n * @return {string} Path component with removed dot segments.\n */\ngoog.Uri.removeDotSegments = function(path) {\n 'use strict';\n if (path == '..' || path == '.') {\n return '';\n\n } else if (\n !goog.string.contains(path, './') && !goog.string.contains(path, '/.')) {\n // This optimization detects uris which do not contain dot-segments,\n // and as a consequence do not require any processing.\n return path;\n\n } else {\n var leadingSlash = goog.string.startsWith(path, '/');\n var segments = path.split('/');\n var out = [];\n\n for (var pos = 0; pos < segments.length;) {\n var segment = segments[pos++];\n\n if (segment == '.') {\n if (leadingSlash && pos == segments.length) {\n out.push('');\n }\n } else if (segment == '..') {\n if (out.length > 1 || out.length == 1 && out[0] != '') {\n out.pop();\n }\n if (leadingSlash && pos == segments.length) {\n out.push('');\n }\n } else {\n out.push(segment);\n leadingSlash = true;\n }\n }\n\n return out.join('/');\n }\n};\n\n\n/**\n * Decodes a value or returns the empty string if it isn't defined or empty.\n * @throws URIError If decodeURIComponent fails to decode val.\n * @param {string|undefined} val Value to decode.\n * @param {boolean=} opt_preserveReserved If true, restricted characters will\n * not be decoded.\n * @return {string} Decoded value.\n * @private\n */\ngoog.Uri.decodeOrEmpty_ = function(val, opt_preserveReserved) {\n 'use strict';\n // Don't use UrlDecode() here because val is not a query parameter.\n if (!val) {\n return '';\n }\n\n // decodeURI has the same output for '%2f' and '%252f'. We double encode %25\n // so that we can distinguish between the 2 inputs. This is later undone by\n // removeDoubleEncoding_.\n return opt_preserveReserved ? decodeURI(val.replace(/%25/g, '%2525')) :\n decodeURIComponent(val);\n};\n\n\n/**\n * If unescapedPart is non null, then escapes any characters in it that aren't\n * valid characters in a url and also escapes any special characters that\n * appear in extra.\n *\n * @param {*} unescapedPart The string to encode.\n * @param {RegExp} extra A character set of characters in [\\01-\\177].\n * @param {boolean=} opt_removeDoubleEncoding If true, remove double percent\n * encoding.\n * @return {?string} null iff unescapedPart == null.\n * @private\n */\ngoog.Uri.encodeSpecialChars_ = function(\n unescapedPart, extra, opt_removeDoubleEncoding) {\n 'use strict';\n if (typeof unescapedPart === 'string') {\n var encoded = encodeURI(unescapedPart).replace(extra, goog.Uri.encodeChar_);\n if (opt_removeDoubleEncoding) {\n // encodeURI double-escapes %XX sequences used to represent restricted\n // characters in some URI components, remove the double escaping here.\n encoded = goog.Uri.removeDoubleEncoding_(encoded);\n }\n return encoded;\n }\n return null;\n};\n\n\n/**\n * Converts a character in [\\01-\\177] to its unicode character equivalent.\n * @param {string} ch One character string.\n * @return {string} Encoded string.\n * @private\n */\ngoog.Uri.encodeChar_ = function(ch) {\n 'use strict';\n var n = ch.charCodeAt(0);\n return '%' + ((n >> 4) & 0xf).toString(16) + (n & 0xf).toString(16);\n};\n\n\n/**\n * Removes double percent-encoding from a string.\n * @param {string} doubleEncodedString String\n * @return {string} String with double encoding removed.\n * @private\n */\ngoog.Uri.removeDoubleEncoding_ = function(doubleEncodedString) {\n 'use strict';\n return doubleEncodedString.replace(/%25([0-9a-fA-F]{2})/g, '%$1');\n};\n\n\n/**\n * Regular expression for characters that are disallowed in the scheme or\n * userInfo part of the URI.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInSchemeOrUserInfo_ = /[#\\/\\?@]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in a relative path.\n * Colon is included due to RFC 3986 3.3.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInRelativePath_ = /[\\#\\?:]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in an absolute path.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInAbsolutePath_ = /[\\#\\?]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in the query.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInQuery_ = /[\\#\\?@]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in the fragment.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInFragment_ = /#/g;\n\n\n/**\n * Checks whether two URIs have the same domain.\n * @param {string} uri1String First URI string.\n * @param {string} uri2String Second URI string.\n * @return {boolean} true if the two URIs have the same domain; false otherwise.\n */\ngoog.Uri.haveSameDomain = function(uri1String, uri2String) {\n 'use strict';\n // Differs from goog.uri.utils.haveSameDomain, since this ignores scheme.\n // TODO(gboyer): Have this just call goog.uri.util.haveSameDomain.\n var pieces1 = goog.uri.utils.split(uri1String);\n var pieces2 = goog.uri.utils.split(uri2String);\n return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==\n pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&\n pieces1[goog.uri.utils.ComponentIndex.PORT] ==\n pieces2[goog.uri.utils.ComponentIndex.PORT];\n};\n\n\n\n/**\n * Class used to represent URI query parameters. It is essentially a hash of\n * name-value pairs, though a name can be present more than once.\n *\n * Has the same interface as the collections in goog.structs.\n *\n * @param {?string=} opt_query Optional encoded query string to parse into\n * the object.\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\n * name in #get.\n * @constructor\n * @struct\n * @final\n */\ngoog.Uri.QueryData = function(opt_query, opt_ignoreCase) {\n 'use strict';\n /**\n * The map containing name/value or name/array-of-values pairs.\n * May be null if it requires parsing from the query string.\n *\n * We need to use a Map because we cannot guarantee that the key names will\n * not be problematic for IE.\n *\n * @private {?Map<string, !Array<*>>}\n */\n this.keyMap_ = null;\n\n /**\n * The number of params, or null if it requires computing.\n * @private {?number}\n */\n this.count_ = null;\n\n /**\n * Encoded query string, or null if it requires computing from the key map.\n * @private {?string}\n */\n this.encodedQuery_ = opt_query || null;\n\n /**\n * If true, ignore the case of the parameter name in #get.\n * @private {boolean}\n */\n this.ignoreCase_ = !!opt_ignoreCase;\n};\n\n\n/**\n * If the underlying key map is not yet initialized, it parses the\n * query string and fills the map with parsed data.\n * @private\n */\ngoog.Uri.QueryData.prototype.ensureKeyMapInitialized_ = function() {\n 'use strict';\n if (!this.keyMap_) {\n this.keyMap_ = /** @type {!Map<string, !Array<*>>} */ (new Map());\n this.count_ = 0;\n if (this.encodedQuery_) {\n var self = this;\n goog.uri.utils.parseQueryData(this.encodedQuery_, function(name, value) {\n 'use strict';\n self.add(goog.string.urlDecode(name), value);\n });\n }\n }\n};\n\n\n/**\n * Creates a new query data instance from a map of names and values.\n *\n * @param {!goog.collections.maps.MapLike<string, ?>|!Object} map Map of string\n * parameter names to parameter value. If parameter value is an array, it is\n * treated as if the key maps to each individual value in the\n * array.\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\n * name in #get.\n * @return {!goog.Uri.QueryData} The populated query data instance.\n */\ngoog.Uri.QueryData.createFromMap = function(map, opt_ignoreCase) {\n 'use strict';\n var keys = goog.structs.getKeys(map);\n if (typeof keys == 'undefined') {\n throw new Error('Keys are undefined');\n }\n\n var queryData = new goog.Uri.QueryData(null, opt_ignoreCase);\n var values = goog.structs.getValues(map);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = values[i];\n if (!Array.isArray(value)) {\n queryData.add(key, value);\n } else {\n queryData.setValues(key, value);\n }\n }\n return queryData;\n};\n\n\n/**\n * Creates a new query data instance from parallel arrays of parameter names\n * and values. Allows for duplicate parameter names. Throws an error if the\n * lengths of the arrays differ.\n *\n * @param {!Array<string>} keys Parameter names.\n * @param {!Array<?>} values Parameter values.\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\n * name in #get.\n * @return {!goog.Uri.QueryData} The populated query data instance.\n */\ngoog.Uri.QueryData.createFromKeysValues = function(\n keys, values, opt_ignoreCase) {\n 'use strict';\n if (keys.length != values.length) {\n throw new Error('Mismatched lengths for keys/values');\n }\n var queryData = new goog.Uri.QueryData(null, opt_ignoreCase);\n for (var i = 0; i < keys.length; i++) {\n queryData.add(keys[i], values[i]);\n }\n return queryData;\n};\n\n\n/**\n * @return {?number} The number of parameters.\n */\ngoog.Uri.QueryData.prototype.getCount = function() {\n 'use strict';\n this.ensureKeyMapInitialized_();\n return this.count_;\n};\n\n\n/**\n * Adds a key value pair.\n * @param {string} key Name.\n * @param {*} value Value.\n * @return {!goog.Uri.QueryData} Instance of this object.\n */\ngoog.Uri.QueryData.prototype.add = function(key, value) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n this.invalidateCache_();\n\n key = this.getKeyName_(key);\n var values = this.keyMap_.get(key);\n if (!values) {\n this.keyMap_.set(key, (values = []));\n }\n values.push(value);\n this.count_ = goog.asserts.assertNumber(this.count_) + 1;\n return this;\n};\n\n\n/**\n * Removes all the params with the given key.\n * @param {string} key Name.\n * @return {boolean} Whether any parameter was removed.\n */\ngoog.Uri.QueryData.prototype.remove = function(key) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n\n key = this.getKeyName_(key);\n if (this.keyMap_.has(key)) {\n this.invalidateCache_();\n\n // Decrement parameter count.\n this.count_ =\n goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length;\n return this.keyMap_.delete(key);\n }\n return false;\n};\n\n\n/**\n * Clears the parameters.\n */\ngoog.Uri.QueryData.prototype.clear = function() {\n 'use strict';\n this.invalidateCache_();\n this.keyMap_ = null;\n this.count_ = 0;\n};\n\n\n/**\n * @return {boolean} Whether we have any parameters.\n */\ngoog.Uri.QueryData.prototype.isEmpty = function() {\n 'use strict';\n this.ensureKeyMapInitialized_();\n return this.count_ == 0;\n};\n\n\n/**\n * Whether there is a parameter with the given name\n * @param {string} key The parameter name to check for.\n * @return {boolean} Whether there is a parameter with the given name.\n */\ngoog.Uri.QueryData.prototype.containsKey = function(key) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n key = this.getKeyName_(key);\n return this.keyMap_.has(key);\n};\n\n\n/**\n * Whether there is a parameter with the given value.\n * @param {*} value The value to check for.\n * @return {boolean} Whether there is a parameter with the given value.\n */\ngoog.Uri.QueryData.prototype.containsValue = function(value) {\n 'use strict';\n // NOTE(arv): This solution goes through all the params even if it was the\n // first param. We can get around this by not reusing code or by switching to\n // iterators.\n var vals = this.getValues();\n return goog.array.contains(vals, value);\n};\n\n\n/**\n * Runs a callback on every key-value pair in the map, including duplicate keys.\n * This won't maintain original order when duplicate keys are interspersed (like\n * getKeys() / getValues()).\n * @param {function(this:SCOPE, ?, string, !goog.Uri.QueryData)} f\n * @param {SCOPE=} opt_scope The value of \"this\" inside f.\n * @template SCOPE\n */\ngoog.Uri.QueryData.prototype.forEach = function(f, opt_scope) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n this.keyMap_.forEach(function(values, key) {\n 'use strict';\n values.forEach(function(value) {\n 'use strict';\n f.call(opt_scope, value, key, this);\n }, this);\n }, this);\n};\n\n\n/**\n * Returns all the keys of the parameters. If a key is used multiple times\n * it will be included multiple times in the returned array\n * @return {!Array<string>} All the keys of the parameters.\n */\ngoog.Uri.QueryData.prototype.getKeys = function() {\n 'use strict';\n this.ensureKeyMapInitialized_();\n // We need to get the values to know how many keys to add.\n const vals = Array.from(this.keyMap_.values());\n const keys = Array.from(this.keyMap_.keys());\n const rv = [];\n for (let i = 0; i < keys.length; i++) {\n const val = vals[i];\n for (let j = 0; j < val.length; j++) {\n rv.push(keys[i]);\n }\n }\n return rv;\n};\n\n\n/**\n * Returns all the values of the parameters with the given name. If the query\n * data has no such key this will return an empty array. If no key is given\n * all values wil be returned.\n * @param {string=} opt_key The name of the parameter to get the values for.\n * @return {!Array<?>} All the values of the parameters with the given name.\n */\ngoog.Uri.QueryData.prototype.getValues = function(opt_key) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n let rv = [];\n if (typeof opt_key === 'string') {\n if (this.containsKey(opt_key)) {\n rv = rv.concat(this.keyMap_.get(this.getKeyName_(opt_key)));\n }\n } else {\n // Return all values.\n const values = Array.from(this.keyMap_.values());\n for (let i = 0; i < values.length; i++) {\n rv = rv.concat(values[i]);\n }\n }\n return rv;\n};\n\n\n/**\n * Sets a key value pair and removes all other keys with the same value.\n *\n * @param {string} key Name.\n * @param {*} value Value.\n * @return {!goog.Uri.QueryData} Instance of this object.\n */\ngoog.Uri.QueryData.prototype.set = function(key, value) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n this.invalidateCache_();\n\n // TODO(chrishenry): This could be better written as\n // this.remove(key), this.add(key, value), but that would reorder\n // the key (since the key is first removed and then added at the\n // end) and we would have to fix unit tests that depend on key\n // ordering.\n key = this.getKeyName_(key);\n if (this.containsKey(key)) {\n this.count_ =\n goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length;\n }\n this.keyMap_.set(key, [value]);\n this.count_ = goog.asserts.assertNumber(this.count_) + 1;\n return this;\n};\n\n\n/**\n * Returns the first value associated with the key. If the query data has no\n * such key this will return undefined or the optional default.\n * @param {string} key The name of the parameter to get the value for.\n * @param {*=} opt_default The default value to return if the query data\n * has no such key.\n * @return {*} The first string value associated with the key, or opt_default\n * if there's no value.\n */\ngoog.Uri.QueryData.prototype.get = function(key, opt_default) {\n 'use strict';\n if (!key) {\n return opt_default;\n }\n var values = this.getValues(key);\n return values.length > 0 ? String(values[0]) : opt_default;\n};\n\n\n/**\n * Sets the values for a key. If the key already exists, this will\n * override all of the existing values that correspond to the key.\n * @param {string} key The key to set values for.\n * @param {!Array<?>} values The values to set.\n */\ngoog.Uri.QueryData.prototype.setValues = function(key, values) {\n 'use strict';\n this.remove(key);\n\n if (values.length > 0) {\n this.invalidateCache_();\n this.keyMap_.set(this.getKeyName_(key), goog.array.clone(values));\n this.count_ = goog.asserts.assertNumber(this.count_) + values.length;\n }\n};\n\n\n/**\n * @return {string} Encoded query string.\n * @override\n */\ngoog.Uri.QueryData.prototype.toString = function() {\n 'use strict';\n if (this.encodedQuery_) {\n return this.encodedQuery_;\n }\n\n if (!this.keyMap_) {\n return '';\n }\n\n const sb = [];\n\n // In the past, we use this.getKeys() and this.getVals(), but that\n // generates a lot of allocations as compared to simply iterating\n // over the keys.\n const keys = Array.from(this.keyMap_.keys());\n for (var i = 0; i < keys.length; i++) {\n const key = keys[i];\n const encodedKey = goog.string.urlEncode(key);\n const val = this.getValues(key);\n for (var j = 0; j < val.length; j++) {\n var param = encodedKey;\n // Ensure that null and undefined are encoded into the url as\n // literal strings.\n if (val[j] !== '') {\n param += '=' + goog.string.urlEncode(val[j]);\n }\n sb.push(param);\n }\n }\n\n return this.encodedQuery_ = sb.join('&');\n};\n\n\n/**\n * @throws URIError If URI is malformed (that is, if decodeURIComponent fails on\n * any of the URI components).\n * @return {string} Decoded query string.\n */\ngoog.Uri.QueryData.prototype.toDecodedString = function() {\n 'use strict';\n return goog.Uri.decodeOrEmpty_(this.toString());\n};\n\n\n/**\n * Invalidate the cache.\n * @private\n */\ngoog.Uri.QueryData.prototype.invalidateCache_ = function() {\n 'use strict';\n this.encodedQuery_ = null;\n};\n\n\n/**\n * Removes all keys that are not in the provided list. (Modifies this object.)\n * @param {Array<string>} keys The desired keys.\n * @return {!goog.Uri.QueryData} a reference to this object.\n */\ngoog.Uri.QueryData.prototype.filterKeys = function(keys) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n this.keyMap_.forEach(function(value, key) {\n 'use strict';\n if (!goog.array.contains(keys, key)) {\n this.remove(key);\n }\n }, this);\n return this;\n};\n\n\n/**\n * Clone the query data instance.\n * @return {!goog.Uri.QueryData} New instance of the QueryData object.\n */\ngoog.Uri.QueryData.prototype.clone = function() {\n 'use strict';\n var rv = new goog.Uri.QueryData();\n rv.encodedQuery_ = this.encodedQuery_;\n if (this.keyMap_) {\n rv.keyMap_ = /** @type {!Map<string, !Array<*>>} */ (new Map(this.keyMap_));\n rv.count_ = this.count_;\n }\n return rv;\n};\n\n\n/**\n * Helper function to get the key name from a JavaScript object. Converts\n * the object to a string, and to lower case if necessary.\n * @private\n * @param {*} arg The object to get a key name from.\n * @return {string} valid key name which can be looked up in #keyMap_.\n */\ngoog.Uri.QueryData.prototype.getKeyName_ = function(arg) {\n 'use strict';\n var keyName = String(arg);\n if (this.ignoreCase_) {\n keyName = keyName.toLowerCase();\n }\n return keyName;\n};\n\n\n/**\n * Ignore case in parameter names.\n * NOTE: If there are already key/value pairs in the QueryData, and\n * ignoreCase_ is set to false, the keys will all be lower-cased.\n * @param {boolean} ignoreCase whether this goog.Uri should ignore case.\n */\ngoog.Uri.QueryData.prototype.setIgnoreCase = function(ignoreCase) {\n 'use strict';\n var resetKeys = ignoreCase && !this.ignoreCase_;\n if (resetKeys) {\n this.ensureKeyMapInitialized_();\n this.invalidateCache_();\n this.keyMap_.forEach(function(value, key) {\n 'use strict';\n var lowerCase = key.toLowerCase();\n if (key != lowerCase) {\n this.remove(key);\n this.setValues(lowerCase, value);\n }\n }, this);\n }\n this.ignoreCase_ = ignoreCase;\n};\n\n\n/**\n * Extends a query data object with another query data or map like object. This\n * operates 'in-place', it does not create a new QueryData object.\n *\n * @param {...(?goog.Uri.QueryData|?goog.collections.maps.MapLike<?,\n * ?>|?Object)} var_args The object from which key value pairs will be\n * copied. Note: does not accept null.\n * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different\n * types of parameters.\n */\ngoog.Uri.QueryData.prototype.extend = function(var_args) {\n 'use strict';\n for (var i = 0; i < arguments.length; i++) {\n var data = arguments[i];\n goog.structs.forEach(data, function(value, key) {\n 'use strict';\n this.add(key, value);\n }, this);\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview The dispose method is used to clean up references and\n * resources.\n */\n\ngoog.module('goog.dispose');\ngoog.module.declareLegacyNamespace();\n\n/**\n * Calls `dispose` on the argument if it supports it. If obj is not an\n * object with a dispose() method, this is a no-op.\n * @param {*} obj The object to dispose of.\n */\nfunction dispose(obj) {\n if (obj && typeof obj.dispose == 'function') {\n obj.dispose();\n }\n}\nexports = dispose;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Codec functions of the v8 wire protocol. Eventually we'd want\n * to support pluggable wire-format to improve wire efficiency and to enable\n * binary encoding. Such support will require an interface class, which\n * will be added later.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.WireV8');\n\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.json');\ngoog.require('goog.json.NativeJsonProcessor');\ngoog.require('goog.labs.net.webChannel.Wire');\ngoog.require('goog.structs');\ngoog.requireType('goog.string.Parser');\n\n\n\n/**\n * The v8 codec class.\n *\n * @constructor\n * @struct\n */\ngoog.labs.net.webChannel.WireV8 = function() {\n 'use strict';\n /**\n * Parser for a response payload. The parser should return an array.\n * @private {!goog.string.Parser}\n */\n this.parser_ = new goog.json.NativeJsonProcessor();\n};\n\n\ngoog.scope(function() {\n'use strict';\nconst WireV8 = goog.labs.net.webChannel.WireV8;\nconst Wire = goog.labs.net.webChannel.Wire;\n\n\n/**\n * Encodes a standalone message into the wire format.\n *\n * May throw exception if the message object contains any invalid elements.\n *\n * @param {!Object|!goog.collections.maps.MapLike} message The message data.\n * V8 only support JS objects (or Map).\n * @param {!Array<string>} buffer The text buffer to write the message to.\n * @param {string=} opt_prefix The prefix for each field of the object.\n */\nWireV8.prototype.encodeMessage = function(message, buffer, opt_prefix) {\n 'use strict';\n const prefix = opt_prefix || '';\n try {\n goog.structs.forEach(message, function(value, key) {\n 'use strict';\n let encodedValue = value;\n if (goog.isObject(value)) {\n encodedValue = goog.json.serialize(value);\n } // keep the fast-path for primitive types\n buffer.push(prefix + key + '=' + encodeURIComponent(encodedValue));\n });\n } catch (ex) {\n // We send a map here because lots of the retry logic relies on map IDs,\n // so we have to send something (possibly redundant).\n buffer.push(\n prefix + 'type' +\n '=' + encodeURIComponent('_badmap'));\n throw ex;\n }\n};\n\n\n/**\n * Encodes all the buffered messages of the forward channel.\n *\n * @param {!Array<Wire.QueuedMap>} messageQueue The message data.\n * V8 only support JS objects.\n * @param {number} count The number of messages to be encoded.\n * @param {?function(!Object)} badMapHandler Callback for bad messages.\n * @return {string} the encoded messages\n */\nWireV8.prototype.encodeMessageQueue = function(\n messageQueue, count, badMapHandler) {\n 'use strict';\n let offset = -1;\n while (true) {\n const sb = ['count=' + count];\n // To save a bit of bandwidth, specify the base mapId and the rest as\n // offsets from it.\n if (offset == -1) {\n if (count > 0) {\n offset = messageQueue[0].mapId;\n sb.push('ofs=' + offset);\n } else {\n offset = 0;\n }\n } else {\n sb.push('ofs=' + offset);\n }\n let done = true;\n for (let i = 0; i < count; i++) {\n let mapId = messageQueue[i].mapId;\n const map = messageQueue[i].map;\n mapId -= offset;\n if (mapId < 0) {\n // redo the encoding in case of retry/reordering, plus extra space\n offset = Math.max(0, messageQueue[i].mapId - 100);\n done = false;\n continue;\n }\n try {\n this.encodeMessage(map, sb, 'req' + mapId + '_');\n } catch (ex) {\n if (badMapHandler) {\n badMapHandler(map);\n }\n }\n }\n if (done) {\n return sb.join('&');\n }\n }\n};\n\n\n/**\n * Decodes a standalone message received from the wire. May throw exception\n * if text is ill-formatted.\n *\n * Must be valid JSON as it is insecure to use eval() to decode JS literals;\n * and eval() is disallowed in Chrome apps too.\n *\n * Invalid JS literals include null array elements, quotas etc.\n *\n * @param {string} messageText The string content as received from the wire.\n * @return {*} The decoded message object.\n */\nWireV8.prototype.decodeMessage = function(messageText) {\n 'use strict';\n const response = this.parser_.parse(messageText);\n goog.asserts.assert(Array.isArray(response)); // throw exception\n return response;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A pool of forward channel requests to enable real-time\n * messaging from the client to server.\n *\n */\n\ngoog.module('goog.labs.net.webChannel.ForwardChannelRequestPool');\n\ngoog.module.declareLegacyNamespace();\n\nconst ChannelRequest = goog.require('goog.labs.net.webChannel.ChannelRequest');\nconst Wire = goog.require('goog.labs.net.webChannel.Wire');\nconst array = goog.require('goog.array');\nconst googString = goog.require('goog.string');\n\n\n/**\n * This class represents the state of all forward channel requests.\n *\n * @param {number=} opt_maxPoolSize The maximum pool size.\n *\n * @struct @constructor @final\n */\nconst ForwardChannelRequestPool = function(opt_maxPoolSize) {\n /**\n * The max pool size as configured.\n *\n * @private {number}\n */\n this.maxPoolSizeConfigured_ =\n opt_maxPoolSize || ForwardChannelRequestPool.MAX_POOL_SIZE_;\n\n /**\n * The current size limit of the request pool. This limit is meant to be\n * read-only after the channel is fully opened.\n *\n * If SPDY or HTTP2 is enabled, set it to the max pool size, which is also\n * configurable.\n *\n * @private {number}\n */\n this.maxSize_ = ForwardChannelRequestPool.isSpdyOrHttp2Enabled_() ?\n this.maxPoolSizeConfigured_ :\n 1;\n\n /**\n * The container for all the pending request objects.\n *\n * @private {?Set<?ChannelRequest>}\n */\n this.requestPool_ = null;\n\n if (this.maxSize_ > 1) {\n this.requestPool_ = new Set();\n }\n\n /**\n * The single request object when the pool size is limited to one.\n *\n * @private {?ChannelRequest}\n */\n this.request_ = null;\n\n /**\n * Saved pending messages when the pool is cancelled.\n *\n * @private {!Array<Wire.QueuedMap>}\n */\n this.pendingMessages_ = [];\n};\n\n\n/**\n * The default size limit of the request pool.\n *\n * @private {number}\n */\nForwardChannelRequestPool.MAX_POOL_SIZE_ = 10;\n\n\n/**\n * @return {boolean} True if SPDY or HTTP2 is enabled. Uses chrome-specific APIs\n * as a fallback and will always return false for other browsers where\n * PerformanceNavigationTiming is not available.\n * @private\n */\nForwardChannelRequestPool.isSpdyOrHttp2Enabled_ = function() {\n if (goog.global.PerformanceNavigationTiming) {\n const entrys = /** @type {!Array<!PerformanceNavigationTiming>} */ (\n goog.global.performance.getEntriesByType('navigation'));\n return entrys.length > 0 &&\n (entrys[0].nextHopProtocol == 'hq' ||\n entrys[0].nextHopProtocol == 'h2');\n }\n return !!(\n goog.global.chrome && goog.global.chrome.loadTimes &&\n goog.global.chrome.loadTimes() &&\n goog.global.chrome.loadTimes().wasFetchedViaSpdy);\n};\n\n\n/**\n * Once we know the client protocol (from the handshake), check if we need\n * enable the request pool accordingly. This is more robust than using\n * browser-internal APIs (specific to Chrome).\n *\n * @param {string} clientProtocol The client protocol\n */\nForwardChannelRequestPool.prototype.applyClientProtocol = function(\n clientProtocol) {\n if (this.requestPool_) {\n return;\n }\n\n if (googString.contains(clientProtocol, 'spdy') ||\n googString.contains(clientProtocol, 'quic') ||\n googString.contains(clientProtocol, 'h2')) {\n this.maxSize_ = this.maxPoolSizeConfigured_;\n this.requestPool_ = new Set();\n if (this.request_) {\n this.addRequest(this.request_);\n this.request_ = null;\n }\n }\n};\n\n\n/**\n * @return {boolean} True if the pool is full.\n */\nForwardChannelRequestPool.prototype.isFull = function() {\n if (this.request_) {\n return true;\n }\n\n if (this.requestPool_) {\n return this.requestPool_.size >= this.maxSize_;\n }\n\n return false;\n};\n\n\n/**\n * @return {number} The current size limit.\n */\nForwardChannelRequestPool.prototype.getMaxSize = function() {\n return this.maxSize_;\n};\n\n\n/**\n * @return {number} The number of pending requests in the pool.\n */\nForwardChannelRequestPool.prototype.getRequestCount = function() {\n if (this.request_) {\n return 1;\n }\n\n if (this.requestPool_) {\n return this.requestPool_.size;\n }\n\n return 0;\n};\n\n\n/**\n * @param {ChannelRequest} req The channel request.\n * @return {boolean} True if the request is a included inside the pool.\n */\nForwardChannelRequestPool.prototype.hasRequest = function(req) {\n if (this.request_) {\n return this.request_ == req;\n }\n\n if (this.requestPool_) {\n return this.requestPool_.has(req);\n }\n\n return false;\n};\n\n\n/**\n * Adds a new request to the pool.\n *\n * @param {!ChannelRequest} req The new channel request.\n */\nForwardChannelRequestPool.prototype.addRequest = function(req) {\n if (this.requestPool_) {\n this.requestPool_.add(req);\n } else {\n this.request_ = req;\n }\n};\n\n\n/**\n * Removes the given request from the pool.\n *\n * @param {ChannelRequest} req The channel request.\n * @return {boolean} Whether the request has been removed from the pool.\n */\nForwardChannelRequestPool.prototype.removeRequest = function(req) {\n if (this.request_ && this.request_ == req) {\n this.request_ = null;\n return true;\n }\n\n if (this.requestPool_ && this.requestPool_.has(req)) {\n this.requestPool_.delete(req);\n return true;\n }\n\n return false;\n};\n\n\n/**\n * Clears the pool and cancel all the pending requests.\n */\nForwardChannelRequestPool.prototype.cancel = function() {\n // save any pending messages\n this.pendingMessages_ = this.getPendingMessages();\n\n if (this.request_) {\n this.request_.cancel();\n this.request_ = null;\n return;\n }\n\n if (this.requestPool_ && this.requestPool_.size !== 0) {\n for (const val of this.requestPool_.values()) {\n val.cancel();\n }\n this.requestPool_.clear();\n }\n};\n\n\n/**\n * @return {boolean} Whether there are any pending requests.\n */\nForwardChannelRequestPool.prototype.hasPendingRequest = function() {\n return (this.request_ != null) ||\n (this.requestPool_ != null && this.requestPool_.size !== 0);\n};\n\n\n/**\n * @return {!Array<Wire.QueuedMap>} All the pending messages from the pool,\n * as a new array.\n */\nForwardChannelRequestPool.prototype.getPendingMessages = function() {\n if (this.request_ != null) {\n return this.pendingMessages_.concat(this.request_.getPendingMessages());\n }\n\n if (this.requestPool_ != null && this.requestPool_.size !== 0) {\n let result = this.pendingMessages_;\n for (const val of this.requestPool_.values()) {\n result = result.concat(val.getPendingMessages());\n }\n return result;\n }\n\n return array.clone(this.pendingMessages_);\n};\n\n\n/**\n * Records pending messages, e.g. when a request receives a failed response.\n *\n * @param {!Array<Wire.QueuedMap>} messages Pending messages.\n */\nForwardChannelRequestPool.prototype.addPendingMessages = function(messages) {\n this.pendingMessages_ = this.pendingMessages_.concat(messages);\n};\n\n\n/**\n * Clears any recorded pending messages.\n */\nForwardChannelRequestPool.prototype.clearPendingMessages = function() {\n this.pendingMessages_.length = 0;\n};\n\n\n/**\n * Cancels all pending requests and force the completion of channel requests.\n *\n * Need go through the standard onRequestComplete logic to expose the max-retry\n * failure in the standard way.\n *\n * @param {function(!ChannelRequest)} onComplete The completion callback.\n * @return {boolean} true if any request has been forced to complete.\n */\nForwardChannelRequestPool.prototype.forceComplete = function(onComplete) {\n if (this.request_ != null) {\n this.request_.cancel();\n onComplete(this.request_);\n return true;\n }\n\n if (this.requestPool_ && this.requestPool_.size !== 0) {\n for (const val of this.requestPool_.values()) {\n val.cancel();\n onComplete(val);\n }\n return true;\n }\n\n return false;\n};\n\nexports = ForwardChannelRequestPool;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Generics method for collection-like classes and objects.\n *\n *\n * This file contains functions to work with collections. It supports using\n * Map, Set, Array and Object and other classes that implement collection-like\n * methods.\n * @suppress {strictMissingProperties}\n */\n\n\ngoog.provide('goog.structs');\n\ngoog.require('goog.array');\ngoog.require('goog.object');\n\n\n// We treat an object as a dictionary if it has getKeys or it is an object that\n// isn't arrayLike.\n\n\n/**\n * Returns the number of values in the collection-like object.\n * @param {Object} col The collection-like object.\n * @return {number} The number of values in the collection-like object.\n */\ngoog.structs.getCount = function(col) {\n 'use strict';\n if (col.getCount && typeof col.getCount == 'function') {\n return col.getCount();\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return col.length;\n }\n return goog.object.getCount(col);\n};\n\n\n/**\n * Returns the values of the collection-like object.\n * @param {Object} col The collection-like object.\n * @return {!Array<?>} The values in the collection-like object.\n */\ngoog.structs.getValues = function(col) {\n 'use strict';\n if (col.getValues && typeof col.getValues == 'function') {\n return col.getValues();\n }\n // ES6 Map and Set both define a values function that returns an iterator.\n // The typeof check allows the compiler to remove the Map and Set polyfills\n // if they are otherwise unused throughout the entire binary.\n if ((typeof Map !== 'undefined' && col instanceof Map) ||\n (typeof Set !== 'undefined' && col instanceof Set)) {\n return Array.from(col.values());\n }\n if (typeof col === 'string') {\n return col.split('');\n }\n if (goog.isArrayLike(col)) {\n var rv = [];\n var l = col.length;\n for (var i = 0; i < l; i++) {\n rv.push(col[i]);\n }\n return rv;\n }\n return goog.object.getValues(col);\n};\n\n\n/**\n * Returns the keys of the collection. Some collections have no notion of\n * keys/indexes and this function will return undefined in those cases.\n * @param {Object} col The collection-like object.\n * @return {!Array|undefined} The keys in the collection.\n */\ngoog.structs.getKeys = function(col) {\n 'use strict';\n if (col.getKeys && typeof col.getKeys == 'function') {\n return col.getKeys();\n }\n // if we have getValues but no getKeys we know this is a key-less collection\n if (col.getValues && typeof col.getValues == 'function') {\n return undefined;\n }\n // ES6 Map and Set both define a keys function that returns an iterator. For\n // Sets this iterates over the same values as the values iterator.\n // The typeof check allows the compiler to remove the Map and Set polyfills\n // if they are otherwise unused throughout the entire binary.\n if (typeof Map !== 'undefined' && col instanceof Map) {\n return Array.from(col.keys());\n }\n // Unlike the native Set, goog.structs.Set does not expose keys as the values.\n if (typeof Set !== 'undefined' && col instanceof Set) {\n return undefined;\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n var rv = [];\n var l = col.length;\n for (var i = 0; i < l; i++) {\n rv.push(i);\n }\n return rv;\n }\n\n return goog.object.getKeys(col);\n};\n\n\n/**\n * Whether the collection contains the given value. This is O(n) and uses\n * equals (==) to test the existence.\n * @param {Object} col The collection-like object.\n * @param {*} val The value to check for.\n * @return {boolean} True if the map contains the value.\n */\ngoog.structs.contains = function(col, val) {\n 'use strict';\n if (col.contains && typeof col.contains == 'function') {\n return col.contains(val);\n }\n if (col.containsValue && typeof col.containsValue == 'function') {\n return col.containsValue(val);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return goog.array.contains(/** @type {!Array<?>} */ (col), val);\n }\n return goog.object.containsValue(col, val);\n};\n\n\n/**\n * Whether the collection is empty.\n * @param {Object} col The collection-like object.\n * @return {boolean} True if empty.\n */\ngoog.structs.isEmpty = function(col) {\n 'use strict';\n if (col.isEmpty && typeof col.isEmpty == 'function') {\n return col.isEmpty();\n }\n\n // We do not use goog.string.isEmptyOrWhitespace because here we treat the\n // string as\n // collection and as such even whitespace matters\n\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return /** @type {!Array<?>} */ (col).length === 0;\n }\n return goog.object.isEmpty(col);\n};\n\n\n/**\n * Removes all the elements from the collection.\n * @param {Object} col The collection-like object.\n * @return {void}\n */\ngoog.structs.clear = function(col) {\n 'use strict';\n // NOTE(arv): This should not contain strings because strings are immutable\n if (col.clear && typeof col.clear == 'function') {\n col.clear();\n } else if (goog.isArrayLike(col)) {\n goog.array.clear(/** @type {IArrayLike<?>} */ (col));\n } else {\n goog.object.clear(col);\n }\n};\n\n\n/**\n * Calls a function for each value in a collection. The function takes\n * three arguments; the value, the key and the collection.\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):?} f The function to call for every value.\n * This function takes\n * 3 arguments (the value, the key or undefined if the collection has no\n * notion of keys, and the collection) and the return value is irrelevant.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {void}\n * @template T,S\n * @deprecated Use a more specific method, e.g. native Array.prototype.forEach,\n * or for-of.\n */\ngoog.structs.forEach = function(col, f, opt_obj) {\n 'use strict';\n if (col.forEach && typeof col.forEach == 'function') {\n col.forEach(f, opt_obj);\n } else if (goog.isArrayLike(col) || typeof col === 'string') {\n Array.prototype.forEach.call(/** @type {!Array<?>} */ (col), f, opt_obj);\n } else {\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n for (var i = 0; i < l; i++) {\n f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col);\n }\n }\n};\n\n\n/**\n * Calls a function for every value in the collection. When a call returns true,\n * adds the value to a new collection (Array is returned by default).\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\n * value. This function takes\n * 3 arguments (the value, the key or undefined if the collection has no\n * notion of keys, and the collection) and should return a Boolean. If the\n * return value is true the value is added to the result collection. If it\n * is false the value is not included.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {!Object|!Array<?>} A new collection where the passed values are\n * present. If col is a key-less collection an array is returned. If col\n * has keys and values a plain old JS object is returned.\n * @template T,S\n */\ngoog.structs.filter = function(col, f, opt_obj) {\n 'use strict';\n if (typeof col.filter == 'function') {\n return col.filter(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.filter.call(\n /** @type {!Array<?>} */ (col), f, opt_obj);\n }\n\n var rv;\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n if (keys) {\n rv = {};\n for (var i = 0; i < l; i++) {\n if (f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col)) {\n rv[keys[i]] = values[i];\n }\n }\n } else {\n // We should not use Array#filter here since we want to make sure that\n // the index is undefined as well as make sure that col is passed to the\n // function.\n rv = [];\n for (var i = 0; i < l; i++) {\n if (f.call(opt_obj, values[i], undefined, col)) {\n rv.push(values[i]);\n }\n }\n }\n return rv;\n};\n\n\n/**\n * Calls a function for every value in the collection and adds the result into a\n * new collection (defaults to creating a new Array).\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):V} f The function to call for every value.\n * This function takes 3 arguments (the value, the key or undefined if the\n * collection has no notion of keys, and the collection) and should return\n * something. The result will be used as the value in the new collection.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {!Object<V>|!Array<V>} A new collection with the new values. If\n * col is a key-less collection an array is returned. If col has keys and\n * values a plain old JS object is returned.\n * @template T,S,V\n */\ngoog.structs.map = function(col, f, opt_obj) {\n 'use strict';\n if (typeof col.map == 'function') {\n return col.map(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.map.call(/** @type {!Array<?>} */ (col), f, opt_obj);\n }\n\n var rv;\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n if (keys) {\n rv = {};\n for (var i = 0; i < l; i++) {\n rv[keys[i]] = f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col);\n }\n } else {\n // We should not use Array#map here since we want to make sure that\n // the index is undefined as well as make sure that col is passed to the\n // function.\n rv = [];\n for (var i = 0; i < l; i++) {\n rv[i] = f.call(/** @type {?} */ (opt_obj), values[i], undefined, col);\n }\n }\n return rv;\n};\n\n\n/**\n * Calls f for each value in a collection. If any call returns true this returns\n * true (without checking the rest). If all returns false this returns false.\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\n * value. This function takes 3 arguments (the value, the key or undefined\n * if the collection has no notion of keys, and the collection) and should\n * return a boolean.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {boolean} True if any value passes the test.\n * @template T,S\n */\ngoog.structs.some = function(col, f, opt_obj) {\n 'use strict';\n if (typeof col.some == 'function') {\n return col.some(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.some.call(\n /** @type {!Array<?>} */ (col), f, opt_obj);\n }\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) {\n return true;\n }\n }\n return false;\n};\n\n\n/**\n * Calls f for each value in a collection. If all calls return true this return\n * true this returns true. If any returns false this returns false at this point\n * and does not continue to check the remaining values.\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\n * value. This function takes 3 arguments (the value, the key or\n * undefined if the collection has no notion of keys, and the collection)\n * and should return a boolean.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {boolean} True if all key-value pairs pass the test.\n * @template T,S\n */\ngoog.structs.every = function(col, f, opt_obj) {\n 'use strict';\n if (typeof col.every == 'function') {\n return col.every(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.every.call(\n /** @type {!Array<?>} */ (col), f, opt_obj);\n }\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (!f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) {\n return false;\n }\n }\n return true;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Simple utilities for dealing with URI strings.\n *\n * This package is deprecated in favour of the Closure URL package (goog.url)\n * when manipulating URIs for use by a browser. This package uses regular\n * expressions to parse a potential URI which can fall out of sync with how a\n * browser will actually interpret the URI. See\n * `goog.uri.utils.setUrlPackageSupportLoggingHandler` for one way to identify\n * URIs that should instead be parsed using the URL package.\n *\n * This is intended to be a lightweight alternative to constructing goog.Uri\n * objects. Whereas goog.Uri adds several kilobytes to the binary regardless\n * of how much of its functionality you use, this is designed to be a set of\n * mostly-independent utilities so that the compiler includes only what is\n * necessary for the task. Estimated savings of porting is 5k pre-gzip and\n * 1.5k post-gzip. To ensure the savings remain, future developers should\n * avoid adding new functionality to existing functions, but instead create\n * new ones and factor out shared code.\n *\n * Many of these utilities have limited functionality, tailored to common\n * cases. The query parameter utilities assume that the parameter keys are\n * already encoded, since most keys are compile-time alphanumeric strings. The\n * query parameter mutation utilities also do not tolerate fragment identifiers.\n *\n * By design, these functions can be slower than goog.Uri equivalents.\n * Repeated calls to some of functions may be quadratic in behavior for IE,\n * although the effect is somewhat limited given the 2kb limit.\n *\n * One advantage of the limited functionality here is that this approach is\n * less sensitive to differences in URI encodings than goog.Uri, since these\n * functions operate on strings directly, rather than decoding them and\n * then re-encoding.\n *\n * Uses features of RFC 3986 for parsing/formatting URIs:\n * http://www.ietf.org/rfc/rfc3986.txt\n */\n\ngoog.provide('goog.uri.utils');\ngoog.provide('goog.uri.utils.ComponentIndex');\ngoog.provide('goog.uri.utils.QueryArray');\ngoog.provide('goog.uri.utils.QueryValue');\ngoog.provide('goog.uri.utils.StandardQueryParam');\n\ngoog.require('goog.asserts');\ngoog.require('goog.string');\n\n\n/**\n * Character codes inlined to avoid object allocations due to charCode.\n * @enum {number}\n * @private\n */\ngoog.uri.utils.CharCode_ = {\n AMPERSAND: 38,\n EQUAL: 61,\n HASH: 35,\n QUESTION: 63\n};\n\n\n/**\n * Builds a URI string from already-encoded parts.\n *\n * No encoding is performed. Any component may be omitted as either null or\n * undefined.\n *\n * @param {?string=} opt_scheme The scheme such as 'http'.\n * @param {?string=} opt_userInfo The user name before the '@'.\n * @param {?string=} opt_domain The domain such as 'www.google.com', already\n * URI-encoded.\n * @param {(string|number|null)=} opt_port The port number.\n * @param {?string=} opt_path The path, already URI-encoded. If it is not\n * empty, it must begin with a slash.\n * @param {?string=} opt_queryData The URI-encoded query data.\n * @param {?string=} opt_fragment The URI-encoded fragment identifier.\n * @return {string} The fully combined URI.\n */\ngoog.uri.utils.buildFromEncodedParts = function(\n opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData,\n opt_fragment) {\n 'use strict';\n var out = '';\n\n if (opt_scheme) {\n out += opt_scheme + ':';\n }\n\n if (opt_domain) {\n out += '//';\n\n if (opt_userInfo) {\n out += opt_userInfo + '@';\n }\n\n out += opt_domain;\n\n if (opt_port) {\n out += ':' + opt_port;\n }\n }\n\n if (opt_path) {\n out += opt_path;\n }\n\n if (opt_queryData) {\n out += '?' + opt_queryData;\n }\n\n if (opt_fragment) {\n out += '#' + opt_fragment;\n }\n\n return out;\n};\n\n\n/**\n * A regular expression for breaking a URI into its component parts.\n *\n * {@link http://www.ietf.org/rfc/rfc3986.txt} says in Appendix B\n * As the \"first-match-wins\" algorithm is identical to the \"greedy\"\n * disambiguation method used by POSIX regular expressions, it is natural and\n * commonplace to use a regular expression for parsing the potential five\n * components of a URI reference.\n *\n * The following line is the regular expression for breaking-down a\n * well-formed URI reference into its components.\n *\n * <pre>\n * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?\n * 12 3 4 5 6 7 8 9\n * </pre>\n *\n * The numbers in the second line above are only to assist readability; they\n * indicate the reference points for each subexpression (i.e., each paired\n * parenthesis). We refer to the value matched for subexpression <n> as $<n>.\n * For example, matching the above expression to\n * <pre>\n * http://www.ics.uci.edu/pub/ietf/uri/#Related\n * </pre>\n * results in the following subexpression matches:\n * <pre>\n * $1 = http:\n * $2 = http\n * $3 = //www.ics.uci.edu\n * $4 = www.ics.uci.edu\n * $5 = /pub/ietf/uri/\n * $6 = <undefined>\n * $7 = <undefined>\n * $8 = #Related\n * $9 = Related\n * </pre>\n * where <undefined> indicates that the component is not present, as is the\n * case for the query component in the above example. Therefore, we can\n * determine the value of the five components as\n * <pre>\n * scheme = $2\n * authority = $4\n * path = $5\n * query = $7\n * fragment = $9\n * </pre>\n *\n * The regular expression has been modified slightly to expose the\n * userInfo, domain, and port separately from the authority.\n * The modified version yields\n * <pre>\n * $1 = http scheme\n * $2 = <undefined> userInfo -\\\n * $3 = www.ics.uci.edu domain | authority\n * $4 = <undefined> port -/\n * $5 = /pub/ietf/uri/ path\n * $6 = <undefined> query without ?\n * $7 = Related fragment without #\n * </pre>\n *\n * TODO(user): separate out the authority terminating characters once this\n * file is moved to ES6.\n * @type {!RegExp}\n * @private\n */\ngoog.uri.utils.splitRe_ = new RegExp(\n '^' + // Anchor against the entire string.\n '(?:' +\n '([^:/?#.]+)' + // scheme - ignore special characters\n // used by other URL parts such as :,\n // ?, /, #, and .\n ':)?' +\n '(?://' +\n '(?:([^\\\\\\\\/?#]*)@)?' + // userInfo\n '([^\\\\\\\\/?#]*?)' + // domain\n '(?::([0-9]+))?' + // port\n '(?=[\\\\\\\\/?#]|$)' + // authority-terminating character.\n ')?' +\n '([^?#]+)?' + // path\n '(?:\\\\?([^#]*))?' + // query\n '(?:#([\\\\s\\\\S]*))?' + // fragment. Can't use '.*' with 's' flag as Firefox\n // doesn't support the flag, and can't use an\n // \"everything set\" ([^]) as IE10 doesn't match any\n // characters with it.\n '$');\n\n\n/**\n * The index of each URI component in the return value of goog.uri.utils.split.\n * @enum {number}\n */\ngoog.uri.utils.ComponentIndex = {\n SCHEME: 1,\n USER_INFO: 2,\n DOMAIN: 3,\n PORT: 4,\n PATH: 5,\n QUERY_DATA: 6,\n FRAGMENT: 7\n};\n\n/**\n * @type {?function(string)}\n * @private\n */\ngoog.uri.utils.urlPackageSupportLoggingHandler_ = null;\n\n/**\n * @param {?function(string)} handler The handler function to call when a URI\n * with a protocol that is better supported by the Closure URL package is\n * detected.\n */\ngoog.uri.utils.setUrlPackageSupportLoggingHandler = function(handler) {\n 'use strict';\n goog.uri.utils.urlPackageSupportLoggingHandler_ = handler;\n};\n\n/**\n * Splits a URI into its component parts.\n *\n * Each component can be accessed via the component indices; for example:\n * <pre>\n * goog.uri.utils.split(someStr)[goog.uri.utils.ComponentIndex.QUERY_DATA];\n * </pre>\n *\n * @param {string} uri The URI string to examine.\n * @return {!Array<string|undefined>} Each component still URI-encoded.\n * Each component that is present will contain the encoded value, whereas\n * components that are not present will be undefined or empty, depending\n * on the browser's regular expression implementation. Never null, since\n * arbitrary strings may still look like path names.\n */\ngoog.uri.utils.split = function(uri) {\n 'use strict';\n // See @return comment -- never null.\n var result = /** @type {!Array<string|undefined>} */ (\n uri.match(goog.uri.utils.splitRe_));\n if (goog.uri.utils.urlPackageSupportLoggingHandler_ &&\n ['http', 'https', 'ws', 'wss',\n 'ftp'].indexOf(result[goog.uri.utils.ComponentIndex.SCHEME]) >= 0) {\n goog.uri.utils.urlPackageSupportLoggingHandler_(uri);\n }\n return result;\n};\n\n\n/**\n * @param {?string} uri A possibly null string.\n * @param {boolean=} opt_preserveReserved If true, percent-encoding of RFC-3986\n * reserved characters will not be removed.\n * @return {?string} The string URI-decoded, or null if uri is null.\n * @private\n */\ngoog.uri.utils.decodeIfPossible_ = function(uri, opt_preserveReserved) {\n 'use strict';\n if (!uri) {\n return uri;\n }\n\n return opt_preserveReserved ? decodeURI(uri) : decodeURIComponent(uri);\n};\n\n\n/**\n * Gets a URI component by index.\n *\n * It is preferred to use the getPathEncoded() variety of functions ahead,\n * since they are more readable.\n *\n * @param {goog.uri.utils.ComponentIndex} componentIndex The component index.\n * @param {string} uri The URI to examine.\n * @return {?string} The still-encoded component, or null if the component\n * is not present.\n * @private\n */\ngoog.uri.utils.getComponentByIndex_ = function(componentIndex, uri) {\n 'use strict';\n // Convert undefined, null, and empty string into null.\n return goog.uri.utils.split(uri)[componentIndex] || null;\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The protocol or scheme, or null if none. Does not\n * include trailing colons or slashes.\n */\ngoog.uri.utils.getScheme = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.SCHEME, uri);\n};\n\n\n/**\n * Gets the effective scheme for the URL. If the URL is relative then the\n * scheme is derived from the page's location.\n * @param {string} uri The URI to examine.\n * @return {string} The protocol or scheme, always lower case.\n */\ngoog.uri.utils.getEffectiveScheme = function(uri) {\n 'use strict';\n var scheme = goog.uri.utils.getScheme(uri);\n if (!scheme && goog.global.self && goog.global.self.location) {\n var protocol = goog.global.self.location.protocol;\n scheme = protocol.slice(0, -1);\n }\n // NOTE: When called from a web worker in Firefox 3.5, location may be null.\n // All other browsers with web workers support self.location from the worker.\n return scheme ? scheme.toLowerCase() : '';\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The user name still encoded, or null if none.\n */\ngoog.uri.utils.getUserInfoEncoded = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.USER_INFO, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded user info, or null if none.\n */\ngoog.uri.utils.getUserInfo = function(uri) {\n 'use strict';\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getUserInfoEncoded(uri));\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The domain name still encoded, or null if none.\n */\ngoog.uri.utils.getDomainEncoded = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.DOMAIN, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded domain, or null if none.\n */\ngoog.uri.utils.getDomain = function(uri) {\n 'use strict';\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getDomainEncoded(uri), true /* opt_preserveReserved */);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?number} The port number, or null if none.\n */\ngoog.uri.utils.getPort = function(uri) {\n 'use strict';\n // Coerce to a number. If the result of getComponentByIndex_ is null or\n // non-numeric, the number coersion yields NaN. This will then return\n // null for all non-numeric cases (though also zero, which isn't a relevant\n // port number).\n return Number(\n goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.PORT, uri)) ||\n null;\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The path still encoded, or null if none. Includes the\n * leading slash, if any.\n */\ngoog.uri.utils.getPathEncoded = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.PATH, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded path, or null if none. Includes the leading\n * slash, if any.\n */\ngoog.uri.utils.getPath = function(uri) {\n 'use strict';\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getPathEncoded(uri), true /* opt_preserveReserved */);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The query data still encoded, or null if none. Does not\n * include the question mark itself.\n */\ngoog.uri.utils.getQueryData = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.QUERY_DATA, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The fragment identifier, or null if none. Does not\n * include the hash mark itself.\n */\ngoog.uri.utils.getFragmentEncoded = function(uri) {\n 'use strict';\n // The hash mark may not appear in any other part of the URL.\n var hashIndex = uri.indexOf('#');\n return hashIndex < 0 ? null : uri.slice(hashIndex + 1);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @param {?string} fragment The encoded fragment identifier, or null if none.\n * Does not include the hash mark itself.\n * @return {string} The URI with the fragment set.\n */\ngoog.uri.utils.setFragmentEncoded = function(uri, fragment) {\n 'use strict';\n return goog.uri.utils.removeFragment(uri) + (fragment ? '#' + fragment : '');\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded fragment identifier, or null if none. Does\n * not include the hash mark.\n */\ngoog.uri.utils.getFragment = function(uri) {\n 'use strict';\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getFragmentEncoded(uri));\n};\n\n\n/**\n * Extracts everything up to the port of the URI.\n * @param {string} uri The URI string.\n * @return {string} Everything up to and including the port.\n */\ngoog.uri.utils.getHost = function(uri) {\n 'use strict';\n var pieces = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n pieces[goog.uri.utils.ComponentIndex.SCHEME],\n pieces[goog.uri.utils.ComponentIndex.USER_INFO],\n pieces[goog.uri.utils.ComponentIndex.DOMAIN],\n pieces[goog.uri.utils.ComponentIndex.PORT]);\n};\n\n\n/**\n * Returns the origin for a given URL.\n * @param {string} uri The URI string.\n * @return {string} Everything up to and including the port.\n */\ngoog.uri.utils.getOrigin = function(uri) {\n 'use strict';\n var pieces = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n pieces[goog.uri.utils.ComponentIndex.SCHEME], null /* opt_userInfo */,\n pieces[goog.uri.utils.ComponentIndex.DOMAIN],\n pieces[goog.uri.utils.ComponentIndex.PORT]);\n};\n\n\n/**\n * Extracts the path of the URL and everything after.\n * @param {string} uri The URI string.\n * @return {string} The URI, starting at the path and including the query\n * parameters and fragment identifier.\n */\ngoog.uri.utils.getPathAndAfter = function(uri) {\n 'use strict';\n var pieces = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n null, null, null, null, pieces[goog.uri.utils.ComponentIndex.PATH],\n pieces[goog.uri.utils.ComponentIndex.QUERY_DATA],\n pieces[goog.uri.utils.ComponentIndex.FRAGMENT]);\n};\n\n\n/**\n * Gets the URI with the fragment identifier removed.\n * @param {string} uri The URI to examine.\n * @return {string} Everything preceding the hash mark.\n */\ngoog.uri.utils.removeFragment = function(uri) {\n 'use strict';\n // The hash mark may not appear in any other part of the URL.\n var hashIndex = uri.indexOf('#');\n return hashIndex < 0 ? uri : uri.slice(0, hashIndex);\n};\n\n\n/**\n * Ensures that two URI's have the exact same domain, scheme, and port.\n *\n * Unlike the version in goog.Uri, this checks protocol, and therefore is\n * suitable for checking against the browser's same-origin policy.\n *\n * @param {string} uri1 The first URI.\n * @param {string} uri2 The second URI.\n * @return {boolean} Whether they have the same scheme, domain and port.\n */\ngoog.uri.utils.haveSameDomain = function(uri1, uri2) {\n 'use strict';\n var pieces1 = goog.uri.utils.split(uri1);\n var pieces2 = goog.uri.utils.split(uri2);\n return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==\n pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&\n pieces1[goog.uri.utils.ComponentIndex.SCHEME] ==\n pieces2[goog.uri.utils.ComponentIndex.SCHEME] &&\n pieces1[goog.uri.utils.ComponentIndex.PORT] ==\n pieces2[goog.uri.utils.ComponentIndex.PORT];\n};\n\n\n/**\n * Asserts that there are no fragment or query identifiers, only in uncompiled\n * mode.\n * @param {string} uri The URI to examine.\n * @private\n */\ngoog.uri.utils.assertNoFragmentsOrQueries_ = function(uri) {\n 'use strict';\n goog.asserts.assert(\n uri.indexOf('#') < 0 && uri.indexOf('?') < 0,\n 'goog.uri.utils: Fragment or query identifiers are not supported: [%s]',\n uri);\n};\n\n\n/**\n * Supported query parameter values by the parameter serializing utilities.\n *\n * If a value is null or undefined, the key-value pair is skipped, as an easy\n * way to omit parameters conditionally. Non-array parameters are converted\n * to a string and URI encoded. Array values are expanded into multiple\n * &key=value pairs, with each element stringized and URI-encoded.\n *\n * @typedef {*}\n */\ngoog.uri.utils.QueryValue;\n\n\n/**\n * An array representing a set of query parameters with alternating keys\n * and values.\n *\n * Keys are assumed to be URI encoded already and live at even indices. See\n * goog.uri.utils.QueryValue for details on how parameter values are encoded.\n *\n * Example:\n * <pre>\n * var data = [\n * // Simple param: ?name=BobBarker\n * 'name', 'BobBarker',\n * // Conditional param -- may be omitted entirely.\n * 'specialDietaryNeeds', hasDietaryNeeds() ? getDietaryNeeds() : null,\n * // Multi-valued param: &house=LosAngeles&house=NewYork&house=null\n * 'house', ['LosAngeles', 'NewYork', null]\n * ];\n * </pre>\n *\n * @typedef {!Array<string|goog.uri.utils.QueryValue>}\n */\ngoog.uri.utils.QueryArray;\n\n\n/**\n * Parses encoded query parameters and calls callback function for every\n * parameter found in the string.\n *\n * Missing value of parameter (e.g. “…&key&…”) is treated as if the value was an\n * empty string. Keys may be empty strings (e.g. “…&=value&…”) which also means\n * that “…&=&…” and “…&&…” will result in an empty key and value.\n *\n * @param {string} encodedQuery Encoded query string excluding question mark at\n * the beginning.\n * @param {function(string, string)} callback Function called for every\n * parameter found in query string. The first argument (name) will not be\n * urldecoded (so the function is consistent with buildQueryData), but the\n * second will. If the parameter has no value (i.e. “=” was not present)\n * the second argument (value) will be an empty string.\n */\ngoog.uri.utils.parseQueryData = function(encodedQuery, callback) {\n 'use strict';\n if (!encodedQuery) {\n return;\n }\n var pairs = encodedQuery.split('&');\n for (var i = 0; i < pairs.length; i++) {\n var indexOfEquals = pairs[i].indexOf('=');\n var name = null;\n var value = null;\n if (indexOfEquals >= 0) {\n name = pairs[i].substring(0, indexOfEquals);\n value = pairs[i].substring(indexOfEquals + 1);\n } else {\n name = pairs[i];\n }\n callback(name, value ? goog.string.urlDecode(value) : '');\n }\n};\n\n\n/**\n * Split the URI into 3 parts where the [1] is the queryData without a leading\n * '?'. For example, the URI http://foo.com/bar?a=b#abc returns\n * ['http://foo.com/bar','a=b','#abc'].\n * @param {string} uri The URI to parse.\n * @return {!Array<string>} An array representation of uri of length 3 where the\n * middle value is the queryData without a leading '?'.\n * @private\n */\ngoog.uri.utils.splitQueryData_ = function(uri) {\n 'use strict';\n // Find the query data and hash.\n var hashIndex = uri.indexOf('#');\n if (hashIndex < 0) {\n hashIndex = uri.length;\n }\n var questionIndex = uri.indexOf('?');\n var queryData;\n if (questionIndex < 0 || questionIndex > hashIndex) {\n questionIndex = hashIndex;\n queryData = '';\n } else {\n queryData = uri.substring(questionIndex + 1, hashIndex);\n }\n return [uri.slice(0, questionIndex), queryData, uri.slice(hashIndex)];\n};\n\n\n/**\n * Join an array created by splitQueryData_ back into a URI.\n * @param {!Array<string>} parts A URI in the form generated by splitQueryData_.\n * @return {string} The joined URI.\n * @private\n */\ngoog.uri.utils.joinQueryData_ = function(parts) {\n 'use strict';\n return parts[0] + (parts[1] ? '?' + parts[1] : '') + parts[2];\n};\n\n\n/**\n * @param {string} queryData\n * @param {string} newData\n * @return {string}\n * @private\n */\ngoog.uri.utils.appendQueryData_ = function(queryData, newData) {\n 'use strict';\n if (!newData) {\n return queryData;\n }\n return queryData ? queryData + '&' + newData : newData;\n};\n\n\n/**\n * @param {string} uri\n * @param {string} queryData\n * @return {string}\n * @private\n */\ngoog.uri.utils.appendQueryDataToUri_ = function(uri, queryData) {\n 'use strict';\n if (!queryData) {\n return uri;\n }\n var parts = goog.uri.utils.splitQueryData_(uri);\n parts[1] = goog.uri.utils.appendQueryData_(parts[1], queryData);\n return goog.uri.utils.joinQueryData_(parts);\n};\n\n\n/**\n * Appends key=value pairs to an array, supporting multi-valued objects.\n * @param {*} key The key prefix.\n * @param {goog.uri.utils.QueryValue} value The value to serialize.\n * @param {!Array<string>} pairs The array to which the 'key=value' strings\n * should be appended.\n * @private\n */\ngoog.uri.utils.appendKeyValuePairs_ = function(key, value, pairs) {\n 'use strict';\n goog.asserts.assertString(key);\n if (Array.isArray(value)) {\n // Convince the compiler it's an array.\n goog.asserts.assertArray(value);\n for (var j = 0; j < value.length; j++) {\n // Convert to string explicitly, to short circuit the null and array\n // logic in this function -- this ensures that null and undefined get\n // written as literal 'null' and 'undefined', and arrays don't get\n // expanded out but instead encoded in the default way.\n goog.uri.utils.appendKeyValuePairs_(key, String(value[j]), pairs);\n }\n } else if (value != null) {\n // Skip a top-level null or undefined entirely.\n pairs.push(\n key +\n // Check for empty string. Zero gets encoded into the url as literal\n // strings. For empty string, skip the equal sign, to be consistent\n // with UriBuilder.java.\n (value === '' ? '' : '=' + goog.string.urlEncode(value)));\n }\n};\n\n\n/**\n * Builds a query data string from a sequence of alternating keys and values.\n * Currently generates \"&key&\" for empty args.\n *\n * @param {!IArrayLike<string|goog.uri.utils.QueryValue>} keysAndValues\n * Alternating keys and values. See the QueryArray typedef.\n * @param {number=} opt_startIndex A start offset into the arary, defaults to 0.\n * @return {string} The encoded query string, in the form 'a=1&b=2'.\n */\ngoog.uri.utils.buildQueryData = function(keysAndValues, opt_startIndex) {\n 'use strict';\n goog.asserts.assert(\n Math.max(keysAndValues.length - (opt_startIndex || 0), 0) % 2 == 0,\n 'goog.uri.utils: Key/value lists must be even in length.');\n\n var params = [];\n for (var i = opt_startIndex || 0; i < keysAndValues.length; i += 2) {\n var key = /** @type {string} */ (keysAndValues[i]);\n goog.uri.utils.appendKeyValuePairs_(key, keysAndValues[i + 1], params);\n }\n return params.join('&');\n};\n\n\n/**\n * Builds a query data string from a map.\n * Currently generates \"&key&\" for empty args.\n *\n * @param {!Object<string, goog.uri.utils.QueryValue>} map An object where keys\n * are URI-encoded parameter keys, and the values are arbitrary types\n * or arrays. Keys with a null value are dropped.\n * @return {string} The encoded query string, in the form 'a=1&b=2'.\n */\ngoog.uri.utils.buildQueryDataFromMap = function(map) {\n 'use strict';\n var params = [];\n for (var key in map) {\n goog.uri.utils.appendKeyValuePairs_(key, map[key], params);\n }\n return params.join('&');\n};\n\n\n/**\n * Appends URI parameters to an existing URI.\n *\n * The variable arguments may contain alternating keys and values. Keys are\n * assumed to be already URI encoded. The values should not be URI-encoded,\n * and will instead be encoded by this function.\n * <pre>\n * appendParams('http://www.foo.com?existing=true',\n * 'key1', 'value1',\n * 'key2', 'value?willBeEncoded',\n * 'key3', ['valueA', 'valueB', 'valueC'],\n * 'key4', null);\n * result: 'http://www.foo.com?existing=true&' +\n * 'key1=value1&' +\n * 'key2=value%3FwillBeEncoded&' +\n * 'key3=valueA&key3=valueB&key3=valueC'\n * </pre>\n *\n * A single call to this function will not exhibit quadratic behavior in IE,\n * whereas multiple repeated calls may, although the effect is limited by\n * fact that URL's generally can't exceed 2kb.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {...(goog.uri.utils.QueryArray|goog.uri.utils.QueryValue)}\n * var_args\n * An array or argument list conforming to goog.uri.utils.QueryArray.\n * @return {string} The URI with all query parameters added.\n */\ngoog.uri.utils.appendParams = function(uri, var_args) {\n 'use strict';\n var queryData = arguments.length == 2 ?\n goog.uri.utils.buildQueryData(arguments[1], 0) :\n goog.uri.utils.buildQueryData(arguments, 1);\n return goog.uri.utils.appendQueryDataToUri_(uri, queryData);\n};\n\n\n/**\n * Appends query parameters from a map.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {!Object<goog.uri.utils.QueryValue>} map An object where keys are\n * URI-encoded parameter keys, and the values are arbitrary types or arrays.\n * Keys with a null value are dropped.\n * @return {string} The new parameters.\n */\ngoog.uri.utils.appendParamsFromMap = function(uri, map) {\n 'use strict';\n var queryData = goog.uri.utils.buildQueryDataFromMap(map);\n return goog.uri.utils.appendQueryDataToUri_(uri, queryData);\n};\n\n\n/**\n * Appends a single URI parameter.\n *\n * Repeated calls to this can exhibit quadratic behavior in IE6 due to the\n * way string append works, though it should be limited given the 2kb limit.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {string} key The key, which must already be URI encoded.\n * @param {*=} opt_value The value, which will be stringized and encoded\n * (assumed not already to be encoded). If omitted, undefined, or null, the\n * key will be added as a valueless parameter.\n * @return {string} The URI with the query parameter added.\n */\ngoog.uri.utils.appendParam = function(uri, key, opt_value) {\n 'use strict';\n var value = (opt_value != null) ? '=' + goog.string.urlEncode(opt_value) : '';\n return goog.uri.utils.appendQueryDataToUri_(uri, key + value);\n};\n\n\n/**\n * Finds the next instance of a query parameter with the specified name.\n *\n * Does not instantiate any objects.\n *\n * @param {string} uri The URI to search. May contain a fragment identifier\n * if opt_hashIndex is specified.\n * @param {number} startIndex The index to begin searching for the key at. A\n * match may be found even if this is one character after the ampersand.\n * @param {string} keyEncoded The URI-encoded key.\n * @param {number} hashOrEndIndex Index to stop looking at. If a hash\n * mark is present, it should be its index, otherwise it should be the\n * length of the string.\n * @return {number} The position of the first character in the key's name,\n * immediately after either a question mark or a dot.\n * @private\n */\ngoog.uri.utils.findParam_ = function(\n uri, startIndex, keyEncoded, hashOrEndIndex) {\n 'use strict';\n var index = startIndex;\n var keyLength = keyEncoded.length;\n\n // Search for the key itself and post-filter for surronuding punctuation,\n // rather than expensively building a regexp.\n while ((index = uri.indexOf(keyEncoded, index)) >= 0 &&\n index < hashOrEndIndex) {\n var precedingChar = uri.charCodeAt(index - 1);\n // Ensure that the preceding character is '&' or '?'.\n if (precedingChar == goog.uri.utils.CharCode_.AMPERSAND ||\n precedingChar == goog.uri.utils.CharCode_.QUESTION) {\n // Ensure the following character is '&', '=', '#', or NaN\n // (end of string).\n var followingChar = uri.charCodeAt(index + keyLength);\n if (!followingChar || followingChar == goog.uri.utils.CharCode_.EQUAL ||\n followingChar == goog.uri.utils.CharCode_.AMPERSAND ||\n followingChar == goog.uri.utils.CharCode_.HASH) {\n return index;\n }\n }\n index += keyLength + 1;\n }\n\n return -1;\n};\n\n\n/**\n * Regular expression for finding a hash mark or end of string.\n * @type {RegExp}\n * @private\n */\ngoog.uri.utils.hashOrEndRe_ = /#|$/;\n\n\n/**\n * Determines if the URI contains a specific key.\n *\n * Performs no object instantiations.\n *\n * @param {string} uri The URI to process. May contain a fragment\n * identifier.\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\n * @return {boolean} Whether the key is present.\n */\ngoog.uri.utils.hasParam = function(uri, keyEncoded) {\n 'use strict';\n return goog.uri.utils.findParam_(\n uri, 0, keyEncoded, uri.search(goog.uri.utils.hashOrEndRe_)) >= 0;\n};\n\n\n/**\n * Gets the first value of a query parameter.\n * @param {string} uri The URI to process. May contain a fragment.\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\n * @return {?string} The first value of the parameter (URI-decoded), or null\n * if the parameter is not found.\n */\ngoog.uri.utils.getParamValue = function(uri, keyEncoded) {\n 'use strict';\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\n var foundIndex =\n goog.uri.utils.findParam_(uri, 0, keyEncoded, hashOrEndIndex);\n\n if (foundIndex < 0) {\n return null;\n } else {\n var endPosition = uri.indexOf('&', foundIndex);\n if (endPosition < 0 || endPosition > hashOrEndIndex) {\n endPosition = hashOrEndIndex;\n }\n // Progress forth to the end of the \"key=\" or \"key&\" substring.\n foundIndex += keyEncoded.length + 1;\n return goog.string.urlDecode(\n uri.slice(foundIndex, endPosition !== -1 ? endPosition : 0));\n }\n};\n\n\n/**\n * Gets all values of a query parameter.\n * @param {string} uri The URI to process. May contain a fragment.\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\n * @return {!Array<string>} All URI-decoded values with the given key.\n * If the key is not found, this will have length 0, but never be null.\n */\ngoog.uri.utils.getParamValues = function(uri, keyEncoded) {\n 'use strict';\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\n var position = 0;\n var foundIndex;\n var result = [];\n\n while ((foundIndex = goog.uri.utils.findParam_(\n uri, position, keyEncoded, hashOrEndIndex)) >= 0) {\n // Find where this parameter ends, either the '&' or the end of the\n // query parameters.\n position = uri.indexOf('&', foundIndex);\n if (position < 0 || position > hashOrEndIndex) {\n position = hashOrEndIndex;\n }\n\n // Progress forth to the end of the \"key=\" or \"key&\" substring.\n foundIndex += keyEncoded.length + 1;\n result.push(\n goog.string.urlDecode(uri.slice(foundIndex, Math.max(position, 0))));\n }\n\n return result;\n};\n\n\n/**\n * Regexp to find trailing question marks and ampersands.\n * @type {RegExp}\n * @private\n */\ngoog.uri.utils.trailingQueryPunctuationRe_ = /[?&]($|#)/;\n\n\n/**\n * Removes all instances of a query parameter.\n * @param {string} uri The URI to process. Must not contain a fragment.\n * @param {string} keyEncoded The URI-encoded key.\n * @return {string} The URI with all instances of the parameter removed.\n */\ngoog.uri.utils.removeParam = function(uri, keyEncoded) {\n 'use strict';\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\n var position = 0;\n var foundIndex;\n var buffer = [];\n\n // Look for a query parameter.\n while ((foundIndex = goog.uri.utils.findParam_(\n uri, position, keyEncoded, hashOrEndIndex)) >= 0) {\n // Get the portion of the query string up to, but not including, the ?\n // or & starting the parameter.\n buffer.push(uri.substring(position, foundIndex));\n // Progress to immediately after the '&'. If not found, go to the end.\n // Avoid including the hash mark.\n position = Math.min(\n (uri.indexOf('&', foundIndex) + 1) || hashOrEndIndex, hashOrEndIndex);\n }\n\n // Append everything that is remaining.\n buffer.push(uri.slice(position));\n\n // Join the buffer, and remove trailing punctuation that remains.\n return buffer.join('').replace(\n goog.uri.utils.trailingQueryPunctuationRe_, '$1');\n};\n\n\n/**\n * Replaces all existing definitions of a parameter with a single definition.\n *\n * Repeated calls to this can exhibit quadratic behavior due to the need to\n * find existing instances and reconstruct the string, though it should be\n * limited given the 2kb limit. Consider using appendParams or setParamsFromMap\n * to update multiple parameters in bulk.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {string} keyEncoded The key, which must already be URI encoded.\n * @param {*} value The value, which will be stringized and encoded (assumed\n * not already to be encoded).\n * @return {string} The URI with the query parameter added.\n */\ngoog.uri.utils.setParam = function(uri, keyEncoded, value) {\n 'use strict';\n return goog.uri.utils.appendParam(\n goog.uri.utils.removeParam(uri, keyEncoded), keyEncoded, value);\n};\n\n\n/**\n * Effeciently set or remove multiple query parameters in a URI. Order of\n * unchanged parameters will not be modified, all updated parameters will be\n * appended to the end of the query. Params with values of null or undefined are\n * removed.\n *\n * @param {string} uri The URI to process.\n * @param {!Object<string, goog.uri.utils.QueryValue>} params A list of\n * parameters to update. If null or undefined, the param will be removed.\n * @return {string} An updated URI where the query data has been updated with\n * the params.\n */\ngoog.uri.utils.setParamsFromMap = function(uri, params) {\n 'use strict';\n var parts = goog.uri.utils.splitQueryData_(uri);\n var queryData = parts[1];\n var buffer = [];\n if (queryData) {\n queryData.split('&').forEach(function(pair) {\n 'use strict';\n var indexOfEquals = pair.indexOf('=');\n var name = indexOfEquals >= 0 ? pair.slice(0, indexOfEquals) : pair;\n if (!params.hasOwnProperty(name)) {\n buffer.push(pair);\n }\n });\n }\n parts[1] = goog.uri.utils.appendQueryData_(\n buffer.join('&'), goog.uri.utils.buildQueryDataFromMap(params));\n return goog.uri.utils.joinQueryData_(parts);\n};\n\n\n/**\n * Generates a URI path using a given URI and a path with checks to\n * prevent consecutive \"//\". The baseUri passed in must not contain\n * query or fragment identifiers. The path to append may not contain query or\n * fragment identifiers.\n *\n * @param {string} baseUri URI to use as the base.\n * @param {string} path Path to append.\n * @return {string} Updated URI.\n */\ngoog.uri.utils.appendPath = function(baseUri, path) {\n 'use strict';\n goog.uri.utils.assertNoFragmentsOrQueries_(baseUri);\n\n // Remove any trailing '/'\n if (goog.string.endsWith(baseUri, '/')) {\n baseUri = baseUri.slice(0, -1);\n }\n // Remove any leading '/'\n if (goog.string.startsWith(path, '/')) {\n path = path.slice(1);\n }\n return '' + baseUri + '/' + path;\n};\n\n\n/**\n * Replaces the path.\n * @param {string} uri URI to use as the base.\n * @param {string} path New path.\n * @return {string} Updated URI.\n */\ngoog.uri.utils.setPath = function(uri, path) {\n 'use strict';\n // Add any missing '/'.\n if (!goog.string.startsWith(path, '/')) {\n path = '/' + path;\n }\n var parts = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n parts[goog.uri.utils.ComponentIndex.SCHEME],\n parts[goog.uri.utils.ComponentIndex.USER_INFO],\n parts[goog.uri.utils.ComponentIndex.DOMAIN],\n parts[goog.uri.utils.ComponentIndex.PORT], path,\n parts[goog.uri.utils.ComponentIndex.QUERY_DATA],\n parts[goog.uri.utils.ComponentIndex.FRAGMENT]);\n};\n\n\n/**\n * Standard supported query parameters.\n * @enum {string}\n */\ngoog.uri.utils.StandardQueryParam = {\n\n /** Unused parameter for unique-ifying. */\n RANDOM: 'zx'\n};\n\n\n/**\n * Sets the zx parameter of a URI to a random value.\n * @param {string} uri Any URI.\n * @return {string} That URI with the \"zx\" parameter added or replaced to\n * contain a random string.\n */\ngoog.uri.utils.makeUnique = function(uri) {\n 'use strict';\n return goog.uri.utils.setParam(\n uri, goog.uri.utils.StandardQueryParam.RANDOM,\n goog.string.getRandomString());\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Interface and shared data structures for implementing\n * different wire protocol versions.\n */\ngoog.provide('goog.labs.net.webChannel.Wire');\ngoog.provide('goog.labs.net.webChannel.Wire.QueuedMap');\n\n\n\ngoog.require('goog.collections.maps');\n\n\n\n/**\n * The interface class.\n * @interface\n */\ngoog.labs.net.webChannel.Wire = class {\n constructor() {}\n};\n\n\n/**\n * The latest protocol version that this class supports. We request this version\n * from the server when opening the connection. Should match\n * LATEST_CHANNEL_VERSION on the server code.\n * @type {number}\n */\ngoog.labs.net.webChannel.Wire.LATEST_CHANNEL_VERSION = 8;\n\n\n/**\n * The JSON field key for the raw data wrapper object.\n * @type {string}\n */\ngoog.labs.net.webChannel.Wire.RAW_DATA_KEY = '__data__';\n\n\n\n/**\n * Simple container class for a (mapId, map) pair.\n */\ngoog.labs.net.webChannel.Wire.QueuedMap = class {\n /**\n * @param {number} mapId The id for this map.\n * @param {!Object|!goog.collections.maps.MapLike} map The map itself.\n * @param {!Object=} opt_context The context associated with the map.\n */\n constructor(mapId, map, opt_context) {\n 'use strict';\n /**\n * The id for this map.\n * @type {number}\n */\n this.mapId = mapId;\n\n /**\n * The map itself.\n * @type {!Object|!goog.collections.maps.MapLike}\n */\n this.map = map;\n\n /**\n * The context for the map.\n * @type {Object}\n */\n this.context = opt_context || null;\n }\n\n /**\n * @return {number|undefined} the size of the raw JSON message or\n * undefined if the message is not encoded as a raw JSON message\n */\n getRawDataSize() {\n 'use strict';\n if (goog.labs.net.webChannel.Wire.RAW_DATA_KEY in this.map) {\n const data = this.map[goog.labs.net.webChannel.Wire.RAW_DATA_KEY];\n if (typeof data === 'string') {\n return data.length;\n }\n }\n\n return undefined;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n\n/**\n * @fileoverview Defines a class for parsing JSON using the browser's built in\n * JSON library.\n */\n\ngoog.module('goog.json.NativeJsonProcessor');\ngoog.module.declareLegacyNamespace();\n\nconst Parser = goog.require('goog.string.Parser');\nconst Stringifier = goog.require('goog.string.Stringifier');\nconst asserts = goog.require('goog.asserts');\nconst {Replacer, Reviver} = goog.require('goog.json.types');\n\n\n\n/**\n * A class that parses and stringifies JSON using the browser's built-in JSON\n * library.\n *\n\n * @implements {Parser}\n * @implements {Stringifier}\n * @final\n */\nexports = class {\n /**\n * @param {?Replacer=} opt_replacer An optional replacer to use during\n * serialization.\n * @param {?=} opt_reviver An optional reviver to use during\n * parsing.\n */\n constructor(opt_replacer, opt_reviver) {\n asserts.assert(goog.global['JSON'] !== undefined, 'JSON not defined');\n\n /**\n * @type {!Replacer|null|undefined}\n * @private\n */\n this.replacer_ = opt_replacer;\n\n /**\n * @type {!Reviver|null|undefined}\n * @private\n */\n this.reviver_ = opt_reviver;\n };\n\n /**\n * Serializes an object or a value to a string.\n * Agnostic to the particular format of object and string.\n *\n * @param {*} object The object to stringify.\n * @return {string} A string representation of the input.\n * @override\n */\n stringify(object) {\n return goog.global['JSON'].stringify(object, this.replacer_);\n }\n\n /**\n * Parses a string into an object and returns the result.\n * Agnostic to the format of string and object.\n *\n * @param {string} s The string to parse.\n * @return {*} The object generated from the string.\n * @override\n */\n parse(s) {\n return goog.global['JSON'].parse(s, this.reviver_);\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for creating functions. Loosely inspired by these\n * java classes from the Guava library:\n * com.google.common.base.Functions\n * https://google.github.io/guava/releases/snapshot-jre/api/docs/index.html?com/google/common/base/Functions.html\n *\n * com.google.common.base.Predicates\n * https://google.github.io/guava/releases/snapshot-jre/api/docs/index.html?com/google/common/base/Predicates.html\n *\n * More about these can be found at\n * https://github.com/google/guava/wiki/FunctionalExplained\n */\n\n\ngoog.provide('goog.functions');\n\n\n/**\n * Creates a function that always returns the same value.\n * @param {T} retValue The value to return.\n * @return {function():T} The new function.\n * @template T\n */\ngoog.functions.constant = function(retValue) {\n 'use strict';\n return function() {\n 'use strict';\n return retValue;\n };\n};\n\n\n/**\n * Always returns false.\n * @type {function(...): boolean}\n */\ngoog.functions.FALSE = function() {\n 'use strict';\n return false;\n};\n\n\n/**\n * Always returns true.\n * @type {function(...): boolean}\n */\ngoog.functions.TRUE = function() {\n 'use strict';\n return true;\n};\n\n\n/**\n * Always returns `null`.\n * @type {function(...): null}\n */\ngoog.functions.NULL = function() {\n 'use strict';\n return null;\n};\n\n\n/**\n * Always returns `undefined`.\n * @type {function(...): undefined}\n */\ngoog.functions.UNDEFINED = function() {\n return undefined;\n};\n\n/**\n * Always returns `undefined` (loosely-typed version).\n * @type {!Function}\n */\ngoog.functions.EMPTY = /** @type {?} */ (goog.functions.UNDEFINED);\n\n\n/**\n * A simple function that returns the first argument of whatever is passed\n * into it.\n * @param {T=} opt_returnValue The single value that will be returned.\n * @param {...*} var_args Optional trailing arguments. These are ignored.\n * @return {T} The first argument passed in, or undefined if nothing was passed.\n * @template T\n */\ngoog.functions.identity = function(opt_returnValue, var_args) {\n 'use strict';\n return opt_returnValue;\n};\n\n\n/**\n * Creates a function that always throws an error with the given message.\n * @param {string} message The error message.\n * @return {!Function} The error-throwing function.\n */\ngoog.functions.error = function(message) {\n 'use strict';\n return function() {\n 'use strict';\n throw new Error(message);\n };\n};\n\n\n/**\n * Creates a function that throws the given object.\n * @param {*} err An object to be thrown.\n * @return {!Function} The error-throwing function.\n */\ngoog.functions.fail = function(err) {\n 'use strict';\n return function() {\n 'use strict';\n throw err;\n };\n};\n\n\n/**\n * Given a function, create a function that keeps opt_numArgs arguments and\n * silently discards all additional arguments.\n * @param {Function} f The original function.\n * @param {number=} opt_numArgs The number of arguments to keep. Defaults to 0.\n * @return {!Function} A version of f that only keeps the first opt_numArgs\n * arguments.\n */\ngoog.functions.lock = function(f, opt_numArgs) {\n 'use strict';\n opt_numArgs = opt_numArgs || 0;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n return f.apply(self, Array.prototype.slice.call(arguments, 0, opt_numArgs));\n };\n};\n\n\n/**\n * Creates a function that returns its nth argument.\n * @param {number} n The position of the return argument.\n * @return {!Function} A new function.\n */\ngoog.functions.nth = function(n) {\n 'use strict';\n return function() {\n 'use strict';\n return arguments[n];\n };\n};\n\n\n/**\n * Like goog.partial(), except that arguments are added after arguments to the\n * returned function.\n *\n * Usage:\n * function f(arg1, arg2, arg3, arg4) { ... }\n * var g = goog.functions.partialRight(f, arg3, arg4);\n * g(arg1, arg2);\n *\n * @param {!Function} fn A function to partially apply.\n * @param {...*} var_args Additional arguments that are partially applied to fn\n * at the end.\n * @return {!Function} A partially-applied form of the function goog.partial()\n * was invoked as a method of.\n */\ngoog.functions.partialRight = function(fn, var_args) {\n 'use strict';\n const rightArgs = Array.prototype.slice.call(arguments, 1);\n return function() {\n 'use strict';\n // Even in strict mode, IE10/11 and Edge (non-Chromium) use global context\n // when free-calling functions. To catch cases where people were using this\n // erroneously, we explicitly change the context to undefined to match\n // strict mode specifications.\n let self = /** @type {*} */ (this);\n if (self === goog.global) {\n self = undefined;\n }\n const newArgs = Array.prototype.slice.call(arguments);\n newArgs.push.apply(newArgs, rightArgs);\n return fn.apply(self, newArgs);\n };\n};\n\n\n/**\n * Given a function, create a new function that swallows its return value\n * and replaces it with a new one.\n * @param {Function} f A function.\n * @param {T} retValue A new return value.\n * @return {function(...?):T} A new function.\n * @template T\n */\ngoog.functions.withReturnValue = function(f, retValue) {\n 'use strict';\n return goog.functions.sequence(f, goog.functions.constant(retValue));\n};\n\n\n/**\n * Creates a function that returns whether its argument equals the given value.\n *\n * Example:\n * var key = goog.object.findKey(obj, goog.functions.equalTo('needle'));\n *\n * @param {*} value The value to compare to.\n * @param {boolean=} opt_useLooseComparison Whether to use a loose (==)\n * comparison rather than a strict (===) one. Defaults to false.\n * @return {function(*):boolean} The new function.\n */\ngoog.functions.equalTo = function(value, opt_useLooseComparison) {\n 'use strict';\n return function(other) {\n 'use strict';\n return opt_useLooseComparison ? (value == other) : (value === other);\n };\n};\n\n\n/**\n * Creates the composition of the functions passed in.\n * For example, (goog.functions.compose(f, g))(a) is equivalent to f(g(a)).\n * @param {function(...?):T} fn The final function.\n * @param {...Function} var_args A list of functions.\n * @return {function(...?):T} The composition of all inputs.\n * @template T\n */\ngoog.functions.compose = function(fn, var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n let result;\n if (length) {\n result = functions[length - 1].apply(self, arguments);\n }\n\n for (let i = length - 2; i >= 0; i--) {\n result = functions[i].call(self, result);\n }\n return result;\n };\n};\n\n\n/**\n * Creates a function that calls the functions passed in in sequence, and\n * returns the value of the last function. For example,\n * (goog.functions.sequence(f, g))(x) is equivalent to f(x),g(x).\n * @param {...Function} var_args A list of functions.\n * @return {!Function} A function that calls all inputs in sequence.\n */\ngoog.functions.sequence = function(var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n let result;\n for (let i = 0; i < length; i++) {\n result = functions[i].apply(self, arguments);\n }\n return result;\n };\n};\n\n\n/**\n * Creates a function that returns true if each of its components evaluates\n * to true. The components are evaluated in order, and the evaluation will be\n * short-circuited as soon as a function returns false.\n * For example, (goog.functions.and(f, g))(x) is equivalent to f(x) && g(x).\n * @param {...Function} var_args A list of functions.\n * @return {function(...?):boolean} A function that ANDs its component\n * functions.\n */\ngoog.functions.and = function(var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n for (let i = 0; i < length; i++) {\n if (!functions[i].apply(self, arguments)) {\n return false;\n }\n }\n return true;\n };\n};\n\n\n/**\n * Creates a function that returns true if any of its components evaluates\n * to true. The components are evaluated in order, and the evaluation will be\n * short-circuited as soon as a function returns true.\n * For example, (goog.functions.or(f, g))(x) is equivalent to f(x) || g(x).\n * @param {...Function} var_args A list of functions.\n * @return {function(...?):boolean} A function that ORs its component\n * functions.\n */\ngoog.functions.or = function(var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n for (let i = 0; i < length; i++) {\n if (functions[i].apply(self, arguments)) {\n return true;\n }\n }\n return false;\n };\n};\n\n\n/**\n * Creates a function that returns the Boolean opposite of a provided function.\n * For example, (goog.functions.not(f))(x) is equivalent to !f(x).\n * @param {!Function} f The original function.\n * @return {function(...?):boolean} A function that delegates to f and returns\n * opposite.\n */\ngoog.functions.not = function(f) {\n 'use strict';\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n return !f.apply(self, arguments);\n };\n};\n\n\n/**\n * Generic factory function to construct an object given the constructor\n * and the arguments. Intended to be bound to create object factories.\n *\n * Example:\n *\n * var factory = goog.partial(goog.functions.create, Class);\n *\n * @param {function(new:T, ...)} constructor The constructor for the Object.\n * @param {...*} var_args The arguments to be passed to the constructor.\n * @return {T} A new instance of the class given in `constructor`.\n * @template T\n * @deprecated This function does not work with ES6 class constructors. Use\n * arrow functions + spread args instead.\n */\ngoog.functions.create = function(constructor, var_args) {\n 'use strict';\n /**\n * @constructor\n * @final\n */\n const temp = function() {};\n temp.prototype = constructor.prototype;\n\n // obj will have constructor's prototype in its chain and\n // 'obj instanceof constructor' will be true.\n const obj = new temp();\n\n // obj is initialized by constructor.\n // arguments is only array-like so lacks shift(), but can be used with\n // the Array prototype function.\n constructor.apply(obj, Array.prototype.slice.call(arguments, 1));\n return obj;\n};\n\n\n/**\n * @define {boolean} Whether the return value cache should be used.\n * This should only be used to disable caches when testing.\n */\ngoog.functions.CACHE_RETURN_VALUE =\n goog.define('goog.functions.CACHE_RETURN_VALUE', true);\n\n\n/**\n * Gives a wrapper function that caches the return value of a parameterless\n * function when first called.\n *\n * When called for the first time, the given function is called and its\n * return value is cached (thus this is only appropriate for idempotent\n * functions). Subsequent calls will return the cached return value. This\n * allows the evaluation of expensive functions to be delayed until first used.\n *\n * To cache the return values of functions with parameters, see goog.memoize.\n *\n * @param {function():T} fn A function to lazily evaluate.\n * @return {function():T} A wrapped version the function.\n * @template T\n */\ngoog.functions.cacheReturnValue = function(fn) {\n 'use strict';\n let called = false;\n let value;\n\n return function() {\n 'use strict';\n if (!goog.functions.CACHE_RETURN_VALUE) {\n return fn();\n }\n\n if (!called) {\n value = fn();\n called = true;\n }\n\n return value;\n };\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once. All\n * additional calls are no-ops.\n *\n * This is particularly useful for initialization functions\n * that should be called, at most, once.\n *\n * @param {function():*} f Function to call.\n * @return {function():undefined} Wrapped function.\n */\ngoog.functions.once = function(f) {\n 'use strict';\n // Keep a reference to the function that we null out when we're done with\n // it -- that way, the function can be GC'd when we're done with it.\n let inner = f;\n return function() {\n 'use strict';\n if (inner) {\n const tmp = inner;\n inner = null;\n tmp();\n }\n };\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once per interval\n * (specified in milliseconds). If the wrapper function is called N times within\n * that interval, only the Nth call will go through.\n *\n * This is particularly useful for batching up repeated actions where the\n * last action should win. This can be used, for example, for refreshing an\n * autocomplete pop-up every so often rather than updating with every keystroke,\n * since the final text typed by the user is the one that should produce the\n * final autocomplete results. For more stateful debouncing with support for\n * pausing, resuming, and canceling debounced actions, use\n * `goog.async.Debouncer`.\n *\n * @param {function(this:SCOPE, ...?)} f Function to call.\n * @param {number} interval Interval over which to debounce. The function will\n * only be called after the full interval has elapsed since the last call.\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\n * @return {function(...?): undefined} Wrapped function.\n * @template SCOPE\n */\ngoog.functions.debounce = function(f, interval, opt_scope) {\n 'use strict';\n let timeout = 0;\n return /** @type {function(...?)} */ (function(var_args) {\n 'use strict';\n goog.global.clearTimeout(timeout);\n const args = arguments;\n timeout = goog.global.setTimeout(function() {\n 'use strict';\n f.apply(opt_scope, args);\n }, interval);\n });\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once per interval\n * (specified in milliseconds). If the wrapper function is called N times in\n * that interval, both the 1st and the Nth calls will go through.\n *\n * This is particularly useful for limiting repeated user requests where the\n * the last action should win, but you also don't want to wait until the end of\n * the interval before sending a request out, as it leads to a perception of\n * slowness for the user.\n *\n * @param {function(this:SCOPE, ...?)} f Function to call.\n * @param {number} interval Interval over which to throttle. The function can\n * only be called once per interval.\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\n * @return {function(...?): undefined} Wrapped function.\n * @template SCOPE\n */\ngoog.functions.throttle = function(f, interval, opt_scope) {\n 'use strict';\n let timeout = 0;\n let shouldFire = false;\n let storedArgs = [];\n\n const handleTimeout = function() {\n 'use strict';\n timeout = 0;\n if (shouldFire) {\n shouldFire = false;\n fire();\n }\n };\n\n const fire = function() {\n 'use strict';\n timeout = goog.global.setTimeout(handleTimeout, interval);\n let args = storedArgs;\n storedArgs = []; // Avoid a space leak by clearing stored arguments.\n f.apply(opt_scope, args);\n };\n\n return /** @type {function(...?)} */ (function(var_args) {\n 'use strict';\n storedArgs = arguments;\n if (!timeout) {\n fire();\n } else {\n shouldFire = true;\n }\n });\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once per interval\n * (specified in milliseconds). If the wrapper function is called N times within\n * that interval, only the 1st call will go through.\n *\n * This is particularly useful for limiting repeated user requests where the\n * first request is guaranteed to have all the data required to perform the\n * final action, so there's no need to wait until the end of the interval before\n * sending the request out.\n *\n * @param {function(this:SCOPE, ...?)} f Function to call.\n * @param {number} interval Interval over which to rate-limit. The function will\n * only be called once per interval, and ignored for the remainer of the\n * interval.\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\n * @return {function(...?): undefined} Wrapped function.\n * @template SCOPE\n */\ngoog.functions.rateLimit = function(f, interval, opt_scope) {\n 'use strict';\n let timeout = 0;\n\n const handleTimeout = function() {\n 'use strict';\n timeout = 0;\n };\n\n return /** @type {function(...?)} */ (function(var_args) {\n 'use strict';\n if (!timeout) {\n timeout = goog.global.setTimeout(handleTimeout, interval);\n f.apply(opt_scope, arguments);\n }\n });\n};\n\n/**\n * Returns true if the specified value is a function.\n * @param {*} val Variable to test.\n * @return {boolean} Whether variable is a function.\n */\ngoog.functions.isFunction = (val) => {\n return typeof val === 'function';\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utility functions for managing networking, such as\n * testing network connectivity.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.netUtils');\n\ngoog.require('goog.Uri');\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\n\ngoog.scope(function() {\n'use strict';\nconst netUtils = goog.labs.net.webChannel.netUtils;\nconst WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\n\n\n/**\n * Default timeout to allow for URI pings.\n * @type {number}\n */\nnetUtils.NETWORK_TIMEOUT = 10000;\n\n\n/**\n * Pings the network with an image URI to check if an error is a server error\n * or user's network error.\n *\n * The caller needs to add a 'rand' parameter to make sure the response is\n * not fulfilled by browser cache.\n *\n * @param {function(boolean)} callback The function to call back with results.\n * @param {goog.Uri=} opt_imageUri The URI (of an image) to use for the network\n * test.\n */\nnetUtils.testNetwork = function(callback, opt_imageUri) {\n 'use strict';\n let uri = opt_imageUri;\n if (!uri) {\n // default google.com image\n uri = new goog.Uri('//www.google.com/images/cleardot.gif');\n\n if (!(goog.global.location && goog.global.location.protocol == 'http')) {\n uri.setScheme('https'); // e.g. chrome-extension\n }\n uri.makeUnique();\n }\n\n netUtils.testLoadImage(uri.toString(), netUtils.NETWORK_TIMEOUT, callback);\n};\n\n\n/**\n * Test loading the given image, retrying if necessary.\n * @param {string} url URL to the image.\n * @param {number} timeout Milliseconds before giving up.\n * @param {function(boolean)} callback Function to call with results.\n * @param {number} retries The number of times to retry.\n * @param {!WebChannelDebug} channelDebug The debug object\n * @param {number=} opt_pauseBetweenRetriesMS Optional number of milliseconds\n * between retries - defaults to 0.\n */\nnetUtils.testLoadImageWithRetries = function(\n url, timeout, callback, retries, channelDebug, opt_pauseBetweenRetriesMS) {\n 'use strict';\n channelDebug.debug('TestLoadImageWithRetries: ' + opt_pauseBetweenRetriesMS);\n if (retries == 0) {\n // no more retries, give up\n callback(false);\n return;\n }\n\n const pauseBetweenRetries = opt_pauseBetweenRetriesMS || 0;\n retries--;\n netUtils.testLoadImage(url, timeout, function(succeeded) {\n 'use strict';\n if (succeeded) {\n callback(true);\n } else {\n // try again\n goog.global.setTimeout(function() {\n 'use strict';\n netUtils.testLoadImageWithRetries(\n url, timeout, callback, retries, channelDebug, pauseBetweenRetries);\n }, pauseBetweenRetries);\n }\n });\n};\n\n\n/**\n * Test loading the given image.\n * @param {string} url URL to the image.\n * @param {number} timeout Milliseconds before giving up.\n * @param {function(boolean)} callback Function to call with results.\n * @suppress {strictMissingProperties} Part of the go/strict_warnings_migration\n */\nnetUtils.testLoadImage = function(url, timeout, callback) {\n 'use strict';\n const channelDebug = new WebChannelDebug();\n channelDebug.debug('TestLoadImage: loading ' + url);\n if (goog.global.Image) {\n const img = new Image();\n img.onload = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: loaded',\n true, callback);\n img.onerror = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: error',\n false, callback);\n img.onabort = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: abort',\n false, callback);\n img.ontimeout = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: timeout',\n false, callback);\n\n goog.global.setTimeout(function() {\n 'use strict';\n if (img.ontimeout) {\n img.ontimeout();\n }\n }, timeout);\n img.src = url;\n } else {\n // log ERROR_OTHER from environements where Image is not supported\n callback(false);\n }\n};\n\n\n/**\n * Wrap the image callback with debug and cleanup logic.\n * @param {!WebChannelDebug} channelDebug The WebChannelDebug object.\n * @param {!Image} img The image element.\n * @param {string} debugText The debug text.\n * @param {boolean} result The result of image loading.\n * @param {function(boolean)} callback The image callback.\n * @private\n */\nnetUtils.imageCallback_ = function(\n channelDebug, img, debugText, result, callback) {\n 'use strict';\n try {\n channelDebug.debug(debugText);\n netUtils.clearImageCallbacks_(img);\n callback(result);\n } catch (e) {\n channelDebug.dumpException(e);\n }\n};\n\n\n/**\n * Clears handlers to avoid memory leaks.\n * @param {Image} img The image to clear handlers from.\n * @private\n * @suppress {strictMissingProperties} Part of the go/strict_warnings_migration\n */\nnetUtils.clearImageCallbacks_ = function(img) {\n 'use strict';\n img.onload = null;\n img.onerror = null;\n img.onabort = null;\n img.ontimeout = null;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.provide('goog.net.FetchXmlHttp');\ngoog.provide('goog.net.FetchXmlHttpFactory');\n\ngoog.require('goog.asserts');\ngoog.require('goog.events.EventTarget');\ngoog.require('goog.functions');\ngoog.require('goog.log');\ngoog.require('goog.net.XhrLike');\ngoog.require('goog.net.XmlHttpFactory');\n\n\n\n/**\n * @record\n */\ngoog.net.FetchXmlHttpFactoryOptions = function() {\n /**\n * @type {!WorkerGlobalScope|undefined} The Service Worker global scope.\n */\n this.worker;\n\n /**\n * @type {boolean|undefined} Whether to store the FetchXmlHttp response as an\n * array of Uint8Arrays. If this is true then the 'responseType' attribute\n * must be empty.\n */\n this.streamBinaryChunks;\n};\n\n\n\n/**\n * Factory for creating Xhr objects that uses the native fetch() method.\n * https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\n * @param {!goog.net.FetchXmlHttpFactoryOptions} opts\n * @extends {goog.net.XmlHttpFactory}\n * @struct\n * @constructor\n */\ngoog.net.FetchXmlHttpFactory = function(opts) {\n 'use strict';\n goog.net.FetchXmlHttpFactory.base(this, 'constructor');\n\n /** @private @final {?WorkerGlobalScope} */\n this.worker_ = opts.worker || null;\n\n /** @private @final {boolean} */\n this.streamBinaryChunks_ = opts.streamBinaryChunks || false;\n\n /** @private {!RequestCredentials|undefined} */\n this.credentialsMode_ = undefined;\n\n /** @private {!RequestCache|undefined} */\n this.cacheMode_ = undefined;\n};\ngoog.inherits(goog.net.FetchXmlHttpFactory, goog.net.XmlHttpFactory);\n\n\n/** @override */\ngoog.net.FetchXmlHttpFactory.prototype.createInstance = function() {\n 'use strict';\n const instance =\n new goog.net.FetchXmlHttp(this.worker_, this.streamBinaryChunks_);\n if (this.credentialsMode_) {\n instance.setCredentialsMode(this.credentialsMode_);\n }\n if (this.cacheMode_) {\n instance.setCacheMode(this.cacheMode_);\n }\n return instance;\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttpFactory.prototype.internalGetOptions =\n goog.functions.constant({});\n\n\n/**\n * @param {!RequestCredentials} credentialsMode The credentials mode of the\n * Service Worker fetch.\n */\ngoog.net.FetchXmlHttpFactory.prototype.setCredentialsMode = function(\n credentialsMode) {\n 'use strict';\n this.credentialsMode_ = credentialsMode;\n};\n\n\n/**\n * @param {!RequestCache} cacheMode The cache mode of the Service Worker fetch.\n */\ngoog.net.FetchXmlHttpFactory.prototype.setCacheMode = function(cacheMode) {\n 'use strict';\n this.cacheMode_ = cacheMode;\n};\n\n\n\n/**\n * FetchXmlHttp object constructor.\n * @param {?WorkerGlobalScope} worker\n * @param {boolean} streamBinaryChunks\n * @extends {goog.events.EventTarget}\n * @implements {goog.net.XhrLike}\n * @constructor\n * @struct\n */\ngoog.net.FetchXmlHttp = function(worker, streamBinaryChunks) {\n 'use strict';\n goog.net.FetchXmlHttp.base(this, 'constructor');\n\n /** @private @final {?WorkerGlobalScope} */\n this.worker_ = worker;\n\n /** @private @final {boolean} */\n this.streamBinaryChunks_ = streamBinaryChunks;\n\n /** @private {RequestCredentials|undefined} */\n this.credentialsMode_ = undefined;\n\n /** @private {RequestCache|undefined} */\n this.cacheMode_ = undefined;\n\n /**\n * Request state.\n * @type {goog.net.FetchXmlHttp.RequestState}\n */\n this.readyState = goog.net.FetchXmlHttp.RequestState.UNSENT;\n\n /**\n * HTTP status.\n * @type {number}\n */\n this.status = 0;\n\n /**\n * HTTP status string.\n * @type {string}\n */\n this.statusText = '';\n\n /**\n * Content of the response.\n * @type {string|!ArrayBuffer|!Array<!Uint8Array>}\n */\n this.response = '';\n\n /**\n * Content of the response.\n * @type {string}\n */\n this.responseText = '';\n\n /**\n * The type of the response. If this is set to 'arraybuffer' the request will\n * be discrete, streaming is only supported for text encoded requests.\n * @type {string}\n */\n this.responseType = '';\n\n /**\n * Document response entity body.\n * NOTE: This is always null and not supported by this class.\n * @final {null}\n */\n this.responseXML = null;\n\n /**\n * Method to call when the state changes.\n * @type {?function()}\n */\n this.onreadystatechange = null;\n\n /** @private {!Headers} */\n this.requestHeaders_ = new Headers();\n\n /** @private {?Headers} */\n this.responseHeaders_ = null;\n\n /**\n * Request method (GET or POST).\n * @private {string}\n */\n this.method_ = 'GET';\n\n /**\n * Request URL.\n * @private {string}\n */\n this.url_ = '';\n\n /**\n * Whether the request is in progress.\n * @private {boolean}\n */\n this.inProgress_ = false;\n\n /** @private @final {?goog.log.Logger} */\n this.logger_ = goog.log.getLogger('goog.net.FetchXmlHttp');\n\n /** @private {?Response} */\n this.fetchResponse_ = null;\n\n /** @private {!ReadableStreamDefaultReader|null} */\n this.currentReader_ = null;\n\n /** @private {?TextDecoder} */\n this.textDecoder_ = null;\n};\ngoog.inherits(goog.net.FetchXmlHttp, goog.events.EventTarget);\n\n\n/**\n * State of the requests.\n * @enum {number}\n */\ngoog.net.FetchXmlHttp.RequestState = {\n UNSENT: 0,\n OPENED: 1,\n HEADER_RECEIVED: 2,\n LOADING: 3,\n DONE: 4,\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.open = function(method, url, opt_async) {\n 'use strict';\n goog.asserts.assert(!!opt_async, 'Only async requests are supported.');\n if (this.readyState != goog.net.FetchXmlHttp.RequestState.UNSENT) {\n this.abort();\n throw new Error('Error reopening a connection');\n }\n\n this.method_ = method;\n this.url_ = url;\n\n this.readyState = goog.net.FetchXmlHttp.RequestState.OPENED;\n this.dispatchCallback_();\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.send = function(opt_data) {\n 'use strict';\n if (this.readyState != goog.net.FetchXmlHttp.RequestState.OPENED) {\n this.abort();\n throw new Error('need to call open() first. ');\n }\n\n this.inProgress_ = true;\n const requestInit = {\n headers: this.requestHeaders_,\n method: this.method_,\n credentials: this.credentialsMode_,\n cache: this.cacheMode_,\n };\n if (opt_data) {\n requestInit['body'] = opt_data;\n }\n\n (this.worker_ || goog.global)\n .fetch(new Request(this.url_, /** @type {!RequestInit} */ (requestInit)))\n .then(\n this.handleResponse_.bind(this), this.handleSendFailure_.bind(this));\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.abort = function() {\n 'use strict';\n this.response = this.responseText = '';\n this.requestHeaders_ = new Headers();\n this.status = 0;\n\n if (!!this.currentReader_) {\n this.currentReader_.cancel('Request was aborted.')\n .catch(\n e => goog.log.warning(\n this.logger_, 'Fetch reader cancellation error.', e));\n }\n\n if (((this.readyState >= goog.net.FetchXmlHttp.RequestState.OPENED) &&\n this.inProgress_) &&\n (this.readyState != goog.net.FetchXmlHttp.RequestState.DONE)) {\n this.inProgress_ = false;\n this.requestDone_();\n }\n\n this.readyState = goog.net.FetchXmlHttp.RequestState.UNSENT;\n};\n\n\n/**\n * Handles the fetch response.\n * @param {!Response} response\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleResponse_ = function(response) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n this.fetchResponse_ = response;\n\n if (!this.responseHeaders_) {\n this.status = this.fetchResponse_.status;\n this.statusText = this.fetchResponse_.statusText;\n this.responseHeaders_ = response.headers;\n this.readyState = goog.net.FetchXmlHttp.RequestState.HEADER_RECEIVED;\n this.dispatchCallback_();\n }\n // A callback may abort the request.\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n this.readyState = goog.net.FetchXmlHttp.RequestState.LOADING;\n this.dispatchCallback_();\n // A callback may abort the request.\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n if (this.responseType === 'arraybuffer') {\n response.arrayBuffer().then(\n this.handleResponseArrayBuffer_.bind(this),\n this.handleSendFailure_.bind(this));\n } else if (\n typeof (goog.global.ReadableStream) !== 'undefined' &&\n 'body' in response) {\n this.currentReader_ =\n /** @type {!ReadableStreamDefaultReader} */ (response.body.getReader());\n if (this.streamBinaryChunks_) {\n if (this.responseType) {\n throw new Error(\n 'responseType must be empty for \"streamBinaryChunks\" mode responses.');\n }\n this.response = [];\n } else {\n this.response = this.responseText = '';\n this.textDecoder_ = new TextDecoder();\n }\n this.readInputFromFetch_();\n } else {\n response.text().then(\n this.handleResponseText_.bind(this),\n this.handleSendFailure_.bind(this));\n }\n};\n\n\n/**\n * Reads the next chunk of data from the fetch response.\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.readInputFromFetch_ = function() {\n 'use strict';\n this.currentReader_.read()\n .then(this.handleDataFromStream_.bind(this))\n .catch(this.handleSendFailure_.bind(this));\n};\n\n\n/**\n * Handles a chunk of data from the fetch response stream reader.\n * @param {!IIterableResult} result\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleDataFromStream_ = function(result) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n if (this.streamBinaryChunks_ && result.value) {\n // When streamBinaryChunks_ is enabled, \"response\" is an array\n /** @type {!Array} */ (this.response)\n .push(/** @type {!Uint8Array} */ (result.value));\n } else if (!this.streamBinaryChunks_) {\n const dataPacket = result.value ?\n /** @type {!Uint8Array} */ (result.value) :\n new Uint8Array(0);\n const newText =\n this.textDecoder_.decode(dataPacket, {stream: !result.done});\n if (newText) {\n this.responseText += newText;\n this.response = this.responseText;\n }\n }\n if (result.done) {\n this.requestDone_();\n } else {\n this.dispatchCallback_();\n }\n\n if (this.readyState == goog.net.FetchXmlHttp.RequestState.LOADING) {\n this.readInputFromFetch_();\n }\n};\n\n/**\n * Handles the response text.\n * @param {string} responseText\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleResponseText_ = function(responseText) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n this.response = this.responseText = responseText;\n this.requestDone_();\n};\n\n\n/**\n * Handles the response text.\n * @param {!ArrayBuffer} responseArrayBuffer\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleResponseArrayBuffer_ = function(\n responseArrayBuffer) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n this.response = responseArrayBuffer;\n this.requestDone_();\n};\n\n\n/**\n * Handles the send failure.\n * @param {*} error\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleSendFailure_ = function(error) {\n 'use strict';\n const e = error instanceof Error ? error : Error(error);\n goog.log.warning(this.logger_, 'Failed to fetch url ' + this.url_, e);\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n this.requestDone_();\n};\n\n\n/**\n * Sets the request state to DONE and performs cleanup.\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.requestDone_ = function() {\n 'use strict';\n this.readyState = goog.net.FetchXmlHttp.RequestState.DONE;\n\n this.fetchResponse_ = null;\n this.currentReader_ = null;\n this.textDecoder_ = null;\n\n this.dispatchCallback_();\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.setRequestHeader = function(header, value) {\n 'use strict';\n this.requestHeaders_.append(header, value);\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.getResponseHeader = function(header) {\n 'use strict';\n // TODO(user): This method should return null when the headers are not\n // present or the specified header is missing. The externs need to be fixed.\n if (!this.responseHeaders_) {\n goog.log.warning(\n this.logger_,\n 'Attempting to get response header but no headers have been received ' +\n 'for url: ' + this.url_);\n return '';\n }\n return this.responseHeaders_.get(header.toLowerCase()) || '';\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.getAllResponseHeaders = function() {\n 'use strict';\n if (!this.responseHeaders_) {\n goog.log.warning(\n this.logger_,\n 'Attempting to get all response headers but no headers have been ' +\n 'received for url: ' + this.url_);\n return '';\n }\n const lines = [];\n const iter = this.responseHeaders_.entries();\n let entry = iter.next();\n while (!entry.done) {\n const pair = entry.value;\n lines.push(pair[0] + ': ' + pair[1]);\n entry = iter.next();\n }\n return lines.join('\\r\\n');\n};\n\n\n/**\n * @param {!RequestCredentials} credentialsMode The credentials mode of the\n * Service Worker fetch.\n */\ngoog.net.FetchXmlHttp.prototype.setCredentialsMode = function(credentialsMode) {\n 'use strict';\n this.credentialsMode_ = credentialsMode;\n};\n\n/**\n * @return {!RequestCredentials|undefined} The credentials mode of the\n * Service Worker fetch.\n */\ngoog.net.FetchXmlHttp.prototype.getCredentialsMode = function() {\n 'use strict';\n return this.credentialsMode_;\n};\n\n/**\n * @param {!RequestCache} cacheMode The cache mode of the Service Worker fetch.\n */\ngoog.net.FetchXmlHttp.prototype.setCacheMode = function(cacheMode) {\n 'use strict';\n this.cacheMode_ = cacheMode;\n};\n\n\n/**\n * Dispatches the callback, if the callback attribute is defined.\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.dispatchCallback_ = function() {\n 'use strict';\n if (this.onreadystatechange) {\n this.onreadystatechange.call(this);\n }\n};\n\n// Polyfill XmlHttpRequest's withCredentials property for specifying whether to\n// include credentials on cross domain requests.\nObject.defineProperty(goog.net.FetchXmlHttp.prototype, 'withCredentials', {\n get:\n /**\n * @this {goog.net.FetchXmlHttp}\n * @return {boolean} Whether to include credentials in cross domain\n * requests.\n */\n function() {\n 'use strict';\n return this.getCredentialsMode() === 'include';\n },\n\n set:\n /**\n * @param {boolean} value Whether to include credentials in cross domain\n * requests.\n * @this {goog.net.FetchXmlHttp}\n **/\n function(value) {\n 'use strict';\n this.setCredentialsMode(value ? 'include' : 'same-origin');\n }\n});\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n\n/**\n * @fileoverview Utility to attempt native JSON processing, falling back to\n * goog.json if not available.\n *\n * This is intended as a drop-in for current users of goog.json who want\n * to take advantage of native JSON if present.\n */\n\ngoog.provide('goog.json.hybrid');\n\ngoog.require('goog.asserts');\ngoog.require('goog.json');\n\n\n/**\n * Attempts to serialize the JSON string natively, falling back to\n * `goog.json.serialize` if unsuccessful.\n * @param {!Object} obj JavaScript object to serialize to JSON.\n * @return {string} Resulting JSON string.\n */\ngoog.json.hybrid.stringify = goog.json.USE_NATIVE_JSON ?\n goog.global['JSON']['stringify'] :\n function(obj) {\n 'use strict';\n if (goog.global.JSON) {\n try {\n return goog.global.JSON.stringify(obj);\n } catch (e) {\n // Native serialization failed. Fall through to retry with\n // goog.json.serialize.\n }\n }\n\n return goog.json.serialize(obj);\n };\n\n\n/**\n * Attempts to parse the JSON string natively, falling back to\n * the supplied `fallbackParser` if unsuccessful.\n * @param {string} jsonString JSON string to parse.\n * @param {function(string):Object} fallbackParser Fallback JSON parser used\n * if native\n * @return {?Object} Resulting JSON object.\n * @private\n */\ngoog.json.hybrid.parse_ = function(jsonString, fallbackParser) {\n 'use strict';\n if (goog.global.JSON) {\n try {\n var obj = goog.global.JSON.parse(jsonString);\n goog.asserts.assert(typeof obj == 'object');\n return /** @type {?Object} */ (obj);\n } catch (e) {\n // Native parse failed. Fall through to retry with goog.json.parse.\n }\n }\n\n return fallbackParser(jsonString);\n};\n\n\n/**\n * Attempts to parse the JSON string natively, falling back to\n * `goog.json.parse` if unsuccessful.\n * @param {string} jsonString JSON string to parse.\n * @return {?Object} Resulting JSON object.\n */\ngoog.json.hybrid.parse = goog.json.USE_NATIVE_JSON ?\n goog.global['JSON']['parse'] :\n function(jsonString) {\n 'use strict';\n return goog.json.hybrid.parse_(jsonString, goog.json.parse);\n };\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Constants for HTTP status codes.\n */\n\ngoog.provide('goog.net.HttpStatus');\n\n\n/**\n * HTTP Status Codes defined in RFC 2616, RFC 6585, RFC 4918 and RFC 7538.\n * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html\n * @see http://tools.ietf.org/html/rfc6585\n * @see https://tools.ietf.org/html/rfc4918\n * @see https://tools.ietf.org/html/rfc7538\n * @enum {number}\n */\ngoog.net.HttpStatus = {\n // Informational 1xx\n CONTINUE: 100,\n SWITCHING_PROTOCOLS: 101,\n\n // Successful 2xx\n OK: 200,\n CREATED: 201,\n ACCEPTED: 202,\n NON_AUTHORITATIVE_INFORMATION: 203,\n NO_CONTENT: 204,\n RESET_CONTENT: 205,\n PARTIAL_CONTENT: 206,\n MULTI_STATUS: 207,\n\n // Redirection 3xx\n MULTIPLE_CHOICES: 300,\n MOVED_PERMANENTLY: 301,\n FOUND: 302,\n SEE_OTHER: 303,\n NOT_MODIFIED: 304,\n USE_PROXY: 305,\n TEMPORARY_REDIRECT: 307,\n PERMANENT_REDIRECT: 308,\n\n // Client Error 4xx\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n NOT_ACCEPTABLE: 406,\n PROXY_AUTHENTICATION_REQUIRED: 407,\n REQUEST_TIMEOUT: 408,\n CONFLICT: 409,\n GONE: 410,\n LENGTH_REQUIRED: 411,\n PRECONDITION_FAILED: 412,\n REQUEST_ENTITY_TOO_LARGE: 413,\n REQUEST_URI_TOO_LONG: 414,\n UNSUPPORTED_MEDIA_TYPE: 415,\n REQUEST_RANGE_NOT_SATISFIABLE: 416,\n EXPECTATION_FAILED: 417,\n UNPROCESSABLE_ENTITY: 422,\n LOCKED: 423,\n FAILED_DEPENDENCY: 424,\n PRECONDITION_REQUIRED: 428,\n TOO_MANY_REQUESTS: 429,\n REQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n CLIENT_CLOSED_REQUEST: 499, // Nonstandard, used by GRPC\n\n // Server Error 5xx\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n HTTP_VERSION_NOT_SUPPORTED: 505,\n INSUFFICIENT_STORAGE: 507,\n NETWORK_AUTHENTICATION_REQUIRED: 511,\n\n /*\n * IE returns this code for 204 due to its use of URLMon, which returns this\n * code for 'Operation Aborted'. The status text is 'Unknown', the response\n * headers are ''. Known to occur on IE 6 on XP through IE9 on Win7.\n */\n QUIRK_IE_NO_CONTENT: 1223,\n};\n\n\n/**\n * Returns whether the given status should be considered successful.\n *\n * Successful codes are OK (200), CREATED (201), ACCEPTED (202),\n * NO CONTENT (204), PARTIAL CONTENT (206), NOT MODIFIED (304),\n * and IE's no content code (1223).\n *\n * @param {number} status The status code to test.\n * @return {boolean} Whether the status code should be considered successful.\n */\ngoog.net.HttpStatus.isSuccess = function(status) {\n 'use strict';\n switch (status) {\n case goog.net.HttpStatus.OK:\n case goog.net.HttpStatus.CREATED:\n case goog.net.HttpStatus.ACCEPTED:\n case goog.net.HttpStatus.NO_CONTENT:\n case goog.net.HttpStatus.PARTIAL_CONTENT:\n case goog.net.HttpStatus.NOT_MODIFIED:\n case goog.net.HttpStatus.QUIRK_IE_NO_CONTENT:\n return true;\n\n default:\n return false;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Provides CORS support for HTTP based RPC requests.\n *\n * As part of net.rpc package, CORS features provided by this class\n * depend on the server support. Please check related specs to decide how\n * to enable any of the features provided by this class.\n */\n\ngoog.module('goog.net.rpc.HttpCors');\n\nconst GoogUri = goog.require('goog.Uri');\nconst googObject = goog.require('goog.object');\nconst googString = goog.require('goog.string');\nconst googUriUtils = goog.require('goog.uri.utils');\n\n\n/**\n * The default URL parameter name to overwrite http headers with a URL param\n * to avoid CORS preflight.\n *\n * See https://github.com/whatwg/fetch/issues/210#issue-129531743 for the spec.\n *\n * @type {string}\n */\nexports.HTTP_HEADERS_PARAM_NAME = '$httpHeaders';\n\n\n/**\n * The default URL parameter name to overwrite http method with a URL param\n * to avoid CORS preflight.\n *\n * See https://github.com/whatwg/fetch/issues/210#issue-129531743 for the spec.\n *\n * @type {string}\n */\nexports.HTTP_METHOD_PARAM_NAME = '$httpMethod';\n\n\n/**\n * Generates the URL parameter value with custom headers encoded as\n * HTTP/1.1 headers block.\n *\n * @param {!Object<string, string>} headers The custom headers.\n * @return {string} The URL param to overwrite custom HTTP headers.\n */\nexports.generateHttpHeadersOverwriteParam = function(headers) {\n let result = '';\n googObject.forEach(headers, function(value, key) {\n result += key;\n result += ':';\n result += value;\n result += '\\r\\n';\n });\n return result;\n};\n\n\n/**\n * Generates the URL-encoded URL parameter value with custom headers encoded as\n * HTTP/1.1 headers block.\n *\n * @param {!Object<string, string>} headers The custom headers.\n * @return {string} The URL param to overwrite custom HTTP headers.\n */\nexports.generateEncodedHttpHeadersOverwriteParam = function(headers) {\n return googString.urlEncode(\n exports.generateHttpHeadersOverwriteParam(headers));\n};\n\n\n/**\n * Sets custom HTTP headers via an overwrite URL param.\n *\n * @param {!GoogUri|string} url The URI object or a string path.\n * @param {string} urlParam The URL param name.\n * @param {!Object<string, string>} extraHeaders The HTTP headers.\n * @return {!GoogUri|string} The URI object or a string path with headers\n * encoded as a url param.\n */\nexports.setHttpHeadersWithOverwriteParam = function(\n url, urlParam, extraHeaders) {\n if (googObject.isEmpty(extraHeaders)) {\n return url;\n }\n const httpHeaders = exports.generateHttpHeadersOverwriteParam(extraHeaders);\n if (typeof url === 'string') {\n return googUriUtils.appendParam(\n url, googString.urlEncode(urlParam), httpHeaders);\n } else {\n url.setParameterValue(urlParam, httpHeaders); // duplicate removed!\n return url;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Implementation of a WebChannel transport using WebChannelBase.\n *\n * When WebChannelBase is used as the underlying transport, the capabilities\n * of the WebChannel are limited to what's supported by the implementation.\n * Particularly, multiplexing is not possible, and only strings are\n * supported as message types.\n */\n\ngoog.provide('goog.labs.net.webChannel.WebChannelBaseTransport');\n\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.events.EventTarget');\ngoog.require('goog.json');\ngoog.require('goog.labs.net.webChannel.ChannelRequest');\ngoog.require('goog.labs.net.webChannel.WebChannelBase');\ngoog.require('goog.labs.net.webChannel.Wire');\ngoog.require('goog.log');\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.net.WebChannelTransport');\ngoog.require('goog.object');\ngoog.require('goog.string');\n\n\n\n/**\n * Implementation of {@link goog.net.WebChannelTransport} with\n * {@link goog.labs.net.webChannel.WebChannelBase} as the underlying channel\n * implementation.\n *\n * @constructor\n * @struct\n * @implements {goog.net.WebChannelTransport}\n * @final\n */\ngoog.labs.net.webChannel.WebChannelBaseTransport = function() {\n 'use strict';\n if (!goog.labs.net.webChannel.ChannelRequest.supportsXhrStreaming()) {\n throw new Error('Environmental error: no available transport.');\n }\n};\n\n\ngoog.scope(function() {\n'use strict';\nconst WebChannelBaseTransport =\n goog.labs.net.webChannel.WebChannelBaseTransport;\nconst WebChannelBase = goog.labs.net.webChannel.WebChannelBase;\nconst Wire = goog.labs.net.webChannel.Wire;\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.prototype.createWebChannel = function(\n url, opt_options) {\n 'use strict';\n return new WebChannelBaseTransport.Channel(url, opt_options);\n};\n\n\n\n/**\n * Implementation of the {@link goog.net.WebChannel} interface.\n *\n * @param {string} url The URL path for the new WebChannel instance.\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\n * new WebChannel instance.\n *\n * @constructor\n * @implements {goog.net.WebChannel}\n * @extends {goog.events.EventTarget}\n * @final\n */\nWebChannelBaseTransport.Channel = function(url, opt_options) {\n 'use strict';\n WebChannelBaseTransport.Channel.base(this, 'constructor');\n\n /**\n * @private {!WebChannelBase} The underlying channel object.\n */\n this.channel_ = new WebChannelBase(\n opt_options, goog.net.WebChannelTransport.CLIENT_VERSION);\n\n /**\n * @private {string} The URL of the target server end-point.\n */\n this.url_ = url;\n\n /**\n * @private {goog.log.Logger} The logger for this class.\n */\n this.logger_ =\n goog.log.getLogger('goog.labs.net.webChannel.WebChannelBaseTransport');\n\n /**\n * @private {Object<string, string>} Extra URL parameters\n * to be added to each HTTP request.\n */\n this.messageUrlParams_ =\n (opt_options && opt_options.messageUrlParams) || null;\n\n let messageHeaders = (opt_options && opt_options.messageHeaders) || null;\n\n // default is false\n if (opt_options && opt_options.clientProtocolHeaderRequired) {\n if (messageHeaders) {\n goog.object.set(\n messageHeaders, goog.net.WebChannel.X_CLIENT_PROTOCOL,\n goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL);\n } else {\n messageHeaders = goog.object.create(\n goog.net.WebChannel.X_CLIENT_PROTOCOL,\n goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL);\n }\n }\n\n this.channel_.setExtraHeaders(messageHeaders);\n\n let initHeaders = (opt_options && opt_options.initMessageHeaders) || null;\n\n if (opt_options && opt_options.messageContentType) {\n if (initHeaders) {\n goog.object.set(\n initHeaders, goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE,\n opt_options.messageContentType);\n } else {\n initHeaders = goog.object.create(\n goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE,\n opt_options.messageContentType);\n }\n }\n\n if (opt_options && opt_options.clientProfile) {\n if (initHeaders) {\n goog.object.set(\n initHeaders, goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE,\n opt_options.clientProfile);\n } else {\n initHeaders = goog.object.create(\n goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE,\n opt_options.clientProfile);\n }\n }\n\n this.channel_.setInitHeaders(initHeaders);\n\n const httpHeadersOverwriteParam =\n opt_options && opt_options.httpHeadersOverwriteParam;\n if (httpHeadersOverwriteParam &&\n !goog.string.isEmptyOrWhitespace(httpHeadersOverwriteParam)) {\n this.channel_.setHttpHeadersOverwriteParam(httpHeadersOverwriteParam);\n }\n\n /**\n * @private {boolean} Whether to enable CORS.\n */\n this.supportsCrossDomainXhr_ =\n (opt_options && opt_options.supportsCrossDomainXhr) || false;\n\n /**\n * @private {boolean} Whether to send raw Json and bypass v8 wire format.\n */\n this.sendRawJson_ = (opt_options && opt_options.sendRawJson) || false;\n\n // Note that httpSessionIdParam will be ignored if the same parameter name\n // has already been specified with messageUrlParams\n const httpSessionIdParam = opt_options && opt_options.httpSessionIdParam;\n if (httpSessionIdParam &&\n !goog.string.isEmptyOrWhitespace(httpSessionIdParam)) {\n this.channel_.setHttpSessionIdParam(httpSessionIdParam);\n if (goog.object.containsKey(this.messageUrlParams_, httpSessionIdParam)) {\n goog.object.remove(this.messageUrlParams_, httpSessionIdParam);\n goog.log.warning(\n this.logger_,\n 'Ignore httpSessionIdParam also specified with messageUrlParams: ' +\n httpSessionIdParam);\n }\n }\n\n /**\n * The channel handler.\n *\n * @private {!WebChannelBaseTransport.Channel.Handler_}\n */\n this.channelHandler_ = new WebChannelBaseTransport.Channel.Handler_(this);\n};\ngoog.inherits(WebChannelBaseTransport.Channel, goog.events.EventTarget);\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.open = function() {\n 'use strict';\n this.channel_.setHandler(this.channelHandler_);\n if (this.supportsCrossDomainXhr_) {\n this.channel_.setSupportsCrossDomainXhrs(true);\n }\n this.channel_.connect(this.url_, (this.messageUrlParams_ || undefined));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.close = function() {\n 'use strict';\n this.channel_.disconnect();\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.halfClose = function() {\n 'use strict';\n // to be implemented\n throw new Error('Not implemented');\n};\n\n\n/**\n * The WebChannelBase only supports object types.\n *\n * @param {!goog.net.WebChannel.MessageData} message The message to send.\n *\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.send = function(message) {\n 'use strict';\n this.channel_.sendMap(this.messageToMapObject_(message));\n};\n\n\n/**\n * Converts a message to the map used by the underlying channel.\n *\n * @param {!goog.net.WebChannel.MessageData} message\n * @return {!Object|!goog.collections.maps.MapLike}\n */\nWebChannelBaseTransport.Channel.prototype.messageToMapObject_ = function(\n message) {\n 'use strict';\n goog.asserts.assert(\n goog.isObject(message) || typeof message === 'string',\n 'only object type or raw string is supported');\n\n if (typeof message === 'string') {\n const rawJson = {};\n rawJson[Wire.RAW_DATA_KEY] = message;\n return rawJson;\n }\n\n if (this.sendRawJson_) {\n const rawJson = {};\n rawJson[Wire.RAW_DATA_KEY] = goog.json.serialize(message);\n return rawJson;\n }\n\n return message;\n};\n\n\n/**\n * Converts the map used by the underlying channel to a message.\n *\n * NOTE: In the case of the message being JS Object or string, the exact same\n * object passed during `messageToMapObject_()` is returned. In the case of raw\n * JSON, an equal (but not the same) object is returned (due to serialization).\n *\n * @param {!Object|!goog.collections.maps.MapLike} map\n * @return {!goog.net.WebChannel.MessageData}\n */\nWebChannelBaseTransport.Channel.prototype.mapObjectToMessage_ = function(map) {\n 'use strict';\n if (Wire.RAW_DATA_KEY in map) {\n const rawMessage = map[Wire.RAW_DATA_KEY];\n\n if (this.sendRawJson_) {\n return /** @type {!goog.net.WebChannel.MessageData} */ (\n goog.json.parse(rawMessage));\n } else { // string message\n return rawMessage;\n }\n }\n\n return map;\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.disposeInternal = function() {\n 'use strict';\n this.channel_.setHandler(null);\n delete this.channelHandler_;\n this.channel_.disconnect();\n delete this.channel_;\n\n WebChannelBaseTransport.Channel.base(this, 'disposeInternal');\n};\n\n\n\n/**\n * The message event.\n *\n * @param {!Array<?>|!Object} array The data array from the underlying channel.\n * @constructor\n * @extends {goog.net.WebChannel.MessageEvent}\n * @final\n */\nWebChannelBaseTransport.Channel.MessageEvent = function(array) {\n 'use strict';\n WebChannelBaseTransport.Channel.MessageEvent.base(this, 'constructor');\n\n // Metadata as HTTP headers and status code (always come in a pair).\n if (array['__headers__']) {\n this.headers = array['__headers__'];\n this.statusCode = array['__status__'];\n delete array['__headers__'];\n delete array['__status__'];\n }\n\n // single-metadata only\n const metadata = array['__sm__'];\n if (metadata) {\n this.metadataKey = goog.object.getAnyKey(metadata);\n if (this.metadataKey) {\n this.data = goog.object.get(metadata, this.metadataKey);\n } else {\n this.data = metadata; // empty\n }\n } else {\n this.data = array;\n }\n};\ngoog.inherits(\n WebChannelBaseTransport.Channel.MessageEvent,\n goog.net.WebChannel.MessageEvent);\n\n\n\n/**\n * The error event.\n *\n * @param {WebChannelBase.Error} error The error code.\n * @constructor\n * @extends {goog.net.WebChannel.ErrorEvent}\n * @final\n */\nWebChannelBaseTransport.Channel.ErrorEvent = function(error) {\n 'use strict';\n WebChannelBaseTransport.Channel.ErrorEvent.base(this, 'constructor');\n\n /**\n * High-level status code.\n */\n this.status = goog.net.WebChannel.ErrorStatus.NETWORK_ERROR;\n\n /**\n * @const {WebChannelBase.Error} Internal error code, for debugging use only.\n */\n this.errorCode = error;\n};\ngoog.inherits(\n WebChannelBaseTransport.Channel.ErrorEvent, goog.net.WebChannel.ErrorEvent);\n\n\n\n/**\n * Implementation of {@link WebChannelBase.Handler} interface.\n *\n * @param {!WebChannelBaseTransport.Channel} channel The enclosing WebChannel.\n *\n * @constructor\n * @extends {WebChannelBase.Handler}\n * @private\n */\nWebChannelBaseTransport.Channel.Handler_ = function(channel) {\n 'use strict';\n WebChannelBaseTransport.Channel.Handler_.base(this, 'constructor');\n\n /**\n * @type {!WebChannelBaseTransport.Channel}\n * @private\n */\n this.channel_ = channel;\n};\ngoog.inherits(WebChannelBaseTransport.Channel.Handler_, WebChannelBase.Handler);\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelOpened = function(\n channel) {\n 'use strict';\n goog.log.info(\n this.channel_.logger_, 'WebChannel opened on ' + this.channel_.url_);\n this.channel_.dispatchEvent(goog.net.WebChannel.EventType.OPEN);\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelHandleArray =\n function(channel, array) {\n 'use strict';\n goog.asserts.assert(array, 'array expected to be defined');\n this.channel_.dispatchEvent(\n new WebChannelBaseTransport.Channel.MessageEvent(array));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelError = function(\n channel, error) {\n 'use strict';\n goog.log.info(\n this.channel_.logger_,\n 'WebChannel aborted on ' + this.channel_.url_ +\n ' due to channel error: ' + error);\n this.channel_.dispatchEvent(\n new WebChannelBaseTransport.Channel.ErrorEvent(error));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelClosed = function(\n channel, opt_pendingMaps, opt_undeliveredMaps) {\n 'use strict';\n goog.log.info(\n this.channel_.logger_, 'WebChannel closed on ' + this.channel_.url_);\n this.channel_.dispatchEvent(goog.net.WebChannel.EventType.CLOSE);\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.getRuntimeProperties = function() {\n 'use strict';\n return new WebChannelBaseTransport.ChannelProperties(this, this.channel_);\n};\n\n\n\n/**\n * Implementation of the {@link goog.net.WebChannel.RuntimeProperties}.\n *\n * @param {!WebChannelBaseTransport.Channel} transportChannel The transport\n * channel object.\n * @param {!WebChannelBase} channel The underlying channel object.\n *\n * @constructor\n * @implements {goog.net.WebChannel.RuntimeProperties}\n * @final\n */\nWebChannelBaseTransport.ChannelProperties = function(\n transportChannel, channel) {\n 'use strict';\n /**\n * The transport channel object.\n *\n * @private @const {!WebChannelBaseTransport.Channel}\n */\n this.transportChannel_ = transportChannel;\n\n /**\n * The underlying channel object.\n *\n * @private @const {!WebChannelBase}\n */\n this.channel_ = channel;\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getConcurrentRequestLimit =\n function() {\n 'use strict';\n return this.channel_.getForwardChannelRequestPool().getMaxSize();\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.isSpdyEnabled = function() {\n 'use strict';\n return this.getConcurrentRequestLimit() > 1;\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getPendingRequestCount =\n function() {\n 'use strict';\n return this.channel_.getForwardChannelRequestPool().getRequestCount();\n};\n\n\n/**\n * @override\n * @return {!Array<!goog.net.WebChannel.MessageData>}\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getNonAckedMessages =\n function() {\n 'use strict';\n return this.channel_.getNonAckedMaps().map(\n queued_map => this.transportChannel_.mapObjectToMessage_(queued_map.map));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getHttpSessionId =\n function() {\n 'use strict';\n return this.channel_.getHttpSessionId();\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.commit = function(\n callback) {\n 'use strict';\n this.channel_.setForwardChannelFlushCallback(callback);\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.notifyNonAckedMessageCount =\n goog.abstractMethod;\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.onCommit =\n goog.abstractMethod;\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.ackCommit =\n goog.abstractMethod;\n\n\n/**\n * @override\n * @return {!Object<string, string>|undefined}\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getLastResponseHeaders =\n function() {\n 'use strict';\n return this.channel_.getLastResponseHeaders();\n};\n\n/** @override */\nWebChannelBaseTransport.ChannelProperties.prototype.getLastStatusCode =\n function() {\n 'use strict';\n return this.channel_.getLastStatusCode();\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview MD5 cryptographic hash.\n * Implementation of http://tools.ietf.org/html/rfc1321 with common\n * optimizations and tweaks (see http://en.wikipedia.org/wiki/MD5).\n *\n * Usage:\n * var md5 = new goog.crypt.Md5();\n * md5.update(bytes);\n * var hash = md5.digest();\n *\n * Performance:\n * Chrome 23 ~680 Mbit/s\n * Chrome 13 (in a VM) ~250 Mbit/s\n * Firefox 6.0 (in a VM) ~100 Mbit/s\n * IE9 (in a VM) ~27 Mbit/s\n * Firefox 3.6 ~15 Mbit/s\n * IE8 (in a VM) ~13 Mbit/s\n */\n\ngoog.provide('goog.crypt.Md5');\n\ngoog.require('goog.crypt.Hash');\n\n\n\n/**\n * MD5 cryptographic hash constructor.\n * @constructor\n * @extends {goog.crypt.Hash}\n * @final\n * @struct\n */\ngoog.crypt.Md5 = function() {\n 'use strict';\n goog.crypt.Md5.base(this, 'constructor');\n\n this.blockSize = 512 / 8;\n\n /**\n * Holds the current values of accumulated A-D variables (MD buffer).\n * @type {!Array<number>}\n * @private\n */\n this.chain_ = new Array(4);\n\n /**\n * A buffer holding the data until the whole block can be processed.\n * @type {!Array<number>}\n * @private\n */\n this.block_ = new Array(this.blockSize);\n\n /**\n * The length of yet-unprocessed data as collected in the block.\n * @type {number}\n * @private\n */\n this.blockLength_ = 0;\n\n /**\n * The total length of the message so far.\n * @type {number}\n * @private\n */\n this.totalLength_ = 0;\n\n this.reset();\n};\ngoog.inherits(goog.crypt.Md5, goog.crypt.Hash);\n\n\n/**\n * Integer rotation constants used by the abbreviated implementation.\n * They are hardcoded in the unrolled implementation, so it is left\n * here commented out.\n * @type {Array<number>}\n * @private\n *\ngoog.crypt.Md5.S_ = [\n 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,\n 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21\n];\n */\n\n/**\n * Sine function constants used by the abbreviated implementation.\n * They are hardcoded in the unrolled implementation, so it is left\n * here commented out.\n * @type {Array<number>}\n * @private\n *\ngoog.crypt.Md5.T_ = [\n 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,\n 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,\n 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,\n 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,\n 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,\n 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,\n 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,\n 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,\n 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,\n 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,\n 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,\n 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,\n 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,\n 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,\n 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,\n 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391\n];\n */\n\n\n/** @override */\ngoog.crypt.Md5.prototype.reset = function() {\n 'use strict';\n this.chain_[0] = 0x67452301;\n this.chain_[1] = 0xefcdab89;\n this.chain_[2] = 0x98badcfe;\n this.chain_[3] = 0x10325476;\n\n this.blockLength_ = 0;\n this.totalLength_ = 0;\n};\n\n\n/**\n * Internal compress helper function. It takes a block of data (64 bytes)\n * and updates the accumulator.\n * @param {Array<number>|Uint8Array|string} buf The block to compress.\n * @param {number=} opt_offset Offset of the block in the buffer.\n * @private\n */\ngoog.crypt.Md5.prototype.compress_ = function(buf, opt_offset) {\n 'use strict';\n if (!opt_offset) {\n opt_offset = 0;\n }\n\n // We allocate the array every time, but it's cheap in practice.\n var X = new Array(16);\n\n // Get 16 little endian words. It is not worth unrolling this for Chrome 11.\n if (typeof buf === 'string') {\n for (var i = 0; i < 16; ++i) {\n X[i] = (buf.charCodeAt(opt_offset++)) |\n (buf.charCodeAt(opt_offset++) << 8) |\n (buf.charCodeAt(opt_offset++) << 16) |\n (buf.charCodeAt(opt_offset++) << 24);\n }\n } else {\n for (var i = 0; i < 16; ++i) {\n X[i] = (buf[opt_offset++]) | (buf[opt_offset++] << 8) |\n (buf[opt_offset++] << 16) | (buf[opt_offset++] << 24);\n }\n }\n\n var A = this.chain_[0];\n var B = this.chain_[1];\n var C = this.chain_[2];\n var D = this.chain_[3];\n var sum = 0;\n\n /*\n * This is an abbreviated implementation, it is left here commented out for\n * reference purposes. See below for an unrolled version in use.\n *\n var f, n, tmp;\n for (var i = 0; i < 64; ++i) {\n\n if (i < 16) {\n f = (D ^ (B & (C ^ D)));\n n = i;\n } else if (i < 32) {\n f = (C ^ (D & (B ^ C)));\n n = (5 * i + 1) % 16;\n } else if (i < 48) {\n f = (B ^ C ^ D);\n n = (3 * i + 5) % 16;\n } else {\n f = (C ^ (B | (~D)));\n n = (7 * i) % 16;\n }\n\n tmp = D;\n D = C;\n C = B;\n sum = (A + f + goog.crypt.Md5.T_[i] + X[n]) & 0xffffffff;\n B += ((sum << goog.crypt.Md5.S_[i]) & 0xffffffff) |\n (sum >>> (32 - goog.crypt.Md5.S_[i]));\n A = tmp;\n }\n */\n\n /*\n * This is an unrolled MD5 implementation, which gives ~30% speedup compared\n * to the abbreviated implementation above, as measured on Chrome 11. It is\n * important to keep 32-bit croppings to minimum and inline the integer\n * rotation.\n */\n sum = (A + (D ^ (B & (C ^ D))) + X[0] + 0xd76aa478) & 0xffffffff;\n A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25));\n sum = (D + (C ^ (A & (B ^ C))) + X[1] + 0xe8c7b756) & 0xffffffff;\n D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20));\n sum = (C + (B ^ (D & (A ^ B))) + X[2] + 0x242070db) & 0xffffffff;\n C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15));\n sum = (B + (A ^ (C & (D ^ A))) + X[3] + 0xc1bdceee) & 0xffffffff;\n B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10));\n sum = (A + (D ^ (B & (C ^ D))) + X[4] + 0xf57c0faf) & 0xffffffff;\n A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25));\n sum = (D + (C ^ (A & (B ^ C))) + X[5] + 0x4787c62a) & 0xffffffff;\n D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20));\n sum = (C + (B ^ (D & (A ^ B))) + X[6] + 0xa8304613) & 0xffffffff;\n C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15));\n sum = (B + (A ^ (C & (D ^ A))) + X[7] + 0xfd469501) & 0xffffffff;\n B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10));\n sum = (A + (D ^ (B & (C ^ D))) + X[8] + 0x698098d8) & 0xffffffff;\n A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25));\n sum = (D + (C ^ (A & (B ^ C))) + X[9] + 0x8b44f7af) & 0xffffffff;\n D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20));\n sum = (C + (B ^ (D & (A ^ B))) + X[10] + 0xffff5bb1) & 0xffffffff;\n C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15));\n sum = (B + (A ^ (C & (D ^ A))) + X[11] + 0x895cd7be) & 0xffffffff;\n B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10));\n sum = (A + (D ^ (B & (C ^ D))) + X[12] + 0x6b901122) & 0xffffffff;\n A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25));\n sum = (D + (C ^ (A & (B ^ C))) + X[13] + 0xfd987193) & 0xffffffff;\n D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20));\n sum = (C + (B ^ (D & (A ^ B))) + X[14] + 0xa679438e) & 0xffffffff;\n C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15));\n sum = (B + (A ^ (C & (D ^ A))) + X[15] + 0x49b40821) & 0xffffffff;\n B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10));\n sum = (A + (C ^ (D & (B ^ C))) + X[1] + 0xf61e2562) & 0xffffffff;\n A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27));\n sum = (D + (B ^ (C & (A ^ B))) + X[6] + 0xc040b340) & 0xffffffff;\n D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23));\n sum = (C + (A ^ (B & (D ^ A))) + X[11] + 0x265e5a51) & 0xffffffff;\n C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18));\n sum = (B + (D ^ (A & (C ^ D))) + X[0] + 0xe9b6c7aa) & 0xffffffff;\n B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12));\n sum = (A + (C ^ (D & (B ^ C))) + X[5] + 0xd62f105d) & 0xffffffff;\n A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27));\n sum = (D + (B ^ (C & (A ^ B))) + X[10] + 0x02441453) & 0xffffffff;\n D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23));\n sum = (C + (A ^ (B & (D ^ A))) + X[15] + 0xd8a1e681) & 0xffffffff;\n C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18));\n sum = (B + (D ^ (A & (C ^ D))) + X[4] + 0xe7d3fbc8) & 0xffffffff;\n B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12));\n sum = (A + (C ^ (D & (B ^ C))) + X[9] + 0x21e1cde6) & 0xffffffff;\n A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27));\n sum = (D + (B ^ (C & (A ^ B))) + X[14] + 0xc33707d6) & 0xffffffff;\n D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23));\n sum = (C + (A ^ (B & (D ^ A))) + X[3] + 0xf4d50d87) & 0xffffffff;\n C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18));\n sum = (B + (D ^ (A & (C ^ D))) + X[8] + 0x455a14ed) & 0xffffffff;\n B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12));\n sum = (A + (C ^ (D & (B ^ C))) + X[13] + 0xa9e3e905) & 0xffffffff;\n A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27));\n sum = (D + (B ^ (C & (A ^ B))) + X[2] + 0xfcefa3f8) & 0xffffffff;\n D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23));\n sum = (C + (A ^ (B & (D ^ A))) + X[7] + 0x676f02d9) & 0xffffffff;\n C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18));\n sum = (B + (D ^ (A & (C ^ D))) + X[12] + 0x8d2a4c8a) & 0xffffffff;\n B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12));\n sum = (A + (B ^ C ^ D) + X[5] + 0xfffa3942) & 0xffffffff;\n A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28));\n sum = (D + (A ^ B ^ C) + X[8] + 0x8771f681) & 0xffffffff;\n D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21));\n sum = (C + (D ^ A ^ B) + X[11] + 0x6d9d6122) & 0xffffffff;\n C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16));\n sum = (B + (C ^ D ^ A) + X[14] + 0xfde5380c) & 0xffffffff;\n B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9));\n sum = (A + (B ^ C ^ D) + X[1] + 0xa4beea44) & 0xffffffff;\n A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28));\n sum = (D + (A ^ B ^ C) + X[4] + 0x4bdecfa9) & 0xffffffff;\n D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21));\n sum = (C + (D ^ A ^ B) + X[7] + 0xf6bb4b60) & 0xffffffff;\n C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16));\n sum = (B + (C ^ D ^ A) + X[10] + 0xbebfbc70) & 0xffffffff;\n B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9));\n sum = (A + (B ^ C ^ D) + X[13] + 0x289b7ec6) & 0xffffffff;\n A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28));\n sum = (D + (A ^ B ^ C) + X[0] + 0xeaa127fa) & 0xffffffff;\n D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21));\n sum = (C + (D ^ A ^ B) + X[3] + 0xd4ef3085) & 0xffffffff;\n C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16));\n sum = (B + (C ^ D ^ A) + X[6] + 0x04881d05) & 0xffffffff;\n B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9));\n sum = (A + (B ^ C ^ D) + X[9] + 0xd9d4d039) & 0xffffffff;\n A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28));\n sum = (D + (A ^ B ^ C) + X[12] + 0xe6db99e5) & 0xffffffff;\n D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21));\n sum = (C + (D ^ A ^ B) + X[15] + 0x1fa27cf8) & 0xffffffff;\n C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16));\n sum = (B + (C ^ D ^ A) + X[2] + 0xc4ac5665) & 0xffffffff;\n B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9));\n sum = (A + (C ^ (B | (~D))) + X[0] + 0xf4292244) & 0xffffffff;\n A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26));\n sum = (D + (B ^ (A | (~C))) + X[7] + 0x432aff97) & 0xffffffff;\n D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22));\n sum = (C + (A ^ (D | (~B))) + X[14] + 0xab9423a7) & 0xffffffff;\n C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17));\n sum = (B + (D ^ (C | (~A))) + X[5] + 0xfc93a039) & 0xffffffff;\n B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11));\n sum = (A + (C ^ (B | (~D))) + X[12] + 0x655b59c3) & 0xffffffff;\n A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26));\n sum = (D + (B ^ (A | (~C))) + X[3] + 0x8f0ccc92) & 0xffffffff;\n D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22));\n sum = (C + (A ^ (D | (~B))) + X[10] + 0xffeff47d) & 0xffffffff;\n C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17));\n sum = (B + (D ^ (C | (~A))) + X[1] + 0x85845dd1) & 0xffffffff;\n B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11));\n sum = (A + (C ^ (B | (~D))) + X[8] + 0x6fa87e4f) & 0xffffffff;\n A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26));\n sum = (D + (B ^ (A | (~C))) + X[15] + 0xfe2ce6e0) & 0xffffffff;\n D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22));\n sum = (C + (A ^ (D | (~B))) + X[6] + 0xa3014314) & 0xffffffff;\n C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17));\n sum = (B + (D ^ (C | (~A))) + X[13] + 0x4e0811a1) & 0xffffffff;\n B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11));\n sum = (A + (C ^ (B | (~D))) + X[4] + 0xf7537e82) & 0xffffffff;\n A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26));\n sum = (D + (B ^ (A | (~C))) + X[11] + 0xbd3af235) & 0xffffffff;\n D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22));\n sum = (C + (A ^ (D | (~B))) + X[2] + 0x2ad7d2bb) & 0xffffffff;\n C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17));\n sum = (B + (D ^ (C | (~A))) + X[9] + 0xeb86d391) & 0xffffffff;\n B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11));\n\n this.chain_[0] = (this.chain_[0] + A) & 0xffffffff;\n this.chain_[1] = (this.chain_[1] + B) & 0xffffffff;\n this.chain_[2] = (this.chain_[2] + C) & 0xffffffff;\n this.chain_[3] = (this.chain_[3] + D) & 0xffffffff;\n};\n\n\n/** @override */\ngoog.crypt.Md5.prototype.update = function(bytes, opt_length) {\n 'use strict';\n if (opt_length === undefined) {\n opt_length = bytes.length;\n }\n var lengthMinusBlock = opt_length - this.blockSize;\n\n // Copy some object properties to local variables in order to save on access\n // time from inside the loop (~10% speedup was observed on Chrome 11).\n var block = this.block_;\n var blockLength = this.blockLength_;\n var i = 0;\n\n // The outer while loop should execute at most twice.\n while (i < opt_length) {\n // When we have no data in the block to top up, we can directly process the\n // input buffer (assuming it contains sufficient data). This gives ~30%\n // speedup on Chrome 14 and ~70% speedup on Firefox 6.0, but requires that\n // the data is provided in large chunks (or in multiples of 64 bytes).\n if (blockLength == 0) {\n while (i <= lengthMinusBlock) {\n this.compress_(bytes, i);\n i += this.blockSize;\n }\n }\n\n if (typeof bytes === 'string') {\n while (i < opt_length) {\n block[blockLength++] = bytes.charCodeAt(i++);\n if (blockLength == this.blockSize) {\n this.compress_(block);\n blockLength = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n } else {\n while (i < opt_length) {\n block[blockLength++] = bytes[i++];\n if (blockLength == this.blockSize) {\n this.compress_(block);\n blockLength = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n }\n }\n\n this.blockLength_ = blockLength;\n this.totalLength_ += opt_length;\n};\n\n\n/** @override */\ngoog.crypt.Md5.prototype.digest = function() {\n 'use strict';\n // This must accommodate at least 1 padding byte (0x80), 8 bytes of\n // total bitlength, and must end at a 64-byte boundary.\n var pad = new Array(\n (this.blockLength_ < 56 ? this.blockSize : this.blockSize * 2) -\n this.blockLength_);\n\n // Add padding: 0x80 0x00*\n pad[0] = 0x80;\n for (var i = 1; i < pad.length - 8; ++i) {\n pad[i] = 0;\n }\n // Add the total number of bits, little endian 64-bit integer.\n var totalBits = this.totalLength_ * 8;\n for (var i = pad.length - 8; i < pad.length; ++i) {\n pad[i] = totalBits & 0xff;\n totalBits /= 0x100; // Don't use bit-shifting here!\n }\n this.update(pad);\n\n var digest = new Array(16);\n var n = 0;\n for (var i = 0; i < 4; ++i) {\n for (var j = 0; j < 32; j += 8) {\n digest[n++] = (this.chain_[i] >>> j) & 0xff;\n }\n }\n return digest;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Abstract cryptographic hash interface.\n *\n * See goog.crypt.Sha1 and goog.crypt.Md5 for sample implementations.\n */\n\ngoog.provide('goog.crypt.Hash');\n\n\n\n/**\n * Create a cryptographic hash instance.\n *\n * @constructor\n * @struct\n */\ngoog.crypt.Hash = function() {\n 'use strict';\n /**\n * The block size for the hasher.\n * @type {number}\n */\n this.blockSize = -1;\n};\n\n\n/**\n * Resets the internal accumulator.\n */\ngoog.crypt.Hash.prototype.reset = goog.abstractMethod;\n\n\n/**\n * Adds a byte array (array with values in [0-255] range) or a string (must\n * only contain 8-bit, i.e., Latin1 characters) to the internal accumulator.\n *\n * Many hash functions operate on blocks of data and implement optimizations\n * when a full chunk of data is readily available. Hence it is often preferable\n * to provide large chunks of data (a kilobyte or more) than to repeatedly\n * call the update method with few tens of bytes. If this is not possible, or\n * not feasible, it might be good to provide data in multiplies of hash block\n * size (often 64 bytes). Please see the implementation and performance tests\n * of your favourite hash.\n *\n * @param {Array<number>|Uint8Array|string} bytes Data used for the update.\n * @param {number=} opt_length Number of bytes to use.\n */\ngoog.crypt.Hash.prototype.update = goog.abstractMethod;\n\n\n/**\n * @return {!Array<number>} The finalized hash computed\n * from the internal accumulator.\n */\ngoog.crypt.Hash.prototype.digest = goog.abstractMethod;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Defines an Integer class for representing (potentially)\n * infinite length two's-complement integer values.\n *\n * For the specific case of 64-bit integers, use goog.math.Long, which is more\n * efficient.\n */\n\ngoog.provide('goog.math.Integer');\n\ngoog.require('goog.reflect');\n\n/**\n * Constructs a two's-complement integer an array containing bits of the\n * integer in 32-bit (signed) pieces, given in little-endian order (i.e.,\n * lowest-order bits in the first piece), and the sign of -1 or 0.\n *\n * See the from* functions below for other convenient ways of constructing\n * Integers.\n *\n * The internal representation of an integer is an array of 32-bit signed\n * pieces, along with a sign (0 or -1) that indicates the contents of all the\n * other 32-bit pieces out to infinity. We use 32-bit pieces because these are\n * the size of integers on which JavaScript performs bit-operations. For\n * operations like addition and multiplication, we split each number into 16-bit\n * pieces, which can easily be multiplied within JavaScript's floating-point\n * representation without overflow or change in sign.\n *\n * @struct\n * @constructor\n * @param {Array<number>} bits Array containing the bits of the number.\n * @param {number} sign The sign of the number: -1 for negative and 0 positive.\n * @final\n */\ngoog.math.Integer = function(bits, sign) {\n 'use strict';\n /**\n * @type {number}\n * @private\n */\n this.sign_ = sign;\n\n // Note: using a local variable while initializing the array helps the\n // compiler understand that assigning to the array is local side-effect and\n // that enables the entire constructor to be seen as side-effect free.\n var localBits = [];\n\n // Copy the 32-bit signed integer values passed in. We prune out those at the\n // top that equal the sign since they are redundant.\n var top = true;\n\n for (var i = bits.length - 1; i >= 0; i--) {\n var val = bits[i] | 0;\n if (!top || val != sign) {\n localBits[i] = val;\n top = false;\n }\n }\n\n /**\n * @type {!Array<number>}\n * @private\n * @const\n */\n this.bits_ = localBits;\n};\n\n\n// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the\n// from* methods on which they depend.\n\n\n/**\n * A cache of the Integer representations of small integer values.\n * @type {!Object<number, !goog.math.Integer>}\n * @private\n */\ngoog.math.Integer.IntCache_ = {};\n\n\n/**\n * Returns an Integer representing the given (32-bit) integer value.\n * @param {number} value A 32-bit integer value.\n * @return {!goog.math.Integer} The corresponding Integer value.\n */\ngoog.math.Integer.fromInt = function(value) {\n 'use strict';\n if (-128 <= value && value < 128) {\n return goog.reflect.cache(\n goog.math.Integer.IntCache_, value, function(val) {\n 'use strict';\n return new goog.math.Integer([val | 0], val < 0 ? -1 : 0);\n });\n }\n return new goog.math.Integer([value | 0], value < 0 ? -1 : 0);\n};\n\n\n/**\n * Returns an Integer representing the given value, provided that it is a finite\n * number. Otherwise, zero is returned.\n * @param {number} value The value in question.\n * @return {!goog.math.Integer} The corresponding Integer value.\n */\ngoog.math.Integer.fromNumber = function(value) {\n 'use strict';\n if (isNaN(value) || !isFinite(value)) {\n return goog.math.Integer.ZERO;\n } else if (value < 0) {\n return goog.math.Integer.fromNumber(-value).negate();\n } else {\n var bits = [];\n var pow = 1;\n for (var i = 0; value >= pow; i++) {\n bits[i] = (value / pow) | 0;\n pow *= goog.math.Integer.TWO_PWR_32_DBL_;\n }\n return new goog.math.Integer(bits, 0);\n }\n};\n\n\n/**\n * Returns a Integer representing the value that comes by concatenating the\n * given entries, each is assumed to be 32 signed bits, given in little-endian\n * order (lowest order bits in the lowest index), and sign-extending the highest\n * order 32-bit value.\n * @param {Array<number>} bits The bits of the number, in 32-bit signed pieces,\n * in little-endian order.\n * @return {!goog.math.Integer} The corresponding Integer value.\n */\ngoog.math.Integer.fromBits = function(bits) {\n 'use strict';\n var high = bits[bits.length - 1];\n return new goog.math.Integer(bits, high & (1 << 31) ? -1 : 0);\n};\n\n\n/**\n * Returns an Integer representation of the given string, written using the\n * given radix.\n * @param {string} str The textual representation of the Integer.\n * @param {number=} opt_radix The radix in which the text is written.\n * @return {!goog.math.Integer} The corresponding Integer value.\n */\ngoog.math.Integer.fromString = function(str, opt_radix) {\n 'use strict';\n if (str.length == 0) {\n throw new Error('number format error: empty string');\n }\n\n var radix = opt_radix || 10;\n if (radix < 2 || 36 < radix) {\n throw new Error('radix out of range: ' + radix);\n }\n\n if (str.charAt(0) == '-') {\n return goog.math.Integer.fromString(str.substring(1), radix).negate();\n } else if (str.indexOf('-') >= 0) {\n throw new Error('number format error: interior \"-\" character');\n }\n\n // Do several (8) digits each time through the loop, so as to\n // minimize the calls to the very expensive emulated div.\n var radixToPower = goog.math.Integer.fromNumber(Math.pow(radix, 8));\n\n var result = goog.math.Integer.ZERO;\n for (var i = 0; i < str.length; i += 8) {\n var size = Math.min(8, str.length - i);\n var value = parseInt(str.substring(i, i + size), radix);\n if (size < 8) {\n var power = goog.math.Integer.fromNumber(Math.pow(radix, size));\n result = result.multiply(power).add(goog.math.Integer.fromNumber(value));\n } else {\n result = result.multiply(radixToPower);\n result = result.add(goog.math.Integer.fromNumber(value));\n }\n }\n return result;\n};\n\n\n/**\n * A number used repeatedly in calculations. This must appear before the first\n * call to the from* functions below.\n * @type {number}\n * @private\n */\ngoog.math.Integer.TWO_PWR_32_DBL_ = (1 << 16) * (1 << 16);\n\n\n/** @type {!goog.math.Integer} */\ngoog.math.Integer.ZERO = goog.math.Integer.fromInt(0);\n\n/** @type {!goog.math.Integer} */\ngoog.math.Integer.ONE = goog.math.Integer.fromInt(1);\n\n\n/**\n * @const\n * @type {!goog.math.Integer}\n * @private\n */\ngoog.math.Integer.TWO_PWR_24_ = goog.math.Integer.fromInt(1 << 24);\n\n/**\n * Returns the value, assuming it is a 32-bit integer.\n * @return {number} The corresponding int value.\n */\ngoog.math.Integer.prototype.toInt = function() {\n 'use strict';\n return this.bits_.length > 0 ? this.bits_[0] : this.sign_;\n};\n\n\n/** @return {number} The closest floating-point representation to this value. */\ngoog.math.Integer.prototype.toNumber = function() {\n 'use strict';\n if (this.isNegative()) {\n return -this.negate().toNumber();\n } else {\n var val = 0;\n var pow = 1;\n for (var i = 0; i < this.bits_.length; i++) {\n val += this.getBitsUnsigned(i) * pow;\n pow *= goog.math.Integer.TWO_PWR_32_DBL_;\n }\n return val;\n }\n};\n\n\n/**\n * @param {number=} opt_radix The radix in which the text should be written.\n * @return {string} The textual representation of this value.\n * @override\n */\ngoog.math.Integer.prototype.toString = function(opt_radix) {\n 'use strict';\n var radix = opt_radix || 10;\n if (radix < 2 || 36 < radix) {\n throw new Error('radix out of range: ' + radix);\n }\n\n if (this.isZero()) {\n return '0';\n } else if (this.isNegative()) {\n return '-' + this.negate().toString(radix);\n }\n\n // Do several (6) digits each time through the loop, so as to\n // minimize the calls to the very expensive emulated div.\n var radixToPower = goog.math.Integer.fromNumber(Math.pow(radix, 6));\n\n var rem = this;\n var result = '';\n while (true) {\n var remDiv = rem.divide(radixToPower);\n // The right shifting fixes negative values in the case when\n // intval >= 2^31; for more details see\n // https://github.com/google/closure-library/pull/498\n var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt() >>> 0;\n var digits = intval.toString(radix);\n\n rem = remDiv;\n if (rem.isZero()) {\n return digits + result;\n } else {\n while (digits.length < 6) {\n digits = '0' + digits;\n }\n result = '' + digits + result;\n }\n }\n};\n\n\n/**\n * Returns the index-th 32-bit (signed) piece of the Integer according to\n * little-endian order (i.e., index 0 contains the smallest bits).\n * @param {number} index The index in question.\n * @return {number} The requested 32-bits as a signed number.\n */\ngoog.math.Integer.prototype.getBits = function(index) {\n 'use strict';\n if (index < 0) {\n return 0; // Allowing this simplifies bit shifting operations below...\n } else if (index < this.bits_.length) {\n return this.bits_[index];\n } else {\n return this.sign_;\n }\n};\n\n\n/**\n * Returns the index-th 32-bit piece as an unsigned number.\n * @param {number} index The index in question.\n * @return {number} The requested 32-bits as an unsigned number.\n */\ngoog.math.Integer.prototype.getBitsUnsigned = function(index) {\n 'use strict';\n var val = this.getBits(index);\n return val >= 0 ? val : goog.math.Integer.TWO_PWR_32_DBL_ + val;\n};\n\n\n/** @return {number} The sign bit of this number, -1 or 0. */\ngoog.math.Integer.prototype.getSign = function() {\n 'use strict';\n return this.sign_;\n};\n\n\n/** @return {boolean} Whether this value is zero. */\ngoog.math.Integer.prototype.isZero = function() {\n 'use strict';\n if (this.sign_ != 0) {\n return false;\n }\n for (var i = 0; i < this.bits_.length; i++) {\n if (this.bits_[i] != 0) {\n return false;\n }\n }\n return true;\n};\n\n\n/** @return {boolean} Whether this value is negative. */\ngoog.math.Integer.prototype.isNegative = function() {\n 'use strict';\n return this.sign_ == -1;\n};\n\n\n/** @return {boolean} Whether this value is odd. */\ngoog.math.Integer.prototype.isOdd = function() {\n 'use strict';\n return (this.bits_.length == 0) && (this.sign_ == -1) ||\n (this.bits_.length > 0) && ((this.bits_[0] & 1) != 0);\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer equals the other.\n */\ngoog.math.Integer.prototype.equals = function(other) {\n 'use strict';\n if (this.sign_ != other.sign_) {\n return false;\n }\n var len = Math.max(this.bits_.length, other.bits_.length);\n for (var i = 0; i < len; i++) {\n if (this.getBits(i) != other.getBits(i)) {\n return false;\n }\n }\n return true;\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer does not equal the other.\n */\ngoog.math.Integer.prototype.notEquals = function(other) {\n 'use strict';\n return !this.equals(other);\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer is greater than the other.\n */\ngoog.math.Integer.prototype.greaterThan = function(other) {\n 'use strict';\n return this.compare(other) > 0;\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer is greater than or equal to the other.\n */\ngoog.math.Integer.prototype.greaterThanOrEqual = function(other) {\n 'use strict';\n return this.compare(other) >= 0;\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer is less than the other.\n */\ngoog.math.Integer.prototype.lessThan = function(other) {\n 'use strict';\n return this.compare(other) < 0;\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer is less than or equal to the other.\n */\ngoog.math.Integer.prototype.lessThanOrEqual = function(other) {\n 'use strict';\n return this.compare(other) <= 0;\n};\n\n\n/**\n * Compares this Integer with the given one.\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {number} 0 if they are the same, 1 if the this is greater, and -1\n * if the given one is greater.\n */\ngoog.math.Integer.prototype.compare = function(other) {\n 'use strict';\n var diff = this.subtract(other);\n if (diff.isNegative()) {\n return -1;\n } else if (diff.isZero()) {\n return 0;\n } else {\n return +1;\n }\n};\n\n\n/**\n * Returns an integer with only the first numBits bits of this value, sign\n * extended from the final bit.\n * @param {number} numBits The number of bits by which to shift.\n * @return {!goog.math.Integer} The shorted integer value.\n */\ngoog.math.Integer.prototype.shorten = function(numBits) {\n 'use strict';\n var arr_index = (numBits - 1) >> 5;\n var bit_index = (numBits - 1) % 32;\n var bits = [];\n for (var i = 0; i < arr_index; i++) {\n bits[i] = this.getBits(i);\n }\n var sigBits = bit_index == 31 ? 0xFFFFFFFF : (1 << (bit_index + 1)) - 1;\n var val = this.getBits(arr_index) & sigBits;\n if (val & (1 << bit_index)) {\n val |= 0xFFFFFFFF - sigBits;\n bits[arr_index] = val;\n return new goog.math.Integer(bits, -1);\n } else {\n bits[arr_index] = val;\n return new goog.math.Integer(bits, 0);\n }\n};\n\n\n/** @return {!goog.math.Integer} The negation of this value. */\ngoog.math.Integer.prototype.negate = function() {\n 'use strict';\n return this.not().add(goog.math.Integer.ONE);\n};\n\n\n/** @return {!goog.math.Integer} The absolute value of this value. */\ngoog.math.Integer.prototype.abs = function() {\n 'use strict';\n return this.isNegative() ? this.negate() : this;\n};\n\n\n/**\n * Returns the sum of this and the given Integer.\n * @param {goog.math.Integer} other The Integer to add to this.\n * @return {!goog.math.Integer} The Integer result.\n */\ngoog.math.Integer.prototype.add = function(other) {\n 'use strict';\n var len = Math.max(this.bits_.length, other.bits_.length);\n var arr = [];\n var carry = 0;\n\n for (var i = 0; i <= len; i++) {\n var a1 = this.getBits(i) >>> 16;\n var a0 = this.getBits(i) & 0xFFFF;\n\n var b1 = other.getBits(i) >>> 16;\n var b0 = other.getBits(i) & 0xFFFF;\n\n var c0 = carry + a0 + b0;\n var c1 = (c0 >>> 16) + a1 + b1;\n carry = c1 >>> 16;\n c0 &= 0xFFFF;\n c1 &= 0xFFFF;\n arr[i] = (c1 << 16) | c0;\n }\n return goog.math.Integer.fromBits(arr);\n};\n\n\n/**\n * Returns the difference of this and the given Integer.\n * @param {goog.math.Integer} other The Integer to subtract from this.\n * @return {!goog.math.Integer} The Integer result.\n */\ngoog.math.Integer.prototype.subtract = function(other) {\n 'use strict';\n return this.add(other.negate());\n};\n\n\n/**\n * Returns the product of this and the given Integer.\n * @param {goog.math.Integer} other The Integer to multiply against this.\n * @return {!goog.math.Integer} The product of this and the other.\n */\ngoog.math.Integer.prototype.multiply = function(other) {\n 'use strict';\n if (this.isZero()) {\n return goog.math.Integer.ZERO;\n } else if (other.isZero()) {\n return goog.math.Integer.ZERO;\n }\n\n if (this.isNegative()) {\n if (other.isNegative()) {\n return this.negate().multiply(other.negate());\n } else {\n return this.negate().multiply(other).negate();\n }\n } else if (other.isNegative()) {\n return this.multiply(other.negate()).negate();\n }\n\n // If both numbers are small, use float multiplication\n if (this.lessThan(goog.math.Integer.TWO_PWR_24_) &&\n other.lessThan(goog.math.Integer.TWO_PWR_24_)) {\n return goog.math.Integer.fromNumber(this.toNumber() * other.toNumber());\n }\n\n // Fill in an array of 16-bit products.\n var len = this.bits_.length + other.bits_.length;\n var arr = [];\n for (var i = 0; i < 2 * len; i++) {\n arr[i] = 0;\n }\n for (var i = 0; i < this.bits_.length; i++) {\n for (var j = 0; j < other.bits_.length; j++) {\n var a1 = this.getBits(i) >>> 16;\n var a0 = this.getBits(i) & 0xFFFF;\n\n var b1 = other.getBits(j) >>> 16;\n var b0 = other.getBits(j) & 0xFFFF;\n\n arr[2 * i + 2 * j] += a0 * b0;\n goog.math.Integer.carry16_(arr, 2 * i + 2 * j);\n arr[2 * i + 2 * j + 1] += a1 * b0;\n goog.math.Integer.carry16_(arr, 2 * i + 2 * j + 1);\n arr[2 * i + 2 * j + 1] += a0 * b1;\n goog.math.Integer.carry16_(arr, 2 * i + 2 * j + 1);\n arr[2 * i + 2 * j + 2] += a1 * b1;\n goog.math.Integer.carry16_(arr, 2 * i + 2 * j + 2);\n }\n }\n\n // Combine the 16-bit values into 32-bit values.\n for (var i = 0; i < len; i++) {\n arr[i] = (arr[2 * i + 1] << 16) | arr[2 * i];\n }\n for (var i = len; i < 2 * len; i++) {\n arr[i] = 0;\n }\n return new goog.math.Integer(arr, 0);\n};\n\n\n/**\n * Carries any overflow from the given index into later entries.\n * @param {Array<number>} bits Array of 16-bit values in little-endian order.\n * @param {number} index The index in question.\n * @private\n */\ngoog.math.Integer.carry16_ = function(bits, index) {\n 'use strict';\n while ((bits[index] & 0xFFFF) != bits[index]) {\n bits[index + 1] += bits[index] >>> 16;\n bits[index] &= 0xFFFF;\n index++;\n }\n};\n\n\n/**\n * Returns \"this\" Integer divided by the given one. Both \"this\" and the given\n * Integer MUST be positive.\n *\n * This method is only needed for very large numbers (>10^308),\n * for which the original division algorithm gets into an infinite\n * loop (see https://github.com/google/closure-library/issues/500).\n *\n * The algorithm has some possible performance enhancements (or\n * could be rewritten entirely), it's just an initial solution for\n * the issue linked above.\n *\n * @param {!goog.math.Integer} other The Integer to divide \"this\" by.\n * @return {!goog.math.Integer.DivisionResult}\n * @private\n */\ngoog.math.Integer.prototype.slowDivide_ = function(other) {\n 'use strict';\n if (this.isNegative() || other.isNegative()) {\n throw new Error('slowDivide_ only works with positive integers.');\n }\n\n var twoPower = goog.math.Integer.ONE;\n var multiple = other;\n\n // First we have to figure out what the highest bit of the result\n // is, so we increase \"twoPower\" and \"multiple\" until \"multiple\"\n // exceeds \"this\".\n while (multiple.lessThanOrEqual(this)) {\n twoPower = twoPower.shiftLeft(1);\n multiple = multiple.shiftLeft(1);\n }\n\n // Rewind by one power of two, giving us the highest bit of the\n // result.\n var res = twoPower.shiftRight(1);\n var total = multiple.shiftRight(1);\n\n // Now we starting decreasing \"multiple\" and \"twoPower\" to find the\n // rest of the bits of the result.\n var total2;\n multiple = multiple.shiftRight(2);\n twoPower = twoPower.shiftRight(2);\n while (!multiple.isZero()) {\n // whenever we can add \"multiple\" to the total and not exceed\n // \"this\", that means we've found a 1 bit. Else we've found a 0\n // and don't need to add to the result.\n total2 = total.add(multiple);\n if (total2.lessThanOrEqual(this)) {\n res = res.add(twoPower);\n total = total2;\n }\n multiple = multiple.shiftRight(1);\n twoPower = twoPower.shiftRight(1);\n }\n\n\n // TODO(user): Calculate this more efficiently during the division.\n // This is kind of a waste since it isn't always needed, but it keeps the\n // API smooth. Since this is already a slow path it probably isn't a big deal.\n var remainder = this.subtract(res.multiply(other));\n return new goog.math.Integer.DivisionResult(res, remainder);\n};\n\n\n/**\n * Returns this Integer divided by the given one.\n * @param {!goog.math.Integer} other The Integer to divide this by.\n * @return {!goog.math.Integer} This value divided by the given one.\n */\ngoog.math.Integer.prototype.divide = function(other) {\n 'use strict';\n return this.divideAndRemainder(other).quotient;\n};\n\n\n/**\n * A struct for holding the quotient and remainder of a division.\n *\n * @constructor\n * @final\n * @struct\n *\n * @param {!goog.math.Integer} quotient\n * @param {!goog.math.Integer} remainder\n */\ngoog.math.Integer.DivisionResult = function(quotient, remainder) {\n 'use strict';\n /** @const */\n this.quotient = quotient;\n\n /** @const */\n this.remainder = remainder;\n};\n\n\n/**\n * Returns this Integer divided by the given one, as well as the remainder of\n * that division.\n *\n * @param {!goog.math.Integer} other The Integer to divide this by.\n * @return {!goog.math.Integer.DivisionResult}\n */\ngoog.math.Integer.prototype.divideAndRemainder = function(other) {\n 'use strict';\n if (other.isZero()) {\n throw new Error('division by zero');\n } else if (this.isZero()) {\n return new goog.math.Integer.DivisionResult(\n goog.math.Integer.ZERO, goog.math.Integer.ZERO);\n }\n\n if (this.isNegative()) {\n // Do the division on the negative of the numerator...\n var result = this.negate().divideAndRemainder(other);\n return new goog.math.Integer.DivisionResult(\n // ...and flip the sign back after.\n result.quotient.negate(),\n // The remainder must always have the same sign as the numerator.\n result.remainder.negate());\n } else if (other.isNegative()) {\n // Do the division on the negative of the denominator...\n var result = this.divideAndRemainder(other.negate());\n return new goog.math.Integer.DivisionResult(\n // ...and flip the sign back after.\n result.quotient.negate(),\n // The remainder must always have the same sign as the numerator.\n result.remainder);\n }\n\n // Have to degrade to slowDivide for Very Large Numbers, because\n // they're out of range for the floating-point approximation\n // technique used below.\n if (this.bits_.length > 30) {\n return this.slowDivide_(other);\n }\n\n // Repeat the following until the remainder is less than other: find a\n // floating-point that approximates remainder / other *from below*, add this\n // into the result, and subtract it from the remainder. It is critical that\n // the approximate value is less than or equal to the real value so that the\n // remainder never becomes negative.\n var res = goog.math.Integer.ZERO;\n var rem = this;\n while (rem.greaterThanOrEqual(other)) {\n // Approximate the result of division. This may be a little greater or\n // smaller than the actual value.\n var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));\n\n // We will tweak the approximate result by changing it in the 48-th digit or\n // the smallest non-fractional digit, whichever is larger.\n var log2 = Math.ceil(Math.log(approx) / Math.LN2);\n var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48);\n\n // Decrease the approximation until it is smaller than the remainder. Note\n // that if it is too large, the product overflows and is negative.\n var approxRes = goog.math.Integer.fromNumber(approx);\n var approxRem = approxRes.multiply(other);\n while (approxRem.isNegative() || approxRem.greaterThan(rem)) {\n approx -= delta;\n approxRes = goog.math.Integer.fromNumber(approx);\n approxRem = approxRes.multiply(other);\n }\n\n // We know the answer can't be zero... and actually, zero would cause\n // infinite recursion since we would make no progress.\n if (approxRes.isZero()) {\n approxRes = goog.math.Integer.ONE;\n }\n\n res = res.add(approxRes);\n rem = rem.subtract(approxRem);\n }\n return new goog.math.Integer.DivisionResult(res, rem);\n};\n\n\n/**\n * Returns this Integer modulo the given one.\n * @param {!goog.math.Integer} other The Integer by which to mod.\n * @return {!goog.math.Integer} This value modulo the given one.\n */\ngoog.math.Integer.prototype.modulo = function(other) {\n 'use strict';\n return this.divideAndRemainder(other).remainder;\n};\n\n\n/** @return {!goog.math.Integer} The bitwise-NOT of this value. */\ngoog.math.Integer.prototype.not = function() {\n 'use strict';\n var len = this.bits_.length;\n var arr = [];\n for (var i = 0; i < len; i++) {\n arr[i] = ~this.bits_[i];\n }\n return new goog.math.Integer(arr, ~this.sign_);\n};\n\n\n/**\n * Returns the bitwise-AND of this Integer and the given one.\n * @param {goog.math.Integer} other The Integer to AND with this.\n * @return {!goog.math.Integer} The bitwise-AND of this and the other.\n */\ngoog.math.Integer.prototype.and = function(other) {\n 'use strict';\n var len = Math.max(this.bits_.length, other.bits_.length);\n var arr = [];\n for (var i = 0; i < len; i++) {\n arr[i] = this.getBits(i) & other.getBits(i);\n }\n return new goog.math.Integer(arr, this.sign_ & other.sign_);\n};\n\n\n/**\n * Returns the bitwise-OR of this Integer and the given one.\n * @param {goog.math.Integer} other The Integer to OR with this.\n * @return {!goog.math.Integer} The bitwise-OR of this and the other.\n */\ngoog.math.Integer.prototype.or = function(other) {\n 'use strict';\n var len = Math.max(this.bits_.length, other.bits_.length);\n var arr = [];\n for (var i = 0; i < len; i++) {\n arr[i] = this.getBits(i) | other.getBits(i);\n }\n return new goog.math.Integer(arr, this.sign_ | other.sign_);\n};\n\n\n/**\n * Returns the bitwise-XOR of this Integer and the given one.\n * @param {goog.math.Integer} other The Integer to XOR with this.\n * @return {!goog.math.Integer} The bitwise-XOR of this and the other.\n */\ngoog.math.Integer.prototype.xor = function(other) {\n 'use strict';\n var len = Math.max(this.bits_.length, other.bits_.length);\n var arr = [];\n for (var i = 0; i < len; i++) {\n arr[i] = this.getBits(i) ^ other.getBits(i);\n }\n return new goog.math.Integer(arr, this.sign_ ^ other.sign_);\n};\n\n\n/**\n * Returns this value with bits shifted to the left by the given amount.\n * @param {number} numBits The number of bits by which to shift.\n * @return {!goog.math.Integer} This shifted to the left by the given amount.\n */\ngoog.math.Integer.prototype.shiftLeft = function(numBits) {\n 'use strict';\n var arr_delta = numBits >> 5;\n var bit_delta = numBits % 32;\n var len = this.bits_.length + arr_delta + (bit_delta > 0 ? 1 : 0);\n var arr = [];\n for (var i = 0; i < len; i++) {\n if (bit_delta > 0) {\n arr[i] = (this.getBits(i - arr_delta) << bit_delta) |\n (this.getBits(i - arr_delta - 1) >>> (32 - bit_delta));\n } else {\n arr[i] = this.getBits(i - arr_delta);\n }\n }\n return new goog.math.Integer(arr, this.sign_);\n};\n\n\n/**\n * Returns this value with bits shifted to the right by the given amount.\n * @param {number} numBits The number of bits by which to shift.\n * @return {!goog.math.Integer} This shifted to the right by the given amount.\n */\ngoog.math.Integer.prototype.shiftRight = function(numBits) {\n 'use strict';\n var arr_delta = numBits >> 5;\n var bit_delta = numBits % 32;\n var len = this.bits_.length - arr_delta;\n var arr = [];\n for (var i = 0; i < len; i++) {\n if (bit_delta > 0) {\n arr[i] = (this.getBits(i + arr_delta) >>> bit_delta) |\n (this.getBits(i + arr_delta + 1) << (32 - bit_delta));\n } else {\n arr[i] = this.getBits(i + arr_delta);\n }\n }\n return new goog.math.Integer(arr, this.sign_);\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Transport support for WebChannel.\n *\n * The <code>WebChannelTransport</code> implementation serves as the factory\n * for <code>WebChannel</code>, which offers an abstraction for\n * point-to-point socket-like communication similar to what BrowserChannel\n * or HTML5 WebSocket offers.\n */\n\ngoog.provide('goog.net.WebChannelTransport');\n\ngoog.requireType('goog.net.WebChannel');\ngoog.requireType('goog.net.WebChannel.Options');\n\n\n\n/**\n * A WebChannelTransport instance represents a shared context of logical\n * connectivity between a browser client and a remote origin.\n *\n * Over a single WebChannelTransport instance, multiple WebChannels may be\n * created against different URLs, which may all share the same\n * underlying connectivity (i.e. TCP connection) whenever possible.\n *\n * When multi-domains are supported, such as CORS, multiple origins may be\n * supported over a single WebChannelTransport instance at the same time.\n *\n * Sharing between different window contexts such as tabs is not addressed\n * by WebChannelTransport. Applications may choose HTML5 shared workers\n * or other techniques to access the same transport instance\n * across different window contexts.\n *\n * @interface\n */\ngoog.net.WebChannelTransport = function() {};\n\n\n/**\n * The client version. This integer value will be passed to the server\n * when a channel is opened to inform the server the client \"capabilities\".\n *\n * Wire protocol version is a different concept and is internal to the\n * transport implementation.\n *\n * @const\n * @type {number}\n */\ngoog.net.WebChannelTransport.CLIENT_VERSION = 22;\n\n\n/**\n * Create a new WebChannel instance.\n *\n * The new WebChannel is to be opened against the server-side resource\n * as specified by the given URL. See {@link goog.net.WebChannel} for detailed\n * semantics.\n *\n * @param {string} url The URL path for the new WebChannel instance.\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\n * new WebChannel instance. The configuration object is reusable after\n * the new channel instance is created.\n * @return {!goog.net.WebChannel} the newly created WebChannel instance.\n */\ngoog.net.WebChannelTransport.prototype.createWebChannel = goog.abstractMethod;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Bring in closure-library dependencies\n */\n\ngoog.provide('firebase.webchannel.wrapper');\n\n// goog.net.WebChannelTransport\ngoog.require('goog.net.createWebChannelTransport');\ngoog.require('goog.net.FetchXmlHttpFactory');\ngoog.require('goog.labs.net.webChannel.requestStats');\ngoog.require('goog.labs.net.webChannel.WebChannelBaseTransport');\n\n/**\n * NOTE: The `createWebChannel` function takes an options object as a second param\n * whose properties are typically mangled. We override these in externs/overrides.js\n * Without those externs, this does not function properly.\n */\ngoog.labs.net.webChannel.WebChannelBaseTransport.prototype['createWebChannel'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.prototype.createWebChannel;\ngoog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype['send'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.send;\ngoog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype['open'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.open;\ngoog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype['close'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.close;\n\n// goog.net.ErrorCode\ngoog.require('goog.net.ErrorCode');\ngoog.net.ErrorCode['NO_ERROR'] = goog.net.ErrorCode.NO_ERROR;\ngoog.net.ErrorCode['TIMEOUT'] = goog.net.ErrorCode.TIMEOUT;\ngoog.net.ErrorCode['HTTP_ERROR'] = goog.net.ErrorCode.HTTP_ERROR;\n\n// goog.net.ErrorType\ngoog.require('goog.net.EventType');\ngoog.net.EventType['COMPLETE'] = goog.net.EventType.COMPLETE;\n\n// goog.net.WebChannel\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.events.EventTarget');\ngoog.net.WebChannel['EventType'] = goog.net.WebChannel.EventType;\ngoog.net.WebChannel.EventType['OPEN'] = goog.net.WebChannel.EventType.OPEN;\ngoog.net.WebChannel.EventType['CLOSE'] = goog.net.WebChannel.EventType.CLOSE;\ngoog.net.WebChannel.EventType['ERROR'] = goog.net.WebChannel.EventType.ERROR;\ngoog.net.WebChannel.EventType['MESSAGE'] =\n goog.net.WebChannel.EventType.MESSAGE;\ngoog.events.EventTarget.prototype['listen'] =\n goog.events.EventTarget.prototype.listen;\n\ngoog.require('goog.net.XhrIo');\ngoog.net.XhrIo.prototype['listenOnce'] = goog.net.XhrIo.prototype.listenOnce;\ngoog.net.XhrIo.prototype['getLastError'] =\n goog.net.XhrIo.prototype.getLastError;\ngoog.net.XhrIo.prototype['getLastErrorCode'] =\n goog.net.XhrIo.prototype.getLastErrorCode;\ngoog.net.XhrIo.prototype['getStatus'] = goog.net.XhrIo.prototype.getStatus;\ngoog.net.XhrIo.prototype['getResponseJson'] =\n goog.net.XhrIo.prototype.getResponseJson;\ngoog.net.XhrIo.prototype['getResponseText'] =\n goog.net.XhrIo.prototype.getResponseText;\ngoog.net.XhrIo.prototype['send'] = goog.net.XhrIo.prototype.send;\ngoog.net.XhrIo.prototype['setWithCredentials'] =\n goog.net.XhrIo.prototype.setWithCredentials;\n\ngoog.require('goog.crypt.Md5');\ngoog.crypt.Md5.prototype['digest'] = goog.crypt.Md5.prototype.digest;\ngoog.crypt.Md5.prototype['reset'] = goog.crypt.Md5.prototype.reset;\ngoog.crypt.Md5.prototype['update'] = goog.crypt.Md5.prototype.update;\n\ngoog.require('goog.math.Integer');\ngoog.math.Integer.prototype['add'] = goog.math.Integer.prototype.add;\ngoog.math.Integer.prototype['multiply'] = goog.math.Integer.prototype.multiply;\ngoog.math.Integer.prototype['modulo'] = goog.math.Integer.prototype.modulo;\ngoog.math.Integer.prototype['compare'] = goog.math.Integer.prototype.compare;\ngoog.math.Integer.prototype['toNumber'] = goog.math.Integer.prototype.toNumber;\ngoog.math.Integer.prototype['toString'] = goog.math.Integer.prototype.toString;\ngoog.math.Integer.prototype['getBits'] = goog.math.Integer.prototype.getBits;\ngoog.math.Integer['fromNumber'] = goog.math.Integer.fromNumber;\ngoog.math.Integer['fromString'] = goog.math.Integer.fromString;\n\nmodule['exports']['createWebChannelTransport'] =\n goog.net.createWebChannelTransport;\nmodule['exports']['getStatEventTarget'] =\n goog.labs.net.webChannel.requestStats.getStatEventTarget;\nmodule['exports']['ErrorCode'] = goog.net.ErrorCode;\nmodule['exports']['EventType'] = goog.net.EventType;\nmodule['exports']['Event'] = goog.labs.net.webChannel.requestStats.Event;\nmodule['exports']['Stat'] = goog.labs.net.webChannel.requestStats.Stat;\nmodule['exports']['FetchXmlHttpFactory'] = goog.net.FetchXmlHttpFactory;\nmodule['exports']['WebChannel'] = goog.net.WebChannel;\nmodule['exports']['XhrIo'] = goog.net.XhrIo;\nmodule['exports']['Md5'] = goog.crypt.Md5;\nmodule['exports']['Integer'] = goog.math.Integer;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Default factory for <code>WebChannelTransport</code> to\n * avoid exposing concrete classes to clients.\n */\n\ngoog.provide('goog.net.createWebChannelTransport');\n\ngoog.require('goog.labs.net.webChannel.WebChannelBaseTransport');\ngoog.requireType('goog.net.WebChannelTransport');\n\n\n/**\n * Create a new WebChannelTransport instance using the default implementation.\n * Throws an error message if no default transport available in the current\n * environment.\n *\n * @return {!goog.net.WebChannelTransport} the newly created transport instance.\n */\ngoog.net.createWebChannelTransport = function() {\n 'use strict';\n return new goog.labs.net.webChannel.WebChannelBaseTransport();\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n * <ul>\n * <li>`debug` for the most verbose logging level, primarily for\n * debugging.</li>\n * <li>`error` to log errors only.</li>\n * <li><code>`silent` to turn off logging.</li>\n * </ul>\n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n logClient.setLogLevel(logLevel);\n}\n\nexport function logDebug(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n const args = obj.map(argToString);\n logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function logError(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n const args = obj.map(argToString);\n logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * @internal\n */\nexport function logWarn(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n const args = obj.map(argToString);\n logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj: unknown): string | unknown {\n if (typeof obj === 'string') {\n return obj;\n } else {\n try {\n return formatJSON(obj);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Formats an object as a JSON string, suitable for logging. */\nexport function formatJSON(value: unknown): string {\n return JSON.stringify(value);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../core/version';\n\nimport { logError } from './log';\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */\nexport function fail(failure: string = 'Unexpected state'): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const message =\n `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ` + failure;\n logError(message);\n\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n */\nexport function hardAssert(\n assertion: boolean,\n message?: string\n): asserts assertion {\n if (!assertion) {\n fail(message);\n }\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */\nexport function debugAssert(\n assertion: boolean,\n message: string\n): asserts assertion {\n if (!assertion) {\n fail(message);\n }\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */\nexport function debugCast<T>(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n debugAssert(\n obj instanceof constructor,\n `Expected type '${constructor.name}', but was '${obj.constructor.name}'`\n );\n return obj as T;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * The set of Firestore status codes. The codes are the same at the ones\n * exposed by gRPC here:\n * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md\n *\n * Possible values:\n * - 'cancelled': The operation was cancelled (typically by the caller).\n * - 'unknown': Unknown error or an error from a different error domain.\n * - 'invalid-argument': Client specified an invalid argument. Note that this\n * differs from 'failed-precondition'. 'invalid-argument' indicates\n * arguments that are problematic regardless of the state of the system\n * (e.g. an invalid field name).\n * - 'deadline-exceeded': Deadline expired before operation could complete.\n * For operations that change the state of the system, this error may be\n * returned even if the operation has completed successfully. For example,\n * a successful response from a server could have been delayed long enough\n * for the deadline to expire.\n * - 'not-found': Some requested document was not found.\n * - 'already-exists': Some document that we attempted to create already\n * exists.\n * - 'permission-denied': The caller does not have permission to execute the\n * specified operation.\n * - 'resource-exhausted': Some resource has been exhausted, perhaps a\n * per-user quota, or perhaps the entire file system is out of space.\n * - 'failed-precondition': Operation was rejected because the system is not\n * in a state required for the operation's execution.\n * - 'aborted': The operation was aborted, typically due to a concurrency\n * issue like transaction aborts, etc.\n * - 'out-of-range': Operation was attempted past the valid range.\n * - 'unimplemented': Operation is not implemented or not supported/enabled.\n * - 'internal': Internal errors. Means some invariants expected by\n * underlying system has been broken. If you see one of these errors,\n * something is very broken.\n * - 'unavailable': The service is currently unavailable. This is most likely\n * a transient condition and may be corrected by retrying with a backoff.\n * - 'data-loss': Unrecoverable data loss or corruption.\n * - 'unauthenticated': The request does not have valid authentication\n * credentials for the operation.\n */\nexport type FirestoreErrorCode =\n | 'cancelled'\n | 'unknown'\n | 'invalid-argument'\n | 'deadline-exceeded'\n | 'not-found'\n | 'already-exists'\n | 'permission-denied'\n | 'resource-exhausted'\n | 'failed-precondition'\n | 'aborted'\n | 'out-of-range'\n | 'unimplemented'\n | 'internal'\n | 'unavailable'\n | 'data-loss'\n | 'unauthenticated';\n\n/**\n * Error Codes describing the different ways Firestore can fail. These come\n * directly from GRPC.\n */\nexport type Code = FirestoreErrorCode;\n\nexport const Code = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: 'ok' as FirestoreErrorCode,\n\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: 'cancelled' as FirestoreErrorCode,\n\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: 'unknown' as FirestoreErrorCode,\n\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: 'invalid-argument' as FirestoreErrorCode,\n\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: 'deadline-exceeded' as FirestoreErrorCode,\n\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: 'not-found' as FirestoreErrorCode,\n\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: 'already-exists' as FirestoreErrorCode,\n\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller can not be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: 'permission-denied' as FirestoreErrorCode,\n\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: 'unauthenticated' as FirestoreErrorCode,\n\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: 'resource-exhausted' as FirestoreErrorCode,\n\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: 'failed-precondition' as FirestoreErrorCode,\n\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: 'aborted' as FirestoreErrorCode,\n\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: 'out-of-range' as FirestoreErrorCode,\n\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: 'unimplemented' as FirestoreErrorCode,\n\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: 'internal' as FirestoreErrorCode,\n\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: 'unavailable' as FirestoreErrorCode,\n\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: 'data-loss' as FirestoreErrorCode\n};\n\n/** An error returned by a Firestore operation. */\nexport class FirestoreError extends FirebaseError {\n /** The stack of the error. */\n readonly stack?: string;\n\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n readonly code: FirestoreErrorCode,\n /**\n * A custom error description.\n */\n readonly message: string\n ) {\n super(code, message);\n\n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Resolver<R> {\n (value: R | Promise<R>): void;\n}\n\nexport interface Rejecter {\n (reason?: Error): void;\n}\n\nexport class Deferred<R = void> {\n promise: Promise<R>;\n // Assigned synchronously in constructor by Promise constructor callback.\n resolve!: Resolver<R>;\n reject!: Rejecter;\n\n constructor() {\n this.promise = new Promise((resolve: Resolver<R>, reject: Rejecter) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\n\n/**\n * Takes an array of values and a function from a value to a Promise. The function is run on each\n * value sequentially, waiting for the previous promise to resolve before starting the next one.\n * The returned promise resolves once the function has been run on all values.\n */\nexport function sequence<T>(\n values: T[],\n fn: (value: T) => Promise<void>\n): Promise<void> {\n let p = Promise.resolve();\n for (const value of values) {\n p = p.then(() => fn(value));\n }\n return p;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { User } from '../auth/user';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { Deferred } from '../util/promise';\n\n// TODO(mikelehen): This should be split into multiple files and probably\n// moved to an auth/ folder to match other platforms.\n\n/**\n * @internal\n */\nexport type AuthTokenFactory = () => string;\n\n/**\n * @internal\n */\nexport interface FirstPartyCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'firstParty';\n ['sessionIndex']: string;\n ['iamToken']: string | null;\n ['authTokenFactory']: AuthTokenFactory | null;\n}\n\nexport interface ProviderCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'provider';\n ['client']: CredentialsProvider<User>;\n}\n\n/** Settings for private credentials */\nexport type CredentialsSettings =\n | FirstPartyCredentialsSettings\n | ProviderCredentialsSettings;\n\nexport type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';\nexport interface Token {\n /** Type of token. */\n type: TokenType;\n\n /**\n * The user with which the token is associated (used for persisting user\n * state on disk, etc.).\n * This will be null for Tokens of the type 'AppCheck'.\n */\n user?: User;\n\n /** Header values to set for this token */\n headers: Map<string, string>;\n}\n\nexport class OAuthToken implements Token {\n type = 'OAuth' as TokenType;\n headers = new Map();\n\n constructor(value: string, public user: User) {\n this.headers.set('Authorization', `Bearer ${value}`);\n }\n}\n\n/**\n * A Listener for credential change events. The listener should fetch a new\n * token and may need to invalidate other state if the current user has also\n * changed.\n */\nexport type CredentialChangeListener<T> = (credential: T) => Promise<void>;\n\n/**\n * Provides methods for getting the uid and token for the current user and\n * listening for changes.\n */\nexport interface CredentialsProvider<T> {\n /**\n * Starts the credentials provider and specifies a listener to be notified of\n * credential changes (sign-in / sign-out, token changes). It is immediately\n * called once with the initial user.\n *\n * The change listener is invoked on the provided AsyncQueue.\n */\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<T>\n ): void;\n\n /** Requests a token for the current user. */\n getToken(): Promise<Token | null>;\n\n /**\n * Marks the last retrieved token as invalid, making the next GetToken request\n * force-refresh the token.\n */\n invalidateToken(): void;\n\n shutdown(): void;\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */\nexport class EmptyAuthCredentialsProvider implements CredentialsProvider<User> {\n getToken(): Promise<Token | null> {\n return Promise.resolve<Token | null>(null);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED));\n }\n\n shutdown(): void {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */\nexport class EmulatorAuthCredentialsProvider\n implements CredentialsProvider<User>\n{\n constructor(private token: Token) {}\n\n /**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n private changeListener: CredentialChangeListener<User> | null = null;\n\n getToken(): Promise<Token | null> {\n return Promise.resolve(this.token);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {\n debugAssert(\n !this.changeListener,\n 'Can only call setChangeListener() once.'\n );\n this.changeListener = changeListener;\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(this.token.user!));\n }\n\n shutdown(): void {\n this.changeListener = null;\n }\n}\n\n/** Credential provider for the Lite SDK. */\nexport class LiteAuthCredentialsProvider implements CredentialsProvider<User> {\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(authProvider: Provider<FirebaseAuthInternalName>) {\n authProvider.onInit(auth => {\n this.auth = auth;\n });\n }\n\n getToken(): Promise<Token | null> {\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken().then(tokenData => {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 'Invalid tokenData returned from getToken():' + tokenData\n );\n return new OAuthToken(\n tokenData.accessToken,\n new User(this.auth!.getUid())\n );\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {}\n\n shutdown(): void {}\n}\n\nexport class FirebaseAuthCredentialsProvider\n implements CredentialsProvider<User>\n{\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n private tokenListener!: () => void;\n\n /** Tracks the current User. */\n private currentUser: User = User.UNAUTHENTICATED;\n\n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n private tokenCounter = 0;\n\n private forceRefresh = false;\n\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(private authProvider: Provider<FirebaseAuthInternalName>) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {\n let lastTokenId = this.tokenCounter;\n\n // A change listener that prevents double-firing for the same token change.\n const guardedChangeListener: (user: User) => Promise<void> = user => {\n if (this.tokenCounter !== lastTokenId) {\n lastTokenId = this.tokenCounter;\n return changeListener(user);\n } else {\n return Promise.resolve();\n }\n };\n\n // A promise that can be waited on to block on the next token change.\n // This promise is re-created after each change.\n let nextToken = new Deferred<void>();\n\n this.tokenListener = () => {\n this.tokenCounter++;\n this.currentUser = this.getUser();\n nextToken.resolve();\n nextToken = new Deferred<void>();\n asyncQueue.enqueueRetryable(() =>\n guardedChangeListener(this.currentUser)\n );\n };\n\n const awaitNextToken: () => void = () => {\n const currentTokenAttempt = nextToken;\n asyncQueue.enqueueRetryable(async () => {\n await currentTokenAttempt.promise;\n await guardedChangeListener(this.currentUser);\n });\n };\n\n const registerAuth = (auth: FirebaseAuthInternal): void => {\n logDebug('FirebaseAuthCredentialsProvider', 'Auth detected');\n this.auth = auth;\n this.auth.addAuthTokenListener(this.tokenListener);\n awaitNextToken();\n };\n\n this.authProvider.onInit(auth => registerAuth(auth));\n\n // Our users can initialize Auth right after Firestore, so we give it\n // a chance to register itself with the component framework before we\n // determine whether to start up in unauthenticated mode.\n setTimeout(() => {\n if (!this.auth) {\n const auth = this.authProvider.getImmediate({ optional: true });\n if (auth) {\n registerAuth(auth);\n } else {\n // If auth is still not available, proceed with `null` user\n logDebug('FirebaseAuthCredentialsProvider', 'Auth not yet detected');\n nextToken.resolve();\n nextToken = new Deferred<void>();\n }\n }\n }, 0);\n\n awaitNextToken();\n }\n\n getToken(): Promise<Token | null> {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAuthCredentialsProvider not started.'\n );\n\n // Take note of the current value of the tokenCounter so that this method\n // can fail (with an ABORTED error) if there is a token change while the\n // request is outstanding.\n const initialTokenCounter = this.tokenCounter;\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken(forceRefresh).then(tokenData => {\n // Cancel the request since the token changed while the request was\n // outstanding so the response is potentially for a previous user (which\n // user, we can't be sure).\n if (this.tokenCounter !== initialTokenCounter) {\n logDebug(\n 'FirebaseAuthCredentialsProvider',\n 'getToken aborted due to token change.'\n );\n return this.getToken();\n } else {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 'Invalid tokenData returned from getToken():' + tokenData\n );\n return new OAuthToken(tokenData.accessToken, this.currentUser);\n } else {\n return null;\n }\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.auth) {\n this.auth.removeAuthTokenListener(this.tokenListener!);\n }\n }\n\n // Auth.getUid() can return null even with a user logged in. It is because\n // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n // This method should only be called in the AuthTokenListener callback\n // to guarantee to get the actual user.\n private getUser(): User {\n const currentUid = this.auth && this.auth.getUid();\n hardAssert(\n currentUid === null || typeof currentUid === 'string',\n 'Received invalid UID: ' + currentUid\n );\n return new User(currentUid);\n }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */\nexport class FirstPartyToken implements Token {\n type = 'FirstParty' as TokenType;\n user = User.FIRST_PARTY;\n private _headers = new Map();\n\n constructor(\n private readonly sessionIndex: string,\n private readonly iamToken: string | null,\n private readonly authTokenFactory: AuthTokenFactory | null\n ) {}\n\n /**\n * Gets an authorization token, using a provided factory function, or return\n * null.\n */\n private getAuthToken(): string | null {\n if (this.authTokenFactory) {\n return this.authTokenFactory();\n } else {\n return null;\n }\n }\n\n get headers(): Map<string, string> {\n this._headers.set('X-Goog-AuthUser', this.sessionIndex);\n // Use array notation to prevent minification\n const authHeaderTokenValue = this.getAuthToken();\n if (authHeaderTokenValue) {\n this._headers.set('Authorization', authHeaderTokenValue);\n }\n if (this.iamToken) {\n this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken);\n }\n\n return this._headers;\n }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */\nexport class FirstPartyAuthCredentialsProvider\n implements CredentialsProvider<User>\n{\n constructor(\n private sessionIndex: string,\n private iamToken: string | null,\n private authTokenFactory: AuthTokenFactory | null\n ) {}\n\n getToken(): Promise<Token | null> {\n return Promise.resolve(\n new FirstPartyToken(\n this.sessionIndex,\n this.iamToken,\n this.authTokenFactory\n )\n );\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {\n // Fire with initial uid.\n asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY));\n }\n\n shutdown(): void {}\n\n invalidateToken(): void {}\n}\n\nexport class AppCheckToken implements Token {\n type = 'AppCheck' as TokenType;\n headers = new Map();\n\n constructor(private value: string) {\n if (value && value.length > 0) {\n this.headers.set('x-firebase-appcheck', this.value);\n }\n }\n}\n\nexport class FirebaseAppCheckTokenProvider\n implements CredentialsProvider<string>\n{\n /**\n * The AppCheck token listener registered with FirebaseApp, retained here so\n * we can unregister it.\n */\n private tokenListener!: AppCheckTokenListener;\n private forceRefresh = false;\n private appCheck: FirebaseAppCheckInternal | null = null;\n private latestAppCheckToken: string | null = null;\n\n constructor(\n private appCheckProvider: Provider<AppCheckInternalComponentName>\n ) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<string>\n ): void {\n const onTokenChanged: (\n tokenResult: AppCheckTokenResult\n ) => Promise<void> = tokenResult => {\n if (tokenResult.error != null) {\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Error getting App Check token; using placeholder token instead. Error: ${tokenResult.error.message}`\n );\n }\n const tokenUpdated = tokenResult.token !== this.latestAppCheckToken;\n this.latestAppCheckToken = tokenResult.token;\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Received ${tokenUpdated ? 'new' : 'existing'} token.`\n );\n return tokenUpdated\n ? changeListener(tokenResult.token)\n : Promise.resolve();\n };\n\n this.tokenListener = (tokenResult: AppCheckTokenResult) => {\n asyncQueue.enqueueRetryable(() => onTokenChanged(tokenResult));\n };\n\n const registerAppCheck = (appCheck: FirebaseAppCheckInternal): void => {\n logDebug('FirebaseAppCheckTokenProvider', 'AppCheck detected');\n this.appCheck = appCheck;\n this.appCheck.addTokenListener(this.tokenListener);\n };\n\n this.appCheckProvider.onInit(appCheck => registerAppCheck(appCheck));\n\n // Our users can initialize AppCheck after Firestore, so we give it\n // a chance to register itself with the component framework.\n setTimeout(() => {\n if (!this.appCheck) {\n const appCheck = this.appCheckProvider.getImmediate({ optional: true });\n if (appCheck) {\n registerAppCheck(appCheck);\n } else {\n // If AppCheck is still not available, proceed without it.\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n 'AppCheck not yet detected'\n );\n }\n }\n }, 0);\n }\n\n getToken(): Promise<Token | null> {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAppCheckTokenProvider not started.'\n );\n\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken(forceRefresh).then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 'Invalid tokenResult returned from getToken():' + tokenResult\n );\n this.latestAppCheckToken = tokenResult.token;\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.appCheck) {\n this.appCheck.removeTokenListener(this.tokenListener!);\n }\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */\nexport class EmptyAppCheckTokenProvider implements CredentialsProvider<string> {\n getToken(): Promise<Token | null> {\n return Promise.resolve<Token | null>(new AppCheckToken(''));\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<string>\n ): void {}\n\n shutdown(): void {}\n}\n\n/** AppCheck token provider for the Lite SDK. */\nexport class LiteAppCheckTokenProvider implements CredentialsProvider<string> {\n private appCheck: FirebaseAppCheckInternal | null = null;\n\n constructor(\n private appCheckProvider: Provider<AppCheckInternalComponentName>\n ) {\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise<Token | null> {\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken().then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 'Invalid tokenResult returned from getToken():' + tokenResult\n );\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<string>\n ): void {}\n\n shutdown(): void {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeAuthCredentialsProvider(\n credentials?: CredentialsSettings\n): CredentialsProvider<User> {\n if (!credentials) {\n return new EmptyAuthCredentialsProvider();\n }\n switch (credentials['type']) {\n case 'firstParty':\n return new FirstPartyAuthCredentialsProvider(\n credentials['sessionIndex'] || '0',\n credentials['iamToken'] || null,\n credentials['authTokenFactory'] || null\n );\n\n case 'provider':\n return credentials['client'];\n\n default:\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'makeAuthCredentialsProvider failed due to invalid credential type'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../../util/assert';\n\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nexport function randomBytes(nBytes: number): Uint8Array {\n debugAssert(nBytes >= 0, `Expecting non-negative nBytes, got: ${nBytes}`);\n\n // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n const crypto =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof self !== 'undefined' && (self.crypto || (self as any)['msCrypto']);\n const bytes = new Uint8Array(nBytes);\n if (crypto && typeof crypto.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n // Falls back to Math.random\n for (let i = 0; i < nBytes; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n return bytes;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { randomBytes } from '../platform/random_bytes';\n\nimport { debugAssert } from './assert';\n\nexport type EventHandler<E> = (value: E) => void;\nexport interface Indexable {\n [k: string]: unknown;\n}\n\n/**\n * A utility class for generating unique alphanumeric IDs of a specified length.\n *\n * @internal\n * Exported internally for testing purposes.\n */\nexport class AutoId {\n static newId(): string {\n // Alphanumeric characters\n const chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n // The largest byte value that is a multiple of `char.length`.\n const maxMultiple = Math.floor(256 / chars.length) * chars.length;\n debugAssert(\n 0 < maxMultiple && maxMultiple < 256,\n `Expect maxMultiple to be (0, 256), but got ${maxMultiple}`\n );\n\n let autoId = '';\n const targetLength = 20;\n while (autoId.length < targetLength) {\n const bytes = randomBytes(40);\n for (let i = 0; i < bytes.length; ++i) {\n // Only accept values that are [0, maxMultiple), this ensures they can\n // be evenly mapped to indices of `chars` via a modulo operation.\n if (autoId.length < targetLength && bytes[i] < maxMultiple) {\n autoId += chars.charAt(bytes[i] % chars.length);\n }\n }\n }\n debugAssert(autoId.length === targetLength, 'Invalid auto ID: ' + autoId);\n\n return autoId;\n }\n}\n\nexport function primitiveComparator<T>(left: T, right: T): number {\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n return 0;\n}\n\nexport interface Equatable<T> {\n isEqual(other: T): boolean;\n}\n\nexport interface Iterable<V> {\n forEach: (cb: (v: V) => void) => void;\n}\n\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals<T>(\n left: T[],\n right: T[],\n comparator: (l: T, r: T) => boolean\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => comparator(value, right[index]));\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nexport function immediateSuccessor(s: string): string {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\nimport { primitiveComparator } from '../util/misc';\n\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\nconst MIN_SECONDS = -62135596800;\n\n// Number of nanoseconds in a millisecond.\nconst MS_TO_NANOS = 1e6;\n\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nexport class Timestamp {\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */\n static now(): Timestamp {\n return Timestamp.fromMillis(Date.now());\n }\n\n /**\n * Creates a new timestamp from the given date.\n *\n * @param date - The date to initialize the `Timestamp` from.\n * @returns A new `Timestamp` representing the same point in time as the given\n * date.\n */\n static fromDate(date: Date): Timestamp {\n return Timestamp.fromMillis(date.getTime());\n }\n\n /**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds - Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @returns A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */\n static fromMillis(milliseconds: number): Timestamp {\n const seconds = Math.floor(milliseconds / 1000);\n const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS);\n return new Timestamp(seconds, nanos);\n }\n\n /**\n * Creates a new timestamp.\n *\n * @param seconds - The number of seconds of UTC time since Unix epoch\n * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59Z inclusive.\n * @param nanoseconds - The non-negative fractions of a second at nanosecond\n * resolution. Negative second values with fractions must still have\n * non-negative nanoseconds values that count forward in time. Must be\n * from 0 to 999,999,999 inclusive.\n */\n constructor(\n /**\n * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n */\n readonly seconds: number,\n /**\n * The fractions of a second at nanosecond resolution.*\n */\n readonly nanoseconds: number\n ) {\n if (nanoseconds < 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (nanoseconds >= 1e9) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (seconds < MIN_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n // This will break in the year 10,000.\n if (seconds >= 253402300800) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n }\n\n /**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n * causes a loss of precision since `Date` objects only support millisecond\n * precision.\n *\n * @returns JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */\n toDate(): Date {\n return new Date(this.toMillis());\n }\n\n /**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @returns The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */\n toMillis(): number {\n return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS;\n }\n\n _compareTo(other: Timestamp): number {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanoseconds, other.nanoseconds);\n }\n return primitiveComparator(this.seconds, other.seconds);\n }\n\n /**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other - The `Timestamp` to compare against.\n * @returns true if this `Timestamp` is equal to the provided one.\n */\n isEqual(other: Timestamp): boolean {\n return (\n other.seconds === this.seconds && other.nanoseconds === this.nanoseconds\n );\n }\n\n /** Returns a textual representation of this `Timestamp`. */\n toString(): string {\n return (\n 'Timestamp(seconds=' +\n this.seconds +\n ', nanoseconds=' +\n this.nanoseconds +\n ')'\n );\n }\n\n /** Returns a JSON-serializable representation of this `Timestamp`. */\n toJSON(): { seconds: number; nanoseconds: number } {\n return { seconds: this.seconds, nanoseconds: this.nanoseconds };\n }\n\n /**\n * Converts this object to a primitive string, which allows `Timestamp` objects\n * to be compared using the `>`, `<=`, `>=` and `>` operators.\n */\n valueOf(): string {\n // This method returns a string of the form <seconds>.<nanoseconds> where\n // <seconds> is translated to have a non-negative value and both <seconds>\n // and <nanoseconds> are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexiographical ordering that matches\n // the expected ordering. The <seconds> translation is done to avoid having\n // a leading negative sign (i.e. a leading '-' character) in its string\n // representation, which would affect its lexiographical ordering.\n const adjustedSeconds = this.seconds - MIN_SECONDS;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n const formattedSeconds = String(adjustedSeconds).padStart(12, '0');\n const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');\n return formattedSeconds + '.' + formattedNanoseconds;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\n\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nexport class SnapshotVersion {\n static fromTimestamp(value: Timestamp): SnapshotVersion {\n return new SnapshotVersion(value);\n }\n\n static min(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(0, 0));\n }\n\n static max(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1));\n }\n\n private constructor(private timestamp: Timestamp) {}\n\n compareTo(other: SnapshotVersion): number {\n return this.timestamp._compareTo(other.timestamp);\n }\n\n isEqual(other: SnapshotVersion): boolean {\n return this.timestamp.isEqual(other.timestamp);\n }\n\n /** Returns a number representation of the version for use in spec tests. */\n toMicroseconds(): number {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;\n }\n\n toString(): string {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n }\n\n toTimestamp(): Timestamp {\n return this.timestamp;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DOCUMENT_KEY_NAME = '__name__';\n\n/**\n * Path represents an ordered sequence of string segments.\n */\nabstract class BasePath<B extends BasePath<B>> {\n private segments: string[];\n private offset: number;\n private len: number;\n\n constructor(segments: string[], offset?: number, length?: number) {\n if (offset === undefined) {\n offset = 0;\n } else if (offset > segments.length) {\n fail('offset ' + offset + ' out of range ' + segments.length);\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail('length ' + length + ' out of range ' + (segments.length - offset));\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n }\n\n /**\n * Abstract constructor method to construct an instance of B with the given\n * parameters.\n */\n protected abstract construct(\n segments: string[],\n offset?: number,\n length?: number\n ): B;\n\n /**\n * Returns a String representation.\n *\n * Implementing classes are required to provide deterministic implementations as\n * the String representation is used to obtain canonical Query IDs.\n */\n abstract toString(): string;\n\n get length(): number {\n return this.len;\n }\n\n isEqual(other: B): boolean {\n return BasePath.comparator(this, other) === 0;\n }\n\n child(nameOrPath: string | B): B {\n const segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof BasePath) {\n nameOrPath.forEach(segment => {\n segments.push(segment);\n });\n } else {\n segments.push(nameOrPath);\n }\n return this.construct(segments);\n }\n\n /** The index of one past the last segment of the path. */\n private limit(): number {\n return this.offset + this.length;\n }\n\n popFirst(size?: number): B {\n size = size === undefined ? 1 : size;\n debugAssert(\n this.length >= size,\n \"Can't call popFirst() with less segments\"\n );\n return this.construct(\n this.segments,\n this.offset + size,\n this.length - size\n );\n }\n\n popLast(): B {\n debugAssert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n\n firstSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n }\n\n lastSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.get(this.length - 1);\n }\n\n get(index: number): string {\n debugAssert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n }\n\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n isPrefixOf(other: this): boolean {\n if (other.length < this.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n isImmediateParentOf(potentialChild: this): boolean {\n if (this.length + 1 !== potentialChild.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== potentialChild.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n forEach(fn: (segment: string) => void): void {\n for (let i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n }\n\n toArray(): string[] {\n return this.segments.slice(this.offset, this.limit());\n }\n\n static comparator<T extends BasePath<T>>(\n p1: BasePath<T>,\n p2: BasePath<T>\n ): number {\n const len = Math.min(p1.length, p2.length);\n for (let i = 0; i < len; i++) {\n const left = p1.get(i);\n const right = p2.get(i);\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n }\n if (p1.length < p2.length) {\n return -1;\n }\n if (p1.length > p2.length) {\n return 1;\n }\n return 0;\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */\nexport class ResourcePath extends BasePath<ResourcePath> {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): ResourcePath {\n return new ResourcePath(segments, offset, length);\n }\n\n canonicalString(): string {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n return this.toArray().join('/');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */\n static fromString(...pathComponents: string[]): ResourcePath {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n const segments: string[] = [];\n for (const path of pathComponents) {\n if (path.indexOf('//') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid segment (${path}). Paths must not contain // in them.`\n );\n }\n // Strip leading and traling slashed.\n segments.push(...path.split('/').filter(segment => segment.length > 0));\n }\n\n return new ResourcePath(segments);\n }\n\n static emptyPath(): ResourcePath {\n return new ResourcePath([]);\n }\n}\n\nconst identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */\nexport class FieldPath extends BasePath<FieldPath> {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): FieldPath {\n return new FieldPath(segments, offset, length);\n }\n\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n private static isValidIdentifier(segment: string): boolean {\n return identifierRegExp.test(segment);\n }\n\n canonicalString(): string {\n return this.toArray()\n .map(str => {\n str = str.replace(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns true if this field references the key of a document.\n */\n isKeyField(): boolean {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n }\n\n /**\n * The field designating the key of a document.\n */\n static keyField(): FieldPath {\n return new FieldPath([DOCUMENT_KEY_NAME]);\n }\n\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */\n static fromServerFormat(path: string): FieldPath {\n const segments: string[] = [];\n let current = '';\n let i = 0;\n\n const addCurrentSegment = (): void => {\n if (current.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field path (${path}). Paths must not be empty, begin ` +\n `with '.', end with '.', or contain '..'`\n );\n }\n segments.push(current);\n current = '';\n };\n\n let inBackticks = false;\n\n while (i < path.length) {\n const c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has trailing escape character: ' + path\n );\n }\n const next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has invalid escape sequence: ' + path\n );\n }\n current += next;\n i += 2;\n } else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n } else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n } else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n\n if (inBackticks) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unterminated ` in path: ' + path\n );\n }\n\n return new FieldPath(segments);\n }\n\n static emptyPath(): FieldPath {\n return new FieldPath([]);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\n\nimport { ResourcePath } from './path';\n\n/**\n * @internal\n */\nexport class DocumentKey {\n constructor(readonly path: ResourcePath) {\n debugAssert(\n DocumentKey.isDocumentKey(path),\n 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/')\n );\n }\n\n static fromPath(path: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(path));\n }\n\n static fromName(name: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(name).popFirst(5));\n }\n\n static empty(): DocumentKey {\n return new DocumentKey(ResourcePath.emptyPath());\n }\n\n get collectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.popLast().lastSegment();\n }\n\n /** Returns true if the document is in the specified collectionId. */\n hasCollectionId(collectionId: string): boolean {\n return (\n this.path.length >= 2 &&\n this.path.get(this.path.length - 2) === collectionId\n );\n }\n\n /** Returns the collection group (i.e. the name of the parent collection) for this key. */\n getCollectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.get(this.path.length - 2);\n }\n\n /** Returns the fully qualified path to the parent collection. */\n getCollectionPath(): ResourcePath {\n return this.path.popLast();\n }\n\n isEqual(other: DocumentKey | null): boolean {\n return (\n other !== null && ResourcePath.comparator(this.path, other.path) === 0\n );\n }\n\n toString(): string {\n return this.path.toString();\n }\n\n static comparator(k1: DocumentKey, k2: DocumentKey): number {\n return ResourcePath.comparator(k1.path, k2.path);\n }\n\n static isDocumentKey(path: ResourcePath): boolean {\n return path.length % 2 === 0;\n }\n\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param segments - The segments of the path to the document\n * @returns A new instance of DocumentKey\n */\n static fromSegments(segments: string[]): DocumentKey {\n return new DocumentKey(new ResourcePath(segments.slice()));\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { primitiveComparator } from '../util/misc';\n\nimport { Document } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldPath } from './path';\n\n/**\n * The initial mutation batch id for each index. Gets updated during index\n * backfill.\n */\nexport const INITIAL_LARGEST_BATCH_ID = -1;\n\n/**\n * The initial sequence number for each index. Gets updated during index\n * backfill.\n */\nexport const INITIAL_SEQUENCE_NUMBER = 0;\n\n/**\n * An index definition for field indexes in Firestore.\n *\n * Every index is associated with a collection. The definition contains a list\n * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or\n * `CONTAINS` for ArrayContains/ArrayContainsAny queries).\n *\n * Unlike the backend, the SDK does not differentiate between collection or\n * collection group-scoped indices. Every index can be used for both single\n * collection and collection group queries.\n */\nexport class FieldIndex {\n /** An ID for an index that has not yet been added to persistence. */\n static UNKNOWN_ID = -1;\n\n constructor(\n /**\n * The index ID. Returns -1 if the index ID is not available (e.g. the index\n * has not yet been persisted).\n */\n readonly indexId: number,\n /** The collection ID this index applies to. */\n readonly collectionGroup: string,\n /** The field segments for this index. */\n readonly fields: IndexSegment[],\n /** Shows how up-to-date the index is for the current user. */\n readonly indexState: IndexState\n ) {}\n}\n\n/** Returns the ArrayContains/ArrayContainsAny segment for this index. */\nexport function fieldIndexGetArraySegment(\n fieldIndex: FieldIndex\n): IndexSegment | undefined {\n return fieldIndex.fields.find(s => s.kind === IndexKind.CONTAINS);\n}\n\n/** Returns all directional (ascending/descending) segments for this index. */\nexport function fieldIndexGetDirectionalSegments(\n fieldIndex: FieldIndex\n): IndexSegment[] {\n return fieldIndex.fields.filter(s => s.kind !== IndexKind.CONTAINS);\n}\n\n/**\n * Returns the order of the document key component for the given index.\n *\n * PORTING NOTE: This is only used in the Web IndexedDb implementation.\n */\nexport function fieldIndexGetKeyOrder(fieldIndex: FieldIndex): IndexKind {\n const directionalSegments = fieldIndexGetDirectionalSegments(fieldIndex);\n return directionalSegments.length === 0\n ? IndexKind.ASCENDING\n : directionalSegments[directionalSegments.length - 1].kind;\n}\n\n/**\n * Compares indexes by collection group and segments. Ignores update time and\n * index ID.\n */\nexport function fieldIndexSemanticComparator(\n left: FieldIndex,\n right: FieldIndex\n): number {\n let cmp = primitiveComparator(left.collectionGroup, right.collectionGroup);\n if (cmp !== 0) {\n return cmp;\n }\n\n for (let i = 0; i < Math.min(left.fields.length, right.fields.length); ++i) {\n cmp = indexSegmentComparator(left.fields[i], right.fields[i]);\n if (cmp !== 0) {\n return cmp;\n }\n }\n return primitiveComparator(left.fields.length, right.fields.length);\n}\n\n/** Returns a debug representation of the field index */\nexport function fieldIndexToString(fieldIndex: FieldIndex): string {\n return `id=${fieldIndex.indexId}|cg=${\n fieldIndex.collectionGroup\n }|f=${fieldIndex.fields.map(f => `${f.fieldPath}:${f.kind}`).join(',')}`;\n}\n\n/** The type of the index, e.g. for which type of query it can be used. */\nexport const enum IndexKind {\n // Note: The order of these values cannot be changed as the enum values are\n // stored in IndexedDb.\n /**\n * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries.\n */\n ASCENDING,\n /**\n * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries.\n */\n DESCENDING,\n /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */\n CONTAINS\n}\n\n/** An index component consisting of field path and index type. */\nexport class IndexSegment {\n constructor(\n /** The field path of the component. */\n readonly fieldPath: FieldPath,\n /** The fields sorting order. */\n readonly kind: IndexKind\n ) {}\n}\n\nfunction indexSegmentComparator(\n left: IndexSegment,\n right: IndexSegment\n): number {\n const cmp = FieldPath.comparator(left.fieldPath, right.fieldPath);\n if (cmp !== 0) {\n return cmp;\n }\n return primitiveComparator(left.kind, right.kind);\n}\n\n/**\n * Stores the \"high water mark\" that indicates how updated the Index is for the\n * current user.\n */\nexport class IndexState {\n constructor(\n /**\n * Indicates when the index was last updated (relative to other indexes).\n */\n readonly sequenceNumber: number,\n /** The the latest indexed read time, document and batch id. */\n readonly offset: IndexOffset\n ) {}\n\n /** The state of an index that has not yet been backfilled. */\n static empty(): IndexState {\n return new IndexState(INITIAL_SEQUENCE_NUMBER, IndexOffset.min());\n }\n}\n\n/**\n * Creates an offset that matches all documents with a read time higher than\n * `readTime`.\n */\nexport function newIndexOffsetSuccessorFromReadTime(\n readTime: SnapshotVersion,\n largestBatchId: number\n): IndexOffset {\n // We want to create an offset that matches all documents with a read time\n // greater than the provided read time. To do so, we technically need to\n // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use\n // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use\n // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches\n // all valid document IDs.\n const successorSeconds = readTime.toTimestamp().seconds;\n const successorNanos = readTime.toTimestamp().nanoseconds + 1;\n const successor = SnapshotVersion.fromTimestamp(\n successorNanos === 1e9\n ? new Timestamp(successorSeconds + 1, 0)\n : new Timestamp(successorSeconds, successorNanos)\n );\n return new IndexOffset(successor, DocumentKey.empty(), largestBatchId);\n}\n\n/** Creates a new offset based on the provided document. */\nexport function newIndexOffsetFromDocument(document: Document): IndexOffset {\n return new IndexOffset(\n document.readTime,\n document.key,\n INITIAL_LARGEST_BATCH_ID\n );\n}\n\n/**\n * Stores the latest read time, document and batch ID that were processed for an\n * index.\n */\nexport class IndexOffset {\n constructor(\n /**\n * The latest read time version that has been indexed by Firestore for this\n * field index.\n */\n readonly readTime: SnapshotVersion,\n\n /**\n * The key of the last document that was indexed for this query. Use\n * `DocumentKey.empty()` if no document has been indexed.\n */\n readonly documentKey: DocumentKey,\n\n /*\n * The largest mutation batch id that's been processed by Firestore.\n */\n readonly largestBatchId: number\n ) {}\n\n /** Returns an offset that sorts before all regular offsets. */\n static min(): IndexOffset {\n return new IndexOffset(\n SnapshotVersion.min(),\n DocumentKey.empty(),\n INITIAL_LARGEST_BATCH_ID\n );\n }\n\n /** Returns an offset that sorts after all regular offsets. */\n static max(): IndexOffset {\n return new IndexOffset(\n SnapshotVersion.max(),\n DocumentKey.empty(),\n INITIAL_LARGEST_BATCH_ID\n );\n }\n}\n\nexport function indexOffsetComparator(\n left: IndexOffset,\n right: IndexOffset\n): number {\n let cmp = left.readTime.compareTo(right.readTime);\n if (cmp !== 0) {\n return cmp;\n }\n cmp = DocumentKey.comparator(left.documentKey, right.documentKey);\n if (cmp !== 0) {\n return cmp;\n }\n return primitiveComparator(left.largestBatchId, right.largestBatchId);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber } from '../core/types';\nexport const PRIMARY_LEASE_LOST_ERROR_MSG =\n 'The current tab is not in the required state to perform this operation. ' +\n 'It might be necessary to refresh the browser tab.';\n\n/** The different modes supported by `Persistence.runTransaction()`. */\nexport type PersistenceTransactionMode =\n | 'readonly'\n | 'readwrite'\n | 'readwrite-primary';\n\n/**\n * A base class representing a persistence transaction, encapsulating both the\n * transaction's sequence numbers as well as a list of onCommitted listeners.\n *\n * When you call Persistence.runTransaction(), it will create a transaction and\n * pass it to your callback. You then pass it to any method that operates\n * on persistence.\n */\nexport abstract class PersistenceTransaction {\n private readonly onCommittedListeners: Array<() => void> = [];\n\n abstract readonly currentSequenceNumber: ListenSequenceNumber;\n\n addOnCommittedListener(listener: () => void): void {\n this.onCommittedListeners.push(listener);\n }\n\n raiseOnCommittedEvent(): void {\n this.onCommittedListeners.forEach(listener => listener());\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { IndexManager } from './index_manager';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { LruGarbageCollector, LruResults } from './lru_garbage_collector';\nimport { PRIMARY_LEASE_LOST_ERROR_MSG } from './persistence_transaction';\n\nexport interface LocalStore {\n collectGarbage(garbageCollector: LruGarbageCollector): Promise<LruResults>;\n\n /** Manages the list of active field and collection indices. */\n indexManager: IndexManager;\n\n /**\n * The \"local\" view of all documents (layering mutationQueue on top of\n * remoteDocumentCache).\n */\n localDocuments: LocalDocumentsView;\n}\n\n/**\n * Verifies the error thrown by a LocalStore operation. If a LocalStore\n * operation fails because the primary lease has been taken by another client,\n * we ignore the error (the persistence layer will immediately call\n * `applyPrimaryLease` to propagate the primary state change). All other errors\n * are re-thrown.\n *\n * @param err - An error returned by a LocalStore operation.\n * @returns A Promise that resolves after we recovered, or the original error.\n */\nexport async function ignoreIfPrimaryLeaseLoss(\n err: FirestoreError\n): Promise<void> {\n if (\n err.code === Code.FAILED_PRECONDITION &&\n err.message === PRIMARY_LEASE_LOST_ERROR_MSG\n ) {\n logDebug('LocalStore', 'Unexpectedly lost primary lease');\n } else {\n throw err;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\n\nexport type FulfilledHandler<T, R> =\n | ((result: T) => R | PersistencePromise<R>)\n | null;\nexport type RejectedHandler<R> =\n | ((reason: Error) => R | PersistencePromise<R>)\n | null;\nexport type Resolver<T> = (value?: T) => void;\nexport type Rejector = (error: Error) => void;\n\n/**\n * PersistencePromise is essentially a re-implementation of Promise except\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\n * are executed synchronously when a PersistencePromise resolves rather than\n * asynchronously (Promise implementations use setImmediate() or similar).\n *\n * This is necessary to interoperate with IndexedDB which will automatically\n * commit transactions if control is returned to the event loop without\n * synchronously initiating another operation on the transaction.\n *\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\n * Promises.\n */\nexport class PersistencePromise<T> {\n // NOTE: next/catchCallback will always point to our own wrapper functions,\n // not the user's raw next() or catch() callbacks.\n private nextCallback: FulfilledHandler<T, unknown> = null;\n private catchCallback: RejectedHandler<unknown> = null;\n\n // When the operation resolves, we'll set result or error and mark isDone.\n private result: T | undefined = undefined;\n private error: Error | undefined = undefined;\n private isDone = false;\n\n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n private callbackAttached = false;\n\n constructor(callback: (resolve: Resolver<T>, reject: Rejector) => void) {\n callback(\n value => {\n this.isDone = true;\n this.result = value;\n if (this.nextCallback) {\n // value should be defined unless T is Void, but we can't express\n // that in the type system.\n this.nextCallback(value!);\n }\n },\n error => {\n this.isDone = true;\n this.error = error;\n if (this.catchCallback) {\n this.catchCallback(error);\n }\n }\n );\n }\n\n catch<R>(\n fn: (error: Error) => R | PersistencePromise<R>\n ): PersistencePromise<R> {\n return this.next(undefined, fn);\n }\n\n next<R>(\n nextFn?: FulfilledHandler<T, R>,\n catchFn?: RejectedHandler<R>\n ): PersistencePromise<R> {\n if (this.callbackAttached) {\n fail('Called next() or catch() twice for PersistencePromise');\n }\n this.callbackAttached = true;\n if (this.isDone) {\n if (!this.error) {\n return this.wrapSuccess(nextFn, this.result!);\n } else {\n return this.wrapFailure(catchFn, this.error);\n }\n } else {\n return new PersistencePromise<R>((resolve, reject) => {\n this.nextCallback = (value: T) => {\n this.wrapSuccess(nextFn, value).next(resolve, reject);\n };\n this.catchCallback = (error: Error) => {\n this.wrapFailure(catchFn, error).next(resolve, reject);\n };\n });\n }\n }\n\n toPromise(): Promise<T> {\n return new Promise((resolve, reject) => {\n this.next(resolve, reject);\n });\n }\n\n private wrapUserFunction<R>(\n fn: () => R | PersistencePromise<R>\n ): PersistencePromise<R> {\n try {\n const result = fn();\n if (result instanceof PersistencePromise) {\n return result;\n } else {\n return PersistencePromise.resolve(result);\n }\n } catch (e) {\n return PersistencePromise.reject<R>(e as Error);\n }\n }\n\n private wrapSuccess<R>(\n nextFn: FulfilledHandler<T, R> | undefined,\n value: T\n ): PersistencePromise<R> {\n if (nextFn) {\n return this.wrapUserFunction(() => nextFn(value));\n } else {\n // If there's no nextFn, then R must be the same as T\n return PersistencePromise.resolve<R>(value as unknown as R);\n }\n }\n\n private wrapFailure<R>(\n catchFn: RejectedHandler<R> | undefined,\n error: Error\n ): PersistencePromise<R> {\n if (catchFn) {\n return this.wrapUserFunction(() => catchFn(error));\n } else {\n return PersistencePromise.reject<R>(error);\n }\n }\n\n static resolve(): PersistencePromise<void>;\n static resolve<R>(result: R): PersistencePromise<R>;\n static resolve<R>(result?: R): PersistencePromise<R | void> {\n return new PersistencePromise<R | void>((resolve, reject) => {\n resolve(result);\n });\n }\n\n static reject<R>(error: Error): PersistencePromise<R> {\n return new PersistencePromise<R>((resolve, reject) => {\n reject(error);\n });\n }\n\n static waitFor(\n // Accept all Promise types in waitFor().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n all: { forEach: (cb: (el: PersistencePromise<any>) => void) => void }\n ): PersistencePromise<void> {\n return new PersistencePromise<void>((resolve, reject) => {\n let expectedCount = 0;\n let resolvedCount = 0;\n let done = false;\n\n all.forEach(element => {\n ++expectedCount;\n element.next(\n () => {\n ++resolvedCount;\n if (done && resolvedCount === expectedCount) {\n resolve();\n }\n },\n err => reject(err)\n );\n });\n\n done = true;\n if (resolvedCount === expectedCount) {\n resolve();\n }\n });\n }\n\n /**\n * Given an array of predicate functions that asynchronously evaluate to a\n * boolean, implements a short-circuiting `or` between the results. Predicates\n * will be evaluated until one of them returns `true`, then stop. The final\n * result will be whether any of them returned `true`.\n */\n static or(\n predicates: Array<() => PersistencePromise<boolean>>\n ): PersistencePromise<boolean> {\n let p: PersistencePromise<boolean> =\n PersistencePromise.resolve<boolean>(false);\n for (const predicate of predicates) {\n p = p.next(isTrue => {\n if (isTrue) {\n return PersistencePromise.resolve<boolean>(isTrue);\n } else {\n return predicate();\n }\n });\n }\n return p;\n }\n\n /**\n * Given an iterable, call the given function on each element in the\n * collection and wait for all of the resulting concurrent PersistencePromises\n * to resolve.\n */\n static forEach<R, S>(\n collection: { forEach: (cb: (r: R, s: S) => void) => void },\n f:\n | ((r: R, s: S) => PersistencePromise<void>)\n | ((r: R) => PersistencePromise<void>)\n ): PersistencePromise<void>;\n static forEach<R>(\n collection: { forEach: (cb: (r: R) => void) => void },\n f: (r: R) => PersistencePromise<void>\n ): PersistencePromise<void>;\n static forEach<R, S>(\n collection: { forEach: (cb: (r: R, s?: S) => void) => void },\n f: (r: R, s?: S) => PersistencePromise<void>\n ): PersistencePromise<void> {\n const promises: Array<PersistencePromise<void>> = [];\n collection.forEach((r, s) => {\n promises.push(f.call(this, r, s));\n });\n return this.waitFor(promises);\n }\n\n /**\n * Concurrently map all array elements through asynchronous function.\n */\n static mapArray<T, U>(\n array: T[],\n f: (t: T) => PersistencePromise<U>\n ): PersistencePromise<U[]> {\n return new PersistencePromise<U[]>((resolve, reject) => {\n const expectedCount = array.length;\n const results: U[] = new Array(expectedCount);\n let resolvedCount = 0;\n for (let i = 0; i < expectedCount; i++) {\n const current = i;\n f(array[current]).next(\n result => {\n results[current] = result;\n ++resolvedCount;\n if (resolvedCount === expectedCount) {\n resolve(results);\n }\n },\n err => reject(err)\n );\n }\n });\n }\n\n /**\n * An alternative to recursive PersistencePromise calls, that avoids\n * potential memory problems from unbounded chains of promises.\n *\n * The `action` will be called repeatedly while `condition` is true.\n */\n static doWhile(\n condition: () => boolean,\n action: () => PersistencePromise<void>\n ): PersistencePromise<void> {\n return new PersistencePromise<void>((resolve, reject) => {\n const process = (): void => {\n if (condition() === true) {\n action().next(() => {\n process();\n }, reject);\n } else {\n resolve();\n }\n };\n process();\n });\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getUA, isIndexedDBAvailable } from '@firebase/util';\n\nimport { debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { Deferred } from '../util/promise';\n\nimport { PersistencePromise } from './persistence_promise';\n\n// References to `window` are guarded by SimpleDb.isAvailable()\n/* eslint-disable no-restricted-globals */\n\nconst LOG_TAG = 'SimpleDb';\n\n/**\n * The maximum number of retry attempts for an IndexedDb transaction that fails\n * with a DOMException.\n */\nconst TRANSACTION_RETRY_COUNT = 3;\n\n// The different modes supported by `SimpleDb.runTransaction()`\ntype SimpleDbTransactionMode = 'readonly' | 'readwrite';\n\nexport interface SimpleDbSchemaConverter {\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise<void>;\n}\n\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nexport class SimpleDbTransaction {\n private aborted = false;\n\n /**\n * A `Promise` that resolves with the result of the IndexedDb transaction.\n */\n private readonly completionDeferred = new Deferred<void>();\n\n static open(\n db: IDBDatabase,\n action: string,\n mode: IDBTransactionMode,\n objectStoreNames: string[]\n ): SimpleDbTransaction {\n try {\n return new SimpleDbTransaction(\n action,\n db.transaction(objectStoreNames, mode)\n );\n } catch (e) {\n throw new IndexedDbTransactionError(action, e as Error);\n }\n }\n\n constructor(\n private readonly action: string,\n private readonly transaction: IDBTransaction\n ) {\n this.transaction.oncomplete = () => {\n this.completionDeferred.resolve();\n };\n this.transaction.onabort = () => {\n if (transaction.error) {\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, transaction.error)\n );\n } else {\n this.completionDeferred.resolve();\n }\n };\n this.transaction.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, error)\n );\n };\n }\n\n get completionPromise(): Promise<void> {\n return this.completionDeferred.promise;\n }\n\n abort(error?: Error): void {\n if (error) {\n this.completionDeferred.reject(error);\n }\n\n if (!this.aborted) {\n logDebug(\n LOG_TAG,\n 'Aborting transaction:',\n error ? error.message : 'Client-initiated abort'\n );\n this.aborted = true;\n this.transaction.abort();\n }\n }\n\n maybeCommit(): void {\n // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n // speed up index DB processing if the event loop remains blocks.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const maybeV3IndexedDb = this.transaction as any;\n if (!this.aborted && typeof maybeV3IndexedDb.commit === 'function') {\n maybeV3IndexedDb.commit();\n }\n }\n\n /**\n * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */\n store<KeyType extends IDBValidKey, ValueType extends unknown>(\n storeName: string\n ): SimpleDbStore<KeyType, ValueType> {\n const store = this.transaction.objectStore(storeName);\n debugAssert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore<KeyType, ValueType>(store);\n }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */\nexport class SimpleDb {\n private db?: IDBDatabase;\n private versionchangelistener?: (event: IDBVersionChangeEvent) => void;\n\n /** Deletes the specified database. */\n static delete(name: string): Promise<void> {\n logDebug(LOG_TAG, 'Removing database:', name);\n return wrapRequest<void>(window.indexedDB.deleteDatabase(name)).toPromise();\n }\n\n /** Returns true if IndexedDB is available in the current environment. */\n static isAvailable(): boolean {\n if (!isIndexedDBAvailable()) {\n return false;\n }\n\n if (SimpleDb.isMockPersistence()) {\n return true;\n }\n\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n\n // Check the UA string to find out the browser.\n const ua = getUA();\n\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n\n // iOS Safari: Disable for users running iOS version < 10.\n const iOSVersion = SimpleDb.getIOSVersion(ua);\n const isUnsupportedIOS = 0 < iOSVersion && iOSVersion < 10;\n\n // Android browser: Disable for userse running version < 4.5.\n const androidVersion = SimpleDb.getAndroidVersion(ua);\n const isUnsupportedAndroid = 0 < androidVersion && androidVersion < 4.5;\n\n if (\n ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0 ||\n isUnsupportedIOS ||\n isUnsupportedAndroid\n ) {\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */\n static isMockPersistence(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.env?.USE_MOCK_PERSISTENCE === 'YES'\n );\n }\n\n /** Helper to get a typed SimpleDbStore from a transaction. */\n static getStore<KeyType extends IDBValidKey, ValueType extends unknown>(\n txn: SimpleDbTransaction,\n store: string\n ): SimpleDbStore<KeyType, ValueType> {\n return txn.store<KeyType, ValueType>(store);\n }\n\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static getIOSVersion(ua: string): number {\n const iOSVersionRegex = ua.match(/i(?:phone|pad|pod) os ([\\d_]+)/i);\n const version = iOSVersionRegex\n ? iOSVersionRegex[1].split('_').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n }\n\n // visible for testing\n /** Parse User Agent to determine Android version. Returns -1 if not found. */\n static getAndroidVersion(ua: string): number {\n const androidVersionRegex = ua.match(/Android ([\\d.]+)/i);\n const version = androidVersionRegex\n ? androidVersionRegex[1].split('.').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n }\n\n /*\n * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support\n * downgrading the schema version. We currently do not support any way to do\n * versioning outside of IndexedDB's versioning mechanism, as only\n * version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n constructor(\n private readonly name: string,\n private readonly version: number,\n private readonly schemaConverter: SimpleDbSchemaConverter\n ) {\n debugAssert(\n SimpleDb.isAvailable(),\n 'IndexedDB not supported in current environment.'\n );\n\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n // whatever reason it's much harder to hit after 12.2 so we only proactively\n // log on 12.2.\n if (iOSVersion === 12.2) {\n logError(\n 'Firestore persistence suffers from a bug in iOS 12.2 ' +\n 'Safari that may cause your app to stop working. See ' +\n 'https://stackoverflow.com/q/56496296/110915 for details ' +\n 'and a potential workaround.'\n );\n }\n }\n\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n */\n async ensureDb(action: string): Promise<IDBDatabase> {\n if (!this.db) {\n logDebug(LOG_TAG, 'Opening database:', this.name);\n this.db = await new Promise<IDBDatabase>((resolve, reject) => {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently. They expect setVersion, as described here:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n const request = indexedDB.open(this.name, this.version);\n\n request.onsuccess = (event: Event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n resolve(db);\n };\n\n request.onblocked = () => {\n reject(\n new IndexedDbTransactionError(\n action,\n 'Cannot upgrade IndexedDB schema while another tab is open. ' +\n 'Close all tabs that access Firestore and reload this page to proceed.'\n )\n );\n };\n\n request.onerror = (event: Event) => {\n const error: DOMException = (event.target as IDBOpenDBRequest).error!;\n if (error.name === 'VersionError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A newer version of the Firestore SDK was previously used and so the persisted ' +\n 'data is not compatible with the version of the SDK you are now using. The SDK ' +\n 'will operate with persistence disabled. If you need persistence, please ' +\n 're-upgrade to a newer version of the SDK or else clear the persisted IndexedDB ' +\n 'data for your app to start fresh.'\n )\n );\n } else if (error.name === 'InvalidStateError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Unable to open an IndexedDB connection. This could be due to running in a ' +\n 'private browsing session on a browser whose private browsing sessions do not ' +\n 'support IndexedDB: ' +\n error\n )\n );\n } else {\n reject(new IndexedDbTransactionError(action, error));\n }\n };\n\n request.onupgradeneeded = (event: IDBVersionChangeEvent) => {\n logDebug(\n LOG_TAG,\n 'Database \"' + this.name + '\" requires upgrade from version:',\n event.oldVersion\n );\n const db = (event.target as IDBOpenDBRequest).result;\n this.schemaConverter\n .createOrUpgrade(\n db,\n request.transaction!,\n event.oldVersion,\n this.version\n )\n .next(() => {\n logDebug(\n LOG_TAG,\n 'Database upgrade to version ' + this.version + ' complete'\n );\n });\n };\n });\n }\n\n if (this.versionchangelistener) {\n this.db.onversionchange = event => this.versionchangelistener!(event);\n }\n return this.db;\n }\n\n setVersionChangeListener(\n versionChangeListener: (event: IDBVersionChangeEvent) => void\n ): void {\n this.versionchangelistener = versionChangeListener;\n if (this.db) {\n this.db.onversionchange = (event: IDBVersionChangeEvent) => {\n return versionChangeListener(event);\n };\n }\n }\n\n async runTransaction<T>(\n action: string,\n mode: SimpleDbTransactionMode,\n objectStores: string[],\n transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise<T>\n ): Promise<T> {\n const readonly = mode === 'readonly';\n let attemptNumber = 0;\n\n while (true) {\n ++attemptNumber;\n\n try {\n this.db = await this.ensureDb(action);\n\n const transaction = SimpleDbTransaction.open(\n this.db,\n action,\n readonly ? 'readonly' : 'readwrite',\n objectStores\n );\n const transactionFnResult = transactionFn(transaction)\n .next(result => {\n transaction.maybeCommit();\n return result;\n })\n .catch(error => {\n // Abort the transaction if there was an error.\n transaction.abort(error);\n // We cannot actually recover, and calling `abort()` will cause the transaction's\n // completion promise to be rejected. This in turn means that we won't use\n // `transactionFnResult` below. We return a rejection here so that we don't add the\n // possibility of returning `void` to the type of `transactionFnResult`.\n return PersistencePromise.reject<T>(error);\n })\n .toPromise();\n\n // As noted above, errors are propagated by aborting the transaction. So\n // we swallow any error here to avoid the browser logging it as unhandled.\n transactionFnResult.catch(() => {});\n\n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n await transaction.completionPromise;\n return transactionFnResult;\n } catch (e) {\n const error = e as Error;\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n const retryable =\n error.name !== 'FirebaseError' &&\n attemptNumber < TRANSACTION_RETRY_COUNT;\n logDebug(\n LOG_TAG,\n 'Transaction failed with error:',\n error.message,\n 'Retrying:',\n retryable\n );\n\n this.close();\n\n if (!retryable) {\n return Promise.reject(error);\n }\n }\n }\n }\n\n close(): void {\n if (this.db) {\n this.db.close();\n }\n this.db = undefined;\n }\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */\nexport class IterationController {\n private shouldStop = false;\n private nextKey: IDBValidKey | null = null;\n\n constructor(private dbCursor: IDBCursorWithValue) {}\n\n get isDone(): boolean {\n return this.shouldStop;\n }\n\n get skipToKey(): IDBValidKey | null {\n return this.nextKey;\n }\n\n set cursor(value: IDBCursorWithValue) {\n this.dbCursor = value;\n }\n\n /**\n * This function can be called to stop iteration at any point.\n */\n done(): void {\n this.shouldStop = true;\n }\n\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */\n skip(key: IDBValidKey): void {\n this.nextKey = key;\n }\n\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n delete(): PersistencePromise<void> {\n return wrapRequest<void>(this.dbCursor.delete());\n }\n}\n\n/**\n * Callback used with iterate() method.\n */\nexport type IterateCallback<KeyType, ValueType> = (\n key: KeyType,\n value: ValueType,\n control: IterationController\n) => void | PersistencePromise<void>;\n\n/** Options available to the iterate() method. */\nexport interface IterateOptions {\n /** Index to iterate over (else primary keys will be iterated) */\n index?: string;\n\n /** IndxedDB Range to iterate over (else entire store will be iterated) */\n range?: IDBKeyRange;\n\n /** If true, values aren't read while iterating. */\n keysOnly?: boolean;\n\n /** If true, iterate over the store in reverse. */\n reverse?: boolean;\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */\nexport class IndexedDbTransactionError extends FirestoreError {\n name = 'IndexedDbTransactionError';\n\n constructor(actionName: string, cause: Error | string) {\n super(\n Code.UNAVAILABLE,\n `IndexedDB transaction '${actionName}' failed: ${cause}`\n );\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */\nexport function isIndexedDbTransactionError(e: Error): boolean {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return e.name === 'IndexedDbTransactionError';\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */\nexport class SimpleDbStore<\n KeyType extends IDBValidKey,\n ValueType extends unknown\n> {\n constructor(private store: IDBObjectStore) {}\n\n /**\n * Writes a value into the Object Store.\n *\n * @param key - Optional explicit key to use when writing the object, else the\n * key will be auto-assigned (e.g. via the defined keyPath for the store).\n * @param value - The object to write.\n */\n put(value: ValueType): PersistencePromise<void>;\n put(key: KeyType, value: ValueType): PersistencePromise<void>;\n put(\n keyOrValue: KeyType | ValueType,\n value?: ValueType\n ): PersistencePromise<void> {\n let request;\n if (value !== undefined) {\n logDebug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue as KeyType);\n } else {\n logDebug(LOG_TAG, 'PUT', this.store.name, '<auto-key>', keyOrValue);\n request = this.store.put(keyOrValue as ValueType);\n }\n return wrapRequest<void>(request);\n }\n\n /**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value - The object to write.\n * @returns The key of the value to add.\n */\n add(value: ValueType): PersistencePromise<KeyType> {\n logDebug(LOG_TAG, 'ADD', this.store.name, value, value);\n const request = this.store.add(value as ValueType);\n return wrapRequest<KeyType>(request);\n }\n\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @returns The object with the specified key or null if no object exists.\n */\n get(key: KeyType): PersistencePromise<ValueType | null> {\n const request = this.store.get(key);\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return wrapRequest<any>(request).next(result => {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n logDebug(LOG_TAG, 'GET', this.store.name, key, result);\n return result;\n });\n }\n\n delete(key: KeyType | IDBKeyRange): PersistencePromise<void> {\n logDebug(LOG_TAG, 'DELETE', this.store.name, key);\n const request = this.store.delete(key);\n return wrapRequest<void>(request);\n }\n\n /**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */\n count(): PersistencePromise<number> {\n logDebug(LOG_TAG, 'COUNT', this.store.name);\n const request = this.store.count();\n return wrapRequest<number>(request);\n }\n\n /** Loads all elements from the object store. */\n loadAll(): PersistencePromise<ValueType[]>;\n /** Loads all elements for the index range from the object store. */\n loadAll(range: IDBKeyRange): PersistencePromise<ValueType[]>;\n /** Loads all elements ordered by the given index. */\n loadAll(index: string): PersistencePromise<ValueType[]>;\n /**\n * Loads all elements from the object store that fall into the provided in the\n * index range for the given index.\n */\n loadAll(index: string, range: IDBKeyRange): PersistencePromise<ValueType[]>;\n loadAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise<ValueType[]> {\n const iterateOptions = this.options(indexOrRange, range);\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster. Unfortunately, getAll() does not support custom indices.\n if (!iterateOptions.index && typeof this.store.getAll === 'function') {\n const request = this.store.getAll(iterateOptions.range);\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n } else {\n const cursor = this.cursor(iterateOptions);\n const results: ValueType[] = [];\n return this.iterateCursor(cursor, (key, value) => {\n results.push(value);\n }).next(() => {\n return results;\n });\n }\n }\n\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */\n loadFirst(\n range: IDBKeyRange,\n count: number | null\n ): PersistencePromise<ValueType[]> {\n const request = this.store.getAll(\n range,\n count === null ? undefined : count\n );\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n }\n\n deleteAll(): PersistencePromise<void>;\n deleteAll(range: IDBKeyRange): PersistencePromise<void>;\n deleteAll(index: string, range: IDBKeyRange): PersistencePromise<void>;\n deleteAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise<void> {\n logDebug(LOG_TAG, 'DELETE ALL', this.store.name);\n const options = this.options(indexOrRange, range);\n options.keysOnly = false;\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, (key, value, control) => {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n }\n\n /**\n * Iterates over keys and values in an object store.\n *\n * @param options - Options specifying how to iterate the objects in the\n * store.\n * @param callback - will be called for each iterated object. Iteration can be\n * canceled at any point by calling the doneFn passed to the callback.\n * The callback can return a PersistencePromise if it performs async\n * operations but note that iteration will continue without waiting for them\n * to complete.\n * @returns A PersistencePromise that resolves once all PersistencePromises\n * returned by callbacks resolve.\n */\n iterate(\n callback: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void>;\n iterate(\n options: IterateOptions,\n callback: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void>;\n iterate(\n optionsOrCallback: IterateOptions | IterateCallback<KeyType, ValueType>,\n callback?: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void> {\n let options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback as IterateCallback<KeyType, ValueType>;\n } else {\n options = optionsOrCallback as IterateOptions;\n }\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n }\n\n /**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */\n iterateSerial(\n callback: (k: KeyType, v: ValueType) => PersistencePromise<boolean>\n ): PersistencePromise<void> {\n const cursorRequest = this.cursor({});\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n\n callback(cursor.primaryKey as KeyType, cursor.value).next(\n shouldContinue => {\n if (shouldContinue) {\n cursor.continue();\n } else {\n resolve();\n }\n }\n );\n };\n });\n }\n\n private iterateCursor(\n cursorRequest: IDBRequest,\n fn: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void> {\n const results: Array<PersistencePromise<void>> = [];\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n const controller = new IterationController(cursor);\n const userResult = fn(\n cursor.primaryKey as KeyType,\n cursor.value,\n controller\n );\n if (userResult instanceof PersistencePromise) {\n const userPromise: PersistencePromise<void> = userResult.catch(\n err => {\n controller.done();\n return PersistencePromise.reject(err);\n }\n );\n results.push(userPromise);\n }\n if (controller.isDone) {\n resolve();\n } else if (controller.skipToKey === null) {\n cursor.continue();\n } else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(() => PersistencePromise.waitFor(results));\n }\n\n private options(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): IterateOptions {\n let indexName: string | undefined = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n } else {\n debugAssert(\n range === undefined,\n '3rd argument must not be defined if 2nd is a range.'\n );\n range = indexOrRange;\n }\n }\n return { index: indexName, range };\n }\n\n private cursor(options: IterateOptions): IDBRequest {\n let direction: IDBCursorDirection = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n const index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n } else {\n return index.openCursor(options.range, direction);\n }\n } else {\n return this.store.openCursor(options.range, direction);\n }\n }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest<R>(request: IDBRequest): PersistencePromise<R> {\n return new PersistencePromise<R>((resolve, reject) => {\n request.onsuccess = (event: Event) => {\n const result = (event.target as IDBRequest).result;\n resolve(result);\n };\n\n request.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n });\n}\n\n// Guard so we only report the error once.\nlet reportedIOSError = false;\nfunction checkForAndReportiOSError(error: DOMException): Error {\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n if (iOSVersion >= 12.2 && iOSVersion < 13) {\n const IOS_ERROR =\n 'An internal error was encountered in the Indexed Database server';\n if (error.message.indexOf(IOS_ERROR) >= 0) {\n // Wrap error in a more descriptive one.\n const newError = new FirestoreError(\n 'internal',\n `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${IOS_ERROR}'. This is likely ` +\n `due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 ` +\n `for details and a potential workaround.`\n );\n if (!reportedIOSError) {\n reportedIOSError = true;\n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout(() => {\n throw newError;\n }, 0);\n }\n return newError;\n }\n }\n return error;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber } from './types';\n\n/**\n * `SequenceNumberSyncer` defines the methods required to keep multiple instances of a\n * `ListenSequence` in sync.\n */\nexport interface SequenceNumberSyncer {\n // Notify the syncer that a new sequence number has been used.\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n // Setting this property allows the syncer to notify when a sequence number has been used, and\n // and lets the ListenSequence adjust its internal previous value accordingly.\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n}\n\n/**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */\nexport class ListenSequence {\n static readonly INVALID: ListenSequenceNumber = -1;\n\n private writeNewSequenceNumber?: (\n newSequenceNumber: ListenSequenceNumber\n ) => void;\n\n constructor(\n private previousValue: ListenSequenceNumber,\n sequenceNumberSyncer?: SequenceNumberSyncer\n ) {\n if (sequenceNumberSyncer) {\n sequenceNumberSyncer.sequenceNumberHandler = sequenceNumber =>\n this.setPreviousValue(sequenceNumber);\n this.writeNewSequenceNumber = sequenceNumber =>\n sequenceNumberSyncer.writeSequenceNumber(sequenceNumber);\n }\n }\n\n private setPreviousValue(\n externalPreviousValue: ListenSequenceNumber\n ): ListenSequenceNumber {\n this.previousValue = Math.max(externalPreviousValue, this.previousValue);\n return this.previousValue;\n }\n\n next(): ListenSequenceNumber {\n const nextValue = ++this.previousValue;\n if (this.writeNewSequenceNumber) {\n this.writeNewSequenceNumber(nextValue);\n }\n return nextValue;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Sentinel value that sorts before any Mutation Batch ID. */\nexport const BATCHID_UNKNOWN = -1;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/** Returns whether the value represents -0. */\nexport function isNegativeZero(value: number): boolean {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return value === 0 && 1 / value === 1 / -0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */\nexport function isSafeInteger(value: unknown): boolean {\n return (\n typeof value === 'number' &&\n Number.isInteger(value) &&\n !isNegativeZero(value) &&\n value <= Number.MAX_SAFE_INTEGER &&\n value >= Number.MIN_SAFE_INTEGER\n );\n}\n\n/** The subset of the browser's Window interface used by the SDK. */\nexport interface WindowLike {\n readonly localStorage: Storage;\n readonly indexedDB: IDBFactory | null;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n\n/** The subset of the browser's Document interface used by the SDK. */\nexport interface DocumentLike {\n readonly visibilityState: DocumentVisibilityState;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchId, TargetId } from '../core/types';\nimport { ResourcePath } from '../model/path';\nimport { fail } from '../util/assert';\n\nimport {\n EncodedResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { DbDocumentMutation } from './indexeddb_schema';\nimport { DbRemoteDocumentStore as DbRemoteDocumentStoreLegacy } from './indexeddb_schema_legacy';\n\n// This file contains static constants and helper functions for IndexedDB.\n// It is split from indexeddb_schema to allow for minification.\n\n/** A timestamp type that can be used in IndexedDb keys. */\nexport type DbTimestampKey = [/* seconds */ number, /* nanos */ number];\n\n// The key for the singleton object in the DbPrimaryClient is a single string.\nexport type DbPrimaryClientKey = typeof DbPrimaryClientKey;\n\n/**\n * Name of the IndexedDb object store.\n *\n * Note that the name 'owner' is chosen to ensure backwards compatibility with\n * older clients that only supported single locked access to the persistence\n * layer.\n */\nexport const DbPrimaryClientStore = 'owner';\n\n/**\n * The key string used for the single object that exists in the\n * DbPrimaryClient store.\n */\n\nexport const DbPrimaryClientKey = 'owner';\n\n/** Object keys in the 'mutationQueues' store are userId strings. */\nexport type DbMutationQueueKey = string;\n\n/** Name of the IndexedDb object store. */\nexport const DbMutationQueueStore = 'mutationQueues';\n\n/** Keys are automatically assigned via the userId property. */\nexport const DbMutationQueueKeyPath = 'userId';\n\n/** The 'mutations' store is keyed by batch ID. */\nexport type DbMutationBatchKey = BatchId;\n\n/** Name of the IndexedDb object store. */\nexport const DbMutationBatchStore = 'mutations';\n\n/** Keys are automatically assigned via the userId, batchId properties. */\nexport const DbMutationBatchKeyPath = 'batchId';\n\n/** The index name for lookup of mutations by user. */\n\nexport const DbMutationBatchUserMutationsIndex = 'userMutationsIndex';\n\n/** The user mutations index is keyed by [userId, batchId] pairs. */\nexport const DbMutationBatchUserMutationsKeyPath = ['userId', 'batchId'];\n\n/**\n * The key for a db document mutation, which is made up of a userID, path, and\n * batchId. Note that the path must be serialized into a form that indexedDB can\n * sort.\n */\nexport type DbDocumentMutationKey = [string, EncodedResourcePath, BatchId];\n\n/**\n * Creates a [userId] key for use in the DbDocumentMutations index to iterate\n * over all of a user's document mutations.\n */\nexport function newDbDocumentMutationPrefixForUser(userId: string): [string] {\n return [userId];\n}\n\n/**\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\n * index to iterate over all at document mutations for a given path or lower.\n */\nexport function newDbDocumentMutationPrefixForPath(\n userId: string,\n path: ResourcePath\n): [string, EncodedResourcePath] {\n return [userId, encodeResourcePath(path)];\n}\n\n/**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */\nexport function newDbDocumentMutationKey(\n userId: string,\n path: ResourcePath,\n batchId: BatchId\n): DbDocumentMutationKey {\n return [userId, encodeResourcePath(path), batchId];\n}\n\n/**\n * Because we store all the useful information for this store in the key,\n * there is no useful information to store as the value. The raw (unencoded)\n * path cannot be stored because IndexedDb doesn't store prototype\n * information.\n */\nexport const DbDocumentMutationPlaceholder: DbDocumentMutation = {};\n\nexport const DbDocumentMutationStore = 'documentMutations';\n\nexport const DbRemoteDocumentStore = 'remoteDocumentsV14';\n\n/**\n * A key in the 'remoteDocumentsV14' object store is an array containing the\n * collection path, the collection group, the read time and the document id.\n */\nexport type DbRemoteDocumentKey = [\n /** path to collection */ string[],\n /** collection group */ string,\n /** read time */ DbTimestampKey,\n /** document ID */ string\n];\n\n/**\n * The primary key of the remote documents store, which allows for efficient\n * access by collection path and read time.\n */\nexport const DbRemoteDocumentKeyPath = [\n 'prefixPath',\n 'collectionGroup',\n 'readTime',\n 'documentId'\n];\n\n/** An index that provides access to documents by key. */\nexport const DbRemoteDocumentDocumentKeyIndex = 'documentKeyIndex';\n\nexport const DbRemoteDocumentDocumentKeyIndexPath = [\n 'prefixPath',\n 'collectionGroup',\n 'documentId'\n];\n\n/**\n * An index that provides access to documents by collection group and read\n * time.\n *\n * This index is used by the index backfiller.\n */\nexport const DbRemoteDocumentCollectionGroupIndex = 'collectionGroupIndex';\n\nexport const DbRemoteDocumentCollectionGroupIndexPath = [\n 'collectionGroup',\n 'readTime',\n 'prefixPath',\n 'documentId'\n];\n\nexport const DbRemoteDocumentGlobalStore = 'remoteDocumentGlobal';\n\nexport const DbRemoteDocumentGlobalKey = 'remoteDocumentGlobalKey';\n\nexport type DbRemoteDocumentGlobalKey = typeof DbRemoteDocumentGlobalKey;\n\n/**\n * A key in the 'targets' object store is a targetId of the query.\n */\nexport type DbTargetKey = TargetId;\n\nexport const DbTargetStore = 'targets';\n\n/** Keys are automatically assigned via the targetId property. */\nexport const DbTargetKeyPath = 'targetId';\n\n/** The name of the queryTargets index. */\nexport const DbTargetQueryTargetsIndexName = 'queryTargetsIndex';\n\n/**\n * The index of all canonicalIds to the targets that they match. This is not\n * a unique mapping because canonicalId does not promise a unique name for all\n * possible queries, so we append the targetId to make the mapping unique.\n */\nexport const DbTargetQueryTargetsKeyPath = ['canonicalId', 'targetId'];\n\n/**\n * The key for a DbTargetDocument, containing a targetId and an encoded resource\n * path.\n */\nexport type DbTargetDocumentKey = [TargetId, EncodedResourcePath];\n\n/** Name of the IndexedDb object store. */\nexport const DbTargetDocumentStore = 'targetDocuments';\n\n/** Keys are automatically assigned via the targetId, path properties. */\nexport const DbTargetDocumentKeyPath = ['targetId', 'path'];\n\n/** The index name for the reverse index. */\nexport const DbTargetDocumentDocumentTargetsIndex = 'documentTargetsIndex';\n\n/** We also need to create the reverse index for these properties. */\nexport const DbTargetDocumentDocumentTargetsKeyPath = ['path', 'targetId'];\n\n/**\n * The type to represent the single allowed key for the DbTargetGlobal store.\n */\nexport type DbTargetGlobalKey = typeof DbTargetGlobalKey;\n/**\n * The key string used for the single object that exists in the\n * DbTargetGlobal store.\n */\nexport const DbTargetGlobalKey = 'targetGlobalKey';\n\nexport const DbTargetGlobalStore = 'targetGlobal';\n\n/**\n * The key for a DbCollectionParent entry, containing the collection ID\n * and the parent path that contains it. Note that the parent path will be an\n * empty path in the case of root-level collections.\n */\nexport type DbCollectionParentKey = [string, EncodedResourcePath];\n\n/** Name of the IndexedDb object store. */\nexport const DbCollectionParentStore = 'collectionParents';\n\n/** Keys are automatically assigned via the collectionId, parent properties. */\nexport const DbCollectionParentKeyPath = ['collectionId', 'parent'];\n\n/** Name of the IndexedDb object store. */\nexport const DbClientMetadataStore = 'clientMetadata';\n\n/** Keys are automatically assigned via the clientId properties. */\nexport const DbClientMetadataKeyPath = 'clientId';\n\n/** Object keys in the 'clientMetadata' store are clientId strings. */\nexport type DbClientMetadataKey = string;\n\nexport type DbBundlesKey = string;\n\n/** Name of the IndexedDb object store. */\nexport const DbBundleStore = 'bundles';\n\nexport const DbBundleKeyPath = 'bundleId';\n\nexport type DbNamedQueriesKey = string;\n\n/** Name of the IndexedDb object store. */\nexport const DbNamedQueryStore = 'namedQueries';\n\nexport const DbNamedQueryKeyPath = 'name';\n\n/** The key for each index consisting of just the index id. */\nexport type DbIndexConfigurationKey = number;\n\n/** Name of the IndexedDb object store. */\nexport const DbIndexConfigurationStore = 'indexConfiguration';\n\nexport const DbIndexConfigurationKeyPath = 'indexId';\n\n/**\n * An index that provides access to the index configurations by collection\n * group.\n *\n * PORTING NOTE: iOS and Android maintain this index in-memory, but this is\n * not possible here as the Web client supports concurrent access to\n * persistence via multi-tab.\n */\nexport const DbIndexConfigurationCollectionGroupIndex = 'collectionGroupIndex';\n\nexport const DbIndexConfigurationCollectionGroupIndexPath = 'collectionGroup';\n\n/** The key for each index state consisting of the index id and its user id. */\nexport type DbIndexStateKey = [number, string];\n\n/** Name of the IndexedDb object store. */\nexport const DbIndexStateStore = 'indexState';\n\nexport const DbIndexStateKeyPath = ['indexId', 'uid'];\n\n/**\n * An index that provides access to documents in a collection sorted by last\n * update time. Used by the backfiller.\n *\n * PORTING NOTE: iOS and Android maintain this index in-memory, but this is\n * not possible here as the Web client supports concurrent access to\n * persistence via multi-tab.\n */\nexport const DbIndexStateSequenceNumberIndex = 'sequenceNumberIndex';\n\nexport const DbIndexStateSequenceNumberIndexPath = ['uid', 'sequenceNumber'];\n\n/**\n * The key for each index entry consists of the index id and its user id,\n * the encoded array and directional value for the indexed fields as well as\n * an ordered and an encoded document path for the indexed document.\n */\nexport type DbIndexEntryKey = [\n number,\n string,\n Uint8Array,\n Uint8Array,\n Uint8Array,\n string[]\n];\n\n/** Name of the IndexedDb object store. */\nexport const DbIndexEntryStore = 'indexEntries';\n\nexport const DbIndexEntryKeyPath = [\n 'indexId',\n 'uid',\n 'arrayValue',\n 'directionalValue',\n 'orderedDocumentKey',\n 'documentKey'\n];\n\nexport const DbIndexEntryDocumentKeyIndex = 'documentKeyIndex';\n\nexport const DbIndexEntryDocumentKeyIndexPath = [\n 'indexId',\n 'uid',\n 'orderedDocumentKey'\n];\n\nexport type DbDocumentOverlayKey = [\n /* userId */ string,\n /* collectionPath */ string,\n /* documentId */ string\n];\n\n/** Name of the IndexedDb object store. */\nexport const DbDocumentOverlayStore = 'documentOverlays';\n\nexport const DbDocumentOverlayKeyPath = [\n 'userId',\n 'collectionPath',\n 'documentId'\n];\n\nexport const DbDocumentOverlayCollectionPathOverlayIndex =\n 'collectionPathOverlayIndex';\n\nexport const DbDocumentOverlayCollectionPathOverlayIndexPath = [\n 'userId',\n 'collectionPath',\n 'largestBatchId'\n];\n\nexport const DbDocumentOverlayCollectionGroupOverlayIndex =\n 'collectionGroupOverlayIndex';\n\nexport const DbDocumentOverlayCollectionGroupOverlayIndexPath = [\n 'userId',\n 'collectionGroup',\n 'largestBatchId'\n];\n\n// Visible for testing\nexport const V1_STORES = [\n DbMutationQueueStore,\n DbMutationBatchStore,\n DbDocumentMutationStore,\n DbRemoteDocumentStoreLegacy,\n DbTargetStore,\n DbPrimaryClientStore,\n DbTargetGlobalStore,\n DbTargetDocumentStore\n];\n\n// Visible for testing\nexport const V3_STORES = V1_STORES;\n// Note: DbRemoteDocumentChanges is no longer used and dropped with v9.\nexport const V4_STORES = [...V3_STORES, DbClientMetadataStore];\nexport const V6_STORES = [...V4_STORES, DbRemoteDocumentGlobalStore];\nexport const V8_STORES = [...V6_STORES, DbCollectionParentStore];\nexport const V11_STORES = [...V8_STORES, DbBundleStore, DbNamedQueryStore];\nexport const V12_STORES = [...V11_STORES, DbDocumentOverlayStore];\nexport const V13_STORES = [\n DbMutationQueueStore,\n DbMutationBatchStore,\n DbDocumentMutationStore,\n DbRemoteDocumentStore,\n DbTargetStore,\n DbPrimaryClientStore,\n DbTargetGlobalStore,\n DbTargetDocumentStore,\n DbClientMetadataStore,\n DbRemoteDocumentGlobalStore,\n DbCollectionParentStore,\n DbBundleStore,\n DbNamedQueryStore,\n DbDocumentOverlayStore\n];\nexport const V14_STORES = V13_STORES;\nexport const V15_STORES = [\n ...V14_STORES,\n DbIndexConfigurationStore,\n DbIndexStateStore,\n DbIndexEntryStore\n];\n\n/**\n * The list of all default IndexedDB stores used throughout the SDK. This is\n * used when creating transactions so that access across all stores is done\n * atomically.\n */\nexport const ALL_STORES = V12_STORES;\n\n/** Returns the object stores for the provided schema. */\nexport function getObjectStores(schemaVersion: number): string[] {\n if (schemaVersion === 15) {\n return V15_STORES;\n } else if (schemaVersion === 14) {\n return V14_STORES;\n } else if (schemaVersion === 13) {\n return V13_STORES;\n } else if (schemaVersion === 12) {\n return V12_STORES;\n } else if (schemaVersion === 11) {\n return V11_STORES;\n } else {\n fail('Only schema version 11 and 12 and 13 are supported');\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document as ProtoDocument } from '../protos/firestore_proto_api';\n\nimport { DbNoDocument, DbUnknownDocument } from './indexeddb_schema';\nimport { DbTimestampKey } from './indexeddb_sentinels';\n\n// This file contains older schema definitions for object stores that were\n// migrated to newer schema versions. These object stores should only be used\n// during schema migrations.\n\nexport interface DbRemoteDocument {\n unknownDocument?: DbUnknownDocument;\n noDocument?: DbNoDocument;\n document?: ProtoDocument;\n hasCommittedMutations?: boolean;\n readTime?: DbTimestampKey;\n parentPath?: string[];\n}\n\nexport type DbRemoteDocumentKey = string[];\nexport const DbRemoteDocumentStore = 'remoteDocuments';\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict<V> {\n [stringKey: string]: V;\n}\n\nexport function objectSize(obj: object): number {\n let count = 0;\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n\nexport function forEach<V>(\n obj: Dict<V> | undefined,\n fn: (key: string, val: V) => void\n): void {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\n\nexport function mapToArray<V, R>(\n obj: Dict<V>,\n fn: (element: V, key: string, obj: Dict<V>) => R\n): R[] {\n const result: R[] = [];\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result.push(fn(obj[key], key, obj));\n }\n }\n return result;\n}\n\nexport function isEmpty<V>(obj: Dict<V>): boolean {\n debugAssert(\n obj != null && typeof obj === 'object',\n 'isEmpty() expects object parameter.'\n );\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, fail } from './assert';\n\n/*\n * Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\nexport type Comparator<K> = (key1: K, key2: K) => number;\n\nexport interface Entry<K, V> {\n key: K;\n value: V;\n}\n\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nexport class SortedMap<K, V> {\n // visible for testing\n root: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n\n constructor(\n public comparator: Comparator<K>,\n root?: LLRBNode<K, V> | LLRBEmptyNode<K, V>\n ) {\n this.root = root ? root : LLRBNode.EMPTY;\n }\n\n // Returns a copy of the map, with the specified key/value added or replaced.\n insert(key: K, value: V): SortedMap<K, V> {\n return new SortedMap<K, V>(\n this.comparator,\n this.root\n .insert(key, value, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns a copy of the map, with the specified key removed.\n remove(key: K): SortedMap<K, V> {\n return new SortedMap<K, V>(\n this.comparator,\n this.root\n .remove(key, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns the value of the node with the given key, or null.\n get(key: K): V | null {\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return node.value;\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\n\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(key: K): number {\n // Number of nodes that were pruned when descending right\n let prunedNodes = 0;\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n } else if (cmp < 0) {\n node = node.left;\n } else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n }\n\n isEmpty(): boolean {\n return this.root.isEmpty();\n }\n\n // Returns the total number of nodes in the map.\n get size(): number {\n return this.root.size;\n }\n\n // Returns the minimum key in the map.\n minKey(): K | null {\n return this.root.minKey();\n }\n\n // Returns the maximum key in the map.\n maxKey(): K | null {\n return this.root.maxKey();\n }\n\n // Traverses the map in key order and calls the specified action function\n // for each key/value pair. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal<T>(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode<K, V>).inorderTraversal(action);\n }\n\n forEach(fn: (k: K, v: V) => void): void {\n this.inorderTraversal((k, v) => {\n fn(k, v);\n return false;\n });\n }\n\n toString(): string {\n const descriptions: string[] = [];\n this.inorderTraversal((k, v) => {\n descriptions.push(`${k}:${v}`);\n return false;\n });\n return `{${descriptions.join(', ')}}`;\n }\n\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal<T>(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode<K, V>).reverseTraversal(action);\n }\n\n // Returns an iterator over the SortedMap.\n getIterator(): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, null, this.comparator, false);\n }\n\n getIteratorFrom(key: K): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, key, this.comparator, false);\n }\n\n getReverseIterator(): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, null, this.comparator, true);\n }\n\n getReverseIteratorFrom(key: K): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, key, this.comparator, true);\n }\n} // end SortedMap\n\n// An iterator over an LLRBNode.\nexport class SortedMapIterator<K, V> {\n private isReverse: boolean;\n private nodeStack: Array<LLRBNode<K, V> | LLRBEmptyNode<K, V>>;\n\n constructor(\n node: LLRBNode<K, V> | LLRBEmptyNode<K, V>,\n startKey: K | null,\n comparator: Comparator<K>,\n isReverse: boolean\n ) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n\n let cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (startKey && isReverse) {\n cmp *= -1;\n }\n\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse) {\n node = node.left;\n } else {\n node = node.right;\n }\n } else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(node);\n break;\n } else {\n // This node is greater than our start key, add it to the stack and move\n // to the next one\n this.nodeStack.push(node);\n if (this.isReverse) {\n node = node.right;\n } else {\n node = node.left;\n }\n }\n }\n }\n\n getNext(): Entry<K, V> {\n debugAssert(\n this.nodeStack.length > 0,\n 'getNext() called on iterator when hasNext() is false.'\n );\n\n let node = this.nodeStack.pop()!;\n const result = { key: node.key, value: node.value };\n\n if (this.isReverse) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.left;\n }\n }\n\n return result;\n }\n\n hasNext(): boolean {\n return this.nodeStack.length > 0;\n }\n\n peek(): Entry<K, V> | null {\n if (this.nodeStack.length === 0) {\n return null;\n }\n\n const node = this.nodeStack[this.nodeStack.length - 1];\n return { key: node.key, value: node.value };\n }\n} // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nexport class LLRBNode<K, V> {\n readonly color: boolean;\n readonly left: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n readonly right: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n readonly size: number;\n\n // Empty node is shared between all LLRB trees.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static EMPTY: LLRBEmptyNode<any, any> = null as any;\n\n static RED = true;\n static BLACK = false;\n\n constructor(\n public key: K,\n public value: V,\n color?: boolean,\n left?: LLRBNode<K, V> | LLRBEmptyNode<K, V>,\n right?: LLRBNode<K, V> | LLRBEmptyNode<K, V>\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n\n // Returns a copy of the current node, optionally replacing pieces of it.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n ): LLRBNode<K, V> {\n return new LLRBNode<K, V>(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n isEmpty(): boolean {\n return false;\n }\n\n // Traverses the tree in key order and calls the specified action function\n // for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal<T>(action: (k: K, v: V) => T): T {\n return (\n (this.left as LLRBNode<K, V>).inorderTraversal(action) ||\n action(this.key, this.value) ||\n (this.right as LLRBNode<K, V>).inorderTraversal(action)\n );\n }\n\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal<T>(action: (k: K, v: V) => T): T {\n return (\n (this.right as LLRBNode<K, V>).reverseTraversal(action) ||\n action(this.key, this.value) ||\n (this.left as LLRBNode<K, V>).reverseTraversal(action)\n );\n }\n\n // Returns the minimum node in the tree.\n private min(): LLRBNode<K, V> {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode<K, V>).min();\n }\n }\n\n // Returns the maximum key in the tree.\n minKey(): K | null {\n return this.min().key;\n }\n\n // Returns the maximum key in the tree.\n maxKey(): K | null {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n // Returns new tree, with the key/value added.\n insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {\n let n: LLRBNode<K, V> = this;\n const cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n } else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n } else {\n n = n.copy(\n null,\n null,\n null,\n null,\n n.right.insert(key, value, comparator)\n );\n }\n return n.fixUp();\n }\n\n private removeMin(): LLRBNode<K, V> | LLRBEmptyNode<K, V> {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n let n: LLRBNode<K, V> = this;\n if (!n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode<K, V>).removeMin(), null);\n return n.fixUp();\n }\n\n // Returns new tree, with the specified item removed.\n remove(\n key: K,\n comparator: Comparator<K>\n ): LLRBNode<K, V> | LLRBEmptyNode<K, V> {\n let smallest: LLRBNode<K, V>;\n let n: LLRBNode<K, V> = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n } else {\n if (n.left.isRed()) {\n n = n.rotateRight();\n }\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n n = n.moveRedRight();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return LLRBNode.EMPTY;\n } else {\n smallest = (n.right as LLRBNode<K, V>).min();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode<K, V>).removeMin()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp();\n }\n\n isRed(): boolean {\n return this.color;\n }\n\n // Returns new tree after performing any needed rotations.\n private fixUp(): LLRBNode<K, V> {\n let n: LLRBNode<K, V> = this;\n if (n.right.isRed() && !n.left.isRed()) {\n n = n.rotateLeft();\n }\n if (n.left.isRed() && n.left.left.isRed()) {\n n = n.rotateRight();\n }\n if (n.left.isRed() && n.right.isRed()) {\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedLeft(): LLRBNode<K, V> {\n let n = this.colorFlip();\n if (n.right.left.isRed()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode<K, V>).rotateRight()\n );\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedRight(): LLRBNode<K, V> {\n let n = this.colorFlip();\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n return n;\n }\n\n private rotateLeft(): LLRBNode<K, V> {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return (this.right as LLRBNode<K, V>).copy(\n null,\n null,\n this.color,\n nl,\n null\n );\n }\n\n private rotateRight(): LLRBNode<K, V> {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return (this.left as LLRBNode<K, V>).copy(null, null, this.color, null, nr);\n }\n\n private colorFlip(): LLRBNode<K, V> {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n const blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n } else {\n return false;\n }\n }\n\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n protected check(): number {\n if (this.isRed() && this.left.isRed()) {\n throw fail('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed()) {\n throw fail('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n const blackDepth = (this.left as LLRBNode<K, V>).check();\n if (blackDepth !== (this.right as LLRBNode<K, V>).check()) {\n throw fail('Black depths differ');\n } else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n }\n} // end LLRBNode\n\n// Represents an empty node (a leaf node in the Red-Black Tree).\nexport class LLRBEmptyNode<K, V> {\n get key(): never {\n throw fail('LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail('LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail('LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail('LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail('LLRBEmptyNode has no right child.');\n }\n size = 0;\n\n // Returns a copy of the current node.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n ): LLRBEmptyNode<K, V> {\n return this;\n }\n\n // Returns a copy of the tree, with the specified key/value added.\n insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {\n return new LLRBNode<K, V>(key, value);\n }\n\n // Returns a copy of the tree, with the specified key removed.\n remove(key: K, comparator: Comparator<K>): LLRBEmptyNode<K, V> {\n return this;\n }\n\n isEmpty(): boolean {\n return true;\n }\n\n inorderTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n reverseTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n minKey(): K | null {\n return null;\n }\n\n maxKey(): K | null {\n return null;\n }\n\n isRed(): boolean {\n return false;\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n return true;\n }\n\n protected check(): 0 {\n return 0;\n }\n} // end LLRBEmptyNode\n\nLLRBNode.EMPTY = new LLRBEmptyNode<unknown, unknown>();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap, SortedMapIterator } from './sorted_map';\n\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nexport class SortedSet<T> {\n private data: SortedMap<T, boolean>;\n\n constructor(private comparator: (left: T, right: T) => number) {\n this.data = new SortedMap<T, boolean>(this.comparator);\n }\n\n has(elem: T): boolean {\n return this.data.get(elem) !== null;\n }\n\n first(): T | null {\n return this.data.minKey();\n }\n\n last(): T | null {\n return this.data.maxKey();\n }\n\n get size(): number {\n return this.data.size;\n }\n\n indexOf(elem: T): number {\n return this.data.indexOf(elem);\n }\n\n /** Iterates elements in order defined by \"comparator\" */\n forEach(cb: (elem: T) => void): void {\n this.data.inorderTraversal((k: T, v: boolean) => {\n cb(k);\n return false;\n });\n }\n\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n forEachInRange(range: [T, T], cb: (elem: T) => void): void {\n const iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n const elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0) {\n return;\n }\n cb(elem.key);\n }\n }\n\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n forEachWhile(cb: (elem: T) => boolean, start?: T): void {\n let iter: SortedMapIterator<T, boolean>;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n } else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n const elem = iter.getNext();\n const result = cb(elem.key);\n if (!result) {\n return;\n }\n }\n }\n\n /** Finds the least element greater than or equal to `elem`. */\n firstAfterOrEqual(elem: T): T | null {\n const iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n }\n\n getIterator(): SortedSetIterator<T> {\n return new SortedSetIterator<T>(this.data.getIterator());\n }\n\n getIteratorFrom(key: T): SortedSetIterator<T> {\n return new SortedSetIterator<T>(this.data.getIteratorFrom(key));\n }\n\n /** Inserts or updates an element */\n add(elem: T): SortedSet<T> {\n return this.copy(this.data.remove(elem).insert(elem, true));\n }\n\n /** Deletes an element */\n delete(elem: T): SortedSet<T> {\n if (!this.has(elem)) {\n return this;\n }\n return this.copy(this.data.remove(elem));\n }\n\n isEmpty(): boolean {\n return this.data.isEmpty();\n }\n\n unionWith(other: SortedSet<T>): SortedSet<T> {\n let result: SortedSet<T> = this;\n\n // Make sure `result` always refers to the larger one of the two sets.\n if (result.size < other.size) {\n result = other;\n other = this;\n }\n\n other.forEach(elem => {\n result = result.add(elem);\n });\n return result;\n }\n\n isEqual(other: SortedSet<T>): boolean {\n if (!(other instanceof SortedSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.data.getIterator();\n const otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n const thisElem = thisIt.getNext().key;\n const otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0) {\n return false;\n }\n }\n return true;\n }\n\n toArray(): T[] {\n const res: T[] = [];\n this.forEach(targetId => {\n res.push(targetId);\n });\n return res;\n }\n\n toString(): string {\n const result: T[] = [];\n this.forEach(elem => result.push(elem));\n return 'SortedSet(' + result.toString() + ')';\n }\n\n private copy(data: SortedMap<T, boolean>): SortedSet<T> {\n const result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n }\n}\n\nexport class SortedSetIterator<T> {\n constructor(private iter: SortedMapIterator<T, boolean>) {}\n\n getNext(): T {\n return this.iter.getNext().key;\n }\n\n hasNext(): boolean {\n return this.iter.hasNext();\n }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffSortedSets<T>(\n before: SortedSet<T>,\n after: SortedSet<T>,\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n const beforeIt = before.getIterator();\n const afterIt = after.getIterator();\n\n let beforeValue = advanceIterator(beforeIt);\n let afterValue = advanceIterator(afterIt);\n\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n while (beforeValue || afterValue) {\n let added = false;\n let removed = false;\n\n if (beforeValue && afterValue) {\n const cmp = comparator(beforeValue, afterValue);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n removed = true;\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n added = true;\n }\n } else if (beforeValue != null) {\n removed = true;\n } else {\n added = true;\n }\n\n if (added) {\n onAdd(afterValue!);\n afterValue = advanceIterator(afterIt);\n } else if (removed) {\n onRemove(beforeValue!);\n beforeValue = advanceIterator(beforeIt);\n } else {\n beforeValue = advanceIterator(beforeIt);\n afterValue = advanceIterator(afterIt);\n }\n }\n}\n\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction advanceIterator<T>(it: SortedSetIterator<T>): T | undefined {\n return it.hasNext() ? it.getNext() : undefined;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { FieldPath } from './path';\n\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */\nexport class FieldMask {\n constructor(readonly fields: FieldPath[]) {\n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n fields.sort(FieldPath.comparator);\n debugAssert(\n !fields.some((v, i) => i !== 0 && v.isEqual(fields[i - 1])),\n 'FieldMask contains field that is not unique: ' +\n fields.find((v, i) => i !== 0 && v.isEqual(fields[i - 1]))!\n );\n }\n\n static empty(): FieldMask {\n return new FieldMask([]);\n }\n\n /**\n * Returns a new FieldMask object that is the result of adding all the given\n * fields paths to this field mask.\n */\n unionWith(extraFields: FieldPath[]): FieldMask {\n let mergedMaskSet = new SortedSet<FieldPath>(FieldPath.comparator);\n for (const fieldPath of this.fields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n for (const fieldPath of extraFields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n return new FieldMask(mergedMaskSet.toArray());\n }\n\n /**\n * Verifies that `fieldPath` is included by at least one field in this field\n * mask.\n *\n * This is an O(n) operation, where `n` is the size of the field mask.\n */\n covers(fieldPath: FieldPath): boolean {\n for (const fieldMaskPath of this.fields) {\n if (fieldMaskPath.isPrefixOf(fieldPath)) {\n return true;\n }\n }\n return false;\n }\n\n isEqual(other: FieldMask): boolean {\n return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r));\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class Base64DecodeError extends Error {\n readonly name = 'Base64DecodeError';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { decodeBase64, encodeBase64 } from '../platform/base64';\n\nimport { primitiveComparator } from './misc';\n\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */\nexport class ByteString {\n static readonly EMPTY_BYTE_STRING = new ByteString('');\n\n private constructor(private readonly binaryString: string) {}\n\n static fromBase64String(base64: string): ByteString {\n const binaryString = decodeBase64(base64);\n return new ByteString(binaryString);\n }\n\n static fromUint8Array(array: Uint8Array): ByteString {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const binaryString = binaryStringFromUint8Array(array);\n return new ByteString(binaryString);\n }\n\n [Symbol.iterator](): Iterator<number> {\n let i = 0;\n return {\n next: () => {\n if (i < this.binaryString.length) {\n return { value: this.binaryString.charCodeAt(i++), done: false };\n } else {\n return { value: undefined, done: true };\n }\n }\n };\n }\n\n toBase64(): string {\n return encodeBase64(this.binaryString);\n }\n\n toUint8Array(): Uint8Array {\n return uint8ArrayFromBinaryString(this.binaryString);\n }\n\n approximateByteSize(): number {\n return this.binaryString.length * 2;\n }\n\n compareTo(other: ByteString): number {\n return primitiveComparator(this.binaryString, other.binaryString);\n }\n\n isEqual(other: ByteString): boolean {\n return this.binaryString === other.binaryString;\n }\n}\n\n/**\n * Helper function to convert an Uint8array to a binary string.\n */\nexport function binaryStringFromUint8Array(array: Uint8Array): string {\n let binaryString = '';\n for (let i = 0; i < array.length; ++i) {\n binaryString += String.fromCharCode(array[i]);\n }\n return binaryString;\n}\n\n/**\n * Helper function to convert a binary string to an Uint8Array.\n */\nexport function uint8ArrayFromBinaryString(binaryString: string): Uint8Array {\n const buffer = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n buffer[i] = binaryString.charCodeAt(i);\n }\n return buffer;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Base64DecodeError } from '../../util/base64_decode_error';\n\n/** Converts a Base64 encoded string to a binary string. */\nexport function decodeBase64(encoded: string): string {\n try {\n return atob(encoded);\n } catch (e) {\n // Check that `DOMException` is defined before using it to avoid\n // \"ReferenceError: Property 'DOMException' doesn't exist\" in react-native.\n // (https://github.com/firebase/firebase-js-sdk/issues/7115)\n if (typeof DOMException !== 'undefined' && e instanceof DOMException) {\n throw new Base64DecodeError('Invalid base64 string: ' + e);\n } else {\n throw e;\n }\n }\n}\n\n/** Converts a binary string to a Base64 encoded string. */\nexport function encodeBase64(raw: string): string {\n return btoa(raw);\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return typeof atob !== 'undefined';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../protos/firestore_proto_api';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nconst ISO_TIMESTAMP_REG_EXP = new RegExp(\n /^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/\n);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */\nexport function normalizeTimestamp(date: Timestamp): {\n seconds: number;\n nanos: number;\n} {\n hardAssert(!!date, 'Cannot normalize null or undefined timestamp.');\n\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (typeof date === 'string') {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n\n // Parse the nanos right out of the string.\n let nanos = 0;\n const fraction = ISO_TIMESTAMP_REG_EXP.exec(date);\n hardAssert(!!fraction, 'invalid timestamp: ' + date);\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n }\n\n // Parse the date to get the seconds.\n const parsedDate = new Date(date);\n const seconds = Math.floor(parsedDate.getTime() / 1000);\n\n return { seconds, nanos };\n } else {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n const seconds = normalizeNumber(date.seconds);\n const nanos = normalizeNumber(date.nanos);\n return { seconds, nanos };\n }\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */\nexport function normalizeNumber(value: number | string | undefined): number {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n } else if (typeof value === 'string') {\n return Number(value);\n } else {\n return 0;\n }\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */\nexport function normalizeByteString(blob: string | Uint8Array): ByteString {\n if (typeof blob === 'string') {\n return ByteString.fromBase64String(blob);\n } else {\n return ByteString.fromUint8Array(blob);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n Value as ProtoValue,\n MapValue as ProtoMapValue\n} from '../protos/firestore_proto_api';\n\nimport { normalizeTimestamp } from './normalize';\n\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * transform. They can only exist in the local view of a document. Therefore\n * they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */\n\nconst SERVER_TIMESTAMP_SENTINEL = 'server_timestamp';\nconst TYPE_KEY = '__type__';\nconst PREVIOUS_VALUE_KEY = '__previous_value__';\nconst LOCAL_WRITE_TIME_KEY = '__local_write_time__';\n\nexport function isServerTimestamp(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === SERVER_TIMESTAMP_SENTINEL;\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\nexport function serverTimestamp(\n localWriteTime: Timestamp,\n previousValue: ProtoValue | null\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: SERVER_TIMESTAMP_SENTINEL\n },\n [LOCAL_WRITE_TIME_KEY]: {\n timestampValue: {\n seconds: localWriteTime.seconds,\n nanos: localWriteTime.nanoseconds\n }\n }\n }\n };\n\n // We should avoid storing deeply nested server timestamp map values\n // because we never use the intermediate \"previous values\".\n // For example:\n // previous: 42L, add: t1, result: t1 -> 42L\n // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)\n // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)\n // `getPreviousValue` recursively traverses server timestamps to find the\n // least recent Value.\n if (previousValue && isServerTimestamp(previousValue)) {\n previousValue = getPreviousValue(previousValue);\n }\n if (previousValue) {\n mapValue.fields![PREVIOUS_VALUE_KEY] = previousValue;\n }\n\n return { mapValue };\n}\n\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nexport function getPreviousValue(value: ProtoValue): ProtoValue | null {\n const previousValue = value.mapValue!.fields![PREVIOUS_VALUE_KEY];\n\n if (isServerTimestamp(previousValue)) {\n return getPreviousValue(previousValue);\n }\n return previousValue;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */\nexport function getLocalWriteTime(value: ProtoValue): Timestamp {\n const localWriteTime = normalizeTimestamp(\n value.mapValue!.fields![LOCAL_WRITE_TIME_KEY].timestampValue!\n );\n return new Timestamp(localWriteTime.seconds, localWriteTime.nanos);\n}\n","import { FirebaseApp } from '@firebase/app';\n\nimport { ExperimentalLongPollingOptions } from '../api/long_polling_options';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class DatabaseInfo {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId - The database to use.\n * @param appId - The Firebase App Id.\n * @param persistenceKey - A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host - The Firestore backend host to connect to.\n * @param ssl - Whether to use SSL when connecting.\n * @param forceLongPolling - Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n * option when using WebChannel as the network transport.\n * @param longPollingOptions Options that configure long-polling.\n * @param useFetchStreams Whether to use the Fetch API instead of\n * XMLHTTPRequest\n */\n constructor(\n readonly databaseId: DatabaseId,\n readonly appId: string,\n readonly persistenceKey: string,\n readonly host: string,\n readonly ssl: boolean,\n readonly forceLongPolling: boolean,\n readonly autoDetectLongPolling: boolean,\n readonly longPollingOptions: ExperimentalLongPollingOptions,\n readonly useFetchStreams: boolean\n ) {}\n}\n\n/** The default database name for a project. */\nexport const DEFAULT_DATABASE_NAME = '(default)';\n\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nexport class DatabaseId {\n readonly database: string;\n constructor(readonly projectId: string, database?: string) {\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n\n static empty(): DatabaseId {\n return new DatabaseId('', '');\n }\n\n get isDefaultDatabase(): boolean {\n return this.database === DEFAULT_DATABASE_NAME;\n }\n\n isEqual(other: {}): boolean {\n return (\n other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database\n );\n }\n}\n\nexport function databaseIdFromApp(\n app: FirebaseApp,\n database?: string\n): DatabaseId {\n if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n '\"projectId\" not provided in firebase.initializeApp.'\n );\n }\n\n return new DatabaseId(app.options.projectId!, database);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseId } from '../core/database_info';\nimport {\n ArrayValue,\n LatLng,\n MapValue,\n Timestamp,\n Value\n} from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport { arrayEquals, primitiveComparator } from '../util/misc';\nimport { forEach, objectSize } from '../util/obj';\nimport { isNegativeZero } from '../util/types';\n\nimport { DocumentKey } from './document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from './normalize';\nimport {\n getLocalWriteTime,\n getPreviousValue,\n isServerTimestamp\n} from './server_timestamps';\nimport { TypeOrder } from './type_order';\n\nconst MAX_VALUE_TYPE = '__max__';\nexport const MAX_VALUE: Value = {\n mapValue: {\n fields: {\n '__type__': { stringValue: MAX_VALUE_TYPE }\n }\n }\n};\n\nexport const MIN_VALUE: Value = {\n nullValue: 'NULL_VALUE'\n};\n\n/** Extracts the backend's type order for the provided value. */\nexport function typeOrder(value: Value): TypeOrder {\n if ('nullValue' in value) {\n return TypeOrder.NullValue;\n } else if ('booleanValue' in value) {\n return TypeOrder.BooleanValue;\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return TypeOrder.NumberValue;\n } else if ('timestampValue' in value) {\n return TypeOrder.TimestampValue;\n } else if ('stringValue' in value) {\n return TypeOrder.StringValue;\n } else if ('bytesValue' in value) {\n return TypeOrder.BlobValue;\n } else if ('referenceValue' in value) {\n return TypeOrder.RefValue;\n } else if ('geoPointValue' in value) {\n return TypeOrder.GeoPointValue;\n } else if ('arrayValue' in value) {\n return TypeOrder.ArrayValue;\n } else if ('mapValue' in value) {\n if (isServerTimestamp(value)) {\n return TypeOrder.ServerTimestampValue;\n } else if (isMaxValue(value)) {\n return TypeOrder.MaxValue;\n }\n return TypeOrder.ObjectValue;\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */\nexport function valueEquals(left: Value, right: Value): boolean {\n if (left === right) {\n return true;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n if (leftType !== rightType) {\n return false;\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n return true;\n case TypeOrder.BooleanValue:\n return left.booleanValue === right.booleanValue;\n case TypeOrder.ServerTimestampValue:\n return getLocalWriteTime(left).isEqual(getLocalWriteTime(right));\n case TypeOrder.TimestampValue:\n return timestampEquals(left, right);\n case TypeOrder.StringValue:\n return left.stringValue === right.stringValue;\n case TypeOrder.BlobValue:\n return blobEquals(left, right);\n case TypeOrder.RefValue:\n return left.referenceValue === right.referenceValue;\n case TypeOrder.GeoPointValue:\n return geoPointEquals(left, right);\n case TypeOrder.NumberValue:\n return numberEquals(left, right);\n case TypeOrder.ArrayValue:\n return arrayEquals(\n left.arrayValue!.values || [],\n right.arrayValue!.values || [],\n valueEquals\n );\n case TypeOrder.ObjectValue:\n return objectEquals(left, right);\n case TypeOrder.MaxValue:\n return true;\n default:\n return fail('Unexpected value type: ' + JSON.stringify(left));\n }\n}\n\nfunction timestampEquals(left: Value, right: Value): boolean {\n if (\n typeof left.timestampValue === 'string' &&\n typeof right.timestampValue === 'string' &&\n left.timestampValue.length === right.timestampValue.length\n ) {\n // Use string equality for ISO 8601 timestamps\n return left.timestampValue === right.timestampValue;\n }\n\n const leftTimestamp = normalizeTimestamp(left.timestampValue!);\n const rightTimestamp = normalizeTimestamp(right.timestampValue!);\n return (\n leftTimestamp.seconds === rightTimestamp.seconds &&\n leftTimestamp.nanos === rightTimestamp.nanos\n );\n}\n\nfunction geoPointEquals(left: Value, right: Value): boolean {\n return (\n normalizeNumber(left.geoPointValue!.latitude) ===\n normalizeNumber(right.geoPointValue!.latitude) &&\n normalizeNumber(left.geoPointValue!.longitude) ===\n normalizeNumber(right.geoPointValue!.longitude)\n );\n}\n\nfunction blobEquals(left: Value, right: Value): boolean {\n return normalizeByteString(left.bytesValue!).isEqual(\n normalizeByteString(right.bytesValue!)\n );\n}\n\nexport function numberEquals(left: Value, right: Value): boolean {\n if ('integerValue' in left && 'integerValue' in right) {\n return (\n normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)\n );\n } else if ('doubleValue' in left && 'doubleValue' in right) {\n const n1 = normalizeNumber(left.doubleValue!);\n const n2 = normalizeNumber(right.doubleValue!);\n\n if (n1 === n2) {\n return isNegativeZero(n1) === isNegativeZero(n2);\n } else {\n return isNaN(n1) && isNaN(n2);\n }\n }\n\n return false;\n}\n\nfunction objectEquals(left: Value, right: Value): boolean {\n const leftMap = left.mapValue!.fields || {};\n const rightMap = right.mapValue!.fields || {};\n\n if (objectSize(leftMap) !== objectSize(rightMap)) {\n return false;\n }\n\n for (const key in leftMap) {\n if (leftMap.hasOwnProperty(key)) {\n if (\n rightMap[key] === undefined ||\n !valueEquals(leftMap[key], rightMap[key])\n ) {\n return false;\n }\n }\n }\n return true;\n}\n\n/** Returns true if the ArrayValue contains the specified element. */\nexport function arrayValueContains(\n haystack: ArrayValue,\n needle: Value\n): boolean {\n return (\n (haystack.values || []).find(v => valueEquals(v, needle)) !== undefined\n );\n}\n\nexport function valueCompare(left: Value, right: Value): number {\n if (left === right) {\n return 0;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n\n if (leftType !== rightType) {\n return primitiveComparator(leftType, rightType);\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n case TypeOrder.MaxValue:\n return 0;\n case TypeOrder.BooleanValue:\n return primitiveComparator(left.booleanValue!, right.booleanValue!);\n case TypeOrder.NumberValue:\n return compareNumbers(left, right);\n case TypeOrder.TimestampValue:\n return compareTimestamps(left.timestampValue!, right.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return compareTimestamps(\n getLocalWriteTime(left),\n getLocalWriteTime(right)\n );\n case TypeOrder.StringValue:\n return primitiveComparator(left.stringValue!, right.stringValue!);\n case TypeOrder.BlobValue:\n return compareBlobs(left.bytesValue!, right.bytesValue!);\n case TypeOrder.RefValue:\n return compareReferences(left.referenceValue!, right.referenceValue!);\n case TypeOrder.GeoPointValue:\n return compareGeoPoints(left.geoPointValue!, right.geoPointValue!);\n case TypeOrder.ArrayValue:\n return compareArrays(left.arrayValue!, right.arrayValue!);\n case TypeOrder.ObjectValue:\n return compareMaps(left.mapValue!, right.mapValue!);\n default:\n throw fail('Invalid value type: ' + leftType);\n }\n}\n\nfunction compareNumbers(left: Value, right: Value): number {\n const leftNumber = normalizeNumber(left.integerValue || left.doubleValue);\n const rightNumber = normalizeNumber(right.integerValue || right.doubleValue);\n\n if (leftNumber < rightNumber) {\n return -1;\n } else if (leftNumber > rightNumber) {\n return 1;\n } else if (leftNumber === rightNumber) {\n return 0;\n } else {\n // one or both are NaN.\n if (isNaN(leftNumber)) {\n return isNaN(rightNumber) ? 0 : -1;\n } else {\n return 1;\n }\n }\n}\n\nfunction compareTimestamps(left: Timestamp, right: Timestamp): number {\n if (\n typeof left === 'string' &&\n typeof right === 'string' &&\n left.length === right.length\n ) {\n return primitiveComparator(left, right);\n }\n\n const leftTimestamp = normalizeTimestamp(left);\n const rightTimestamp = normalizeTimestamp(right);\n\n const comparison = primitiveComparator(\n leftTimestamp.seconds,\n rightTimestamp.seconds\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos);\n}\n\nfunction compareReferences(leftPath: string, rightPath: string): number {\n const leftSegments = leftPath.split('/');\n const rightSegments = rightPath.split('/');\n for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) {\n const comparison = primitiveComparator(leftSegments[i], rightSegments[i]);\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(leftSegments.length, rightSegments.length);\n}\n\nfunction compareGeoPoints(left: LatLng, right: LatLng): number {\n const comparison = primitiveComparator(\n normalizeNumber(left.latitude),\n normalizeNumber(right.latitude)\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(\n normalizeNumber(left.longitude),\n normalizeNumber(right.longitude)\n );\n}\n\nfunction compareBlobs(\n left: string | Uint8Array,\n right: string | Uint8Array\n): number {\n const leftBytes = normalizeByteString(left);\n const rightBytes = normalizeByteString(right);\n return leftBytes.compareTo(rightBytes);\n}\n\nfunction compareArrays(left: ArrayValue, right: ArrayValue): number {\n const leftArray = left.values || [];\n const rightArray = right.values || [];\n\n for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) {\n const compare = valueCompare(leftArray[i], rightArray[i]);\n if (compare) {\n return compare;\n }\n }\n return primitiveComparator(leftArray.length, rightArray.length);\n}\n\nfunction compareMaps(left: MapValue, right: MapValue): number {\n if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {\n return 0;\n } else if (left === MAX_VALUE.mapValue) {\n return 1;\n } else if (right === MAX_VALUE.mapValue) {\n return -1;\n }\n\n const leftMap = left.fields || {};\n const leftKeys = Object.keys(leftMap);\n const rightMap = right.fields || {};\n const rightKeys = Object.keys(rightMap);\n\n // Even though MapValues are likely sorted correctly based on their insertion\n // order (e.g. when received from the backend), local modifications can bring\n // elements out of order. We need to re-sort the elements to ensure that\n // canonical IDs are independent of insertion order.\n leftKeys.sort();\n rightKeys.sort();\n\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) {\n const keyCompare = primitiveComparator(leftKeys[i], rightKeys[i]);\n if (keyCompare !== 0) {\n return keyCompare;\n }\n const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]);\n if (compare !== 0) {\n return compare;\n }\n }\n\n return primitiveComparator(leftKeys.length, rightKeys.length);\n}\n\n/**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */\nexport function canonicalId(value: Value): string {\n return canonifyValue(value);\n}\n\nfunction canonifyValue(value: Value): string {\n if ('nullValue' in value) {\n return 'null';\n } else if ('booleanValue' in value) {\n return '' + value.booleanValue!;\n } else if ('integerValue' in value) {\n return '' + value.integerValue!;\n } else if ('doubleValue' in value) {\n return '' + value.doubleValue!;\n } else if ('timestampValue' in value) {\n return canonifyTimestamp(value.timestampValue!);\n } else if ('stringValue' in value) {\n return value.stringValue!;\n } else if ('bytesValue' in value) {\n return canonifyByteString(value.bytesValue!);\n } else if ('referenceValue' in value) {\n return canonifyReference(value.referenceValue!);\n } else if ('geoPointValue' in value) {\n return canonifyGeoPoint(value.geoPointValue!);\n } else if ('arrayValue' in value) {\n return canonifyArray(value.arrayValue!);\n } else if ('mapValue' in value) {\n return canonifyMap(value.mapValue!);\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nfunction canonifyByteString(byteString: string | Uint8Array): string {\n return normalizeByteString(byteString).toBase64();\n}\n\nfunction canonifyTimestamp(timestamp: Timestamp): string {\n const normalizedTimestamp = normalizeTimestamp(timestamp);\n return `time(${normalizedTimestamp.seconds},${normalizedTimestamp.nanos})`;\n}\n\nfunction canonifyGeoPoint(geoPoint: LatLng): string {\n return `geo(${geoPoint.latitude},${geoPoint.longitude})`;\n}\n\nfunction canonifyReference(referenceValue: string): string {\n return DocumentKey.fromName(referenceValue).toString();\n}\n\nfunction canonifyMap(mapValue: MapValue): string {\n // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n // matching canonical IDs for identical maps, we need to sort the keys.\n const sortedKeys = Object.keys(mapValue.fields || {}).sort();\n\n let result = '{';\n let first = true;\n for (const key of sortedKeys) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += `${key}:${canonifyValue(mapValue.fields![key])}`;\n }\n return result + '}';\n}\n\nfunction canonifyArray(arrayValue: ArrayValue): string {\n let result = '[';\n let first = true;\n for (const value of arrayValue.values || []) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += canonifyValue(value);\n }\n return result + ']';\n}\n\n/**\n * Returns an approximate (and wildly inaccurate) in-memory size for the field\n * value.\n *\n * The memory size takes into account only the actual user data as it resides\n * in memory and ignores object overhead.\n */\nexport function estimateByteSize(value: Value): number {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return 4;\n case TypeOrder.BooleanValue:\n return 4;\n case TypeOrder.NumberValue:\n return 8;\n case TypeOrder.TimestampValue:\n // Timestamps are made up of two distinct numbers (seconds + nanoseconds)\n return 16;\n case TypeOrder.ServerTimestampValue:\n const previousValue = getPreviousValue(value);\n return previousValue ? 16 + estimateByteSize(previousValue) : 16;\n case TypeOrder.StringValue:\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:\n // \"JavaScript's String type is [...] a set of elements of 16-bit unsigned\n // integer values\"\n return value.stringValue!.length * 2;\n case TypeOrder.BlobValue:\n return normalizeByteString(value.bytesValue!).approximateByteSize();\n case TypeOrder.RefValue:\n return value.referenceValue!.length;\n case TypeOrder.GeoPointValue:\n // GeoPoints are made up of two distinct numbers (latitude + longitude)\n return 16;\n case TypeOrder.ArrayValue:\n return estimateArrayByteSize(value.arrayValue!);\n case TypeOrder.ObjectValue:\n return estimateMapByteSize(value.mapValue!);\n default:\n throw fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nfunction estimateMapByteSize(mapValue: MapValue): number {\n let size = 0;\n forEach(mapValue.fields, (key, val) => {\n size += key.length + estimateByteSize(val);\n });\n return size;\n}\n\nfunction estimateArrayByteSize(arrayValue: ArrayValue): number {\n return (arrayValue.values || []).reduce(\n (previousSize, value) => previousSize + estimateByteSize(value),\n 0\n );\n}\n\n/** Returns a reference value for the provided database and key. */\nexport function refValue(databaseId: DatabaseId, key: DocumentKey): Value {\n return {\n referenceValue: `projects/${databaseId.projectId}/databases/${\n databaseId.database\n }/documents/${key.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */\nexport function isInteger(\n value?: Value | null\n): value is { integerValue: string | number } {\n return !!value && 'integerValue' in value;\n}\n\n/** Returns true if `value` is a DoubleValue. */\nexport function isDouble(\n value?: Value | null\n): value is { doubleValue: string | number } {\n return !!value && 'doubleValue' in value;\n}\n\n/** Returns true if `value` is either an IntegerValue or a DoubleValue. */\nexport function isNumber(value?: Value | null): boolean {\n return isInteger(value) || isDouble(value);\n}\n\n/** Returns true if `value` is an ArrayValue. */\nexport function isArray(\n value?: Value | null\n): value is { arrayValue: ArrayValue } {\n return !!value && 'arrayValue' in value;\n}\n\n/** Returns true if `value` is a ReferenceValue. */\nexport function isReferenceValue(\n value?: Value | null\n): value is { referenceValue: string } {\n return !!value && 'referenceValue' in value;\n}\n\n/** Returns true if `value` is a NullValue. */\nexport function isNullValue(\n value?: Value | null\n): value is { nullValue: 'NULL_VALUE' } {\n return !!value && 'nullValue' in value;\n}\n\n/** Returns true if `value` is NaN. */\nexport function isNanValue(\n value?: Value | null\n): value is { doubleValue: 'NaN' | number } {\n return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */\nexport function isMapValue(\n value?: Value | null\n): value is { mapValue: MapValue } {\n return !!value && 'mapValue' in value;\n}\n\n/** Creates a deep copy of `source`. */\nexport function deepClone(source: Value): Value {\n if (source.geoPointValue) {\n return { geoPointValue: { ...source.geoPointValue } };\n } else if (\n source.timestampValue &&\n typeof source.timestampValue === 'object'\n ) {\n return { timestampValue: { ...source.timestampValue } };\n } else if (source.mapValue) {\n const target: Value = { mapValue: { fields: {} } };\n forEach(\n source.mapValue.fields,\n (key, val) => (target.mapValue!.fields![key] = deepClone(val))\n );\n return target;\n } else if (source.arrayValue) {\n const target: Value = { arrayValue: { values: [] } };\n for (let i = 0; i < (source.arrayValue.values || []).length; ++i) {\n target.arrayValue!.values![i] = deepClone(source.arrayValue.values![i]);\n }\n return target;\n } else {\n return { ...source };\n }\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */\nexport function isMaxValue(value: Value): boolean {\n return (\n (((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue ===\n MAX_VALUE_TYPE\n );\n}\n\n/** Returns the lowest value for the given value type (inclusive). */\nexport function valuesGetLowerBound(value: Value): Value {\n if ('nullValue' in value) {\n return MIN_VALUE;\n } else if ('booleanValue' in value) {\n return { booleanValue: false };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { doubleValue: NaN };\n } else if ('timestampValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('stringValue' in value) {\n return { stringValue: '' };\n } else if ('bytesValue' in value) {\n return { bytesValue: '' };\n } else if ('referenceValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('geoPointValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('arrayValue' in value) {\n return { arrayValue: {} };\n } else if ('mapValue' in value) {\n return { mapValue: {} };\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\n/** Returns the largest value for the given value type (exclusive). */\nexport function valuesGetUpperBound(value: Value): Value {\n if ('nullValue' in value) {\n return { booleanValue: false };\n } else if ('booleanValue' in value) {\n return { doubleValue: NaN };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('timestampValue' in value) {\n return { stringValue: '' };\n } else if ('stringValue' in value) {\n return { bytesValue: '' };\n } else if ('bytesValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('referenceValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('geoPointValue' in value) {\n return { arrayValue: {} };\n } else if ('arrayValue' in value) {\n return { mapValue: {} };\n } else if ('mapValue' in value) {\n return MAX_VALUE;\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nexport function lowerBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return -1;\n } else if (!left.inclusive && right.inclusive) {\n return 1;\n }\n\n return 0;\n}\n\nexport function upperBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return 1;\n } else if (!left.inclusive && right.inclusive) {\n return -1;\n }\n\n return 0;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\nimport { forEach } from '../util/obj';\n\nimport { FieldMask } from './field_mask';\nimport { FieldPath } from './path';\nimport { isServerTimestamp } from './server_timestamps';\nimport { deepClone, isMapValue, valueEquals } from './values';\n\nexport interface JsonObject<T> {\n [name: string]: T;\n}\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */\nexport class ObjectValue {\n constructor(readonly value: { mapValue: ProtoMapValue }) {\n debugAssert(\n !isServerTimestamp(value),\n 'ServerTimestamps should be converted to ServerTimestampValue'\n );\n }\n\n static empty(): ObjectValue {\n return new ObjectValue({ mapValue: {} });\n }\n\n /**\n * Returns the value at the given path or null.\n *\n * @param path - the path to search\n * @returns The value at the path or null if the path is not set.\n */\n field(path: FieldPath): ProtoValue | null {\n if (path.isEmpty()) {\n return this.value;\n } else {\n let currentLevel: ProtoValue = this.value;\n for (let i = 0; i < path.length - 1; ++i) {\n currentLevel = (currentLevel.mapValue!.fields || {})[path.get(i)];\n if (!isMapValue(currentLevel)) {\n return null;\n }\n }\n currentLevel = (currentLevel.mapValue!.fields! || {})[path.lastSegment()];\n return currentLevel || null;\n }\n }\n\n /**\n * Sets the field to the provided value.\n *\n * @param path - The field path to set.\n * @param value - The value to set.\n */\n set(path: FieldPath, value: ProtoValue): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot set field for empty path on ObjectValue'\n );\n const fieldsMap = this.getFieldsMap(path.popLast());\n fieldsMap[path.lastSegment()] = deepClone(value);\n }\n\n /**\n * Sets the provided fields to the provided values.\n *\n * @param data - A map of fields to values (or null for deletes).\n */\n setAll(data: Map<FieldPath, ProtoValue | null>): void {\n let parent = FieldPath.emptyPath();\n\n let upserts: { [key: string]: ProtoValue } = {};\n let deletes: string[] = [];\n\n data.forEach((value, path) => {\n if (!parent.isImmediateParentOf(path)) {\n // Insert the accumulated changes at this parent location\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n upserts = {};\n deletes = [];\n parent = path.popLast();\n }\n\n if (value) {\n upserts[path.lastSegment()] = deepClone(value);\n } else {\n deletes.push(path.lastSegment());\n }\n });\n\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n }\n\n /**\n * Removes the field at the specified path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path - The field path to remove.\n */\n delete(path: FieldPath): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot delete field for empty path on ObjectValue'\n );\n const nestedValue = this.field(path.popLast());\n if (isMapValue(nestedValue) && nestedValue.mapValue.fields) {\n delete nestedValue.mapValue.fields[path.lastSegment()];\n }\n }\n\n isEqual(other: ObjectValue): boolean {\n return valueEquals(this.value, other.value);\n }\n\n /**\n * Returns the map that contains the leaf element of `path`. If the parent\n * entry does not yet exist, or if it is not a map, a new map will be created.\n */\n private getFieldsMap(path: FieldPath): Record<string, ProtoValue> {\n let current = this.value;\n\n if (!current.mapValue!.fields) {\n current.mapValue = { fields: {} };\n }\n\n for (let i = 0; i < path.length; ++i) {\n let next = current.mapValue!.fields![path.get(i)];\n if (!isMapValue(next) || !next.mapValue.fields) {\n next = { mapValue: { fields: {} } };\n current.mapValue!.fields![path.get(i)] = next;\n }\n current = next as { mapValue: ProtoMapValue };\n }\n\n return current.mapValue!.fields!;\n }\n\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */\n private applyChanges(\n fieldsMap: Record<string, ProtoValue>,\n inserts: { [key: string]: ProtoValue },\n deletes: string[]\n ): void {\n forEach(inserts, (key, val) => (fieldsMap[key] = val));\n for (const field of deletes) {\n delete fieldsMap[field];\n }\n }\n\n clone(): ObjectValue {\n return new ObjectValue(\n deepClone(this.value) as { mapValue: ProtoMapValue }\n );\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */\nexport function extractFieldMask(value: ProtoMapValue): FieldMask {\n const fields: FieldPath[] = [];\n forEach(value!.fields, (key, value) => {\n const currentPath = new FieldPath([key]);\n if (isMapValue(value)) {\n const nestedMask = extractFieldMask(value.mapValue!);\n const nestedFields = nestedMask.fields;\n if (nestedFields.length === 0) {\n // Preserve the empty map by adding it to the FieldMask.\n fields.push(currentPath);\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const nestedPath of nestedFields) {\n fields.push(currentPath.child(nestedPath));\n }\n }\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n fields.push(currentPath);\n }\n });\n return new FieldMask(fields);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { DocumentKey } from './document_key';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport { valueCompare } from './values';\n\n/**\n * Whether the document represents an existing document, a document that is\n * known to exist or a document whose state or existence is unknown.\n */\nconst enum DocumentType {\n /**\n * Represents the initial state of a MutableDocument when only the document\n * key is known. Invalid documents transition to other states as mutations are\n * applied. If a document remains invalid after applying mutations, it should\n * be discarded.\n *\n * Invalid documents can have neither local nor committed mutations.\n */\n INVALID,\n /**\n * Represents a document in Firestore with a key, version, data and whether\n * the data has local mutations applied to it.\n *\n * Found documents can be sycned or have or committed mutations applied.\n */\n FOUND_DOCUMENT,\n /**\n * Represents that no documents exists for the key at the given version.\n *\n * Documents that are deleted based on a local mutation do not raise snapshots\n * with `hasPendingWrites`. As such, deleted documents never have\n * `HAS_LOCAL_MUTATIONS` set. Once a delete is committed, we store them with\n * `HAS_COMMITTED_MUTATIONS` until we received the delete from the Watch\n * stream.\n */\n NO_DOCUMENT,\n /**\n * Represents an existing document whose data is unknown (e.g. a document that\n * was updated without a known base document).\n *\n * An unknown document always has `HAS_COMMITTED_MUTATIONS` set, since unknown\n * documents can only be generated by applying a patch mutation from a write\n * acknowledgement.\n */\n UNKNOWN_DOCUMENT\n}\n\n/** Describes whether a document has latency-compensated edits applied. */\nconst enum DocumentState {\n /** No mutations applied. Document was sent to us by Watch. */\n SYNCED,\n /**\n * Local mutations applied via the mutation queue. Document is potentially\n * inconsistent.\n */\n HAS_LOCAL_MUTATIONS,\n /**\n * Mutations applied based on a write acknowledgment. Document is potentially\n * inconsistent.\n */\n HAS_COMMITTED_MUTATIONS\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether the\n * data has local mutations applied to it.\n */\nexport interface Document {\n /** The key for this document */\n readonly key: DocumentKey;\n\n /**\n * The version of this document if it exists or a version at which this\n * document was guaranteed to not exist.\n */\n readonly version: SnapshotVersion;\n\n /**\n * The timestamp at which this document was read from the remote server. Uses\n * `SnapshotVersion.min()` for documents created by the user.\n */\n readonly readTime: SnapshotVersion;\n\n /**\n * The timestamp at which the document was created. This value increases\n * monotonically when a document is deleted then recreated. It can also be\n * compared to `createTime` of other documents and the `readTime` of a query.\n */\n readonly createTime: SnapshotVersion;\n\n /** The underlying data of this document or an empty value if no data exists. */\n readonly data: ObjectValue;\n\n /** Returns whether local mutations were applied via the mutation queue. */\n readonly hasLocalMutations: boolean;\n\n /** Returns whether mutations were applied based on a write acknowledgment. */\n readonly hasCommittedMutations: boolean;\n\n /**\n * Whether this document had a local mutation applied that has not yet been\n * acknowledged by Watch.\n */\n readonly hasPendingWrites: boolean;\n\n /**\n * Returns whether this document is valid (i.e. it is an entry in the\n * RemoteDocumentCache, was created by a mutation or read from the backend).\n */\n isValidDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is known at the current\n * version.\n */\n isFoundDocument(): boolean;\n\n /**\n * Returns whether the document is known to not exist at the current version.\n */\n isNoDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is unknown at the current\n * version.\n */\n isUnknownDocument(): boolean;\n\n isEqual(other: Document | null | undefined): boolean;\n\n /** Creates a mutable copy of this document. */\n mutableCopy(): MutableDocument;\n\n toString(): string;\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */\nexport class MutableDocument implements Document {\n private constructor(\n readonly key: DocumentKey,\n private documentType: DocumentType,\n public version: SnapshotVersion,\n public readTime: SnapshotVersion,\n public createTime: SnapshotVersion,\n public data: ObjectValue,\n private documentState: DocumentState\n ) {}\n\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */\n static newInvalidDocument(documentKey: DocumentKey): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.INVALID,\n /* version */ SnapshotVersion.min(),\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */\n static newFoundDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion,\n createTime: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.FOUND_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ createTime,\n value,\n DocumentState.SYNCED\n );\n }\n\n /** Creates a new document that is known to not exist at the given version. */\n static newNoDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.NO_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist at the given version but\n * whose data is not known (e.g. a document that was updated without a known\n * base document).\n */\n static newUnknownDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.UNKNOWN_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.HAS_COMMITTED_MUTATIONS\n );\n }\n\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */\n convertToFoundDocument(\n version: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n // If a document is switching state from being an invalid or deleted\n // document to a valid (FOUND_DOCUMENT) document, either due to receiving an\n // update from Watch or due to applying a local set mutation on top\n // of a deleted document, our best guess about its createTime would be the\n // version at which the document transitioned to a FOUND_DOCUMENT.\n if (\n this.createTime.isEqual(SnapshotVersion.min()) &&\n (this.documentType === DocumentType.NO_DOCUMENT ||\n this.documentType === DocumentType.INVALID)\n ) {\n this.createTime = version;\n }\n this.version = version;\n this.documentType = DocumentType.FOUND_DOCUMENT;\n this.data = value;\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */\n convertToNoDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.NO_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it exists at a given version but\n * that its data is not known (e.g. a document that was updated without a known\n * base document).\n */\n convertToUnknownDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.UNKNOWN_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasCommittedMutations(): MutableDocument {\n debugAssert(\n this.isValidDocument(),\n 'Invalid documents cannot have committed mutations'\n );\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasLocalMutations(): MutableDocument {\n this.documentState = DocumentState.HAS_LOCAL_MUTATIONS;\n this.version = SnapshotVersion.min();\n return this;\n }\n\n setReadTime(readTime: SnapshotVersion): MutableDocument {\n this.readTime = readTime;\n return this;\n }\n\n get hasLocalMutations(): boolean {\n return this.documentState === DocumentState.HAS_LOCAL_MUTATIONS;\n }\n\n get hasCommittedMutations(): boolean {\n return this.documentState === DocumentState.HAS_COMMITTED_MUTATIONS;\n }\n\n get hasPendingWrites(): boolean {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n\n isValidDocument(): boolean {\n return this.documentType !== DocumentType.INVALID;\n }\n\n isFoundDocument(): boolean {\n return this.documentType === DocumentType.FOUND_DOCUMENT;\n }\n\n isNoDocument(): boolean {\n return this.documentType === DocumentType.NO_DOCUMENT;\n }\n\n isUnknownDocument(): boolean {\n return this.documentType === DocumentType.UNKNOWN_DOCUMENT;\n }\n\n isEqual(other: Document | null | undefined): boolean {\n return (\n other instanceof MutableDocument &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.documentType === other.documentType &&\n this.documentState === other.documentState &&\n this.data.isEqual(other.data)\n );\n }\n\n mutableCopy(): MutableDocument {\n return new MutableDocument(\n this.key,\n this.documentType,\n this.version,\n this.readTime,\n this.createTime,\n this.data.clone(),\n this.documentState\n );\n }\n\n toString(): string {\n return (\n `Document(${this.key}, ${this.version}, ${JSON.stringify(\n this.data.value\n )}, ` +\n `{createTime: ${this.createTime}}), ` +\n `{documentType: ${this.documentType}}), ` +\n `{documentState: ${this.documentState}})`\n );\n }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\nexport function compareDocumentsByField(\n field: FieldPath,\n d1: Document,\n d2: Document\n): number {\n const v1 = d1.data.field(field);\n const v2 = d2.data.field(field);\n if (v1 !== null && v2 !== null) {\n return valueCompare(v1, v2);\n } else {\n return fail(\"Trying to compare documents on fields that don't exist\");\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { isReferenceValue, valueCompare, valueEquals } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\n\nimport { Direction, OrderBy } from './order_by';\n\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */\nexport class Bound {\n constructor(readonly position: ProtoValue[], readonly inclusive: boolean) {}\n}\n\nfunction boundCompareToDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): number {\n debugAssert(\n bound.position.length <= orderBy.length,\n \"Bound has more components than query's orderBy\"\n );\n let comparison = 0;\n for (let i = 0; i < bound.position.length; i++) {\n const orderByComponent = orderBy[i];\n const component = bound.position[i];\n if (orderByComponent.field.isKeyField()) {\n debugAssert(\n isReferenceValue(component),\n 'Bound has a non-key value where the key path is being used.'\n );\n comparison = DocumentKey.comparator(\n DocumentKey.fromName(component.referenceValue),\n doc.key\n );\n } else {\n const docValue = doc.data.field(orderByComponent.field);\n debugAssert(\n docValue !== null,\n 'Field should exist since document matched the orderBy already.'\n );\n comparison = valueCompare(component, docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return comparison;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */\nexport function boundSortsAfterDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison >= 0 : comparison > 0;\n}\n\n/**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\nexport function boundSortsBeforeDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison <= 0 : comparison < 0;\n}\n\nexport function boundEquals(left: Bound | null, right: Bound | null): boolean {\n if (left === null) {\n return right === null;\n } else if (right === null) {\n return false;\n }\n\n if (\n left.inclusive !== right.inclusive ||\n left.position.length !== right.position.length\n ) {\n return false;\n }\n for (let i = 0; i < left.position.length; i++) {\n const leftPosition = left.position[i];\n const rightPosition = right.position[i];\n if (!valueEquals(leftPosition, rightPosition)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from '../model/path';\n\n/**\n * The direction of sorting in an order by.\n */\nexport const enum Direction {\n ASCENDING = 'asc',\n DESCENDING = 'desc'\n}\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nexport class OrderBy {\n constructor(\n readonly field: FieldPath,\n readonly dir: Direction = Direction.ASCENDING\n ) {}\n}\n\nexport function canonifyOrderBy(orderBy: OrderBy): string {\n // TODO(b/29183165): Make this collision robust.\n return orderBy.field.canonicalString() + orderBy.dir;\n}\n\nexport function stringifyOrderBy(orderBy: OrderBy): string {\n return `${orderBy.field.canonicalString()} (${orderBy.dir})`;\n}\n\nexport function orderByEquals(left: OrderBy, right: OrderBy): boolean {\n return left.dir === right.dir && left.field.isEqual(right.field);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath } from '../model/path';\nimport {\n arrayValueContains,\n canonicalId,\n isArray,\n isReferenceValue,\n typeOrder,\n valueCompare,\n valueEquals\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail } from '../util/assert';\n\n// The operator of a FieldFilter\nexport const enum Operator {\n LESS_THAN = '<',\n LESS_THAN_OR_EQUAL = '<=',\n EQUAL = '==',\n NOT_EQUAL = '!=',\n GREATER_THAN = '>',\n GREATER_THAN_OR_EQUAL = '>=',\n ARRAY_CONTAINS = 'array-contains',\n IN = 'in',\n NOT_IN = 'not-in',\n ARRAY_CONTAINS_ANY = 'array-contains-any'\n}\n\n// The operator of a CompositeFilter\nexport const enum CompositeOperator {\n OR = 'or',\n AND = 'and'\n}\n\nexport abstract class Filter {\n abstract matches(doc: Document): boolean;\n\n abstract getFlattenedFilters(): readonly FieldFilter[];\n\n abstract getFilters(): Filter[];\n}\n\nexport class FieldFilter extends Filter {\n protected constructor(\n public readonly field: FieldPath,\n public readonly op: Operator,\n public readonly value: ProtoValue\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(\n field: FieldPath,\n op: Operator,\n value: ProtoValue\n ): FieldFilter {\n if (field.isKeyField()) {\n if (op === Operator.IN || op === Operator.NOT_IN) {\n return this.createKeyFieldInFilter(field, op, value);\n } else {\n debugAssert(\n isReferenceValue(value),\n 'Comparing on key, but filter value not a RefValue'\n );\n debugAssert(\n op !== Operator.ARRAY_CONTAINS && op !== Operator.ARRAY_CONTAINS_ANY,\n `'${op.toString()}' queries don't make sense on document keys.`\n );\n return new KeyFieldFilter(field, op, value);\n }\n } else if (op === Operator.ARRAY_CONTAINS) {\n return new ArrayContainsFilter(field, value);\n } else if (op === Operator.IN) {\n debugAssert(\n isArray(value),\n 'IN filter has invalid value: ' + value.toString()\n );\n return new InFilter(field, value);\n } else if (op === Operator.NOT_IN) {\n debugAssert(\n isArray(value),\n 'NOT_IN filter has invalid value: ' + value.toString()\n );\n return new NotInFilter(field, value);\n } else if (op === Operator.ARRAY_CONTAINS_ANY) {\n debugAssert(\n isArray(value),\n 'ARRAY_CONTAINS_ANY filter has invalid value: ' + value.toString()\n );\n return new ArrayContainsAnyFilter(field, value);\n } else {\n return new FieldFilter(field, op, value);\n }\n }\n\n private static createKeyFieldInFilter(\n field: FieldPath,\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n ): FieldFilter {\n debugAssert(\n isArray(value),\n `Comparing on key with ${op.toString()}` +\n ', but filter value not an ArrayValue'\n );\n debugAssert(\n (value.arrayValue.values || []).every(elem => isReferenceValue(elem)),\n `Comparing on key with ${op.toString()}` +\n ', but an array value was not a RefValue'\n );\n\n return op === Operator.IN\n ? new KeyFieldInFilter(field, value)\n : new KeyFieldNotInFilter(field, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n if (this.op === Operator.NOT_EQUAL) {\n return (\n other !== null &&\n this.matchesComparison(valueCompare(other!, this.value))\n );\n }\n\n // Only compare types with matching backend order (such as double and int).\n return (\n other !== null &&\n typeOrder(this.value) === typeOrder(other) &&\n this.matchesComparison(valueCompare(other, this.value))\n );\n }\n\n protected matchesComparison(comparison: number): boolean {\n switch (this.op) {\n case Operator.LESS_THAN:\n return comparison < 0;\n case Operator.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case Operator.EQUAL:\n return comparison === 0;\n case Operator.NOT_EQUAL:\n return comparison !== 0;\n case Operator.GREATER_THAN:\n return comparison > 0;\n case Operator.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail('Unknown FieldFilter operator: ' + this.op);\n }\n }\n\n isInequality(): boolean {\n return (\n [\n Operator.LESS_THAN,\n Operator.LESS_THAN_OR_EQUAL,\n Operator.GREATER_THAN,\n Operator.GREATER_THAN_OR_EQUAL,\n Operator.NOT_EQUAL,\n Operator.NOT_IN\n ].indexOf(this.op) >= 0\n );\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n return [this];\n }\n\n getFilters(): Filter[] {\n return [this];\n }\n}\n\nexport class CompositeFilter extends Filter {\n private memoizedFlattenedFilters: FieldFilter[] | null = null;\n\n protected constructor(\n public readonly filters: readonly Filter[],\n public readonly op: CompositeOperator\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(filters: Filter[], op: CompositeOperator): CompositeFilter {\n return new CompositeFilter(filters, op);\n }\n\n matches(doc: Document): boolean {\n if (compositeFilterIsConjunction(this)) {\n // For conjunctions, all filters must match, so return false if any filter doesn't match.\n return this.filters.find(filter => !filter.matches(doc)) === undefined;\n } else {\n // For disjunctions, at least one filter should match.\n return this.filters.find(filter => filter.matches(doc)) !== undefined;\n }\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n if (this.memoizedFlattenedFilters !== null) {\n return this.memoizedFlattenedFilters;\n }\n\n this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => {\n return result.concat(subfilter.getFlattenedFilters());\n }, [] as FieldFilter[]);\n\n return this.memoizedFlattenedFilters;\n }\n\n // Returns a mutable copy of `this.filters`\n getFilters(): Filter[] {\n return Object.assign([], this.filters);\n }\n}\n\nexport function compositeFilterIsConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.AND;\n}\n\nexport function compositeFilterIsDisjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.OR;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */\nexport function compositeFilterIsFlatConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return (\n compositeFilterIsFlat(compositeFilter) &&\n compositeFilterIsConjunction(compositeFilter)\n );\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */\nexport function compositeFilterIsFlat(\n compositeFilter: CompositeFilter\n): boolean {\n for (const filter of compositeFilter.filters) {\n if (filter instanceof CompositeFilter) {\n return false;\n }\n }\n return true;\n}\n\nexport function canonifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'canonifyFilter() only supports FieldFilters and CompositeFilters'\n );\n\n if (filter instanceof FieldFilter) {\n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return (\n filter.field.canonicalString() +\n filter.op.toString() +\n canonicalId(filter.value)\n );\n } else if (compositeFilterIsFlatConjunction(filter)) {\n // Older SDK versions use an implicit AND operation between their filters.\n // In the new SDK versions, the developer may use an explicit AND filter.\n // To stay consistent with the old usages, we add a special case to ensure\n // the canonical ID for these two are the same. For example:\n // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n return filter.filters.map(filter => canonifyFilter(filter)).join(',');\n } else {\n // filter instanceof CompositeFilter\n const canonicalIdsString = filter.filters\n .map(filter => canonifyFilter(filter))\n .join(',');\n return `${filter.op}(${canonicalIdsString})`;\n }\n}\n\nexport function filterEquals(f1: Filter, f2: Filter): boolean {\n if (f1 instanceof FieldFilter) {\n return fieldFilterEquals(f1, f2);\n } else if (f1 instanceof CompositeFilter) {\n return compositeFilterEquals(f1, f2);\n } else {\n fail('Only FieldFilters and CompositeFilters can be compared');\n }\n}\n\nexport function fieldFilterEquals(f1: FieldFilter, f2: Filter): boolean {\n return (\n f2 instanceof FieldFilter &&\n f1.op === f2.op &&\n f1.field.isEqual(f2.field) &&\n valueEquals(f1.value, f2.value)\n );\n}\n\nexport function compositeFilterEquals(\n f1: CompositeFilter,\n f2: Filter\n): boolean {\n if (\n f2 instanceof CompositeFilter &&\n f1.op === f2.op &&\n f1.filters.length === f2.filters.length\n ) {\n const subFiltersMatch: boolean = f1.filters.reduce(\n (result: boolean, f1Filter: Filter, index: number): boolean =>\n result && filterEquals(f1Filter, f2.filters[index]),\n true\n );\n\n return subFiltersMatch;\n }\n\n return false;\n}\n\n/**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */\nexport function compositeFilterWithAddedFilters(\n compositeFilter: CompositeFilter,\n otherFilters: Filter[]\n): CompositeFilter {\n const mergedFilters = compositeFilter.filters.concat(otherFilters);\n return CompositeFilter.create(mergedFilters, compositeFilter.op);\n}\n\n/** Returns a debug description for `filter`. */\nexport function stringifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'stringifyFilter() only supports FieldFilters and CompositeFilters'\n );\n if (filter instanceof FieldFilter) {\n return stringifyFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return stringifyCompositeFilter(filter);\n } else {\n return 'Filter';\n }\n}\n\nexport function stringifyCompositeFilter(filter: CompositeFilter): string {\n return (\n filter.op.toString() +\n ` {` +\n filter.getFilters().map(stringifyFilter).join(' ,') +\n '}'\n );\n}\n\nexport function stringifyFieldFilter(filter: FieldFilter): string {\n return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(\n filter.value\n )}`;\n}\n\n/** Filter that matches on key fields (i.e. '__name__'). */\nexport class KeyFieldFilter extends FieldFilter {\n private readonly key: DocumentKey;\n\n constructor(field: FieldPath, op: Operator, value: ProtoValue) {\n super(field, op, value);\n debugAssert(\n isReferenceValue(value),\n 'KeyFieldFilter expects a ReferenceValue'\n );\n this.key = DocumentKey.fromName(value.referenceValue);\n }\n\n matches(doc: Document): boolean {\n const comparison = DocumentKey.comparator(doc.key, this.key);\n return this.matchesComparison(comparison);\n }\n}\n\n/** Filter that matches on key fields within an array. */\nexport class KeyFieldInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.IN, value);\n }\n\n matches(doc: Document): boolean {\n return this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */\nexport class KeyFieldNotInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.NOT_IN, value);\n }\n\n matches(doc: Document): boolean {\n return !this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\nfunction extractDocumentKeysFromArrayValue(\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n): DocumentKey[] {\n debugAssert(\n isArray(value),\n 'KeyFieldInFilter/KeyFieldNotInFilter expects an ArrayValue'\n );\n return (value.arrayValue?.values || []).map(v => {\n debugAssert(\n isReferenceValue(v),\n `Comparing on key with ${op.toString()}, but an array value was not ` +\n `a ReferenceValue`\n );\n return DocumentKey.fromName(v.referenceValue);\n });\n}\n\n/** A Filter that implements the array-contains operator. */\nexport class ArrayContainsFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return isArray(other) && arrayValueContains(other.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */\nexport class InFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n debugAssert(isArray(value), 'InFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return other !== null && arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the not-in operator. */\nexport class NotInFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n debugAssert(isArray(value), 'NotInFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n if (\n arrayValueContains(this.value.arrayValue!, { nullValue: 'NULL_VALUE' })\n ) {\n return false;\n }\n const other = doc.data.field(this.field);\n return other !== null && !arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */\nexport class ArrayContainsAnyFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS_ANY, value);\n debugAssert(isArray(value), 'ArrayContainsAnyFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n if (!isArray(other) || !other.arrayValue.values) {\n return false;\n }\n return other.arrayValue.values.some(val =>\n arrayValueContains(this.value.arrayValue!, val)\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind\n} from '../model/field_index';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n canonicalId,\n MAX_VALUE,\n MIN_VALUE,\n lowerBoundCompare,\n upperBoundCompare,\n valuesGetLowerBound,\n valuesGetUpperBound\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugCast } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Bound, boundEquals } from './bound';\nimport {\n Filter,\n FieldFilter,\n canonifyFilter,\n stringifyFilter,\n filterEquals,\n Operator\n} from './filter';\nimport {\n canonifyOrderBy,\n OrderBy,\n orderByEquals,\n stringifyOrderBy\n} from './order_by';\n\n/**\n * A Target represents the WatchTarget representation of a Query, which is used\n * by the LocalStore and the RemoteStore to keep track of and to execute\n * backend queries. While a Query can represent multiple Targets, each Targets\n * maps to a single WatchTarget in RemoteStore and a single TargetData entry\n * in persistence.\n */\nexport interface Target {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly orderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n// Visible for testing\nexport class TargetImpl implements Target {\n memoizedCanonicalId: string | null = null;\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly orderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {}\n}\n\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */\nexport function newTarget(\n path: ResourcePath,\n collectionGroup: string | null = null,\n orderBy: OrderBy[] = [],\n filters: Filter[] = [],\n limit: number | null = null,\n startAt: Bound | null = null,\n endAt: Bound | null = null\n): Target {\n return new TargetImpl(\n path,\n collectionGroup,\n orderBy,\n filters,\n limit,\n startAt,\n endAt\n );\n}\n\nexport function canonifyTarget(target: Target): string {\n const targetImpl = debugCast(target, TargetImpl);\n\n if (targetImpl.memoizedCanonicalId === null) {\n let str = targetImpl.path.canonicalString();\n if (targetImpl.collectionGroup !== null) {\n str += '|cg:' + targetImpl.collectionGroup;\n }\n str += '|f:';\n str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');\n str += '|ob:';\n str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');\n\n if (!isNullOrUndefined(targetImpl.limit)) {\n str += '|l:';\n str += targetImpl.limit!;\n }\n if (targetImpl.startAt) {\n str += '|lb:';\n str += targetImpl.startAt.inclusive ? 'b:' : 'a:';\n str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (targetImpl.endAt) {\n str += '|ub:';\n str += targetImpl.endAt.inclusive ? 'a:' : 'b:';\n str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');\n }\n targetImpl.memoizedCanonicalId = str;\n }\n return targetImpl.memoizedCanonicalId;\n}\n\nexport function stringifyTarget(target: Target): string {\n let str = target.path.canonicalString();\n if (target.collectionGroup !== null) {\n str += ' collectionGroup=' + target.collectionGroup;\n }\n if (target.filters.length > 0) {\n str += `, filters: [${target.filters\n .map(f => stringifyFilter(f))\n .join(', ')}]`;\n }\n if (!isNullOrUndefined(target.limit)) {\n str += ', limit: ' + target.limit;\n }\n if (target.orderBy.length > 0) {\n str += `, orderBy: [${target.orderBy\n .map(o => stringifyOrderBy(o))\n .join(', ')}]`;\n }\n if (target.startAt) {\n str += ', startAt: ';\n str += target.startAt.inclusive ? 'b:' : 'a:';\n str += target.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (target.endAt) {\n str += ', endAt: ';\n str += target.endAt.inclusive ? 'a:' : 'b:';\n str += target.endAt.position.map(p => canonicalId(p)).join(',');\n }\n return `Target(${str})`;\n}\n\nexport function targetEquals(left: Target, right: Target): boolean {\n if (left.limit !== right.limit) {\n return false;\n }\n\n if (left.orderBy.length !== right.orderBy.length) {\n return false;\n }\n\n for (let i = 0; i < left.orderBy.length; i++) {\n if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {\n return false;\n }\n }\n\n if (left.filters.length !== right.filters.length) {\n return false;\n }\n\n for (let i = 0; i < left.filters.length; i++) {\n if (!filterEquals(left.filters[i], right.filters[i])) {\n return false;\n }\n }\n\n if (left.collectionGroup !== right.collectionGroup) {\n return false;\n }\n\n if (!left.path.isEqual(right.path)) {\n return false;\n }\n\n if (!boundEquals(left.startAt, right.startAt)) {\n return false;\n }\n\n return boundEquals(left.endAt, right.endAt);\n}\n\nexport function targetIsDocumentTarget(target: Target): boolean {\n return (\n DocumentKey.isDocumentKey(target.path) &&\n target.collectionGroup === null &&\n target.filters.length === 0\n );\n}\n\n/** Returns the field filters that target the given field path. */\nexport function targetGetFieldFiltersForPath(\n target: Target,\n path: FieldPath\n): FieldFilter[] {\n return target.filters.filter(\n f => f instanceof FieldFilter && f.field.isEqual(path)\n ) as FieldFilter[];\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\nexport function targetGetArrayValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const segment = fieldIndexGetArraySegment(fieldIndex);\n if (segment === undefined) {\n return null;\n }\n\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.ARRAY_CONTAINS_ANY:\n return fieldFilter.value.arrayValue!.values || [];\n case Operator.ARRAY_CONTAINS:\n return [fieldFilter.value];\n default:\n // Remaining filters are not array filters.\n }\n }\n return null;\n}\n\n/**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */\nexport function targetGetNotInValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const values = new Map</* fieldPath = */ string, ProtoValue>();\n\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.EQUAL:\n case Operator.IN:\n // Encode equality prefix, which is encoded in the index value before\n // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n // `value != 'ab'`).\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n break;\n case Operator.NOT_IN:\n case Operator.NOT_EQUAL:\n // NotIn/NotEqual is always a suffix. There cannot be any remaining\n // segments and hence we can return early here.\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n return Array.from(values.values());\n default:\n // Remaining filters cannot be used as notIn bounds.\n }\n }\n }\n\n return null;\n}\n\n/**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */\nexport function targetGetLowerBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)\n : targetGetDescendingBound(target, segment.fieldPath, target.startAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */\nexport function targetGetUpperBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)\n : targetGetAscendingBound(target, segment.fieldPath, target.endAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction targetGetAscendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MIN_VALUE;\n\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MIN_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.LESS_THAN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = valuesGetLowerBound(fieldFilter.value);\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.GREATER_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.GREATER_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MIN_VALUE;\n break;\n default:\n // Remaining filters cannot be used as lower bounds.\n }\n\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) < 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) < 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */\nfunction targetGetDescendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MAX_VALUE;\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MAX_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.GREATER_THAN_OR_EQUAL:\n case Operator.GREATER_THAN:\n filterValue = valuesGetUpperBound(fieldFilter.value);\n filterInclusive = false;\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.LESS_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MAX_VALUE;\n break;\n default:\n // Remaining filters cannot be used as upper bounds.\n }\n\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) > 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) > 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\nexport function targetGetSegmentCount(target: Target): number {\n let fields = new SortedSet<FieldPath>(FieldPath.comparator);\n let hasArraySegment = false;\n\n for (const filter of target.filters) {\n for (const subFilter of filter.getFlattenedFilters()) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (subFilter.field.isKeyField()) {\n continue;\n }\n\n // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n // though these are on the same field, they should be counted as two\n // separate segments in an index.\n if (\n subFilter.op === Operator.ARRAY_CONTAINS ||\n subFilter.op === Operator.ARRAY_CONTAINS_ANY\n ) {\n hasArraySegment = true;\n } else {\n fields = fields.add(subFilter.field);\n }\n }\n }\n\n for (const orderBy of target.orderBy) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (!orderBy.field.isKeyField()) {\n fields = fields.add(orderBy.field);\n }\n }\n\n return fields.size + (hasArraySegment ? 1 : 0);\n}\n\nexport function targetHasLimit(target: Target): boolean {\n return target.limit !== null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { compareDocumentsByField, Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { debugAssert, debugCast, fail } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n Bound,\n boundSortsAfterDocument,\n boundSortsBeforeDocument\n} from './bound';\nimport { FieldFilter, Filter } from './filter';\nimport { Direction, OrderBy } from './order_by';\nimport {\n canonifyTarget,\n newTarget,\n stringifyTarget,\n Target,\n targetEquals\n} from './target';\n\nexport const enum LimitType {\n First = 'F',\n Last = 'L'\n}\n\n/**\n * The Query interface defines all external properties of a query.\n *\n * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy`\n * and `queryToTarget`.\n */\nexport interface Query {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly explicitOrderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly limitType: LimitType;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nexport class QueryImpl implements Query {\n memoizedNormalizedOrderBy: OrderBy[] | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // non-aggregate queries.\n memoizedTarget: Target | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // aggregate queries. Unlike targets for non-aggregate queries,\n // aggregate query targets do not contain normalized order-bys, they only\n // contain explicit order-bys.\n memoizedAggregateTarget: Target | null = null;\n\n /**\n * Initializes a Query with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n */\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly explicitOrderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly limitType: LimitType = LimitType.First,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {\n if (this.startAt) {\n debugAssert(\n this.startAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n if (this.endAt) {\n debugAssert(\n this.endAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n }\n}\n\n/** Creates a new Query instance with the options provided. */\nexport function newQuery(\n path: ResourcePath,\n collectionGroup: string | null,\n explicitOrderBy: OrderBy[],\n filters: Filter[],\n limit: number | null,\n limitType: LimitType,\n startAt: Bound | null,\n endAt: Bound | null\n): Query {\n return new QueryImpl(\n path,\n collectionGroup,\n explicitOrderBy,\n filters,\n limit,\n limitType,\n startAt,\n endAt\n );\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */\nexport function newQueryForPath(path: ResourcePath): Query {\n return new QueryImpl(path);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\nexport function asCollectionQueryAtPath(\n query: Query,\n path: ResourcePath\n): Query {\n return new QueryImpl(\n path,\n /*collectionGroup=*/ null,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nexport function queryMatchesAllDocuments(query: Query): boolean {\n return (\n query.filters.length === 0 &&\n query.limit === null &&\n query.startAt == null &&\n query.endAt == null &&\n (query.explicitOrderBy.length === 0 ||\n (query.explicitOrderBy.length === 1 &&\n query.explicitOrderBy[0].field.isKeyField()))\n );\n}\n\n// Returns the sorted set of inequality filter fields used in this query.\nexport function getInequalityFilterFields(query: Query): SortedSet<FieldPath> {\n let result = new SortedSet<FieldPath>(FieldPath.comparator);\n query.filters.forEach((filter: Filter) => {\n const subFilters = filter.getFlattenedFilters();\n subFilters.forEach((filter: FieldFilter) => {\n if (filter.isInequality()) {\n result = result.add(filter.field);\n }\n });\n });\n return result;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\nexport function newQueryForCollectionGroup(collectionId: string): Query {\n return new QueryImpl(ResourcePath.emptyPath(), collectionId);\n}\n\n/**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\nexport function isDocumentQuery(query: Query): boolean {\n return (\n DocumentKey.isDocumentKey(query.path) &&\n query.collectionGroup === null &&\n query.filters.length === 0\n );\n}\n\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nexport function isCollectionGroupQuery(query: Query): boolean {\n return query.collectionGroup !== null;\n}\n\n/**\n * Returns the normalized order-by constraint that is used to execute the Query,\n * which can be different from the order-by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`). The normalized order-by\n * includes implicit order-bys in addition to the explicit user provided\n * order-bys.\n */\nexport function queryNormalizedOrderBy(query: Query): OrderBy[] {\n const queryImpl = debugCast(query, QueryImpl);\n if (queryImpl.memoizedNormalizedOrderBy === null) {\n queryImpl.memoizedNormalizedOrderBy = [];\n const fieldsNormalized = new Set<string>();\n\n // Any explicit order by fields should be added as is.\n for (const orderBy of queryImpl.explicitOrderBy) {\n queryImpl.memoizedNormalizedOrderBy.push(orderBy);\n fieldsNormalized.add(orderBy.field.canonicalString());\n }\n\n // The order of the implicit ordering always matches the last explicit order by.\n const lastDirection =\n queryImpl.explicitOrderBy.length > 0\n ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n\n // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical\n // order. When there are multiple inequality filters on the same field, the field should be added\n // only once.\n // Note: `SortedSet<FieldPath>` sorts the key field before other fields. However, we want the key\n // field to be sorted last.\n const inequalityFields: SortedSet<FieldPath> =\n getInequalityFilterFields(queryImpl);\n inequalityFields.forEach(field => {\n if (\n !fieldsNormalized.has(field.canonicalString()) &&\n !field.isKeyField()\n ) {\n queryImpl.memoizedNormalizedOrderBy!.push(\n new OrderBy(field, lastDirection)\n );\n }\n });\n\n // Add the document key field to the last if it is not explicitly ordered.\n if (!fieldsNormalized.has(FieldPath.keyField().canonicalString())) {\n queryImpl.memoizedNormalizedOrderBy.push(\n new OrderBy(FieldPath.keyField(), lastDirection)\n );\n }\n }\n return queryImpl.memoizedNormalizedOrderBy;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation.\n */\nexport function queryToTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n if (!queryImpl.memoizedTarget) {\n queryImpl.memoizedTarget = _queryToTarget(\n queryImpl,\n queryNormalizedOrderBy(query)\n );\n }\n\n return queryImpl.memoizedTarget;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation,\n * for use within an aggregate query. Unlike targets for non-aggregate queries,\n * aggregate query targets do not contain normalized order-bys, they only\n * contain explicit order-bys.\n */\nexport function queryToAggregateTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n\n if (!queryImpl.memoizedAggregateTarget) {\n // Do not include implicit order-bys for aggregate queries.\n queryImpl.memoizedAggregateTarget = _queryToTarget(\n queryImpl,\n query.explicitOrderBy\n );\n }\n\n return queryImpl.memoizedAggregateTarget;\n}\n\nfunction _queryToTarget(queryImpl: QueryImpl, orderBys: OrderBy[]): Target {\n if (queryImpl.limitType === LimitType.First) {\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n queryImpl.startAt,\n queryImpl.endAt\n );\n } else {\n // Flip the orderBy directions since we want the last results\n orderBys = orderBys.map(orderBy => {\n const dir =\n orderBy.dir === Direction.DESCENDING\n ? Direction.ASCENDING\n : Direction.DESCENDING;\n return new OrderBy(orderBy.field, dir);\n });\n\n // We need to swap the cursors to match the now-flipped query ordering.\n const startAt = queryImpl.endAt\n ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)\n : null;\n const endAt = queryImpl.startAt\n ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)\n : null;\n\n // Now return as a LimitType.First query.\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n startAt,\n endAt\n );\n }\n}\n\nexport function queryWithAddedFilter(query: Query, filter: Filter): Query {\n debugAssert(\n !isDocumentQuery(query),\n 'No filtering allowed for document query'\n );\n\n const newFilters = query.filters.concat([filter]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n newFilters,\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithAddedOrderBy(query: Query, orderBy: OrderBy): Query {\n debugAssert(\n !query.startAt && !query.endAt,\n 'Bounds must be set after orderBy'\n );\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const newOrderBy = query.explicitOrderBy.concat([orderBy]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n newOrderBy,\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithLimit(\n query: Query,\n limit: number | null,\n limitType: LimitType\n): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n limit,\n limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithStartAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n bound,\n query.endAt\n );\n}\n\nexport function queryWithEndAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n bound\n );\n}\n\nexport function queryEquals(left: Query, right: Query): boolean {\n return (\n targetEquals(queryToTarget(left), queryToTarget(right)) &&\n left.limitType === right.limitType\n );\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nexport function canonifyQuery(query: Query): string {\n return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;\n}\n\nexport function stringifyQuery(query: Query): string {\n return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${\n query.limitType\n })`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */\nexport function queryMatches(query: Query, doc: Document): boolean {\n return (\n doc.isFoundDocument() &&\n queryMatchesPathAndCollectionGroup(query, doc) &&\n queryMatchesOrderBy(query, doc) &&\n queryMatchesFilters(query, doc) &&\n queryMatchesBounds(query, doc)\n );\n}\n\nfunction queryMatchesPathAndCollectionGroup(\n query: Query,\n doc: Document\n): boolean {\n const docPath = doc.key.path;\n if (query.collectionGroup !== null) {\n // NOTE: this.path is currently always empty since we don't expose Collection\n // Group queries rooted at a document path yet.\n return (\n doc.key.hasCollectionId(query.collectionGroup) &&\n query.path.isPrefixOf(docPath)\n );\n } else if (DocumentKey.isDocumentKey(query.path)) {\n // exact match for document queries\n return query.path.isEqual(docPath);\n } else {\n // shallow ancestor queries by default\n return query.path.isImmediateParentOf(docPath);\n }\n}\n\n/**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\nfunction queryMatchesOrderBy(query: Query, doc: Document): boolean {\n // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit).\n // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n // A document with content of {b:1} matches the filters, but does not match the orderBy because\n // it's missing the field 'a'.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n // order-by key always matches\n if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {\n return false;\n }\n }\n return true;\n}\n\nfunction queryMatchesFilters(query: Query, doc: Document): boolean {\n for (const filter of query.filters) {\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n}\n\n/** Makes sure a document is within the bounds, if provided. */\nfunction queryMatchesBounds(query: Query, doc: Document): boolean {\n if (\n query.startAt &&\n !boundSortsBeforeDocument(query.startAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n if (\n query.endAt &&\n !boundSortsAfterDocument(query.endAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n return true;\n}\n\n/**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */\nexport function queryCollectionGroup(query: Query): string {\n return (\n query.collectionGroup ||\n (query.path.length % 2 === 1\n ? query.path.lastSegment()\n : query.path.get(query.path.length - 2))\n );\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */\nexport function newQueryComparator(\n query: Query\n): (d1: Document, d2: Document) => number {\n return (d1: Document, d2: Document): number => {\n let comparedOnKeyField = false;\n for (const orderBy of queryNormalizedOrderBy(query)) {\n const comp = compareDocs(orderBy, d1, d2);\n if (comp !== 0) {\n return comp;\n }\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n debugAssert(\n comparedOnKeyField,\n \"orderBy used that doesn't compare on key field\"\n );\n return 0;\n };\n}\n\nexport function compareDocs(\n orderBy: OrderBy,\n d1: Document,\n d2: Document\n): number {\n const comparison = orderBy.field.isKeyField()\n ? DocumentKey.comparator(d1.key, d2.key)\n : compareDocumentsByField(orderBy.field, d1, d2);\n switch (orderBy.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail('Unknown direction: ' + orderBy.dir);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { forEach, isEmpty } from './obj';\n\ntype Entry<K, V> = [K, V];\n\n/**\n * A map implementation that uses objects as keys. Objects must have an\n * associated equals function and must be immutable. Entries in the map are\n * stored together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */\nexport class ObjectMap<KeyType, ValueType> {\n /**\n * The inner map for a key/value pair. Due to the possibility of collisions we\n * keep a list of entries that we do a linear search through to find an actual\n * match. Note that collisions should be rare, so we still expect near\n * constant time lookups in practice.\n */\n private inner: {\n [canonicalId: string]: Array<Entry<KeyType, ValueType>>;\n } = {};\n\n /** The number of entries stored in the map */\n private innerSize = 0;\n\n constructor(\n private mapKeyFn: (key: KeyType) => string,\n private equalsFn: (l: KeyType, r: KeyType) => boolean\n ) {}\n\n /** Get a value for this key, or undefined if it does not exist. */\n get(key: KeyType): ValueType | undefined {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n return undefined;\n }\n for (const [otherKey, value] of matches) {\n if (this.equalsFn(otherKey, key)) {\n return value;\n }\n }\n return undefined;\n }\n\n has(key: KeyType): boolean {\n return this.get(key) !== undefined;\n }\n\n /** Put this key and value in the map. */\n set(key: KeyType, value: ValueType): void {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n this.inner[id] = [[key, value]];\n this.innerSize++;\n return;\n }\n for (let i = 0; i < matches.length; i++) {\n if (this.equalsFn(matches[i][0], key)) {\n // This is updating an existing entry and does not increase `innerSize`.\n matches[i] = [key, value];\n return;\n }\n }\n matches.push([key, value]);\n this.innerSize++;\n }\n\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */\n delete(key: KeyType): boolean {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n return false;\n }\n for (let i = 0; i < matches.length; i++) {\n if (this.equalsFn(matches[i][0], key)) {\n if (matches.length === 1) {\n delete this.inner[id];\n } else {\n matches.splice(i, 1);\n }\n this.innerSize--;\n return true;\n }\n }\n return false;\n }\n\n forEach(fn: (key: KeyType, val: ValueType) => void): void {\n forEach(this.inner, (_, entries) => {\n for (const [k, v] of entries) {\n fn(k, v);\n }\n });\n }\n\n isEmpty(): boolean {\n return isEmpty(this.inner);\n }\n\n size(): number {\n return this.innerSize;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { OverlayedDocument } from '../local/overlayed_document';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { Mutation } from './mutation';\nimport { Overlay } from './overlay';\n\n/** Miscellaneous collection types / constants. */\n\nexport type MutableDocumentMap = SortedMap<DocumentKey, MutableDocument>;\nconst EMPTY_MUTABLE_DOCUMENT_MAP = new SortedMap<DocumentKey, MutableDocument>(\n DocumentKey.comparator\n);\nexport function mutableDocumentMap(): MutableDocumentMap {\n return EMPTY_MUTABLE_DOCUMENT_MAP;\n}\n\nexport interface DocumentSizeEntries {\n documents: MutableDocumentMap;\n sizeMap: SortedMap<DocumentKey, number>;\n}\n\nexport type DocumentMap = SortedMap<DocumentKey, Document>;\nconst EMPTY_DOCUMENT_MAP = new SortedMap<DocumentKey, Document>(\n DocumentKey.comparator\n);\nexport function documentMap(...docs: Document[]): DocumentMap {\n let map = EMPTY_DOCUMENT_MAP;\n for (const doc of docs) {\n map = map.insert(doc.key, doc);\n }\n return map;\n}\n\nexport type OverlayedDocumentMap = DocumentKeyMap<OverlayedDocument>;\nexport function newOverlayedDocumentMap(): OverlayedDocumentMap {\n return newDocumentKeyMap<OverlayedDocument>();\n}\n\nexport function convertOverlayedDocumentMapToDocumentMap(\n collection: OverlayedDocumentMap\n): DocumentMap {\n let documents = EMPTY_DOCUMENT_MAP;\n collection.forEach(\n (k, v) => (documents = documents.insert(k, v.overlayedDocument))\n );\n return documents;\n}\n\nexport type OverlayMap = DocumentKeyMap<Overlay>;\nexport function newOverlayMap(): OverlayMap {\n return newDocumentKeyMap<Overlay>();\n}\n\nexport type MutationMap = DocumentKeyMap<Mutation>;\nexport function newMutationMap(): MutationMap {\n return newDocumentKeyMap<Mutation>();\n}\n\nexport type DocumentKeyMap<T> = ObjectMap<DocumentKey, T>;\nexport function newDocumentKeyMap<T>(): DocumentKeyMap<T> {\n return new ObjectMap<DocumentKey, T>(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\n}\n\nexport type DocumentVersionMap = SortedMap<DocumentKey, SnapshotVersion>;\nconst EMPTY_DOCUMENT_VERSION_MAP = new SortedMap<DocumentKey, SnapshotVersion>(\n DocumentKey.comparator\n);\nexport function documentVersionMap(): DocumentVersionMap {\n return EMPTY_DOCUMENT_VERSION_MAP;\n}\n\nexport type DocumentKeySet = SortedSet<DocumentKey>;\nconst EMPTY_DOCUMENT_KEY_SET = new SortedSet(DocumentKey.comparator);\nexport function documentKeySet(...keys: DocumentKey[]): DocumentKeySet {\n let set = EMPTY_DOCUMENT_KEY_SET;\n for (const key of keys) {\n set = set.add(key);\n }\n return set;\n}\n\nexport type TargetIdSet = SortedSet<TargetId>;\nconst EMPTY_TARGET_ID_SET = new SortedSet<TargetId>(primitiveComparator);\nexport function targetIdSet(): SortedSet<TargetId> {\n return EMPTY_TARGET_ID_SET;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { isNegativeZero, isSafeInteger } from '../util/types';\n\n/** Base interface for the Serializer implementation. */\nexport interface Serializer {\n readonly useProto3Json: boolean;\n}\n\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */\nexport function toDouble(serializer: Serializer, value: number): ProtoValue {\n if (serializer.useProto3Json) {\n if (isNaN(value)) {\n return { doubleValue: 'NaN' };\n } else if (value === Infinity) {\n return { doubleValue: 'Infinity' };\n } else if (value === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: isNegativeZero(value) ? '-0' : value };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */\nexport function toInteger(value: number): ProtoValue {\n return { integerValue: '' + value };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */\nexport function toNumber(serializer: Serializer, value: number): ProtoValue {\n return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Serializer, toDouble, toInteger } from '../remote/number_serializer';\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport { normalizeNumber } from './normalize';\nimport { serverTimestamp } from './server_timestamps';\nimport { isArray, isInteger, isNumber, valueEquals } from './values';\n\n/** Used to represent a field transform on a mutation. */\nexport class TransformOperation {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n private _ = undefined;\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */\nexport function applyTransformOperationToLocalView(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n localWriteTime: Timestamp\n): ProtoValue {\n if (transform instanceof ServerTimestampTransform) {\n return serverTimestamp(localWriteTime, previousValue);\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n } else {\n debugAssert(\n transform instanceof NumericIncrementTransformOperation,\n 'Expected NumericIncrementTransformOperation but was: ' + transform\n );\n return applyNumericIncrementTransformOperationToLocalView(\n transform,\n previousValue\n );\n }\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */\nexport function applyTransformOperationToRemoteDocument(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n transformResult: ProtoValue | null\n): ProtoValue {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n }\n\n debugAssert(\n transformResult !== null,\n \"Didn't receive transformResult for non-array transform\"\n );\n return transformResult;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */\nexport function computeTransformOperationBaseValue(\n transform: TransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue | null {\n if (transform instanceof NumericIncrementTransformOperation) {\n return isNumber(previousValue) ? previousValue! : { integerValue: 0 };\n }\n return null;\n}\n\nexport function transformOperationEquals(\n left: TransformOperation,\n right: TransformOperation\n): boolean {\n if (\n left instanceof ArrayUnionTransformOperation &&\n right instanceof ArrayUnionTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof ArrayRemoveTransformOperation &&\n right instanceof ArrayRemoveTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof NumericIncrementTransformOperation &&\n right instanceof NumericIncrementTransformOperation\n ) {\n return valueEquals(left.operand, right.operand);\n }\n\n return (\n left instanceof ServerTimestampTransform &&\n right instanceof ServerTimestampTransform\n );\n}\n\n/** Transforms a value into a server-generated timestamp. */\nexport class ServerTimestampTransform extends TransformOperation {}\n\n/** Transforms an array value via a union operation. */\nexport class ArrayUnionTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayUnionTransformOperation(\n transform: ArrayUnionTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n const values = coercedFieldValuesArray(previousValue);\n for (const toUnion of transform.elements) {\n if (!values.some(element => valueEquals(element, toUnion))) {\n values.push(toUnion);\n }\n }\n return { arrayValue: { values } };\n}\n\n/** Transforms an array value via a remove operation. */\nexport class ArrayRemoveTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayRemoveTransformOperation(\n transform: ArrayRemoveTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n let values = coercedFieldValuesArray(previousValue);\n for (const toRemove of transform.elements) {\n values = values.filter(element => !valueEquals(element, toRemove));\n }\n return { arrayValue: { values } };\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */\nexport class NumericIncrementTransformOperation extends TransformOperation {\n constructor(readonly serializer: Serializer, readonly operand: ProtoValue) {\n super();\n debugAssert(\n isNumber(operand),\n 'NumericIncrementTransform transform requires a NumberValue'\n );\n }\n}\n\nexport function applyNumericIncrementTransformOperationToLocalView(\n transform: NumericIncrementTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n const baseValue = computeTransformOperationBaseValue(\n transform,\n previousValue\n )!;\n const sum = asNumber(baseValue) + asNumber(transform.operand);\n if (isInteger(baseValue) && isInteger(transform.operand)) {\n return toInteger(sum);\n } else {\n return toDouble(transform.serializer, sum);\n }\n}\n\nfunction asNumber(value: ProtoValue): number {\n return normalizeNumber(value.integerValue || value.doubleValue);\n}\n\nfunction coercedFieldValuesArray(value: ProtoValue | null): ProtoValue[] {\n return isArray(value) && value.arrayValue.values\n ? value.arrayValue.values.slice()\n : [];\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldMask } from './field_mask';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport {\n applyTransformOperationToLocalView,\n applyTransformOperationToRemoteDocument,\n computeTransformOperationBaseValue,\n TransformOperation,\n transformOperationEquals\n} from './transform_operation';\n\n/** A field path and the TransformOperation to perform upon it. */\nexport class FieldTransform {\n constructor(\n readonly field: FieldPath,\n readonly transform: TransformOperation\n ) {}\n}\n\nexport function fieldTransformEquals(\n left: FieldTransform,\n right: FieldTransform\n): boolean {\n return (\n left.field.isEqual(right.field) &&\n transformOperationEquals(left.transform, right.transform)\n );\n}\n\nexport function fieldTransformsAreEqual(\n left?: FieldTransform[],\n right?: FieldTransform[]\n): boolean {\n if (left === undefined && right === undefined) {\n return true;\n }\n\n if (left && right) {\n return arrayEquals(left, right, (l, r) => fieldTransformEquals(l, r));\n }\n\n return false;\n}\n\n/** The result of successfully applying a mutation to the backend. */\nexport class MutationResult {\n constructor(\n /**\n * The version at which the mutation was committed:\n *\n * - For most operations, this is the updateTime in the WriteResult.\n * - For deletes, the commitTime of the WriteResponse (because deletes are\n * not stored and have no updateTime).\n *\n * Note that these versions can be different: No-op writes will not change\n * the updateTime even though the commitTime advances.\n */\n readonly version: SnapshotVersion,\n /**\n * The resulting fields returned from the backend after a mutation\n * containing field transforms has been committed. Contains one FieldValue\n * for each FieldTransform that was in the mutation.\n *\n * Will be empty if the mutation did not contain any field transforms.\n */\n readonly transformResults: Array<ProtoValue | null>\n ) {}\n}\n\nexport const enum MutationType {\n Set,\n Patch,\n Delete,\n Verify\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */\nexport class Precondition {\n private constructor(\n readonly updateTime?: SnapshotVersion,\n readonly exists?: boolean\n ) {\n debugAssert(\n updateTime === undefined || exists === undefined,\n 'Precondition can specify \"exists\" or \"updateTime\" but not both'\n );\n }\n\n /** Creates a new empty Precondition. */\n static none(): Precondition {\n return new Precondition();\n }\n\n /** Creates a new Precondition with an exists flag. */\n static exists(exists: boolean): Precondition {\n return new Precondition(undefined, exists);\n }\n\n /** Creates a new Precondition based on a version a document exists at. */\n static updateTime(version: SnapshotVersion): Precondition {\n return new Precondition(version);\n }\n\n /** Returns whether this Precondition is empty. */\n get isNone(): boolean {\n return this.updateTime === undefined && this.exists === undefined;\n }\n\n isEqual(other: Precondition): boolean {\n return (\n this.exists === other.exists &&\n (this.updateTime\n ? !!other.updateTime && this.updateTime.isEqual(other.updateTime)\n : !other.updateTime)\n );\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */\nexport function preconditionIsValidForDocument(\n precondition: Precondition,\n document: MutableDocument\n): boolean {\n if (precondition.updateTime !== undefined) {\n return (\n document.isFoundDocument() &&\n document.version.isEqual(precondition.updateTime)\n );\n } else if (precondition.exists !== undefined) {\n return precondition.exists === document.isFoundDocument();\n } else {\n debugAssert(precondition.isNone, 'Precondition should be empty');\n return true;\n }\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation InvalidDocument(v0) Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation InvalidDocument(v0) UnknownDocument(v3)\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation InvalidDocument(v0) NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */\nexport abstract class Mutation {\n abstract readonly type: MutationType;\n abstract readonly key: DocumentKey;\n abstract readonly precondition: Precondition;\n abstract readonly fieldTransforms: FieldTransform[];\n /**\n * Returns a `FieldMask` representing the fields that will be changed by\n * applying this mutation. Returns `null` if the mutation will overwrite the\n * entire document.\n */\n abstract getFieldMask(): FieldMask | null;\n}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */\nexport function calculateOverlayMutation(\n doc: MutableDocument,\n mask: FieldMask | null\n): Mutation | null {\n if (!doc.hasLocalMutations || (mask && mask!.fields.length === 0)) {\n return null;\n }\n\n // mask is null when sets or deletes are applied to the current document.\n if (mask === null) {\n if (doc.isNoDocument()) {\n return new DeleteMutation(doc.key, Precondition.none());\n } else {\n return new SetMutation(doc.key, doc.data, Precondition.none());\n }\n } else {\n const docValue = doc.data;\n const patchValue = ObjectValue.empty();\n let maskSet = new SortedSet<FieldPath>(FieldPath.comparator);\n for (let path of mask.fields) {\n if (!maskSet.has(path)) {\n let value = docValue.field(path);\n // If we are deleting a nested field, we take the immediate parent as\n // the mask used to construct the resulting mutation.\n // Justification: Nested fields can create parent fields implicitly. If\n // only a leaf entry is deleted in later mutations, the parent field\n // should still remain, but we may have lost this information.\n // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n // This leaves the final result (foo, {}). Despite the fact that `doc`\n // has the correct result, `foo` is not in `mask`, and the resulting\n // mutation would miss `foo`.\n if (value === null && path.length > 1) {\n path = path.popLast();\n value = docValue.field(path);\n }\n if (value === null) {\n patchValue.delete(path);\n } else {\n patchValue.set(path, value);\n }\n maskSet = maskSet.add(path);\n }\n }\n return new PatchMutation(\n doc.key,\n patchValue,\n new FieldMask(maskSet.toArray()),\n Precondition.none()\n );\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */\nexport function mutationApplyToRemoteDocument(\n mutation: Mutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n mutationVerifyKeyMatches(mutation, document);\n if (mutation instanceof SetMutation) {\n setMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else if (mutation instanceof PatchMutation) {\n patchMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n deleteMutationApplyToRemoteDocument(mutation, document, mutationResult);\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */\nexport function mutationApplyToLocalView(\n mutation: Mutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n mutationVerifyKeyMatches(mutation, document);\n\n if (mutation instanceof SetMutation) {\n return setMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else if (mutation instanceof PatchMutation) {\n return patchMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n return deleteMutationApplyToLocalView(mutation, document, previousMask);\n }\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */\nexport function mutationExtractBaseValue(\n mutation: Mutation,\n document: Document\n): ObjectValue | null {\n let baseObject: ObjectValue | null = null;\n for (const fieldTransform of mutation.fieldTransforms) {\n const existingValue = document.data.field(fieldTransform.field);\n const coercedValue = computeTransformOperationBaseValue(\n fieldTransform.transform,\n existingValue || null\n );\n\n if (coercedValue != null) {\n if (baseObject === null) {\n baseObject = ObjectValue.empty();\n }\n baseObject.set(fieldTransform.field, coercedValue);\n }\n }\n return baseObject ? baseObject : null;\n}\n\nexport function mutationEquals(left: Mutation, right: Mutation): boolean {\n if (left.type !== right.type) {\n return false;\n }\n\n if (!left.key.isEqual(right.key)) {\n return false;\n }\n\n if (!left.precondition.isEqual(right.precondition)) {\n return false;\n }\n\n if (!fieldTransformsAreEqual(left.fieldTransforms, right.fieldTransforms)) {\n return false;\n }\n\n if (left.type === MutationType.Set) {\n return (left as SetMutation).value.isEqual((right as SetMutation).value);\n }\n\n if (left.type === MutationType.Patch) {\n return (\n (left as PatchMutation).data.isEqual((right as PatchMutation).data) &&\n (left as PatchMutation).fieldMask.isEqual(\n (right as PatchMutation).fieldMask\n )\n );\n }\n\n return true;\n}\n\nfunction mutationVerifyKeyMatches(\n mutation: Mutation,\n document: MutableDocument\n): void {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply a mutation to a document with the same key'\n );\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nexport class SetMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly value: ObjectValue,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Set;\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction setMutationApplyToRemoteDocument(\n mutation: SetMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n // remote document the server has accepted the mutation so the precondition\n // must have held.\n const newData = mutation.value.clone();\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction setMutationApplyToLocalView(\n mutation: SetMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return previousMask;\n }\n\n const newData = mutation.value.clone();\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n return null; // SetMutation overwrites all fields.\n}\n\n/**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */\nexport class PatchMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Patch;\n\n getFieldMask(): FieldMask | null {\n return this.fieldMask;\n }\n}\n\nfunction patchMutationApplyToRemoteDocument(\n mutation: PatchMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and convert to an UnknownDocument with a\n // known updateTime.\n document.convertToUnknownDocument(mutationResult.version);\n return;\n }\n\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction patchMutationApplyToLocalView(\n mutation: PatchMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n return previousMask;\n }\n\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n\n if (previousMask === null) {\n return null;\n }\n\n return previousMask\n .unionWith(mutation.fieldMask.fields)\n .unionWith(mutation.fieldTransforms.map(transform => transform.field));\n}\n\n/**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */\nfunction getPatch(mutation: PatchMutation): Map<FieldPath, ProtoValue | null> {\n const result = new Map<FieldPath, ProtoValue | null>();\n mutation.fieldMask.fields.forEach(fieldPath => {\n if (!fieldPath.isEmpty()) {\n const newValue = mutation.data.field(fieldPath);\n result.set(fieldPath, newValue);\n }\n });\n return result;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */\nfunction serverTransformResults(\n fieldTransforms: FieldTransform[],\n mutableDocument: MutableDocument,\n serverTransformResults: Array<ProtoValue | null>\n): Map<FieldPath, ProtoValue> {\n const transformResults = new Map<FieldPath, ProtoValue>();\n hardAssert(\n fieldTransforms.length === serverTransformResults.length,\n `server transform result count (${serverTransformResults.length}) ` +\n `should match field transform count (${fieldTransforms.length})`\n );\n\n for (let i = 0; i < serverTransformResults.length; i++) {\n const fieldTransform = fieldTransforms[i];\n const transform = fieldTransform.transform;\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToRemoteDocument(\n transform,\n previousValue,\n serverTransformResults[i]\n )\n );\n }\n return transformResults;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n * generate ServerTimestampValues).\n * @param mutableDocument - The document to apply transforms on.\n * @returns The transform results list.\n */\nfunction localTransformResults(\n fieldTransforms: FieldTransform[],\n localWriteTime: Timestamp,\n mutableDocument: MutableDocument\n): Map<FieldPath, ProtoValue> {\n const transformResults = new Map<FieldPath, ProtoValue>();\n for (const fieldTransform of fieldTransforms) {\n const transform = fieldTransform.transform;\n\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToLocalView(\n transform,\n previousValue,\n localWriteTime\n )\n );\n }\n return transformResults;\n}\n\n/** A mutation that deletes the document at the given key. */\nexport class DeleteMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Delete;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction deleteMutationApplyToRemoteDocument(\n mutation: DeleteMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n debugAssert(\n mutationResult.transformResults.length === 0,\n 'Transform results received by DeleteMutation.'\n );\n\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n document\n .convertToNoDocument(mutationResult.version)\n .setHasCommittedMutations();\n}\n\nfunction deleteMutationApplyToLocalView(\n mutation: DeleteMutation,\n document: MutableDocument,\n previousMask: FieldMask | null\n): FieldMask | null {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply mutation to document with same key'\n );\n if (preconditionIsValidForDocument(mutation.precondition, document)) {\n document.convertToNoDocument(document.version).setHasLocalMutations();\n return null;\n }\n return previousMask;\n}\n\n/**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */\nexport class VerifyMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Verify;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport {\n documentKeySet,\n DocumentKeySet,\n MutationMap,\n DocumentVersionMap,\n documentVersionMap,\n newMutationMap,\n OverlayedDocumentMap\n} from './collections';\nimport { MutableDocument } from './document';\nimport { FieldMask } from './field_mask';\nimport {\n calculateOverlayMutation,\n Mutation,\n mutationApplyToLocalView,\n mutationApplyToRemoteDocument,\n mutationEquals,\n MutationResult\n} from './mutation';\n\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */\nexport class MutationBatch {\n /**\n * @param batchId - The unique ID of this mutation batch.\n * @param localWriteTime - The original write time of this mutation.\n * @param baseMutations - Mutations that are used to populate the base\n * values when this mutation is applied locally. This can be used to locally\n * overwrite values that are persisted in the remote document cache. Base\n * mutations are never sent to the backend.\n * @param mutations - The user-provided mutations in this mutation batch.\n * User-provided mutations are applied both locally and remotely on the\n * backend.\n */\n constructor(\n public batchId: BatchId,\n public localWriteTime: Timestamp,\n public baseMutations: Mutation[],\n public mutations: Mutation[]\n ) {\n debugAssert(mutations.length > 0, 'Cannot create an empty mutation batch');\n }\n\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to compute the state of the remote document\n *\n * @param document - The document to apply mutations to.\n * @param batchResult - The result of applying the MutationBatch to the\n * backend.\n */\n applyToRemoteDocument(\n document: MutableDocument,\n batchResult: MutationBatchResult\n ): void {\n const mutationResults = batchResult.mutationResults;\n debugAssert(\n mutationResults.length === this.mutations.length,\n `Mismatch between mutations length\n (${this.mutations.length}) and mutation results length\n (${mutationResults.length}).`\n );\n\n for (let i = 0; i < this.mutations.length; i++) {\n const mutation = this.mutations[i];\n if (mutation.key.isEqual(document.key)) {\n const mutationResult = mutationResults[i];\n mutationApplyToRemoteDocument(mutation, document, mutationResult);\n }\n }\n }\n\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param document - The document to apply mutations to.\n * @param mutatedFields - Fields that have been updated before applying this mutation batch.\n * @returns A `FieldMask` representing all the fields that are mutated.\n */\n applyToLocalView(\n document: MutableDocument,\n mutatedFields: FieldMask | null\n ): FieldMask | null {\n // First, apply the base state. This allows us to apply non-idempotent\n // transform against a consistent set of values.\n for (const mutation of this.baseMutations) {\n if (mutation.key.isEqual(document.key)) {\n mutatedFields = mutationApplyToLocalView(\n mutation,\n document,\n mutatedFields,\n this.localWriteTime\n );\n }\n }\n\n // Second, apply all user-provided mutations.\n for (const mutation of this.mutations) {\n if (mutation.key.isEqual(document.key)) {\n mutatedFields = mutationApplyToLocalView(\n mutation,\n document,\n mutatedFields,\n this.localWriteTime\n );\n }\n }\n return mutatedFields;\n }\n\n /**\n * Computes the local view for all provided documents given the mutations in\n * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to\n * replace all the mutation applications.\n */\n applyToLocalDocumentSet(\n documentMap: OverlayedDocumentMap,\n documentsWithoutRemoteVersion: DocumentKeySet\n ): MutationMap {\n // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations\n // directly (as done in `applyToLocalView()`), we can reduce the complexity\n // to O(n).\n const overlays = newMutationMap();\n this.mutations.forEach(m => {\n const overlayedDocument = documentMap.get(m.key)!;\n // TODO(mutabledocuments): This method should take a MutableDocumentMap\n // and we should remove this cast.\n const mutableDocument =\n overlayedDocument.overlayedDocument as MutableDocument;\n let mutatedFields = this.applyToLocalView(\n mutableDocument,\n overlayedDocument.mutatedFields\n );\n // Set mutatedFields to null if the document is only from local mutations.\n // This creates a Set or Delete mutation, instead of trying to create a\n // patch mutation as the overlay.\n mutatedFields = documentsWithoutRemoteVersion.has(m.key)\n ? null\n : mutatedFields;\n const overlay = calculateOverlayMutation(mutableDocument, mutatedFields);\n if (overlay !== null) {\n overlays.set(m.key, overlay);\n }\n\n if (!mutableDocument.isValidDocument()) {\n mutableDocument.convertToNoDocument(SnapshotVersion.min());\n }\n });\n return overlays;\n }\n\n keys(): DocumentKeySet {\n return this.mutations.reduce(\n (keys, m) => keys.add(m.key),\n documentKeySet()\n );\n }\n\n isEqual(other: MutationBatch): boolean {\n return (\n this.batchId === other.batchId &&\n arrayEquals(this.mutations, other.mutations, (l, r) =>\n mutationEquals(l, r)\n ) &&\n arrayEquals(this.baseMutations, other.baseMutations, (l, r) =>\n mutationEquals(l, r)\n )\n );\n }\n}\n\n/** The result of applying a mutation batch to the backend. */\nexport class MutationBatchResult {\n private constructor(\n readonly batch: MutationBatch,\n readonly commitVersion: SnapshotVersion,\n readonly mutationResults: MutationResult[],\n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n readonly docVersions: DocumentVersionMap\n ) {}\n\n /**\n * Creates a new MutationBatchResult for the given batch and results. There\n * must be one result for each mutation in the batch. This static factory\n * caches a document=>version mapping (docVersions).\n */\n static from(\n batch: MutationBatch,\n commitVersion: SnapshotVersion,\n results: MutationResult[]\n ): MutationBatchResult {\n hardAssert(\n batch.mutations.length === results.length,\n 'Mutations sent ' +\n batch.mutations.length +\n ' must equal results received ' +\n results.length\n );\n\n let versionMap = documentVersionMap();\n const mutations = batch.mutations;\n for (let i = 0; i < mutations.length; i++) {\n versionMap = versionMap.insert(mutations[i].key, results[i].version);\n }\n\n return new MutationBatchResult(batch, commitVersion, results, versionMap);\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from './document_key';\nimport { Mutation } from './mutation';\n\n/**\n * Representation of an overlay computed by Firestore.\n *\n * Holds information about a mutation and the largest batch id in Firestore when\n * the mutation was created.\n */\nexport class Overlay {\n constructor(readonly largestBatchId: number, readonly mutation: Mutation) {}\n\n getKey(): DocumentKey {\n return this.mutation.key;\n }\n\n isEqual(other: Overlay | null): boolean {\n return other !== null && this.mutation === other.mutation;\n }\n\n toString(): string {\n return `Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BloomFilter as ProtoBloomFilter } from '../protos/firestore_proto_api';\n\nexport class ExistenceFilter {\n constructor(public count: number, public unchangedNames?: ProtoBloomFilter) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\nimport { Code } from '../util/error';\nimport { logError } from '../util/log';\n\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */\nenum RpcCode {\n OK = 0,\n CANCELLED = 1,\n UNKNOWN = 2,\n INVALID_ARGUMENT = 3,\n DEADLINE_EXCEEDED = 4,\n NOT_FOUND = 5,\n ALREADY_EXISTS = 6,\n PERMISSION_DENIED = 7,\n UNAUTHENTICATED = 16,\n RESOURCE_EXHAUSTED = 8,\n FAILED_PRECONDITION = 9,\n ABORTED = 10,\n OUT_OF_RANGE = 11,\n UNIMPLEMENTED = 12,\n INTERNAL = 13,\n UNAVAILABLE = 14,\n DATA_LOSS = 15\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nexport function isPermanentError(code: Code): boolean {\n switch (code) {\n case Code.OK:\n return fail('Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependant on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\nexport function isPermanentWriteError(code: Code): boolean {\n return isPermanentError(code) && code !== Code.ABORTED;\n}\n\n/**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\nexport function mapCodeFromRpcStatus(status: string): Code | undefined {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const code: RpcCode = RpcCode[status as any] as any;\n if (code === undefined) {\n return undefined;\n }\n\n return mapCodeFromRpcCode(code);\n}\n\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nexport function mapCodeFromRpcCode(code: number | undefined): Code {\n if (code === undefined) {\n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n logError('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nexport function mapRpcCodeFromCode(code: Code | undefined): number {\n if (code === undefined) {\n return RpcCode.OK;\n }\n\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status - An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpStatus(status?: number): Code {\n if (status === undefined) {\n logError('RPC_ERROR', 'HTTP error has no status');\n return Code.UNKNOWN;\n }\n\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200: // OK\n return Code.OK;\n\n case 400: // Bad Request\n return Code.FAILED_PRECONDITION;\n // Other possibilities based on the forward mapping\n // return Code.INVALID_ARGUMENT;\n // return Code.OUT_OF_RANGE;\n\n case 401: // Unauthorized\n return Code.UNAUTHENTICATED;\n\n case 403: // Forbidden\n return Code.PERMISSION_DENIED;\n\n case 404: // Not Found\n return Code.NOT_FOUND;\n\n case 409: // Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n\n case 416: // Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n\n case 429: // Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n\n case 499: // Client Closed Request\n return Code.CANCELLED;\n\n case 500: // Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n\n case 501: // Unimplemented\n return Code.UNIMPLEMENTED;\n\n case 503: // Service Unavailable\n return Code.UNAVAILABLE;\n\n case 504: // Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n\n default:\n if (status >= 200 && status < 300) {\n return Code.OK;\n }\n if (status >= 400 && status < 500) {\n return Code.FAILED_PRECONDITION;\n }\n if (status >= 500 && status < 600) {\n return Code.INTERNAL;\n }\n return Code.UNKNOWN;\n }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpResponseErrorStatus(status: string): Code {\n const serverError = status.toLowerCase().replace(/_/g, '-');\n return Object.values(Code).indexOf(serverError as Code) >= 0\n ? (serverError as Code)\n : Code.UNKNOWN;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The global, singleton instance of TestingHooksSpi.\n *\n * This variable will be `null` in all cases _except_ when running from\n * integration tests that have registered callbacks to be notified of events\n * that happen during the test execution.\n */\nexport let testingHooksSpi: TestingHooksSpi | null = null;\n\n/**\n * Sets the value of the `testingHooksSpi` object.\n * @param instance the instance to set.\n */\nexport function setTestingHooksSpi(instance: TestingHooksSpi): void {\n if (testingHooksSpi) {\n throw new Error('a TestingHooksSpi instance is already set');\n }\n testingHooksSpi = instance;\n}\n\n/**\n * The \"service provider interface\" for the testing hooks.\n *\n * The implementation of this object will handle the callbacks made by the SDK\n * to be handled by the integration tests.\n *\n * This \"SPI\" is separated from the implementation to avoid import cycles and\n * to enable production builds to fully tree-shake away the testing hooks logic.\n */\nexport interface TestingHooksSpi {\n /**\n * Invokes all callbacks registered with\n * `TestingHooks.onExistenceFilterMismatch()` with the given info.\n */\n notifyOnExistenceFilterMismatch(info: ExistenceFilterMismatchInfo): void;\n}\n\n/**\n * Information about an existence filter mismatch.\n * @internal\n */\nexport interface ExistenceFilterMismatchInfo {\n /** The number of documents that matched the query in the local cache. */\n localCacheCount: number;\n\n /**\n * The number of documents that matched the query on the server, as specified\n * in the ExistenceFilter message's `count` field.\n */\n existenceFilterCount: number;\n\n /**\n * The projectId used when checking documents for membership in the bloom\n * filter.\n */\n projectId: string;\n\n /**\n * The databaseId used when checking documents for membership in the bloom\n * filter.\n */\n databaseId: string;\n\n /**\n * Information about the bloom filter provided by Watch in the ExistenceFilter\n * message's `unchangedNames` field. If this property is omitted or undefined\n * then that means that Watch did _not_ provide a bloom filter.\n */\n bloomFilter?: {\n /**\n * Whether a full requery was averted by using the bloom filter. If false,\n * then something happened, such as a false positive, to prevent using the\n * bloom filter to avoid a full requery.\n */\n applied: boolean;\n\n /** The number of hash functions used in the bloom filter. */\n hashCount: number;\n\n /** The number of bytes in the bloom filter's bitmask. */\n bitmapLength: number;\n\n /** The number of bits of padding in the last byte of the bloom filter. */\n padding: number;\n\n /**\n * Tests the given string for membership in the bloom filter created from\n * the existence filter; will be undefined if creating the bloom filter\n * failed.\n */\n mightContain?: (value: string) => boolean;\n };\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An instance of the Platform's 'TextEncoder' implementation.\n */\nexport function newTextEncoder(): TextEncoder {\n return new TextEncoder();\n}\n\n/**\n * An instance of the Platform's 'TextDecoder' implementation.\n */\nexport function newTextDecoder(): TextDecoder {\n return new TextDecoder('utf-8');\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Md5, Integer } from '@firebase/webchannel-wrapper';\n\nimport { newTextEncoder } from '../platform/text_serializer';\n\nconst MAX_64_BIT_UNSIGNED_INTEGER = new Integer([0xffffffff, 0xffffffff], 0);\n\n// Hash a string using md5 hashing algorithm.\nfunction getMd5HashValue(value: string): Uint8Array {\n const encodedValue = newTextEncoder().encode(value);\n const md5 = new Md5();\n md5.update(encodedValue);\n return new Uint8Array(md5.digest());\n}\n\n// Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using\n// 2’s complement using little endian.\nfunction get64BitUints(Bytes: Uint8Array): [Integer, Integer] {\n const dataView = new DataView(Bytes.buffer);\n const chunk1 = dataView.getUint32(0, /* littleEndian= */ true);\n const chunk2 = dataView.getUint32(4, /* littleEndian= */ true);\n const chunk3 = dataView.getUint32(8, /* littleEndian= */ true);\n const chunk4 = dataView.getUint32(12, /* littleEndian= */ true);\n const integer1 = new Integer([chunk1, chunk2], 0);\n const integer2 = new Integer([chunk3, chunk4], 0);\n return [integer1, integer2];\n}\n\nexport class BloomFilter {\n readonly bitCount: number;\n private readonly bitCountInInteger: Integer;\n\n constructor(\n readonly bitmap: Uint8Array,\n readonly padding: number,\n readonly hashCount: number\n ) {\n if (padding < 0 || padding >= 8) {\n throw new BloomFilterError(`Invalid padding: ${padding}`);\n }\n\n if (hashCount < 0) {\n throw new BloomFilterError(`Invalid hash count: ${hashCount}`);\n }\n\n if (bitmap.length > 0 && this.hashCount === 0) {\n // Only empty bloom filter can have 0 hash count.\n throw new BloomFilterError(`Invalid hash count: ${hashCount}`);\n }\n\n if (bitmap.length === 0 && padding !== 0) {\n // Empty bloom filter should have 0 padding.\n throw new BloomFilterError(\n `Invalid padding when bitmap length is 0: ${padding}`\n );\n }\n\n this.bitCount = bitmap.length * 8 - padding;\n // Set the bit count in Integer to avoid repetition in mightContain().\n this.bitCountInInteger = Integer.fromNumber(this.bitCount);\n }\n\n // Calculate the ith hash value based on the hashed 64bit integers,\n // and calculate its corresponding bit index in the bitmap to be checked.\n private getBitIndex(num1: Integer, num2: Integer, hashIndex: number): number {\n // Calculate hashed value h(i) = h1 + (i * h2).\n let hashValue = num1.add(num2.multiply(Integer.fromNumber(hashIndex)));\n // Wrap if hash value overflow 64bit.\n if (hashValue.compare(MAX_64_BIT_UNSIGNED_INTEGER) === 1) {\n hashValue = new Integer([hashValue.getBits(0), hashValue.getBits(1)], 0);\n }\n return hashValue.modulo(this.bitCountInInteger).toNumber();\n }\n\n // Return whether the bit on the given index in the bitmap is set to 1.\n private isBitSet(index: number): boolean {\n // To retrieve bit n, calculate: (bitmap[n / 8] & (0x01 << (n % 8))).\n const byte = this.bitmap[Math.floor(index / 8)];\n const offset = index % 8;\n return (byte & (0x01 << offset)) !== 0;\n }\n\n mightContain(value: string): boolean {\n // Empty bitmap should always return false on membership check.\n if (this.bitCount === 0) {\n return false;\n }\n const md5HashedValue = getMd5HashValue(value);\n const [hash1, hash2] = get64BitUints(md5HashedValue);\n for (let i = 0; i < this.hashCount; i++) {\n const index = this.getBitIndex(hash1, hash2, i);\n if (!this.isBitSet(index)) {\n return false;\n }\n }\n return true;\n }\n\n /** Create bloom filter for testing purposes only. */\n static create(\n bitCount: number,\n hashCount: number,\n contains: string[]\n ): BloomFilter {\n const padding = bitCount % 8 === 0 ? 0 : 8 - (bitCount % 8);\n const bitmap = new Uint8Array(Math.ceil(bitCount / 8));\n const bloomFilter = new BloomFilter(bitmap, padding, hashCount);\n contains.forEach(item => bloomFilter.insert(item));\n return bloomFilter;\n }\n\n private insert(value: string): void {\n if (this.bitCount === 0) {\n return;\n }\n\n const md5HashedValue = getMd5HashValue(value);\n const [hash1, hash2] = get64BitUints(md5HashedValue);\n for (let i = 0; i < this.hashCount; i++) {\n const index = this.getBitIndex(hash1, hash2, i);\n this.setBit(index);\n }\n }\n\n private setBit(index: number): void {\n const indexOfByte = Math.floor(index / 8);\n const offset = index % 8;\n this.bitmap[indexOfByte] |= 0x01 << offset;\n }\n}\n\nexport class BloomFilterError extends Error {\n readonly name = 'BloomFilterError';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { TargetPurpose } from '../local/target_data';\nimport {\n documentKeySet,\n DocumentKeySet,\n mutableDocumentMap,\n MutableDocumentMap\n} from '../model/collections';\nimport { ByteString } from '../util/byte_string';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\n\n/**\n * An event from the RemoteStore. It is split into targetChanges (changes to the\n * state or the set of documents in our watched targets) and documentUpdates\n * (changes to the actual documents).\n */\nexport class RemoteEvent {\n constructor(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n readonly snapshotVersion: SnapshotVersion,\n /**\n * A map from target to changes to the target. See TargetChange.\n */\n readonly targetChanges: Map<TargetId, TargetChange>,\n /**\n * A map of targets that is known to be inconsistent, and the purpose for\n * re-listening. Listens for these targets should be re-established without\n * resume tokens.\n */\n readonly targetMismatches: SortedMap<TargetId, TargetPurpose>,\n /**\n * A set of which documents have changed or been deleted, along with the\n * doc's new values (if not deleted).\n */\n readonly documentUpdates: MutableDocumentMap,\n /**\n * A set of which document updates are due only to limbo resolution targets.\n */\n readonly resolvedLimboDocuments: DocumentKeySet\n ) {}\n\n /**\n * HACK: Views require RemoteEvents in order to determine whether the view is\n * CURRENT, but secondary tabs don't receive remote events. So this method is\n * used to create a synthesized RemoteEvent that can be used to apply a\n * CURRENT status change to a View, for queries executed in a different tab.\n */\n // PORTING NOTE: Multi-tab only\n static createSynthesizedRemoteEventForCurrentChange(\n targetId: TargetId,\n current: boolean,\n resumeToken: ByteString\n ): RemoteEvent {\n const targetChanges = new Map<TargetId, TargetChange>();\n targetChanges.set(\n targetId,\n TargetChange.createSynthesizedTargetChangeForCurrentChange(\n targetId,\n current,\n resumeToken\n )\n );\n return new RemoteEvent(\n SnapshotVersion.min(),\n targetChanges,\n new SortedMap<TargetId, TargetPurpose>(primitiveComparator),\n mutableDocumentMap(),\n documentKeySet()\n );\n }\n}\n\n/**\n * A TargetChange specifies the set of changes for a specific target as part of\n * a RemoteEvent. These changes track which documents are added, modified or\n * removed, as well as the target's resume token and whether the target is\n * marked CURRENT.\n * The actual changes *to* documents are not part of the TargetChange since\n * documents may be part of multiple targets.\n */\nexport class TargetChange {\n constructor(\n /**\n * An opaque, server-assigned token that allows watching a query to be resumed\n * after disconnecting without retransmitting all the data that matches the\n * query. The resume token essentially identifies a point in time from which\n * the server should resume sending results.\n */\n readonly resumeToken: ByteString,\n /**\n * The \"current\" (synced) status of this target. Note that \"current\"\n * has special meaning in the RPC protocol that implies that a target is\n * both up-to-date and consistent with the rest of the watch stream.\n */\n readonly current: boolean,\n /**\n * The set of documents that were newly assigned to this target as part of\n * this remote event.\n */\n readonly addedDocuments: DocumentKeySet,\n /**\n * The set of documents that were already assigned to this target but received\n * an update during this remote event.\n */\n readonly modifiedDocuments: DocumentKeySet,\n /**\n * The set of documents that were removed from this target as part of this\n * remote event.\n */\n readonly removedDocuments: DocumentKeySet\n ) {}\n\n /**\n * This method is used to create a synthesized TargetChanges that can be used to\n * apply a CURRENT status change to a View (for queries executed in a different\n * tab) or for new queries (to raise snapshots with correct CURRENT status).\n */\n static createSynthesizedTargetChangeForCurrentChange(\n targetId: TargetId,\n current: boolean,\n resumeToken: ByteString\n ): TargetChange {\n return new TargetChange(\n resumeToken,\n current,\n documentKeySet(),\n documentKeySet(),\n documentKeySet()\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseId } from '../core/database_info';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { ChangeType } from '../core/view_snapshot';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport {\n documentKeySet,\n DocumentKeySet,\n mutableDocumentMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { normalizeByteString } from '../model/normalize';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { Base64DecodeError } from '../util/base64_decode_error';\nimport { ByteString } from '../util/byte_string';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport {\n testingHooksSpi,\n ExistenceFilterMismatchInfo as TestingHooksExistenceFilterMismatchInfo\n} from '../util/testing_hooks_spi';\n\nimport { BloomFilter, BloomFilterError } from './bloom_filter';\nimport { ExistenceFilter } from './existence_filter';\nimport { RemoteEvent, TargetChange } from './remote_event';\n\n/**\n * Internal representation of the watcher API protocol buffers.\n */\nexport type WatchChange =\n | DocumentWatchChange\n | WatchTargetChange\n | ExistenceFilterChange;\n\n/**\n * Represents a changed document and a list of target ids to which this change\n * applies.\n *\n * If document has been deleted NoDocument will be provided.\n */\nexport class DocumentWatchChange {\n constructor(\n /** The new document applies to all of these targets. */\n public updatedTargetIds: TargetId[],\n /** The new document is removed from all of these targets. */\n public removedTargetIds: TargetId[],\n /** The key of the document for this change. */\n public key: DocumentKey,\n /**\n * The new document or NoDocument if it was deleted. Is null if the\n * document went out of view without the server sending a new document.\n */\n public newDoc: MutableDocument | null\n ) {}\n}\n\nexport class ExistenceFilterChange {\n constructor(\n public targetId: TargetId,\n public existenceFilter: ExistenceFilter\n ) {}\n}\n\nexport const enum WatchTargetChangeState {\n NoChange,\n Added,\n Removed,\n Current,\n Reset\n}\n\nconst enum BloomFilterApplicationStatus {\n Success,\n Skipped,\n FalsePositive\n}\nexport class WatchTargetChange {\n constructor(\n /** What kind of change occurred to the watch target. */\n public state: WatchTargetChangeState,\n /** The target IDs that were added/removed/set. */\n public targetIds: TargetId[],\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n public resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING,\n /** An RPC error indicating why the watch failed. */\n public cause: FirestoreError | null = null\n ) {}\n}\n\n/** Tracks the internal state of a Watch target. */\nclass TargetState {\n /**\n * The number of pending responses (adds or removes) that we are waiting on.\n * We only consider targets active that have no pending responses.\n */\n private pendingResponses = 0;\n\n /**\n * Keeps track of the document changes since the last raised snapshot.\n *\n * These changes are continuously updated as we receive document updates and\n * always reflect the current set of changes against the last issued snapshot.\n */\n private documentChanges: SortedMap<DocumentKey, ChangeType> =\n snapshotChangesMap();\n\n /** See public getters for explanations of these fields. */\n private _resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING;\n private _current = false;\n\n /**\n * Whether this target state should be included in the next snapshot. We\n * initialize to true so that newly-added targets are included in the next\n * RemoteEvent.\n */\n private _hasPendingChanges = true;\n\n /**\n * Whether this target has been marked 'current'.\n *\n * 'Current' has special meaning in the RPC protocol: It implies that the\n * Watch backend has sent us all changes up to the point at which the target\n * was added and that the target is consistent with the rest of the watch\n * stream.\n */\n get current(): boolean {\n return this._current;\n }\n\n /** The last resume token sent to us for this target. */\n get resumeToken(): ByteString {\n return this._resumeToken;\n }\n\n /** Whether this target has pending target adds or target removes. */\n get isPending(): boolean {\n return this.pendingResponses !== 0;\n }\n\n /** Whether we have modified any state that should trigger a snapshot. */\n get hasPendingChanges(): boolean {\n return this._hasPendingChanges;\n }\n\n /**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. Empty resumeTokens are discarded.\n */\n updateResumeToken(resumeToken: ByteString): void {\n if (resumeToken.approximateByteSize() > 0) {\n this._hasPendingChanges = true;\n this._resumeToken = resumeToken;\n }\n }\n\n /**\n * Creates a target change from the current set of changes.\n *\n * To reset the document changes after raising this snapshot, call\n * `clearPendingChanges()`.\n */\n toTargetChange(): TargetChange {\n let addedDocuments = documentKeySet();\n let modifiedDocuments = documentKeySet();\n let removedDocuments = documentKeySet();\n\n this.documentChanges.forEach((key, changeType) => {\n switch (changeType) {\n case ChangeType.Added:\n addedDocuments = addedDocuments.add(key);\n break;\n case ChangeType.Modified:\n modifiedDocuments = modifiedDocuments.add(key);\n break;\n case ChangeType.Removed:\n removedDocuments = removedDocuments.add(key);\n break;\n default:\n fail('Encountered invalid change type: ' + changeType);\n }\n });\n\n return new TargetChange(\n this._resumeToken,\n this._current,\n addedDocuments,\n modifiedDocuments,\n removedDocuments\n );\n }\n\n /**\n * Resets the document changes and sets `hasPendingChanges` to false.\n */\n clearPendingChanges(): void {\n this._hasPendingChanges = false;\n this.documentChanges = snapshotChangesMap();\n }\n\n addDocumentChange(key: DocumentKey, changeType: ChangeType): void {\n this._hasPendingChanges = true;\n this.documentChanges = this.documentChanges.insert(key, changeType);\n }\n\n removeDocumentChange(key: DocumentKey): void {\n this._hasPendingChanges = true;\n this.documentChanges = this.documentChanges.remove(key);\n }\n\n recordPendingTargetRequest(): void {\n this.pendingResponses += 1;\n }\n\n recordTargetResponse(): void {\n this.pendingResponses -= 1;\n }\n\n markCurrent(): void {\n this._hasPendingChanges = true;\n this._current = true;\n }\n}\n\n/**\n * Interface implemented by RemoteStore to expose target metadata to the\n * WatchChangeAggregator.\n */\nexport interface TargetMetadataProvider {\n /**\n * Returns the set of remote document keys for the given target ID as of the\n * last raised snapshot.\n */\n getRemoteKeysForTarget(targetId: TargetId): DocumentKeySet;\n\n /**\n * Returns the TargetData for an active target ID or 'null' if this target\n * has become inactive\n */\n getTargetDataForTarget(targetId: TargetId): TargetData | null;\n\n /**\n * Returns the database ID of the Firestore instance.\n */\n getDatabaseId(): DatabaseId;\n}\n\nconst LOG_TAG = 'WatchChangeAggregator';\n\n/**\n * A helper class to accumulate watch changes into a RemoteEvent.\n */\nexport class WatchChangeAggregator {\n constructor(private metadataProvider: TargetMetadataProvider) {}\n\n /** The internal state of all tracked targets. */\n private targetStates = new Map<TargetId, TargetState>();\n\n /** Keeps track of the documents to update since the last raised snapshot. */\n private pendingDocumentUpdates = mutableDocumentMap();\n\n /** A mapping of document keys to their set of target IDs. */\n private pendingDocumentTargetMapping = documentTargetMap();\n\n /**\n * A map of targets with existence filter mismatches. These targets are\n * known to be inconsistent and their listens needs to be re-established by\n * RemoteStore.\n */\n private pendingTargetResets = new SortedMap<TargetId, TargetPurpose>(\n primitiveComparator\n );\n\n /**\n * Processes and adds the DocumentWatchChange to the current set of changes.\n */\n handleDocumentChange(docChange: DocumentWatchChange): void {\n for (const targetId of docChange.updatedTargetIds) {\n if (docChange.newDoc && docChange.newDoc.isFoundDocument()) {\n this.addDocumentToTarget(targetId, docChange.newDoc);\n } else {\n this.removeDocumentFromTarget(\n targetId,\n docChange.key,\n docChange.newDoc\n );\n }\n }\n\n for (const targetId of docChange.removedTargetIds) {\n this.removeDocumentFromTarget(targetId, docChange.key, docChange.newDoc);\n }\n }\n\n /** Processes and adds the WatchTargetChange to the current set of changes. */\n handleTargetChange(targetChange: WatchTargetChange): void {\n this.forEachTarget(targetChange, targetId => {\n const targetState = this.ensureTargetState(targetId);\n switch (targetChange.state) {\n case WatchTargetChangeState.NoChange:\n if (this.isActiveTarget(targetId)) {\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Added:\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n targetState.recordTargetResponse();\n if (!targetState.isPending) {\n // We have a freshly added target, so we need to reset any state\n // that we had previously. This can happen e.g. when remove and add\n // back a target for existence filter mismatches.\n targetState.clearPendingChanges();\n }\n targetState.updateResumeToken(targetChange.resumeToken);\n break;\n case WatchTargetChangeState.Removed:\n // We need to keep track of removed targets to we can post-filter and\n // remove any target changes.\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n targetState.recordTargetResponse();\n if (!targetState.isPending) {\n this.removeTarget(targetId);\n }\n debugAssert(\n !targetChange.cause,\n 'WatchChangeAggregator does not handle errored targets'\n );\n break;\n case WatchTargetChangeState.Current:\n if (this.isActiveTarget(targetId)) {\n targetState.markCurrent();\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Reset:\n if (this.isActiveTarget(targetId)) {\n // Reset the target and synthesizes removes for all existing\n // documents. The backend will re-add any documents that still\n // match the target before it sends the next global snapshot.\n this.resetTarget(targetId);\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n default:\n fail('Unknown target watch change state: ' + targetChange.state);\n }\n });\n }\n\n /**\n * Iterates over all targetIds that the watch change applies to: either the\n * targetIds explicitly listed in the change or the targetIds of all currently\n * active targets.\n */\n forEachTarget(\n targetChange: WatchTargetChange,\n fn: (targetId: TargetId) => void\n ): void {\n if (targetChange.targetIds.length > 0) {\n targetChange.targetIds.forEach(fn);\n } else {\n this.targetStates.forEach((_, targetId) => {\n if (this.isActiveTarget(targetId)) {\n fn(targetId);\n }\n });\n }\n }\n\n /**\n * Handles existence filters and synthesizes deletes for filter mismatches.\n * Targets that are invalidated by filter mismatches are added to\n * `pendingTargetResets`.\n */\n handleExistenceFilter(watchChange: ExistenceFilterChange): void {\n const targetId = watchChange.targetId;\n const expectedCount = watchChange.existenceFilter.count;\n\n const targetData = this.targetDataForActiveTarget(targetId);\n if (targetData) {\n const target = targetData.target;\n if (targetIsDocumentTarget(target)) {\n if (expectedCount === 0) {\n // The existence filter told us the document does not exist. We deduce\n // that this document does not exist and apply a deleted document to\n // our updates. Without applying this deleted document there might be\n // another query that will raise this document as part of a snapshot\n // until it is resolved, essentially exposing inconsistency between\n // queries.\n const key = new DocumentKey(target.path);\n this.removeDocumentFromTarget(\n targetId,\n key,\n MutableDocument.newNoDocument(key, SnapshotVersion.min())\n );\n } else {\n hardAssert(\n expectedCount === 1,\n 'Single document existence filter with count: ' + expectedCount\n );\n }\n } else {\n const currentSize = this.getCurrentDocumentCountForTarget(targetId);\n // Existence filter mismatch. Mark the documents as being in limbo, and\n // raise a snapshot with `isFromCache:true`.\n if (currentSize !== expectedCount) {\n // Apply bloom filter to identify and mark removed documents.\n const bloomFilter = this.parseBloomFilter(watchChange);\n const status = bloomFilter\n ? this.applyBloomFilter(bloomFilter, watchChange, currentSize)\n : BloomFilterApplicationStatus.Skipped;\n\n if (status !== BloomFilterApplicationStatus.Success) {\n // If bloom filter application fails, we reset the mapping and\n // trigger re-run of the query.\n this.resetTarget(targetId);\n\n const purpose: TargetPurpose =\n status === BloomFilterApplicationStatus.FalsePositive\n ? TargetPurpose.ExistenceFilterMismatchBloom\n : TargetPurpose.ExistenceFilterMismatch;\n this.pendingTargetResets = this.pendingTargetResets.insert(\n targetId,\n purpose\n );\n }\n testingHooksSpi?.notifyOnExistenceFilterMismatch(\n createExistenceFilterMismatchInfoForTestingHooks(\n currentSize,\n watchChange.existenceFilter,\n this.metadataProvider.getDatabaseId(),\n bloomFilter,\n status\n )\n );\n }\n }\n }\n }\n\n /**\n * Parse the bloom filter from the \"unchanged_names\" field of an existence\n * filter.\n */\n private parseBloomFilter(\n watchChange: ExistenceFilterChange\n ): BloomFilter | null {\n const unchangedNames = watchChange.existenceFilter.unchangedNames;\n if (!unchangedNames || !unchangedNames.bits) {\n return null;\n }\n\n const {\n bits: { bitmap = '', padding = 0 },\n hashCount = 0\n } = unchangedNames;\n\n let normalizedBitmap: Uint8Array;\n try {\n normalizedBitmap = normalizeByteString(bitmap).toUint8Array();\n } catch (err) {\n if (err instanceof Base64DecodeError) {\n logWarn(\n 'Decoding the base64 bloom filter in existence filter failed (' +\n err.message +\n '); ignoring the bloom filter and falling back to full re-query.'\n );\n return null;\n } else {\n throw err;\n }\n }\n\n let bloomFilter: BloomFilter;\n try {\n // BloomFilter throws error if the inputs are invalid.\n bloomFilter = new BloomFilter(normalizedBitmap, padding, hashCount);\n } catch (err) {\n if (err instanceof BloomFilterError) {\n logWarn('BloomFilter error: ', err);\n } else {\n logWarn('Applying bloom filter failed: ', err);\n }\n return null;\n }\n\n if (bloomFilter.bitCount === 0) {\n return null;\n }\n\n return bloomFilter;\n }\n\n /**\n * Apply bloom filter to remove the deleted documents, and return the\n * application status.\n */\n private applyBloomFilter(\n bloomFilter: BloomFilter,\n watchChange: ExistenceFilterChange,\n currentCount: number\n ): BloomFilterApplicationStatus {\n const expectedCount = watchChange.existenceFilter.count;\n\n const removedDocumentCount = this.filterRemovedDocuments(\n bloomFilter,\n watchChange.targetId\n );\n\n return expectedCount === currentCount - removedDocumentCount\n ? BloomFilterApplicationStatus.Success\n : BloomFilterApplicationStatus.FalsePositive;\n }\n\n /**\n * Filter out removed documents based on bloom filter membership result and\n * return number of documents removed.\n */\n private filterRemovedDocuments(\n bloomFilter: BloomFilter,\n targetId: number\n ): number {\n const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n let removalCount = 0;\n\n existingKeys.forEach(key => {\n const databaseId = this.metadataProvider.getDatabaseId();\n const documentPath =\n `projects/${databaseId.projectId}` +\n `/databases/${databaseId.database}` +\n `/documents/${key.path.canonicalString()}`;\n\n if (!bloomFilter.mightContain(documentPath)) {\n this.removeDocumentFromTarget(targetId, key, /*updatedDocument=*/ null);\n removalCount++;\n }\n });\n\n return removalCount;\n }\n\n /**\n * Converts the currently accumulated state into a remote event at the\n * provided snapshot version. Resets the accumulated changes before returning.\n */\n createRemoteEvent(snapshotVersion: SnapshotVersion): RemoteEvent {\n const targetChanges = new Map<TargetId, TargetChange>();\n\n this.targetStates.forEach((targetState, targetId) => {\n const targetData = this.targetDataForActiveTarget(targetId);\n if (targetData) {\n if (targetState.current && targetIsDocumentTarget(targetData.target)) {\n // Document queries for document that don't exist can produce an empty\n // result set. To update our local cache, we synthesize a document\n // delete if we have not previously received the document. This\n // resolves the limbo state of the document, removing it from\n // limboDocumentRefs.\n //\n // TODO(dimond): Ideally we would have an explicit lookup target\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n const key = new DocumentKey(targetData.target.path);\n if (\n this.pendingDocumentUpdates.get(key) === null &&\n !this.targetContainsDocument(targetId, key)\n ) {\n this.removeDocumentFromTarget(\n targetId,\n key,\n MutableDocument.newNoDocument(key, snapshotVersion)\n );\n }\n }\n\n if (targetState.hasPendingChanges) {\n targetChanges.set(targetId, targetState.toTargetChange());\n targetState.clearPendingChanges();\n }\n }\n });\n\n let resolvedLimboDocuments = documentKeySet();\n\n // We extract the set of limbo-only document updates as the GC logic\n // special-cases documents that do not appear in the target cache.\n //\n // TODO(gsoltis): Expand on this comment once GC is available in the JS\n // client.\n this.pendingDocumentTargetMapping.forEach((key, targets) => {\n let isOnlyLimboTarget = true;\n\n targets.forEachWhile(targetId => {\n const targetData = this.targetDataForActiveTarget(targetId);\n if (\n targetData &&\n targetData.purpose !== TargetPurpose.LimboResolution\n ) {\n isOnlyLimboTarget = false;\n return false;\n }\n\n return true;\n });\n\n if (isOnlyLimboTarget) {\n resolvedLimboDocuments = resolvedLimboDocuments.add(key);\n }\n });\n\n this.pendingDocumentUpdates.forEach((_, doc) =>\n doc.setReadTime(snapshotVersion)\n );\n\n const remoteEvent = new RemoteEvent(\n snapshotVersion,\n targetChanges,\n this.pendingTargetResets,\n this.pendingDocumentUpdates,\n resolvedLimboDocuments\n );\n\n this.pendingDocumentUpdates = mutableDocumentMap();\n this.pendingDocumentTargetMapping = documentTargetMap();\n this.pendingTargetResets = new SortedMap<TargetId, TargetPurpose>(\n primitiveComparator\n );\n\n return remoteEvent;\n }\n\n /**\n * Adds the provided document to the internal list of document updates and\n * its document key to the given target's mapping.\n */\n // Visible for testing.\n addDocumentToTarget(targetId: TargetId, document: MutableDocument): void {\n if (!this.isActiveTarget(targetId)) {\n return;\n }\n\n const changeType = this.targetContainsDocument(targetId, document.key)\n ? ChangeType.Modified\n : ChangeType.Added;\n\n const targetState = this.ensureTargetState(targetId);\n targetState.addDocumentChange(document.key, changeType);\n\n this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(\n document.key,\n document\n );\n\n this.pendingDocumentTargetMapping =\n this.pendingDocumentTargetMapping.insert(\n document.key,\n this.ensureDocumentTargetMapping(document.key).add(targetId)\n );\n }\n\n /**\n * Removes the provided document from the target mapping. If the\n * document no longer matches the target, but the document's state is still\n * known (e.g. we know that the document was deleted or we received the change\n * that caused the filter mismatch), the new document can be provided\n * to update the remote document cache.\n */\n // Visible for testing.\n removeDocumentFromTarget(\n targetId: TargetId,\n key: DocumentKey,\n updatedDocument: MutableDocument | null\n ): void {\n if (!this.isActiveTarget(targetId)) {\n return;\n }\n\n const targetState = this.ensureTargetState(targetId);\n if (this.targetContainsDocument(targetId, key)) {\n targetState.addDocumentChange(key, ChangeType.Removed);\n } else {\n // The document may have entered and left the target before we raised a\n // snapshot, so we can just ignore the change.\n targetState.removeDocumentChange(key);\n }\n\n this.pendingDocumentTargetMapping =\n this.pendingDocumentTargetMapping.insert(\n key,\n this.ensureDocumentTargetMapping(key).delete(targetId)\n );\n\n if (updatedDocument) {\n this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(\n key,\n updatedDocument\n );\n }\n }\n\n removeTarget(targetId: TargetId): void {\n this.targetStates.delete(targetId);\n }\n\n /**\n * Returns the current count of documents in the target. This includes both\n * the number of documents that the LocalStore considers to be part of the\n * target as well as any accumulated changes.\n */\n private getCurrentDocumentCountForTarget(targetId: TargetId): number {\n const targetState = this.ensureTargetState(targetId);\n const targetChange = targetState.toTargetChange();\n return (\n this.metadataProvider.getRemoteKeysForTarget(targetId).size +\n targetChange.addedDocuments.size -\n targetChange.removedDocuments.size\n );\n }\n\n /**\n * Increment the number of acks needed from watch before we can consider the\n * server to be 'in-sync' with the client's active targets.\n */\n recordPendingTargetRequest(targetId: TargetId): void {\n // For each request we get we need to record we need a response for it.\n const targetState = this.ensureTargetState(targetId);\n targetState.recordPendingTargetRequest();\n }\n\n private ensureTargetState(targetId: TargetId): TargetState {\n let result = this.targetStates.get(targetId);\n if (!result) {\n result = new TargetState();\n this.targetStates.set(targetId, result);\n }\n return result;\n }\n\n private ensureDocumentTargetMapping(key: DocumentKey): SortedSet<TargetId> {\n let targetMapping = this.pendingDocumentTargetMapping.get(key);\n\n if (!targetMapping) {\n targetMapping = new SortedSet<TargetId>(primitiveComparator);\n this.pendingDocumentTargetMapping =\n this.pendingDocumentTargetMapping.insert(key, targetMapping);\n }\n\n return targetMapping;\n }\n\n /**\n * Verifies that the user is still interested in this target (by calling\n * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs\n * from watch.\n */\n protected isActiveTarget(targetId: TargetId): boolean {\n const targetActive = this.targetDataForActiveTarget(targetId) !== null;\n if (!targetActive) {\n logDebug(LOG_TAG, 'Detected inactive target', targetId);\n }\n return targetActive;\n }\n\n /**\n * Returns the TargetData for an active target (i.e. a target that the user\n * is still interested in that has no outstanding target change requests).\n */\n protected targetDataForActiveTarget(targetId: TargetId): TargetData | null {\n const targetState = this.targetStates.get(targetId);\n return targetState && targetState.isPending\n ? null\n : this.metadataProvider.getTargetDataForTarget(targetId);\n }\n\n /**\n * Resets the state of a Watch target to its initial state (e.g. sets\n * 'current' to false, clears the resume token and removes its target mapping\n * from all documents).\n */\n private resetTarget(targetId: TargetId): void {\n debugAssert(\n !this.targetStates.get(targetId)!.isPending,\n 'Should only reset active targets'\n );\n this.targetStates.set(targetId, new TargetState());\n\n // Trigger removal for any documents currently mapped to this target.\n // These removals will be part of the initial snapshot if Watch does not\n // resend these documents.\n const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n existingKeys.forEach(key => {\n this.removeDocumentFromTarget(targetId, key, /*updatedDocument=*/ null);\n });\n }\n /**\n * Returns whether the LocalStore considers the document to be part of the\n * specified target.\n */\n private targetContainsDocument(\n targetId: TargetId,\n key: DocumentKey\n ): boolean {\n const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n return existingKeys.has(key);\n }\n}\n\nfunction documentTargetMap(): SortedMap<DocumentKey, SortedSet<TargetId>> {\n return new SortedMap<DocumentKey, SortedSet<TargetId>>(\n DocumentKey.comparator\n );\n}\n\nfunction snapshotChangesMap(): SortedMap<DocumentKey, ChangeType> {\n return new SortedMap<DocumentKey, ChangeType>(DocumentKey.comparator);\n}\n\nfunction createExistenceFilterMismatchInfoForTestingHooks(\n localCacheCount: number,\n existenceFilter: ExistenceFilter,\n databaseId: DatabaseId,\n bloomFilter: BloomFilter | null,\n bloomFilterStatus: BloomFilterApplicationStatus\n): TestingHooksExistenceFilterMismatchInfo {\n const result: TestingHooksExistenceFilterMismatchInfo = {\n localCacheCount,\n existenceFilterCount: existenceFilter.count,\n databaseId: databaseId.database,\n projectId: databaseId.projectId\n };\n\n const unchangedNames = existenceFilter.unchangedNames;\n if (unchangedNames) {\n result.bloomFilter = {\n applied: bloomFilterStatus === BloomFilterApplicationStatus.Success,\n hashCount: unchangedNames?.hashCount ?? 0,\n bitmapLength: unchangedNames?.bits?.bitmap?.length ?? 0,\n padding: unchangedNames?.bits?.padding ?? 0,\n mightContain: (value: string): boolean =>\n bloomFilter?.mightContain(value) ?? false\n };\n }\n\n return result;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Aggregate } from '../core/aggregate';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n compositeFilterIsFlatConjunction,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n LimitType,\n newQuery,\n newQueryForPath,\n Query,\n queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget, Target } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n DeleteMutation,\n FieldTransform,\n Mutation,\n MutationResult,\n PatchMutation,\n Precondition,\n SetMutation,\n VerifyMutation\n} from '../model/mutation';\nimport { normalizeTimestamp } from '../model/normalize';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform,\n TransformOperation\n} from '../model/transform_operation';\nimport { isNanValue, isNullValue } from '../model/values';\nimport {\n ApiClientObjectMap as ProtoApiClientObjectMap,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n CompositeFilterOp as ProtoCompositeFilterOp,\n Cursor as ProtoCursor,\n Document as ProtoDocument,\n DocumentMask as ProtoDocumentMask,\n DocumentsTarget as ProtoDocumentsTarget,\n FieldFilterOp as ProtoFieldFilterOp,\n FieldReference as ProtoFieldReference,\n FieldTransform as ProtoFieldTransform,\n Filter as ProtoFilter,\n ListenResponse as ProtoListenResponse,\n Order as ProtoOrder,\n OrderDirection as ProtoOrderDirection,\n Precondition as ProtoPrecondition,\n QueryTarget as ProtoQueryTarget,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n Aggregation as ProtoAggregation,\n Status as ProtoStatus,\n Target as ProtoTarget,\n TargetChangeTargetChangeType as ProtoTargetChangeTargetChangeType,\n Timestamp as ProtoTimestamp,\n Write as ProtoWrite,\n WriteResult as ProtoWriteResult\n} from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExistenceFilter } from './existence_filter';\nimport { Serializer } from './number_serializer';\nimport { mapCodeFromRpcCode } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n WatchChange,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst DIRECTIONS = (() => {\n const dirs: { [dir: string]: ProtoOrderDirection } = {};\n dirs[Direction.ASCENDING] = 'ASCENDING';\n dirs[Direction.DESCENDING] = 'DESCENDING';\n return dirs;\n})();\n\nconst OPERATORS = (() => {\n const ops: { [op: string]: ProtoFieldFilterOp } = {};\n ops[Operator.LESS_THAN] = 'LESS_THAN';\n ops[Operator.LESS_THAN_OR_EQUAL] = 'LESS_THAN_OR_EQUAL';\n ops[Operator.GREATER_THAN] = 'GREATER_THAN';\n ops[Operator.GREATER_THAN_OR_EQUAL] = 'GREATER_THAN_OR_EQUAL';\n ops[Operator.EQUAL] = 'EQUAL';\n ops[Operator.NOT_EQUAL] = 'NOT_EQUAL';\n ops[Operator.ARRAY_CONTAINS] = 'ARRAY_CONTAINS';\n ops[Operator.IN] = 'IN';\n ops[Operator.NOT_IN] = 'NOT_IN';\n ops[Operator.ARRAY_CONTAINS_ANY] = 'ARRAY_CONTAINS_ANY';\n return ops;\n})();\n\nconst COMPOSITE_OPERATORS = (() => {\n const ops: { [op: string]: ProtoCompositeFilterOp } = {};\n ops[CompositeOperator.AND] = 'AND';\n ops[CompositeOperator.OR] = 'OR';\n return ops;\n})();\n\nfunction assertPresent(value: unknown, description: string): asserts value {\n debugAssert(!isNullOrUndefined(value), description + ' is missing');\n}\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nexport class JsonProtoSerializer implements Serializer {\n constructor(\n readonly databaseId: DatabaseId,\n readonly useProto3Json: boolean\n ) {}\n}\n\nfunction fromRpcStatus(status: ProtoStatus): FirestoreError {\n const code =\n status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n}\n\n/**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: <number> } struct.\n */\nfunction toInt32Proto(\n serializer: JsonProtoSerializer,\n val: number | null\n): number | { value: number } | null {\n if (serializer.useProto3Json || isNullOrUndefined(val)) {\n return val;\n } else {\n return { value: val };\n }\n}\n\n/**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */\nfunction fromInt32Proto(\n val: number | { value: number } | undefined\n): number | null {\n let result;\n if (typeof val === 'object') {\n result = val.value;\n } else {\n result = val;\n }\n return isNullOrUndefined(result) ? null : result;\n}\n\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nexport function toTimestamp(\n serializer: JsonProtoSerializer,\n timestamp: Timestamp\n): ProtoTimestamp {\n if (serializer.useProto3Json) {\n // Serialize to ISO-8601 date format, but with full nano resolution.\n // Since JS Date has only millis, let's only use it for the seconds and\n // then manually add the fractions to the end.\n const jsDateStr = new Date(timestamp.seconds * 1000).toISOString();\n // Remove .xxx frac part and Z in the end.\n const strUntilSeconds = jsDateStr.replace(/\\.\\d*/, '').replace('Z', '');\n // Pad the fraction out to 9 digits (nanos).\n const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9);\n\n return `${strUntilSeconds}.${nanoStr}Z`;\n } else {\n return {\n seconds: '' + timestamp.seconds,\n nanos: timestamp.nanoseconds\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n}\n\nfunction fromTimestamp(date: ProtoTimestamp): Timestamp {\n const timestamp = normalizeTimestamp(date);\n return new Timestamp(timestamp.seconds, timestamp.nanos);\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nexport function toBytes(\n serializer: JsonProtoSerializer,\n bytes: ByteString\n): string | Uint8Array {\n if (serializer.useProto3Json) {\n return bytes.toBase64();\n } else {\n return bytes.toUint8Array();\n }\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */\nexport function fromBytes(\n serializer: JsonProtoSerializer,\n value: string | Uint8Array | undefined\n): ByteString {\n if (serializer.useProto3Json) {\n hardAssert(\n value === undefined || typeof value === 'string',\n 'value must be undefined or a string when using proto3 Json'\n );\n return ByteString.fromBase64String(value ? value : '');\n } else {\n hardAssert(\n value === undefined || value instanceof Uint8Array,\n 'value must be undefined or Uint8Array'\n );\n return ByteString.fromUint8Array(value ? value : new Uint8Array());\n }\n}\n\nexport function toVersion(\n serializer: JsonProtoSerializer,\n version: SnapshotVersion\n): ProtoTimestamp {\n return toTimestamp(serializer, version.toTimestamp());\n}\n\nexport function fromVersion(version: ProtoTimestamp): SnapshotVersion {\n hardAssert(!!version, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(fromTimestamp(version));\n}\n\nexport function toResourceName(\n databaseId: DatabaseId,\n path: ResourcePath\n): string {\n return fullyQualifiedPrefixPath(databaseId)\n .child('documents')\n .child(path)\n .canonicalString();\n}\n\nfunction fromResourceName(name: string): ResourcePath {\n const resource = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resource),\n 'Tried to deserialize invalid key ' + resource.toString()\n );\n return resource;\n}\n\nexport function toName(\n serializer: JsonProtoSerializer,\n key: DocumentKey\n): string {\n return toResourceName(serializer.databaseId, key.path);\n}\n\nexport function fromName(\n serializer: JsonProtoSerializer,\n name: string\n): DocumentKey {\n const resource = fromResourceName(name);\n\n if (resource.get(1) !== serializer.databaseId.projectId) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n serializer.databaseId.projectId\n );\n }\n\n if (resource.get(3) !== serializer.databaseId.database) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n serializer.databaseId.database\n );\n }\n return new DocumentKey(extractLocalPathFromResourceName(resource));\n}\n\nfunction toQueryPath(\n serializer: JsonProtoSerializer,\n path: ResourcePath\n): string {\n return toResourceName(serializer.databaseId, path);\n}\n\nfunction fromQueryPath(name: string): ResourcePath {\n const resourceName = fromResourceName(name);\n // In v1beta1 queries for collections at the root did not have a trailing\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n // ability to read the v1beta1 form for compatibility with queries persisted\n // in the local target cache.\n if (resourceName.length === 4) {\n return ResourcePath.emptyPath();\n }\n return extractLocalPathFromResourceName(resourceName);\n}\n\nexport function getEncodedDatabaseId(serializer: JsonProtoSerializer): string {\n const path = new ResourcePath([\n 'projects',\n serializer.databaseId.projectId,\n 'databases',\n serializer.databaseId.database\n ]);\n return path.canonicalString();\n}\n\nfunction fullyQualifiedPrefixPath(databaseId: DatabaseId): ResourcePath {\n return new ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n}\n\nfunction extractLocalPathFromResourceName(\n resourceName: ResourcePath\n): ResourcePath {\n hardAssert(\n resourceName.length > 4 && resourceName.get(4) === 'documents',\n 'tried to deserialize invalid key ' + resourceName.toString()\n );\n return resourceName.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */\nexport function toMutationDocument(\n serializer: JsonProtoSerializer,\n key: DocumentKey,\n fields: ObjectValue\n): ProtoDocument {\n return {\n name: toName(serializer, key),\n fields: fields.value.mapValue.fields\n };\n}\n\nexport function toDocument(\n serializer: JsonProtoSerializer,\n document: MutableDocument\n): ProtoDocument {\n debugAssert(\n !document.hasLocalMutations,\n \"Can't serialize documents with mutations.\"\n );\n return {\n name: toName(serializer, document.key),\n fields: document.data.value.mapValue.fields,\n updateTime: toTimestamp(serializer, document.version.toTimestamp()),\n createTime: toTimestamp(serializer, document.createTime.toTimestamp())\n };\n}\n\nexport function fromDocument(\n serializer: JsonProtoSerializer,\n document: ProtoDocument,\n hasCommittedMutations?: boolean\n): MutableDocument {\n const key = fromName(serializer, document.name!);\n const version = fromVersion(document.updateTime!);\n // If we read a document from persistence that is missing createTime, it's due\n // to older SDK versions not storing this information. In such cases, we'll\n // set the createTime to zero. This can be removed in the long term.\n const createTime = document.createTime\n ? fromVersion(document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: document.fields } });\n const result = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n if (hasCommittedMutations) {\n result.setHasCommittedMutations();\n }\n return hasCommittedMutations ? result.setHasCommittedMutations() : result;\n}\n\nfunction fromFound(\n serializer: JsonProtoSerializer,\n doc: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!doc.found,\n 'Tried to deserialize a found document from a missing document.'\n );\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n const key = fromName(serializer, doc.found.name);\n const version = fromVersion(doc.found.updateTime);\n const createTime = doc.found.createTime\n ? fromVersion(doc.found.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: doc.found.fields } });\n return MutableDocument.newFoundDocument(key, version, createTime, data);\n}\n\nfunction fromMissing(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!result.missing,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 'Tried to deserialize a missing document without a read time.'\n );\n const key = fromName(serializer, result.missing);\n const version = fromVersion(result.readTime);\n return MutableDocument.newNoDocument(key, version);\n}\n\nexport function fromBatchGetDocumentsResponse(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n if ('found' in result) {\n return fromFound(serializer, result);\n } else if ('missing' in result) {\n return fromMissing(serializer, result);\n }\n return fail('invalid batch get response: ' + JSON.stringify(result));\n}\n\nexport function fromWatchChange(\n serializer: JsonProtoSerializer,\n change: ProtoListenResponse\n): WatchChange {\n let watchChange: WatchChange;\n if ('targetChange' in change) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const state = fromWatchTargetChangeState(\n change.targetChange.targetChangeType || 'NO_CHANGE'\n );\n const targetIds: TargetId[] = change.targetChange.targetIds || [];\n\n const resumeToken = fromBytes(serializer, change.targetChange.resumeToken);\n const causeProto = change.targetChange!.cause;\n const cause = causeProto && fromRpcStatus(causeProto);\n watchChange = new WatchTargetChange(\n state,\n targetIds,\n resumeToken,\n cause || null\n );\n } else if ('documentChange' in change) {\n assertPresent(change.documentChange, 'documentChange');\n const entityChange = change.documentChange;\n assertPresent(entityChange.document, 'documentChange.name');\n assertPresent(entityChange.document.name, 'documentChange.document.name');\n assertPresent(\n entityChange.document.updateTime,\n 'documentChange.document.updateTime'\n );\n const key = fromName(serializer, entityChange.document.name);\n const version = fromVersion(entityChange.document.updateTime);\n const createTime = entityChange.document.createTime\n ? fromVersion(entityChange.document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({\n mapValue: { fields: entityChange.document.fields }\n });\n const doc = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n const updatedTargetIds = entityChange.targetIds || [];\n const removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(\n updatedTargetIds,\n removedTargetIds,\n doc.key,\n doc\n );\n } else if ('documentDelete' in change) {\n assertPresent(change.documentDelete, 'documentDelete');\n const docDelete = change.documentDelete;\n assertPresent(docDelete.document, 'documentDelete.document');\n const key = fromName(serializer, docDelete.document);\n const version = docDelete.readTime\n ? fromVersion(docDelete.readTime)\n : SnapshotVersion.min();\n const doc = MutableDocument.newNoDocument(key, version);\n const removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n } else if ('documentRemove' in change) {\n assertPresent(change.documentRemove, 'documentRemove');\n const docRemove = change.documentRemove;\n assertPresent(docRemove.document, 'documentRemove');\n const key = fromName(serializer, docRemove.document);\n const removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n } else if ('filter' in change) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n const filter = change.filter;\n assertPresent(filter.targetId, 'filter.targetId');\n const { count = 0, unchangedNames } = filter;\n const existenceFilter = new ExistenceFilter(count, unchangedNames);\n const targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n } else {\n return fail('Unknown change type ' + JSON.stringify(change));\n }\n return watchChange;\n}\n\nfunction fromWatchTargetChangeState(\n state: ProtoTargetChangeTargetChangeType\n): WatchTargetChangeState {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n } else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n } else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n } else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n } else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n } else {\n return fail('Got unexpected TargetChange.state: ' + state);\n }\n}\n\nexport function versionFromListenResponse(\n change: ProtoListenResponse\n): SnapshotVersion {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n if (!('targetChange' in change)) {\n return SnapshotVersion.min();\n }\n const targetChange = change.targetChange!;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return SnapshotVersion.min();\n }\n if (!targetChange.readTime) {\n return SnapshotVersion.min();\n }\n return fromVersion(targetChange.readTime);\n}\n\nexport function toMutation(\n serializer: JsonProtoSerializer,\n mutation: Mutation\n): ProtoWrite {\n let result: ProtoWrite;\n if (mutation instanceof SetMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.value)\n };\n } else if (mutation instanceof DeleteMutation) {\n result = { delete: toName(serializer, mutation.key) };\n } else if (mutation instanceof PatchMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.data),\n updateMask: toDocumentMask(mutation.fieldMask)\n };\n } else if (mutation instanceof VerifyMutation) {\n result = {\n verify: toName(serializer, mutation.key)\n };\n } else {\n return fail('Unknown mutation type ' + mutation.type);\n }\n\n if (mutation.fieldTransforms.length > 0) {\n result.updateTransforms = mutation.fieldTransforms.map(transform =>\n toFieldTransform(serializer, transform)\n );\n }\n\n if (!mutation.precondition.isNone) {\n result.currentDocument = toPrecondition(serializer, mutation.precondition);\n }\n\n return result;\n}\n\nexport function fromMutation(\n serializer: JsonProtoSerializer,\n proto: ProtoWrite\n): Mutation {\n const precondition = proto.currentDocument\n ? fromPrecondition(proto.currentDocument)\n : Precondition.none();\n\n const fieldTransforms = proto.updateTransforms\n ? proto.updateTransforms.map(transform =>\n fromFieldTransform(serializer, transform)\n )\n : [];\n\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n const key = fromName(serializer, proto.update.name);\n const value = new ObjectValue({\n mapValue: { fields: proto.update.fields }\n });\n\n if (proto.updateMask) {\n const fieldMask = fromDocumentMask(proto.updateMask);\n return new PatchMutation(\n key,\n value,\n fieldMask,\n precondition,\n fieldTransforms\n );\n } else {\n return new SetMutation(key, value, precondition, fieldTransforms);\n }\n } else if (proto.delete) {\n const key = fromName(serializer, proto.delete);\n return new DeleteMutation(key, precondition);\n } else if (proto.verify) {\n const key = fromName(serializer, proto.verify);\n return new VerifyMutation(key, precondition);\n } else {\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\n }\n}\n\nfunction toPrecondition(\n serializer: JsonProtoSerializer,\n precondition: Precondition\n): ProtoPrecondition {\n debugAssert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: toVersion(serializer, precondition.updateTime)\n };\n } else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n } else {\n return fail('Unknown precondition');\n }\n}\n\nfunction fromPrecondition(precondition: ProtoPrecondition): Precondition {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(fromVersion(precondition.updateTime));\n } else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n } else {\n return Precondition.none();\n }\n}\n\nfunction fromWriteResult(\n proto: ProtoWriteResult,\n commitTime: ProtoTimestamp\n): MutationResult {\n // NOTE: Deletes don't have an updateTime.\n let version = proto.updateTime\n ? fromVersion(proto.updateTime)\n : fromVersion(commitTime);\n\n if (version.isEqual(SnapshotVersion.min())) {\n // The Firestore Emulator currently returns an update time of 0 for\n // deletes of non-existing documents (rather than null). This breaks the\n // test \"get deleted doc while offline with source=cache\" as NoDocuments\n // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n // TODO(#2149): Remove this when Emulator is fixed\n version = fromVersion(commitTime);\n }\n\n return new MutationResult(version, proto.transformResults || []);\n}\n\nexport function fromWriteResults(\n protos: ProtoWriteResult[] | undefined,\n commitTime?: ProtoTimestamp\n): MutationResult[] {\n if (protos && protos.length > 0) {\n hardAssert(\n commitTime !== undefined,\n 'Received a write result without a commit time'\n );\n return protos.map(proto => fromWriteResult(proto, commitTime));\n } else {\n return [];\n }\n}\n\nfunction toFieldTransform(\n serializer: JsonProtoSerializer,\n fieldTransform: FieldTransform\n): ProtoFieldTransform {\n const transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n appendMissingElements: {\n values: transform.elements\n }\n };\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n removeAllFromArray: {\n values: transform.elements\n }\n };\n } else if (transform instanceof NumericIncrementTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n increment: transform.operand\n };\n } else {\n throw fail('Unknown transform: ' + fieldTransform.transform);\n }\n}\n\nfunction fromFieldTransform(\n serializer: JsonProtoSerializer,\n proto: ProtoFieldTransform\n): FieldTransform {\n let transform: TransformOperation | null = null;\n if ('setToServerValue' in proto) {\n hardAssert(\n proto.setToServerValue === 'REQUEST_TIME',\n 'Unknown server value transform proto: ' + JSON.stringify(proto)\n );\n transform = new ServerTimestampTransform();\n } else if ('appendMissingElements' in proto) {\n const values = proto.appendMissingElements!.values || [];\n transform = new ArrayUnionTransformOperation(values);\n } else if ('removeAllFromArray' in proto) {\n const values = proto.removeAllFromArray!.values || [];\n transform = new ArrayRemoveTransformOperation(values);\n } else if ('increment' in proto) {\n transform = new NumericIncrementTransformOperation(\n serializer,\n proto.increment!\n );\n } else {\n fail('Unknown transform proto: ' + JSON.stringify(proto));\n }\n const fieldPath = FieldPath.fromServerFormat(proto.fieldPath!);\n return new FieldTransform(fieldPath, transform!);\n}\n\nexport function toDocumentsTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): ProtoDocumentsTarget {\n return { documents: [toQueryPath(serializer, target.path)] };\n}\n\nexport function fromDocumentsTarget(\n documentsTarget: ProtoDocumentsTarget\n): Target {\n const count = documentsTarget.documents!.length;\n hardAssert(\n count === 1,\n 'DocumentsTarget contained other than 1 document: ' + count\n );\n const name = documentsTarget.documents![0];\n return queryToTarget(newQueryForPath(fromQueryPath(name)));\n}\n\nexport function toQueryTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): ProtoQueryTarget {\n // Dissect the path into parent, collectionId, and optional key filter.\n const result: ProtoQueryTarget = { structuredQuery: {} };\n const path = target.path;\n if (target.collectionGroup !== null) {\n debugAssert(\n path.length % 2 === 0,\n 'Collection Group queries should be within a document path or root.'\n );\n result.parent = toQueryPath(serializer, path);\n result.structuredQuery!.from = [\n {\n collectionId: target.collectionGroup,\n allDescendants: true\n }\n ];\n } else {\n debugAssert(\n path.length % 2 !== 0,\n 'Document queries with filters are not supported.'\n );\n result.parent = toQueryPath(serializer, path.popLast());\n result.structuredQuery!.from = [{ collectionId: path.lastSegment() }];\n }\n\n const where = toFilters(target.filters);\n if (where) {\n result.structuredQuery!.where = where;\n }\n\n const orderBy = toOrder(target.orderBy);\n if (orderBy) {\n result.structuredQuery!.orderBy = orderBy;\n }\n\n const limit = toInt32Proto(serializer, target.limit);\n if (limit !== null) {\n result.structuredQuery!.limit = limit;\n }\n\n if (target.startAt) {\n result.structuredQuery!.startAt = toStartAtCursor(target.startAt);\n }\n if (target.endAt) {\n result.structuredQuery!.endAt = toEndAtCursor(target.endAt);\n }\n\n return result;\n}\n\nexport function toRunAggregationQueryRequest(\n serializer: JsonProtoSerializer,\n target: Target,\n aggregates: Aggregate[]\n): {\n request: ProtoRunAggregationQueryRequest;\n aliasMap: Record<string, string>;\n} {\n const queryTarget = toQueryTarget(serializer, target);\n const aliasMap: Record<string, string> = {};\n\n const aggregations: ProtoAggregation[] = [];\n let aggregationNum = 0;\n\n aggregates.forEach(aggregate => {\n // Map all client-side aliases to a unique short-form\n // alias. This avoids issues with client-side aliases that\n // exceed the 1500-byte string size limit.\n const serverAlias = `aggregate_${aggregationNum++}`;\n aliasMap[serverAlias] = aggregate.alias;\n\n if (aggregate.aggregateType === 'count') {\n aggregations.push({\n alias: serverAlias,\n count: {}\n });\n } else if (aggregate.aggregateType === 'avg') {\n aggregations.push({\n alias: serverAlias,\n avg: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n } else if (aggregate.aggregateType === 'sum') {\n aggregations.push({\n alias: serverAlias,\n sum: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n }\n });\n\n return {\n request: {\n structuredAggregationQuery: {\n aggregations,\n structuredQuery: queryTarget.structuredQuery\n },\n parent: queryTarget.parent\n },\n aliasMap\n };\n}\n\nexport function convertQueryTargetToQuery(target: ProtoQueryTarget): Query {\n let path = fromQueryPath(target.parent!);\n\n const query = target.structuredQuery!;\n const fromCount = query.from ? query.from.length : 0;\n let collectionGroup: string | null = null;\n if (fromCount > 0) {\n hardAssert(\n fromCount === 1,\n 'StructuredQuery.from with more than one collection is not supported.'\n );\n const from = query.from![0];\n if (from.allDescendants) {\n collectionGroup = from.collectionId!;\n } else {\n path = path.child(from.collectionId!);\n }\n }\n\n let filterBy: Filter[] = [];\n if (query.where) {\n filterBy = fromFilters(query.where);\n }\n\n let orderBy: OrderBy[] = [];\n if (query.orderBy) {\n orderBy = fromOrder(query.orderBy);\n }\n\n let limit: number | null = null;\n if (query.limit) {\n limit = fromInt32Proto(query.limit);\n }\n\n let startAt: Bound | null = null;\n if (query.startAt) {\n startAt = fromStartAtCursor(query.startAt);\n }\n\n let endAt: Bound | null = null;\n if (query.endAt) {\n endAt = fromEndAtCursor(query.endAt);\n }\n\n return newQuery(\n path,\n collectionGroup,\n orderBy,\n filterBy,\n limit,\n LimitType.First,\n startAt,\n endAt\n );\n}\n\nexport function fromQueryTarget(target: ProtoQueryTarget): Target {\n return queryToTarget(convertQueryTargetToQuery(target));\n}\n\nexport function toListenRequestLabels(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoApiClientObjectMap<string> | null {\n const value = toLabel(targetData.purpose);\n if (value == null) {\n return null;\n } else {\n return {\n 'goog-listen-tags': value\n };\n }\n}\n\nexport function toLabel(purpose: TargetPurpose): string | null {\n switch (purpose) {\n case TargetPurpose.Listen:\n return null;\n case TargetPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case TargetPurpose.ExistenceFilterMismatchBloom:\n return 'existence-filter-mismatch-bloom';\n case TargetPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail('Unrecognized query purpose: ' + purpose);\n }\n}\n\nexport function toTarget(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoTarget {\n let result: ProtoTarget;\n const target = targetData.target;\n\n if (targetIsDocumentTarget(target)) {\n result = { documents: toDocumentsTarget(serializer, target) };\n } else {\n result = { query: toQueryTarget(serializer, target) };\n }\n\n result.targetId = targetData.targetId;\n\n if (targetData.resumeToken.approximateByteSize() > 0) {\n result.resumeToken = toBytes(serializer, targetData.resumeToken);\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n } else if (targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n // TODO(wuandy): Consider removing above check because it is most likely true.\n // Right now, many tests depend on this behaviour though (leaving min() out\n // of serialization).\n result.readTime = toTimestamp(\n serializer,\n targetData.snapshotVersion.toTimestamp()\n );\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n }\n\n return result;\n}\n\nfunction toFilters(filters: Filter[]): ProtoFilter | undefined {\n if (filters.length === 0) {\n return;\n }\n\n return toFilter(CompositeFilter.create(filters, CompositeOperator.AND));\n}\n\nfunction fromFilters(filter: ProtoFilter): Filter[] {\n const result = fromFilter(filter);\n\n if (\n result instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(result)\n ) {\n return result.getFilters();\n }\n\n return [result];\n}\n\nfunction fromFilter(filter: ProtoFilter): Filter {\n if (filter.unaryFilter !== undefined) {\n return fromUnaryFilter(filter);\n } else if (filter.fieldFilter !== undefined) {\n return fromFieldFilter(filter);\n } else if (filter.compositeFilter !== undefined) {\n return fromCompositeFilter(filter);\n } else {\n return fail('Unknown filter: ' + JSON.stringify(filter));\n }\n}\n\nfunction toOrder(orderBys: OrderBy[]): ProtoOrder[] | undefined {\n if (orderBys.length === 0) {\n return;\n }\n return orderBys.map(order => toPropertyOrder(order));\n}\n\nfunction fromOrder(orderBys: ProtoOrder[]): OrderBy[] {\n return orderBys.map(order => fromPropertyOrder(order));\n}\n\nfunction toStartAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction toEndAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: !cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction fromStartAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !!cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\nfunction fromEndAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\n// visible for testing\nexport function toDirection(dir: Direction): ProtoOrderDirection {\n return DIRECTIONS[dir];\n}\n\n// visible for testing\nexport function fromDirection(\n dir: ProtoOrderDirection | undefined\n): Direction | undefined {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n}\n\n// visible for testing\nexport function toOperatorName(op: Operator): ProtoFieldFilterOp {\n return OPERATORS[op];\n}\n\nexport function toCompositeOperatorName(\n op: CompositeOperator\n): ProtoCompositeFilterOp {\n return COMPOSITE_OPERATORS[op];\n}\n\nexport function fromOperatorName(op: ProtoFieldFilterOp): Operator {\n switch (op) {\n case 'EQUAL':\n return Operator.EQUAL;\n case 'NOT_EQUAL':\n return Operator.NOT_EQUAL;\n case 'GREATER_THAN':\n return Operator.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return Operator.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return Operator.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return Operator.LESS_THAN_OR_EQUAL;\n case 'ARRAY_CONTAINS':\n return Operator.ARRAY_CONTAINS;\n case 'IN':\n return Operator.IN;\n case 'NOT_IN':\n return Operator.NOT_IN;\n case 'ARRAY_CONTAINS_ANY':\n return Operator.ARRAY_CONTAINS_ANY;\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified operator');\n default:\n return fail('Unknown operator');\n }\n}\n\nexport function fromCompositeOperatorName(\n op: ProtoCompositeFilterOp\n): CompositeOperator {\n switch (op) {\n case 'AND':\n return CompositeOperator.AND;\n case 'OR':\n return CompositeOperator.OR;\n default:\n return fail('Unknown operator');\n }\n}\n\nexport function toFieldPathReference(path: FieldPath): ProtoFieldReference {\n return { fieldPath: path.canonicalString() };\n}\n\nexport function fromFieldPathReference(\n fieldReference: ProtoFieldReference\n): FieldPath {\n return FieldPath.fromServerFormat(fieldReference.fieldPath!);\n}\n\n// visible for testing\nexport function toPropertyOrder(orderBy: OrderBy): ProtoOrder {\n return {\n field: toFieldPathReference(orderBy.field),\n direction: toDirection(orderBy.dir)\n };\n}\n\nexport function fromPropertyOrder(orderBy: ProtoOrder): OrderBy {\n return new OrderBy(\n fromFieldPathReference(orderBy.field!),\n fromDirection(orderBy.direction)\n );\n}\n\n// visible for testing\nexport function toFilter(filter: Filter): ProtoFilter {\n if (filter instanceof FieldFilter) {\n return toUnaryOrFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return toCompositeFilter(filter);\n } else {\n return fail('Unrecognized filter type ' + JSON.stringify(filter));\n }\n}\n\nexport function toCompositeFilter(filter: CompositeFilter): ProtoFilter {\n const protos = filter.getFilters().map(filter => toFilter(filter));\n\n if (protos.length === 1) {\n return protos[0];\n }\n\n return {\n compositeFilter: {\n op: toCompositeOperatorName(filter.op),\n filters: protos\n }\n };\n}\n\nexport function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter {\n if (filter.op === Operator.EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n } else if (filter.op === Operator.NOT_EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NULL'\n }\n };\n }\n }\n return {\n fieldFilter: {\n field: toFieldPathReference(filter.field),\n op: toOperatorName(filter.op),\n value: filter.value\n }\n };\n}\n\nexport function fromUnaryFilter(filter: ProtoFilter): Filter {\n switch (filter.unaryFilter!.op!) {\n case 'IS_NAN':\n const nanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nanField, Operator.EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NULL':\n const nullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nullField, Operator.EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'IS_NOT_NAN':\n const notNanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNanField, Operator.NOT_EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NOT_NULL':\n const notNullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNullField, Operator.NOT_EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified filter');\n default:\n return fail('Unknown filter');\n }\n}\n\nexport function fromFieldFilter(filter: ProtoFilter): FieldFilter {\n return FieldFilter.create(\n fromFieldPathReference(filter.fieldFilter!.field!),\n fromOperatorName(filter.fieldFilter!.op!),\n filter.fieldFilter!.value!\n );\n}\n\nexport function fromCompositeFilter(filter: ProtoFilter): CompositeFilter {\n return CompositeFilter.create(\n filter.compositeFilter!.filters!.map(filter => fromFilter(filter)),\n fromCompositeOperatorName(filter.compositeFilter!.op!)\n );\n}\n\nexport function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask {\n const canonicalFields: string[] = [];\n fieldMask.fields.forEach(field =>\n canonicalFields.push(field.canonicalString())\n );\n return {\n fieldPaths: canonicalFields\n };\n}\n\nexport function fromDocumentMask(proto: ProtoDocumentMask): FieldMask {\n const paths = proto.fieldPaths || [];\n return new FieldMask(paths.map(path => FieldPath.fromServerFormat(path)));\n}\n\nexport function isValidResourceName(path: ResourcePath): boolean {\n // Resource names have at least 4 components (project ID, database ID)\n return (\n path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases'\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Target } from '../core/target';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { ByteString } from '../util/byte_string';\n\n/** An enumeration of the different purposes we have for targets. */\nexport const enum TargetPurpose {\n /** A regular, normal query target. */\n Listen = 'TargetPurposeListen',\n\n /**\n * The query target was used to refill a query after an existence filter\n * mismatch.\n */\n ExistenceFilterMismatch = 'TargetPurposeExistenceFilterMismatch',\n\n /**\n * The query target was used if the query is the result of a false positive in\n * the bloom filter.\n */\n ExistenceFilterMismatchBloom = 'TargetPurposeExistenceFilterMismatchBloom',\n\n /** The query target was used to resolve a limbo document. */\n LimboResolution = 'TargetPurposeLimboResolution'\n}\n\n/**\n * An immutable set of metadata that the local store tracks for each target.\n */\nexport class TargetData {\n constructor(\n /** The target being listened to. */\n readonly target: Target,\n /**\n * The target ID to which the target corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n readonly targetId: TargetId,\n /** The purpose of the target. */\n readonly purpose: TargetPurpose,\n /**\n * The sequence number of the last transaction during which this target data\n * was modified.\n */\n readonly sequenceNumber: ListenSequenceNumber,\n /** The latest snapshot version seen for this target. */\n readonly snapshotVersion: SnapshotVersion = SnapshotVersion.min(),\n /**\n * The maximum snapshot version at which the associated view\n * contained no limbo documents.\n */\n readonly lastLimboFreeSnapshotVersion: SnapshotVersion = SnapshotVersion.min(),\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n readonly resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING,\n /**\n * The number of documents that last matched the query at the resume token or\n * read time. Documents are counted only when making a listen request with\n * resume token or read time, otherwise, keep it null.\n */\n readonly expectedCount: number | null = null\n ) {}\n\n /** Creates a new target data instance with an updated sequence number. */\n withSequenceNumber(sequenceNumber: number): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n sequenceNumber,\n this.snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n this.resumeToken,\n this.expectedCount\n );\n }\n\n /**\n * Creates a new target data instance with an updated resume token and\n * snapshot version.\n */\n withResumeToken(\n resumeToken: ByteString,\n snapshotVersion: SnapshotVersion\n ): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n resumeToken,\n /* expectedCount= */ null\n );\n }\n\n /**\n * Creates a new target data instance with an updated expected count.\n */\n withExpectedCount(expectedCount: number): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n this.snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n this.resumeToken,\n expectedCount\n );\n }\n\n /**\n * Creates a new target data instance with an updated last limbo free\n * snapshot version number.\n */\n withLastLimboFreeSnapshotVersion(\n lastLimboFreeSnapshotVersion: SnapshotVersion\n ): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n this.snapshotVersion,\n lastLimboFreeSnapshotVersion,\n this.resumeToken,\n this.expectedCount\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../api/timestamp';\nimport { User } from '../auth/user';\nimport { BundleMetadata, NamedQuery } from '../core/bundle';\nimport { LimitType, Query, queryWithLimit } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetIsDocumentTarget } from '../core/target';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n IndexOffset,\n IndexSegment,\n IndexState\n} from '../model/field_index';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { Overlay } from '../model/overlay';\nimport { FieldPath } from '../model/path';\nimport {\n BundledQuery as ProtoBundledQuery,\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { DocumentsTarget as PublicDocumentsTarget } from '../protos/firestore_proto_api';\nimport {\n convertQueryTargetToQuery,\n fromDocument,\n fromDocumentsTarget,\n fromMutation,\n fromQueryTarget,\n fromVersion,\n JsonProtoSerializer,\n toDocument,\n toDocumentsTarget,\n toMutation,\n toQueryTarget\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport {\n DbBundle,\n DbDocumentOverlay,\n DbIndexConfiguration,\n DbIndexState,\n DbMutationBatch,\n DbNamedQuery,\n DbQuery,\n DbRemoteDocument,\n DbTarget,\n DbTimestamp\n} from './indexeddb_schema';\nimport { DbDocumentOverlayKey, DbTimestampKey } from './indexeddb_sentinels';\nimport { TargetData, TargetPurpose } from './target_data';\n\n/** Serializer for values stored in the LocalStore. */\nexport class LocalSerializer {\n constructor(readonly remoteSerializer: JsonProtoSerializer) {}\n}\n\n/** Decodes a remote document from storage locally to a Document. */\nexport function fromDbRemoteDocument(\n localSerializer: LocalSerializer,\n remoteDoc: DbRemoteDocument\n): MutableDocument {\n let doc: MutableDocument;\n if (remoteDoc.document) {\n doc = fromDocument(\n localSerializer.remoteSerializer,\n remoteDoc.document,\n !!remoteDoc.hasCommittedMutations\n );\n } else if (remoteDoc.noDocument) {\n const key = DocumentKey.fromSegments(remoteDoc.noDocument.path);\n const version = fromDbTimestamp(remoteDoc.noDocument.readTime);\n doc = MutableDocument.newNoDocument(key, version);\n if (remoteDoc.hasCommittedMutations) {\n doc.setHasCommittedMutations();\n }\n } else if (remoteDoc.unknownDocument) {\n const key = DocumentKey.fromSegments(remoteDoc.unknownDocument.path);\n const version = fromDbTimestamp(remoteDoc.unknownDocument.version);\n doc = MutableDocument.newUnknownDocument(key, version);\n } else {\n return fail('Unexpected DbRemoteDocument');\n }\n\n if (remoteDoc.readTime) {\n doc.setReadTime(fromDbTimestampKey(remoteDoc.readTime));\n }\n\n return doc;\n}\n\n/** Encodes a document for storage locally. */\nexport function toDbRemoteDocument(\n localSerializer: LocalSerializer,\n document: MutableDocument\n): DbRemoteDocument {\n const key = document.key;\n const remoteDoc: DbRemoteDocument = {\n prefixPath: key.getCollectionPath().popLast().toArray(),\n collectionGroup: key.collectionGroup,\n documentId: key.path.lastSegment(),\n readTime: toDbTimestampKey(document.readTime),\n hasCommittedMutations: document.hasCommittedMutations\n };\n\n if (document.isFoundDocument()) {\n remoteDoc.document = toDocument(localSerializer.remoteSerializer, document);\n } else if (document.isNoDocument()) {\n remoteDoc.noDocument = {\n path: key.path.toArray(),\n readTime: toDbTimestamp(document.version)\n };\n } else if (document.isUnknownDocument()) {\n remoteDoc.unknownDocument = {\n path: key.path.toArray(),\n version: toDbTimestamp(document.version)\n };\n } else {\n return fail('Unexpected Document ' + document);\n }\n return remoteDoc;\n}\n\nexport function toDbTimestampKey(\n snapshotVersion: SnapshotVersion\n): DbTimestampKey {\n const timestamp = snapshotVersion.toTimestamp();\n return [timestamp.seconds, timestamp.nanoseconds];\n}\n\nexport function fromDbTimestampKey(\n dbTimestampKey: DbTimestampKey\n): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestampKey[0], dbTimestampKey[1]);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\nexport function toDbTimestamp(snapshotVersion: SnapshotVersion): DbTimestamp {\n const timestamp = snapshotVersion.toTimestamp();\n return { seconds: timestamp.seconds, nanoseconds: timestamp.nanoseconds };\n}\n\nfunction fromDbTimestamp(dbTimestamp: DbTimestamp): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestamp.seconds, dbTimestamp.nanoseconds);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\n/** Encodes a batch of mutations into a DbMutationBatch for local storage. */\nexport function toDbMutationBatch(\n localSerializer: LocalSerializer,\n userId: string,\n batch: MutationBatch\n): DbMutationBatch {\n const serializedBaseMutations = batch.baseMutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n const serializedMutations = batch.mutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n return {\n userId,\n batchId: batch.batchId,\n localWriteTimeMs: batch.localWriteTime.toMillis(),\n baseMutations: serializedBaseMutations,\n mutations: serializedMutations\n };\n}\n\n/** Decodes a DbMutationBatch into a MutationBatch */\nexport function fromDbMutationBatch(\n localSerializer: LocalSerializer,\n dbBatch: DbMutationBatch\n): MutationBatch {\n const baseMutations = (dbBatch.baseMutations || []).map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n\n // Squash old transform mutations into existing patch or set mutations.\n // The replacement of representing `transforms` with `update_transforms`\n // on the SDK means that old `transform` mutations stored in IndexedDB need\n // to be updated to `update_transforms`.\n // TODO(b/174608374): Remove this code once we perform a schema migration.\n for (let i = 0; i < dbBatch.mutations.length - 1; ++i) {\n const currentMutation = dbBatch.mutations[i];\n const hasTransform =\n i + 1 < dbBatch.mutations.length &&\n dbBatch.mutations[i + 1].transform !== undefined;\n if (hasTransform) {\n debugAssert(\n dbBatch.mutations[i].transform === undefined &&\n dbBatch.mutations[i].update !== undefined,\n 'TransformMutation should be preceded by a patch or set mutation'\n );\n const transformMutation = dbBatch.mutations[i + 1];\n currentMutation.updateTransforms =\n transformMutation.transform!.fieldTransforms;\n dbBatch.mutations.splice(i + 1, 1);\n ++i;\n }\n }\n\n const mutations = dbBatch.mutations.map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n const timestamp = Timestamp.fromMillis(dbBatch.localWriteTimeMs);\n return new MutationBatch(\n dbBatch.batchId,\n timestamp,\n baseMutations,\n mutations\n );\n}\n\n/** Decodes a DbTarget into TargetData */\nexport function fromDbTarget(dbTarget: DbTarget): TargetData {\n const version = fromDbTimestamp(dbTarget.readTime);\n const lastLimboFreeSnapshotVersion =\n dbTarget.lastLimboFreeSnapshotVersion !== undefined\n ? fromDbTimestamp(dbTarget.lastLimboFreeSnapshotVersion)\n : SnapshotVersion.min();\n\n let target: Target;\n if (isDocumentQuery(dbTarget.query)) {\n target = fromDocumentsTarget(dbTarget.query);\n } else {\n target = fromQueryTarget(dbTarget.query);\n }\n return new TargetData(\n target,\n dbTarget.targetId,\n TargetPurpose.Listen,\n dbTarget.lastListenSequenceNumber,\n version,\n lastLimboFreeSnapshotVersion,\n ByteString.fromBase64String(dbTarget.resumeToken)\n );\n}\n\n/** Encodes TargetData into a DbTarget for storage locally. */\nexport function toDbTarget(\n localSerializer: LocalSerializer,\n targetData: TargetData\n): DbTarget {\n debugAssert(\n TargetPurpose.Listen === targetData.purpose,\n 'Only queries with purpose ' +\n TargetPurpose.Listen +\n ' may be stored, got ' +\n targetData.purpose\n );\n const dbTimestamp = toDbTimestamp(targetData.snapshotVersion);\n const dbLastLimboFreeTimestamp = toDbTimestamp(\n targetData.lastLimboFreeSnapshotVersion\n );\n let queryProto: DbQuery;\n if (targetIsDocumentTarget(targetData.target)) {\n queryProto = toDocumentsTarget(\n localSerializer.remoteSerializer,\n targetData.target\n );\n } else {\n queryProto = toQueryTarget(\n localSerializer.remoteSerializer,\n targetData.target\n );\n }\n\n // We can't store the resumeToken as a ByteString in IndexedDb, so we\n // convert it to a base64 string for storage.\n const resumeToken = targetData.resumeToken.toBase64();\n\n // lastListenSequenceNumber is always 0 until we do real GC.\n return {\n targetId: targetData.targetId,\n canonicalId: canonifyTarget(targetData.target),\n readTime: dbTimestamp,\n resumeToken,\n lastListenSequenceNumber: targetData.sequenceNumber,\n lastLimboFreeSnapshotVersion: dbLastLimboFreeTimestamp,\n query: queryProto\n };\n}\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\nfunction isDocumentQuery(dbQuery: DbQuery): dbQuery is PublicDocumentsTarget {\n return (dbQuery as PublicDocumentsTarget).documents !== undefined;\n}\n\n/** Encodes a DbBundle to a BundleMetadata object. */\nexport function fromDbBundle(dbBundle: DbBundle): BundleMetadata {\n return {\n id: dbBundle.bundleId,\n createTime: fromDbTimestamp(dbBundle.createTime),\n version: dbBundle.version\n };\n}\n\n/** Encodes a BundleMetadata to a DbBundle. */\nexport function toDbBundle(metadata: ProtoBundleMetadata): DbBundle {\n return {\n bundleId: metadata.id!,\n createTime: toDbTimestamp(fromVersion(metadata.createTime!)),\n version: metadata.version!\n };\n}\n\n/** Encodes a DbNamedQuery to a NamedQuery. */\nexport function fromDbNamedQuery(dbNamedQuery: DbNamedQuery): NamedQuery {\n return {\n name: dbNamedQuery.name,\n query: fromBundledQuery(dbNamedQuery.bundledQuery),\n readTime: fromDbTimestamp(dbNamedQuery.readTime)\n };\n}\n\n/** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */\nexport function toDbNamedQuery(query: ProtoNamedQuery): DbNamedQuery {\n return {\n name: query.name!,\n readTime: toDbTimestamp(fromVersion(query.readTime!)),\n bundledQuery: query.bundledQuery!\n };\n}\n\n/**\n * Encodes a `BundledQuery` from bundle proto to a Query object.\n *\n * This reconstructs the original query used to build the bundle being loaded,\n * including features exists only in SDKs (for example: limit-to-last).\n */\nexport function fromBundledQuery(bundledQuery: ProtoBundledQuery): Query {\n const query = convertQueryTargetToQuery({\n parent: bundledQuery.parent!,\n structuredQuery: bundledQuery.structuredQuery!\n });\n if (bundledQuery.limitType === 'LAST') {\n debugAssert(\n !!query.limit,\n 'Bundled query has limitType LAST, but limit is null'\n );\n return queryWithLimit(query, query.limit, LimitType.Last);\n }\n return query;\n}\n\n/** Encodes a NamedQuery proto object to a NamedQuery model object. */\nexport function fromProtoNamedQuery(namedQuery: ProtoNamedQuery): NamedQuery {\n return {\n name: namedQuery.name!,\n query: fromBundledQuery(namedQuery.bundledQuery!),\n readTime: fromVersion(namedQuery.readTime!)\n };\n}\n\n/** Decodes a BundleMetadata proto into a BundleMetadata object. */\nexport function fromBundleMetadata(\n metadata: ProtoBundleMetadata\n): BundleMetadata {\n return {\n id: metadata.id!,\n version: metadata.version!,\n createTime: fromVersion(metadata.createTime!)\n };\n}\n\n/** Encodes a DbDocumentOverlay object to an Overlay model object. */\nexport function fromDbDocumentOverlay(\n localSerializer: LocalSerializer,\n dbDocumentOverlay: DbDocumentOverlay\n): Overlay {\n return new Overlay(\n dbDocumentOverlay.largestBatchId,\n fromMutation(\n localSerializer.remoteSerializer,\n dbDocumentOverlay.overlayMutation\n )\n );\n}\n\n/** Decodes an Overlay model object into a DbDocumentOverlay object. */\nexport function toDbDocumentOverlay(\n localSerializer: LocalSerializer,\n userId: string,\n overlay: Overlay\n): DbDocumentOverlay {\n const [_, collectionPath, documentId] = toDbDocumentOverlayKey(\n userId,\n overlay.mutation.key\n );\n return {\n userId,\n collectionPath,\n documentId,\n collectionGroup: overlay.mutation.key.getCollectionGroup(),\n largestBatchId: overlay.largestBatchId,\n overlayMutation: toMutation(\n localSerializer.remoteSerializer,\n overlay.mutation\n )\n };\n}\n\n/**\n * Returns the DbDocumentOverlayKey corresponding to the given user and\n * document key.\n */\nexport function toDbDocumentOverlayKey(\n userId: string,\n docKey: DocumentKey\n): DbDocumentOverlayKey {\n const docId = docKey.path.lastSegment();\n const collectionPath = encodeResourcePath(docKey.path.popLast());\n return [userId, collectionPath, docId];\n}\n\nexport function toDbIndexConfiguration(\n index: FieldIndex\n): DbIndexConfiguration {\n return {\n indexId: index.indexId,\n collectionGroup: index.collectionGroup,\n fields: index.fields.map(s => [s.fieldPath.canonicalString(), s.kind])\n };\n}\n\nexport function fromDbIndexConfiguration(\n index: DbIndexConfiguration,\n state: DbIndexState | null\n): FieldIndex {\n const decodedState = state\n ? new IndexState(\n state.sequenceNumber,\n new IndexOffset(\n fromDbTimestamp(state.readTime),\n new DocumentKey(decodeResourcePath(state.documentKey)),\n state.largestBatchId\n )\n )\n : IndexState.empty();\n const decodedSegments = index.fields.map(\n ([fieldPath, kind]) =>\n new IndexSegment(FieldPath.fromServerFormat(fieldPath), kind)\n );\n return new FieldIndex(\n index.indexId!,\n index.collectionGroup,\n decodedSegments,\n decodedState\n );\n}\n\nexport function toDbIndexState(\n indexId: number,\n user: User,\n sequenceNumber: number,\n offset: IndexOffset\n): DbIndexState {\n return {\n indexId,\n uid: user.uid || '',\n sequenceNumber,\n readTime: toDbTimestamp(offset.readTime),\n documentKey: encodeResourcePath(offset.documentKey.path),\n largestBatchId: offset.largestBatchId\n };\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { normalizeByteString, normalizeNumber } from '../model/normalize';\nimport { isMaxValue } from '../model/values';\nimport { ArrayValue, MapValue, Value } from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport { isNegativeZero } from '../util/types';\n\nimport { DirectionalIndexByteEncoder } from './directional_index_byte_encoder';\n\n// Note: This code is copied from the backend. Code that is not used by\n// Firestore was removed.\n\nconst INDEX_TYPE_NULL = 5;\nconst INDEX_TYPE_BOOLEAN = 10;\nconst INDEX_TYPE_NAN = 13;\nconst INDEX_TYPE_NUMBER = 15;\nconst INDEX_TYPE_TIMESTAMP = 20;\nconst INDEX_TYPE_STRING = 25;\nconst INDEX_TYPE_BLOB = 30;\nconst INDEX_TYPE_REFERENCE = 37;\nconst INDEX_TYPE_GEOPOINT = 45;\nconst INDEX_TYPE_ARRAY = 50;\nconst INDEX_TYPE_MAP = 55;\nconst INDEX_TYPE_REFERENCE_SEGMENT = 60;\n\n// A terminator that indicates that a truncatable value was not truncated.\n// This must be smaller than all other type labels.\nconst NOT_TRUNCATED = 2;\n\n/** Firestore index value writer. */\nexport class FirestoreIndexValueWriter {\n static INSTANCE = new FirestoreIndexValueWriter();\n\n private constructor() {}\n\n // The write methods below short-circuit writing terminators for values\n // containing a (terminating) truncated value.\n //\n // As an example, consider the resulting encoding for:\n //\n // [\"bar\", [2, \"foo\"]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TERM, TERM, TERM)\n // [\"bar\", [2, truncated(\"foo\")]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TRUNC)\n // [\"bar\", truncated([\"foo\"])] -> (STRING, \"bar\", TERM, ARRAY. STRING, \"foo\", TERM, TRUNC)\n\n /** Writes an index value. */\n writeIndexValue(value: Value, encoder: DirectionalIndexByteEncoder): void {\n this.writeIndexValueAux(value, encoder);\n // Write separator to split index values\n // (see go/firestore-storage-format#encodings).\n encoder.writeInfinity();\n }\n\n private writeIndexValueAux(\n indexValue: Value,\n encoder: DirectionalIndexByteEncoder\n ): void {\n if ('nullValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NULL);\n } else if ('booleanValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_BOOLEAN);\n encoder.writeNumber(indexValue.booleanValue ? 1 : 0);\n } else if ('integerValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NUMBER);\n encoder.writeNumber(normalizeNumber(indexValue.integerValue));\n } else if ('doubleValue' in indexValue) {\n const n = normalizeNumber(indexValue.doubleValue);\n if (isNaN(n)) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NAN);\n } else {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NUMBER);\n if (isNegativeZero(n)) {\n // -0.0, 0 and 0.0 are all considered the same\n encoder.writeNumber(0.0);\n } else {\n encoder.writeNumber(n);\n }\n }\n } else if ('timestampValue' in indexValue) {\n const timestamp = indexValue.timestampValue!;\n this.writeValueTypeLabel(encoder, INDEX_TYPE_TIMESTAMP);\n if (typeof timestamp === 'string') {\n encoder.writeString(timestamp);\n } else {\n encoder.writeString(`${timestamp.seconds || ''}`);\n encoder.writeNumber(timestamp.nanos || 0);\n }\n } else if ('stringValue' in indexValue) {\n this.writeIndexString(indexValue.stringValue!, encoder);\n this.writeTruncationMarker(encoder);\n } else if ('bytesValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_BLOB);\n encoder.writeBytes(normalizeByteString(indexValue.bytesValue!));\n this.writeTruncationMarker(encoder);\n } else if ('referenceValue' in indexValue) {\n this.writeIndexEntityRef(indexValue.referenceValue!, encoder);\n } else if ('geoPointValue' in indexValue) {\n const geoPoint = indexValue.geoPointValue!;\n this.writeValueTypeLabel(encoder, INDEX_TYPE_GEOPOINT);\n encoder.writeNumber(geoPoint.latitude || 0);\n encoder.writeNumber(geoPoint.longitude || 0);\n } else if ('mapValue' in indexValue) {\n if (isMaxValue(indexValue)) {\n this.writeValueTypeLabel(encoder, Number.MAX_SAFE_INTEGER);\n } else {\n this.writeIndexMap(indexValue.mapValue!, encoder);\n this.writeTruncationMarker(encoder);\n }\n } else if ('arrayValue' in indexValue) {\n this.writeIndexArray(indexValue.arrayValue!, encoder);\n this.writeTruncationMarker(encoder);\n } else {\n fail('unknown index value type ' + indexValue);\n }\n }\n\n private writeIndexString(\n stringIndexValue: string,\n encoder: DirectionalIndexByteEncoder\n ): void {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_STRING);\n this.writeUnlabeledIndexString(stringIndexValue, encoder);\n }\n\n private writeUnlabeledIndexString(\n stringIndexValue: string,\n encoder: DirectionalIndexByteEncoder\n ): void {\n encoder.writeString(stringIndexValue);\n }\n\n private writeIndexMap(\n mapIndexValue: MapValue,\n encoder: DirectionalIndexByteEncoder\n ): void {\n const map = mapIndexValue.fields || {};\n this.writeValueTypeLabel(encoder, INDEX_TYPE_MAP);\n for (const key of Object.keys(map)) {\n this.writeIndexString(key, encoder);\n this.writeIndexValueAux(map[key], encoder);\n }\n }\n\n private writeIndexArray(\n arrayIndexValue: ArrayValue,\n encoder: DirectionalIndexByteEncoder\n ): void {\n const values = arrayIndexValue.values || [];\n this.writeValueTypeLabel(encoder, INDEX_TYPE_ARRAY);\n for (const element of values) {\n this.writeIndexValueAux(element, encoder);\n }\n }\n\n private writeIndexEntityRef(\n referenceValue: string,\n encoder: DirectionalIndexByteEncoder\n ): void {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_REFERENCE);\n const path = DocumentKey.fromName(referenceValue).path;\n path.forEach(segment => {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_REFERENCE_SEGMENT);\n this.writeUnlabeledIndexString(segment, encoder);\n });\n }\n\n private writeValueTypeLabel(\n encoder: DirectionalIndexByteEncoder,\n typeOrder: number\n ): void {\n encoder.writeNumber(typeOrder);\n }\n\n private writeTruncationMarker(encoder: DirectionalIndexByteEncoder): void {\n // While the SDK does not implement truncation, the truncation marker is\n // used to terminate all variable length values (which are strings, bytes,\n // references, arrays and maps).\n encoder.writeNumber(NOT_TRUNCATED);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Target } from '../core/target';\nimport { DocumentMap } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex, IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager, IndexType } from './index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory implementation of IndexManager.\n */\nexport class MemoryIndexManager implements IndexManager {\n private collectionParentIndex = new MemoryCollectionParentIndex();\n\n addToCollectionParentIndex(\n transaction: PersistenceTransaction,\n collectionPath: ResourcePath\n ): PersistencePromise<void> {\n this.collectionParentIndex.add(collectionPath);\n return PersistencePromise.resolve();\n }\n\n getCollectionParents(\n transaction: PersistenceTransaction,\n collectionId: string\n ): PersistencePromise<ResourcePath[]> {\n return PersistencePromise.resolve(\n this.collectionParentIndex.getEntries(collectionId)\n );\n }\n\n addFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n deleteFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n deleteAllFieldIndexes(\n transaction: PersistenceTransaction\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n createTargetIndexes(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n getDocumentsMatchingTarget(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<DocumentKey[] | null> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve<DocumentKey[] | null>(null);\n }\n\n getIndexType(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<IndexType> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve<IndexType>(IndexType.NONE);\n }\n\n getFieldIndexes(\n transaction: PersistenceTransaction,\n collectionGroup?: string\n ): PersistencePromise<FieldIndex[]> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve<FieldIndex[]>([]);\n }\n\n getNextCollectionGroupToUpdate(\n transaction: PersistenceTransaction\n ): PersistencePromise<string | null> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve<string | null>(null);\n }\n\n getMinOffset(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<IndexOffset> {\n return PersistencePromise.resolve(IndexOffset.min());\n }\n\n getMinOffsetFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string\n ): PersistencePromise<IndexOffset> {\n return PersistencePromise.resolve(IndexOffset.min());\n }\n\n updateCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n updateIndexEntries(\n transaction: PersistenceTransaction,\n documents: DocumentMap\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n}\n\n/**\n * Internal implementation of the collection-parent index exposed by MemoryIndexManager.\n * Also used for in-memory caching by IndexedDbIndexManager and initial index population\n * in indexeddb_schema.ts\n */\nexport class MemoryCollectionParentIndex {\n private index = {} as {\n [collectionId: string]: SortedSet<ResourcePath>;\n };\n\n // Returns false if the entry already existed.\n add(collectionPath: ResourcePath): boolean {\n debugAssert(collectionPath.length % 2 === 1, 'Expected a collection path.');\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n const existingParents =\n this.index[collectionId] ||\n new SortedSet<ResourcePath>(ResourcePath.comparator);\n const added = !existingParents.has(parentPath);\n this.index[collectionId] = existingParents.add(parentPath);\n return added;\n }\n\n has(collectionPath: ResourcePath): boolean {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n const existingParents = this.index[collectionId];\n return existingParents && existingParents.has(parentPath);\n }\n\n getEntries(collectionId: string): ResourcePath[] {\n const parentPaths =\n this.index[collectionId] ||\n new SortedSet<ResourcePath>(ResourcePath.comparator);\n return parentPaths.toArray();\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport {\n canonifyTarget,\n newTarget,\n Target,\n targetEquals,\n targetGetArrayValues,\n targetGetLowerBound,\n targetGetNotInValues,\n targetGetSegmentCount,\n targetGetUpperBound,\n targetHasLimit\n} from '../core/target';\nimport { FirestoreIndexValueWriter } from '../index/firestore_index_value_writer';\nimport { IndexByteEncoder } from '../index/index_byte_encoder';\nimport { IndexEntry, indexEntryComparator } from '../index/index_entry';\nimport { documentKeySet, DocumentMap } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n fieldIndexGetKeyOrder,\n fieldIndexToString,\n IndexKind,\n IndexOffset,\n indexOffsetComparator,\n IndexSegment\n} from '../model/field_index';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { TargetIndexMatcher } from '../model/target_index_matcher';\nimport { isArray, refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { logDebug } from '../util/log';\nimport { getDnfTerms } from '../util/logic_utils';\nimport { immediateSuccessor, primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { diffSortedSets, SortedSet } from '../util/sorted_set';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexManager, IndexType } from './index_manager';\nimport {\n DbCollectionParent,\n DbIndexConfiguration,\n DbIndexEntry,\n DbIndexState\n} from './indexeddb_schema';\nimport {\n DbCollectionParentKey,\n DbCollectionParentStore,\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationKey,\n DbIndexConfigurationStore,\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryKey,\n DbIndexEntryStore,\n DbIndexStateKey,\n DbIndexStateSequenceNumberIndex,\n DbIndexStateStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbIndexConfiguration,\n toDbIndexConfiguration,\n toDbIndexState\n} from './local_serializer';\nimport { MemoryCollectionParentIndex } from './memory_index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nconst LOG_TAG = 'IndexedDbIndexManager';\n\nconst EMPTY_VALUE = new Uint8Array(0);\n\n/**\n * A persisted implementation of IndexManager.\n *\n * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index\n * data as it supports multi-tab access.\n */\nexport class IndexedDbIndexManager implements IndexManager {\n /**\n * An in-memory copy of the index entries we've already written since the SDK\n * launched. Used to avoid re-writing the same entry repeatedly.\n *\n * This is *NOT* a complete cache of what's in persistence and so can never be\n * used to satisfy reads.\n */\n private collectionParentsCache = new MemoryCollectionParentIndex();\n\n private uid: string;\n\n /**\n * Maps from a target to its equivalent list of sub-targets. Each sub-target\n * contains only one term from the target's disjunctive normal form (DNF).\n */\n private targetToDnfSubTargets = new ObjectMap<Target, Target[]>(\n t => canonifyTarget(t),\n (l, r) => targetEquals(l, r)\n );\n\n constructor(private user: User, private readonly databaseId: DatabaseId) {\n this.uid = user.uid || '';\n }\n\n /**\n * Adds a new entry to the collection parent index.\n *\n * Repeated calls for the same collectionPath should be avoided within a\n * transaction as IndexedDbIndexManager only caches writes once a transaction\n * has been committed.\n */\n addToCollectionParentIndex(\n transaction: PersistenceTransaction,\n collectionPath: ResourcePath\n ): PersistencePromise<void> {\n debugAssert(collectionPath.length % 2 === 1, 'Expected a collection path.');\n if (!this.collectionParentsCache.has(collectionPath)) {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n\n transaction.addOnCommittedListener(() => {\n // Add the collection to the in memory cache only if the transaction was\n // successfully committed.\n this.collectionParentsCache.add(collectionPath);\n });\n\n const collectionParent: DbCollectionParent = {\n collectionId,\n parent: encodeResourcePath(parentPath)\n };\n return collectionParentsStore(transaction).put(collectionParent);\n }\n return PersistencePromise.resolve();\n }\n\n getCollectionParents(\n transaction: PersistenceTransaction,\n collectionId: string\n ): PersistencePromise<ResourcePath[]> {\n const parentPaths = [] as ResourcePath[];\n const range = IDBKeyRange.bound(\n [collectionId, ''],\n [immediateSuccessor(collectionId), ''],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n return collectionParentsStore(transaction)\n .loadAll(range)\n .next(entries => {\n for (const entry of entries) {\n // This collectionId guard shouldn't be necessary (and isn't as long\n // as we're running in a real browser), but there's a bug in\n // indexeddbshim that breaks our range in our tests running in node:\n // https://github.com/axemclion/IndexedDBShim/issues/334\n if (entry.collectionId !== collectionId) {\n break;\n }\n parentPaths.push(decodeResourcePath(entry.parent));\n }\n return parentPaths;\n });\n }\n\n addFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise<void> {\n // TODO(indexing): Verify that the auto-incrementing index ID works in\n // Safari & Firefox.\n const indexes = indexConfigurationStore(transaction);\n const dbIndex = toDbIndexConfiguration(index);\n delete dbIndex.indexId; // `indexId` is auto-populated by IndexedDb\n const result = indexes.add(dbIndex);\n if (index.indexState) {\n const states = indexStateStore(transaction);\n return result.next(indexId => {\n states.put(\n toDbIndexState(\n indexId,\n this.user,\n index.indexState.sequenceNumber,\n index.indexState.offset\n )\n );\n });\n } else {\n return result.next();\n }\n }\n\n deleteFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise<void> {\n const indexes = indexConfigurationStore(transaction);\n const states = indexStateStore(transaction);\n const entries = indexEntriesStore(transaction);\n return indexes\n .delete(index.indexId)\n .next(() =>\n states.delete(\n IDBKeyRange.bound(\n [index.indexId],\n [index.indexId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n )\n )\n )\n .next(() =>\n entries.delete(\n IDBKeyRange.bound(\n [index.indexId],\n [index.indexId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n )\n )\n );\n }\n\n deleteAllFieldIndexes(\n transaction: PersistenceTransaction\n ): PersistencePromise<void> {\n const indexes = indexConfigurationStore(transaction);\n const entries = indexEntriesStore(transaction);\n const states = indexStateStore(transaction);\n\n return indexes\n .deleteAll()\n .next(() => entries.deleteAll())\n .next(() => states.deleteAll());\n }\n\n createTargetIndexes(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<void> {\n return PersistencePromise.forEach(\n this.getSubTargets(target),\n (subTarget: Target) => {\n return this.getIndexType(transaction, subTarget).next(type => {\n if (type === IndexType.NONE || type === IndexType.PARTIAL) {\n const targetIndexMatcher = new TargetIndexMatcher(subTarget);\n const fieldIndex = targetIndexMatcher.buildTargetIndex();\n if (fieldIndex != null) {\n return this.addFieldIndex(transaction, fieldIndex);\n }\n }\n });\n }\n );\n }\n\n getDocumentsMatchingTarget(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<DocumentKey[] | null> {\n const indexEntries = indexEntriesStore(transaction);\n\n let canServeTarget = true;\n const indexes = new Map<Target, FieldIndex | null>();\n\n return PersistencePromise.forEach(\n this.getSubTargets(target),\n (subTarget: Target) => {\n return this.getFieldIndex(transaction, subTarget).next(index => {\n canServeTarget &&= !!index;\n indexes.set(subTarget, index);\n });\n }\n ).next(() => {\n if (!canServeTarget) {\n return PersistencePromise.resolve(null as DocumentKey[] | null);\n } else {\n let existingKeys = documentKeySet();\n const result: DocumentKey[] = [];\n return PersistencePromise.forEach(indexes, (index, subTarget) => {\n logDebug(\n LOG_TAG,\n `Using index ${fieldIndexToString(\n index!\n )} to execute ${canonifyTarget(target)}`\n );\n\n const arrayValues = targetGetArrayValues(subTarget, index!);\n const notInValues = targetGetNotInValues(subTarget, index!);\n const lowerBound = targetGetLowerBound(subTarget, index!);\n const upperBound = targetGetUpperBound(subTarget, index!);\n\n const lowerBoundEncoded = this.encodeBound(\n index!,\n subTarget,\n lowerBound\n );\n const upperBoundEncoded = this.encodeBound(\n index!,\n subTarget,\n upperBound\n );\n const notInEncoded = this.encodeValues(\n index!,\n subTarget,\n notInValues\n );\n\n const indexRanges = this.generateIndexRanges(\n index!.indexId,\n arrayValues,\n lowerBoundEncoded,\n lowerBound.inclusive,\n upperBoundEncoded,\n upperBound.inclusive,\n notInEncoded\n );\n return PersistencePromise.forEach(\n indexRanges,\n (indexRange: IDBKeyRange) => {\n return indexEntries\n .loadFirst(indexRange, target.limit)\n .next(entries => {\n entries.forEach(entry => {\n const documentKey = DocumentKey.fromSegments(\n entry.documentKey\n );\n if (!existingKeys.has(documentKey)) {\n existingKeys = existingKeys.add(documentKey);\n result.push(documentKey);\n }\n });\n });\n }\n );\n }).next(() => result as DocumentKey[] | null);\n }\n });\n }\n\n private getSubTargets(target: Target): Target[] {\n let subTargets = this.targetToDnfSubTargets.get(target);\n if (subTargets) {\n return subTargets;\n }\n\n if (target.filters.length === 0) {\n subTargets = [target];\n } else {\n // There is an implicit AND operation between all the filters stored in the target\n const dnf: Filter[] = getDnfTerms(\n CompositeFilter.create(target.filters, CompositeOperator.AND)\n );\n\n subTargets = dnf.map(term =>\n newTarget(\n target.path,\n target.collectionGroup,\n target.orderBy,\n term.getFilters(),\n target.limit,\n target.startAt,\n target.endAt\n )\n );\n }\n\n this.targetToDnfSubTargets.set(target, subTargets);\n return subTargets;\n }\n\n /**\n * Constructs a key range query on `DbIndexEntryStore` that unions all\n * bounds.\n */\n private generateIndexRanges(\n indexId: number,\n arrayValues: ProtoValue[] | null,\n lowerBounds: Uint8Array[],\n lowerBoundInclusive: boolean,\n upperBounds: Uint8Array[],\n upperBoundInclusive: boolean,\n notInValues: Uint8Array[]\n ): IDBKeyRange[] {\n // The number of total index scans we union together. This is similar to a\n // distributed normal form, but adapted for array values. We create a single\n // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter\n // combined with the values from the query bounds.\n const totalScans =\n (arrayValues != null ? arrayValues.length : 1) *\n Math.max(lowerBounds.length, upperBounds.length);\n const scansPerArrayElement =\n totalScans / (arrayValues != null ? arrayValues.length : 1);\n\n const indexRanges: IDBKeyRange[] = [];\n for (let i = 0; i < totalScans; ++i) {\n const arrayValue = arrayValues\n ? this.encodeSingleElement(arrayValues[i / scansPerArrayElement])\n : EMPTY_VALUE;\n\n const lowerBound = this.generateLowerBound(\n indexId,\n arrayValue,\n lowerBounds[i % scansPerArrayElement],\n lowerBoundInclusive\n );\n const upperBound = this.generateUpperBound(\n indexId,\n arrayValue,\n upperBounds[i % scansPerArrayElement],\n upperBoundInclusive\n );\n\n const notInBound = notInValues.map(notIn =>\n this.generateLowerBound(\n indexId,\n arrayValue,\n notIn,\n /* inclusive= */ true\n )\n );\n\n indexRanges.push(...this.createRange(lowerBound, upperBound, notInBound));\n }\n\n return indexRanges;\n }\n\n /** Generates the lower bound for `arrayValue` and `directionalValue`. */\n private generateLowerBound(\n indexId: number,\n arrayValue: Uint8Array,\n directionalValue: Uint8Array,\n inclusive: boolean\n ): IndexEntry {\n const entry = new IndexEntry(\n indexId,\n DocumentKey.empty(),\n arrayValue,\n directionalValue\n );\n return inclusive ? entry : entry.successor();\n }\n\n /** Generates the upper bound for `arrayValue` and `directionalValue`. */\n private generateUpperBound(\n indexId: number,\n arrayValue: Uint8Array,\n directionalValue: Uint8Array,\n inclusive: boolean\n ): IndexEntry {\n const entry = new IndexEntry(\n indexId,\n DocumentKey.empty(),\n arrayValue,\n directionalValue\n );\n return inclusive ? entry.successor() : entry;\n }\n\n private getFieldIndex(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<FieldIndex | null> {\n const targetIndexMatcher = new TargetIndexMatcher(target);\n const collectionGroup =\n target.collectionGroup != null\n ? target.collectionGroup\n : target.path.lastSegment();\n\n return this.getFieldIndexes(transaction, collectionGroup).next(indexes => {\n // Return the index with the most number of segments.\n let index: FieldIndex | null = null;\n for (const candidate of indexes) {\n const matches = targetIndexMatcher.servedByIndex(candidate);\n if (\n matches &&\n (!index || candidate.fields.length > index.fields.length)\n ) {\n index = candidate;\n }\n }\n return index;\n });\n }\n\n getIndexType(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<IndexType> {\n let indexType = IndexType.FULL;\n const subTargets = this.getSubTargets(target);\n return PersistencePromise.forEach(subTargets, (target: Target) => {\n return this.getFieldIndex(transaction, target).next(index => {\n if (!index) {\n indexType = IndexType.NONE;\n } else if (\n indexType !== IndexType.NONE &&\n index.fields.length < targetGetSegmentCount(target)\n ) {\n indexType = IndexType.PARTIAL;\n }\n });\n }).next(() => {\n // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider\n // OR queries that have a `limit` to have a partial index. For such queries we perform sorting\n // and apply the limit in memory as a post-processing step.\n if (\n targetHasLimit(target) &&\n subTargets.length > 1 &&\n indexType === IndexType.FULL\n ) {\n return IndexType.PARTIAL;\n }\n\n return indexType;\n });\n }\n\n /**\n * Returns the byte encoded form of the directional values in the field index.\n * Returns `null` if the document does not have all fields specified in the\n * index.\n */\n private encodeDirectionalElements(\n fieldIndex: FieldIndex,\n document: Document\n ): Uint8Array | null {\n const encoder = new IndexByteEncoder();\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const field = document.data.field(segment.fieldPath);\n if (field == null) {\n return null;\n }\n const directionalEncoder = encoder.forKind(segment.kind);\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n field,\n directionalEncoder\n );\n }\n return encoder.encodedBytes();\n }\n\n /** Encodes a single value to the ascending index format. */\n private encodeSingleElement(value: ProtoValue): Uint8Array {\n const encoder = new IndexByteEncoder();\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n value,\n encoder.forKind(IndexKind.ASCENDING)\n );\n return encoder.encodedBytes();\n }\n\n /**\n * Returns an encoded form of the document key that sorts based on the key\n * ordering of the field index.\n */\n private encodeDirectionalKey(\n fieldIndex: FieldIndex,\n documentKey: DocumentKey\n ): Uint8Array {\n const encoder = new IndexByteEncoder();\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n refValue(this.databaseId, documentKey),\n encoder.forKind(fieldIndexGetKeyOrder(fieldIndex))\n );\n return encoder.encodedBytes();\n }\n\n /**\n * Encodes the given field values according to the specification in `target`.\n * For IN queries, a list of possible values is returned.\n */\n private encodeValues(\n fieldIndex: FieldIndex,\n target: Target,\n values: ProtoValue[] | null\n ): Uint8Array[] {\n if (values === null) {\n return [];\n }\n\n let encoders: IndexByteEncoder[] = [];\n encoders.push(new IndexByteEncoder());\n\n let valueIdx = 0;\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const value = values[valueIdx++];\n for (const encoder of encoders) {\n if (this.isInFilter(target, segment.fieldPath) && isArray(value)) {\n encoders = this.expandIndexValues(encoders, segment, value);\n } else {\n const directionalEncoder = encoder.forKind(segment.kind);\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n value,\n directionalEncoder\n );\n }\n }\n }\n return this.getEncodedBytes(encoders);\n }\n\n /**\n * Encodes the given bounds according to the specification in `target`. For IN\n * queries, a list of possible values is returned.\n */\n private encodeBound(\n fieldIndex: FieldIndex,\n target: Target,\n bound: Bound\n ): Uint8Array[] {\n return this.encodeValues(fieldIndex, target, bound.position);\n }\n\n /** Returns the byte representation for the provided encoders. */\n private getEncodedBytes(encoders: IndexByteEncoder[]): Uint8Array[] {\n const result: Uint8Array[] = [];\n for (let i = 0; i < encoders.length; ++i) {\n result[i] = encoders[i].encodedBytes();\n }\n return result;\n }\n\n /**\n * Creates a separate encoder for each element of an array.\n *\n * The method appends each value to all existing encoders (e.g. filter(\"a\",\n * \"==\", \"a1\").filter(\"b\", \"in\", [\"b1\", \"b2\"]) becomes [\"a1,b1\", \"a1,b2\"]). A\n * list of new encoders is returned.\n */\n private expandIndexValues(\n encoders: IndexByteEncoder[],\n segment: IndexSegment,\n value: ProtoValue\n ): IndexByteEncoder[] {\n const prefixes = [...encoders];\n const results: IndexByteEncoder[] = [];\n for (const arrayElement of value.arrayValue!.values || []) {\n for (const prefix of prefixes) {\n const clonedEncoder = new IndexByteEncoder();\n clonedEncoder.seed(prefix.encodedBytes());\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n arrayElement,\n clonedEncoder.forKind(segment.kind)\n );\n results.push(clonedEncoder);\n }\n }\n return results;\n }\n\n private isInFilter(target: Target, fieldPath: FieldPath): boolean {\n return !!target.filters.find(\n f =>\n f instanceof FieldFilter &&\n f.field.isEqual(fieldPath) &&\n (f.op === Operator.IN || f.op === Operator.NOT_IN)\n );\n }\n\n getFieldIndexes(\n transaction: PersistenceTransaction,\n collectionGroup?: string\n ): PersistencePromise<FieldIndex[]> {\n const indexes = indexConfigurationStore(transaction);\n const states = indexStateStore(transaction);\n\n return (\n collectionGroup\n ? indexes.loadAll(\n DbIndexConfigurationCollectionGroupIndex,\n IDBKeyRange.bound(collectionGroup, collectionGroup)\n )\n : indexes.loadAll()\n ).next(indexConfigs => {\n const result: FieldIndex[] = [];\n return PersistencePromise.forEach(\n indexConfigs,\n (indexConfig: DbIndexConfiguration) => {\n return states\n .get([indexConfig.indexId!, this.uid])\n .next(indexState => {\n result.push(fromDbIndexConfiguration(indexConfig, indexState));\n });\n }\n ).next(() => result);\n });\n }\n\n getNextCollectionGroupToUpdate(\n transaction: PersistenceTransaction\n ): PersistencePromise<string | null> {\n return this.getFieldIndexes(transaction).next(indexes => {\n if (indexes.length === 0) {\n return null;\n }\n indexes.sort((l, r) => {\n const cmp = l.indexState.sequenceNumber - r.indexState.sequenceNumber;\n return cmp !== 0\n ? cmp\n : primitiveComparator(l.collectionGroup, r.collectionGroup);\n });\n return indexes[0].collectionGroup;\n });\n }\n\n updateCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset\n ): PersistencePromise<void> {\n const indexes = indexConfigurationStore(transaction);\n const states = indexStateStore(transaction);\n return this.getNextSequenceNumber(transaction).next(nextSequenceNumber =>\n indexes\n .loadAll(\n DbIndexConfigurationCollectionGroupIndex,\n IDBKeyRange.bound(collectionGroup, collectionGroup)\n )\n .next(configs =>\n PersistencePromise.forEach(configs, (config: DbIndexConfiguration) =>\n states.put(\n toDbIndexState(\n config.indexId!,\n this.user,\n nextSequenceNumber,\n offset\n )\n )\n )\n )\n );\n }\n\n updateIndexEntries(\n transaction: PersistenceTransaction,\n documents: DocumentMap\n ): PersistencePromise<void> {\n // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as\n // it could be used across different IndexedDB transactions. As any cached\n // data might be invalidated by other multi-tab clients, we can only trust\n // data within a single IndexedDB transaction. We therefore add a cache\n // here.\n const memoizedIndexes = new Map<string, FieldIndex[]>();\n return PersistencePromise.forEach(documents, (key, doc) => {\n const memoizedCollectionIndexes = memoizedIndexes.get(\n key.collectionGroup\n );\n const fieldIndexes = memoizedCollectionIndexes\n ? PersistencePromise.resolve(memoizedCollectionIndexes)\n : this.getFieldIndexes(transaction, key.collectionGroup);\n\n return fieldIndexes.next(fieldIndexes => {\n memoizedIndexes.set(key.collectionGroup, fieldIndexes);\n return PersistencePromise.forEach(\n fieldIndexes,\n (fieldIndex: FieldIndex) => {\n return this.getExistingIndexEntries(\n transaction,\n key,\n fieldIndex\n ).next(existingEntries => {\n const newEntries = this.computeIndexEntries(doc, fieldIndex);\n if (!existingEntries.isEqual(newEntries)) {\n return this.updateEntries(\n transaction,\n doc,\n fieldIndex,\n existingEntries,\n newEntries\n );\n }\n return PersistencePromise.resolve();\n });\n }\n );\n });\n });\n }\n\n private addIndexEntry(\n transaction: PersistenceTransaction,\n document: Document,\n fieldIndex: FieldIndex,\n indexEntry: IndexEntry\n ): PersistencePromise<void> {\n const indexEntries = indexEntriesStore(transaction);\n return indexEntries.put({\n indexId: indexEntry.indexId,\n uid: this.uid,\n arrayValue: indexEntry.arrayValue,\n directionalValue: indexEntry.directionalValue,\n orderedDocumentKey: this.encodeDirectionalKey(fieldIndex, document.key),\n documentKey: document.key.path.toArray()\n });\n }\n\n private deleteIndexEntry(\n transaction: PersistenceTransaction,\n document: Document,\n fieldIndex: FieldIndex,\n indexEntry: IndexEntry\n ): PersistencePromise<void> {\n const indexEntries = indexEntriesStore(transaction);\n return indexEntries.delete([\n indexEntry.indexId,\n this.uid,\n indexEntry.arrayValue,\n indexEntry.directionalValue,\n this.encodeDirectionalKey(fieldIndex, document.key),\n document.key.path.toArray()\n ]);\n }\n\n private getExistingIndexEntries(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey,\n fieldIndex: FieldIndex\n ): PersistencePromise<SortedSet<IndexEntry>> {\n const indexEntries = indexEntriesStore(transaction);\n let results = new SortedSet<IndexEntry>(indexEntryComparator);\n return indexEntries\n .iterate(\n {\n index: DbIndexEntryDocumentKeyIndex,\n range: IDBKeyRange.only([\n fieldIndex.indexId,\n this.uid,\n this.encodeDirectionalKey(fieldIndex, documentKey)\n ])\n },\n (_, entry) => {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n documentKey,\n entry.arrayValue,\n entry.directionalValue\n )\n );\n }\n )\n .next(() => results);\n }\n\n /** Creates the index entries for the given document. */\n private computeIndexEntries(\n document: Document,\n fieldIndex: FieldIndex\n ): SortedSet<IndexEntry> {\n let results = new SortedSet<IndexEntry>(indexEntryComparator);\n\n const directionalValue = this.encodeDirectionalElements(\n fieldIndex,\n document\n );\n if (directionalValue == null) {\n return results;\n }\n\n const arraySegment = fieldIndexGetArraySegment(fieldIndex);\n if (arraySegment != null) {\n const value = document.data.field(arraySegment.fieldPath);\n if (isArray(value)) {\n for (const arrayValue of value.arrayValue!.values || []) {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n document.key,\n this.encodeSingleElement(arrayValue),\n directionalValue\n )\n );\n }\n }\n } else {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n document.key,\n EMPTY_VALUE,\n directionalValue\n )\n );\n }\n\n return results;\n }\n\n /**\n * Updates the index entries for the provided document by deleting entries\n * that are no longer referenced in `newEntries` and adding all newly added\n * entries.\n */\n private updateEntries(\n transaction: PersistenceTransaction,\n document: Document,\n fieldIndex: FieldIndex,\n existingEntries: SortedSet<IndexEntry>,\n newEntries: SortedSet<IndexEntry>\n ): PersistencePromise<void> {\n logDebug(LOG_TAG, \"Updating index entries for document '%s'\", document.key);\n\n const promises: Array<PersistencePromise<void>> = [];\n diffSortedSets(\n existingEntries,\n newEntries,\n indexEntryComparator,\n /* onAdd= */ entry => {\n promises.push(\n this.addIndexEntry(transaction, document, fieldIndex, entry)\n );\n },\n /* onRemove= */ entry => {\n promises.push(\n this.deleteIndexEntry(transaction, document, fieldIndex, entry)\n );\n }\n );\n\n return PersistencePromise.waitFor(promises);\n }\n\n private getNextSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise<number> {\n let nextSequenceNumber = 1;\n const states = indexStateStore(transaction);\n return states\n .iterate(\n {\n index: DbIndexStateSequenceNumberIndex,\n reverse: true,\n range: IDBKeyRange.upperBound([this.uid, Number.MAX_SAFE_INTEGER])\n },\n (_, state, controller) => {\n controller.done();\n nextSequenceNumber = state.sequenceNumber + 1;\n }\n )\n .next(() => nextSequenceNumber);\n }\n\n /**\n * Returns a new set of IDB ranges that splits the existing range and excludes\n * any values that match the `notInValue` from these ranges. As an example,\n * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.\n */\n private createRange(\n lower: IndexEntry,\n upper: IndexEntry,\n notInValues: IndexEntry[]\n ): IDBKeyRange[] {\n // The notIn values need to be sorted and unique so that we can return a\n // sorted set of non-overlapping ranges.\n notInValues = notInValues\n .sort((l, r) => indexEntryComparator(l, r))\n .filter(\n (el, i, values) => !i || indexEntryComparator(el, values[i - 1]) !== 0\n );\n\n const bounds: IndexEntry[] = [];\n bounds.push(lower);\n for (const notInValue of notInValues) {\n const cmpToLower = indexEntryComparator(notInValue, lower);\n const cmpToUpper = indexEntryComparator(notInValue, upper);\n\n if (cmpToLower === 0) {\n // `notInValue` is the lower bound. We therefore need to raise the bound\n // to the next value.\n bounds[0] = lower.successor();\n } else if (cmpToLower > 0 && cmpToUpper < 0) {\n // `notInValue` is in the middle of the range\n bounds.push(notInValue);\n bounds.push(notInValue.successor());\n } else if (cmpToUpper > 0) {\n // `notInValue` (and all following values) are out of the range\n break;\n }\n }\n bounds.push(upper);\n\n const ranges: IDBKeyRange[] = [];\n for (let i = 0; i < bounds.length; i += 2) {\n // If we encounter two bounds that will create an unmatchable key range,\n // then we return an empty set of key ranges.\n if (this.isRangeMatchable(bounds[i], bounds[i + 1])) {\n return [];\n }\n\n const lowerBound = [\n bounds[i].indexId,\n this.uid,\n bounds[i].arrayValue,\n bounds[i].directionalValue,\n EMPTY_VALUE,\n []\n ] as DbIndexEntryKey;\n\n const upperBound = [\n bounds[i + 1].indexId,\n this.uid,\n bounds[i + 1].arrayValue,\n bounds[i + 1].directionalValue,\n EMPTY_VALUE,\n []\n ] as DbIndexEntryKey;\n\n ranges.push(IDBKeyRange.bound(lowerBound, upperBound));\n }\n return ranges;\n }\n\n isRangeMatchable(lowerBound: IndexEntry, upperBound: IndexEntry): boolean {\n // If lower bound is greater than the upper bound, then the key\n // range can never be matched.\n return indexEntryComparator(lowerBound, upperBound) > 0;\n }\n\n getMinOffsetFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string\n ): PersistencePromise<IndexOffset> {\n return this.getFieldIndexes(transaction, collectionGroup).next(\n getMinOffsetFromFieldIndexes\n );\n }\n\n getMinOffset(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<IndexOffset> {\n return PersistencePromise.mapArray(\n this.getSubTargets(target),\n (subTarget: Target) =>\n this.getFieldIndex(transaction, subTarget).next(index =>\n index ? index : fail('Target cannot be served from index')\n )\n ).next(getMinOffsetFromFieldIndexes);\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the collectionParents\n * document store.\n */\nfunction collectionParentsStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbCollectionParentKey, DbCollectionParent> {\n return getStore<DbCollectionParentKey, DbCollectionParent>(\n txn,\n DbCollectionParentStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index entry object store.\n */\nfunction indexEntriesStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbIndexEntryKey, DbIndexEntry> {\n return getStore<DbIndexEntryKey, DbIndexEntry>(txn, DbIndexEntryStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index configuration object store.\n */\nfunction indexConfigurationStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbIndexConfigurationKey, DbIndexConfiguration> {\n return getStore<DbIndexConfigurationKey, DbIndexConfiguration>(\n txn,\n DbIndexConfigurationStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index state object store.\n */\nfunction indexStateStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbIndexStateKey, DbIndexState> {\n return getStore<DbIndexStateKey, DbIndexState>(txn, DbIndexStateStore);\n}\n\nfunction getMinOffsetFromFieldIndexes(fieldIndexes: FieldIndex[]): IndexOffset {\n hardAssert(\n fieldIndexes.length !== 0,\n 'Found empty index group when looking for least recent index offset.'\n );\n\n let minOffset: IndexOffset = fieldIndexes[0].indexState.offset;\n let maxBatchId: number = minOffset.largestBatchId;\n for (let i = 1; i < fieldIndexes.length; i++) {\n const newOffset: IndexOffset = fieldIndexes[i].indexState.offset;\n if (indexOffsetComparator(newOffset, minOffset) < 0) {\n minOffset = newOffset;\n }\n if (maxBatchId < newOffset.largestBatchId) {\n maxBatchId = newOffset.largestBatchId;\n }\n }\n return new IndexOffset(minOffset.readTime, minOffset.documentKey, maxBatchId);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/**\n * Describes a map whose keys are active target ids. We do not care about the type of the\n * values.\n */\nexport type ActiveTargets = SortedMap<TargetId, unknown>;\n\nexport const GC_DID_NOT_RUN: LruResults = {\n didRun: false,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nexport const LRU_COLLECTION_DISABLED = -1;\nexport const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\n\nexport class LruParams {\n private static readonly DEFAULT_COLLECTION_PERCENTILE = 10;\n private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000;\n\n static withCacheSize(cacheSize: number): LruParams {\n return new LruParams(\n cacheSize,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n }\n\n static readonly DEFAULT: LruParams = new LruParams(\n LRU_DEFAULT_CACHE_SIZE_BYTES,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n\n static readonly DISABLED: LruParams = new LruParams(\n LRU_COLLECTION_DISABLED,\n 0,\n 0\n );\n\n constructor(\n // When we attempt to collect, we will only do so if the cache size is greater than this\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n readonly cacheSizeCollectionThreshold: number,\n // The percentage of sequence numbers that we will attempt to collect\n readonly percentileToCollect: number,\n // A cap on the total number of sequence numbers that will be collected. This prevents\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\n readonly maximumSequenceNumbersToCollect: number\n ) {}\n}\n\nexport interface LruGarbageCollector {\n readonly params: LruParams;\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<LruResults>;\n\n /** Given a percentile of target to collect, returns the number of targets to collect. */\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise<number>;\n\n /** Returns the nth sequence number, counting in order from the smallest. */\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise<number>;\n\n /**\n * Removes documents that have a sequence number equal to or less than the\n * upper bound and are not otherwise pinned.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number>;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number>;\n\n /**\n * Removes targets with a sequence number equal to or less than the given\n * upper bound, and removes document associations with those targets.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number>;\n}\n\n/**\n * Describes the results of a garbage collection run. `didRun` will be set to\n * `false` if collection was skipped (either it is disabled or the cache size\n * has not hit the threshold). If collection ran, the other fields will be\n * filled in with the details of the results.\n */\nexport interface LruResults {\n readonly didRun: boolean;\n readonly sequenceNumbersCollected: number;\n readonly targetsRemoved: number;\n readonly documentsRemoved: number;\n}\n\n/**\n * Persistence layers intending to use LRU Garbage collection should have\n * reference delegates that implement this interface. This interface defines the\n * operations that the LRU garbage collector needs from the persistence layer.\n */\nexport interface LruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n /** Enumerates all the targets in the TargetCache. */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (target: TargetData) => void\n ): PersistencePromise<void>;\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number>;\n\n /**\n * Enumerates sequence numbers for documents not associated with a target.\n * Note that this may include duplicate sequence numbers.\n */\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise<void>;\n\n /**\n * Removes all targets that have a sequence number less than or equal to\n * `upperBound`, and are not present in the `activeTargetIds` set.\n *\n * @returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number>;\n\n /**\n * Removes all unreferenced documents from the cache that have a sequence\n * number less than or equal to the given `upperBound`.\n *\n * @returns the number of documents removed.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number>;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number>;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TargetId } from './types';\n\n/** Offset to ensure non-overlapping target ids. */\nconst OFFSET = 2;\n\n/**\n * Generates monotonically increasing target IDs for sending targets to the\n * watch stream.\n *\n * The client constructs two generators, one for the target cache, and one for\n * for the sync engine (to generate limbo documents targets). These\n * generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\nexport class TargetIdGenerator {\n constructor(private lastId: number) {}\n\n next(): TargetId {\n this.lastId += OFFSET;\n return this.lastId;\n }\n\n static forTargetCache(): TargetIdGenerator {\n // The target cache generator must return '2' in its first call to `next()`\n // as there is no differentiation in the protocol layer between an unset\n // number and the number '0'. If we were to sent a target with target ID\n // '0', the backend would consider it unset and replace it with its own ID.\n return new TargetIdGenerator(2 - OFFSET);\n }\n\n static forSyncEngine(): TargetIdGenerator {\n // Sync engine assigns target IDs for limbo document detection.\n return new TargetIdGenerator(1 - OFFSET);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, MutableDocumentMap } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */\nexport abstract class RemoteDocumentChangeBuffer {\n // A mapping of document key to the new cache entry that should be written.\n protected changes: ObjectMap<DocumentKey, MutableDocument> = new ObjectMap(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\n\n private changesApplied = false;\n\n protected abstract getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MutableDocument>;\n\n protected abstract getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<MutableDocumentMap>;\n\n protected abstract applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise<void>;\n\n /**\n * Buffers a `RemoteDocumentCache.addEntry()` call.\n *\n * You can only modify documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */\n addEntry(document: MutableDocument): void {\n this.assertNotApplied();\n this.changes.set(document.key, document);\n }\n\n /**\n * Buffers a `RemoteDocumentCache.removeEntry()` call.\n *\n * You can only remove documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */\n removeEntry(key: DocumentKey, readTime: SnapshotVersion): void {\n this.assertNotApplied();\n this.changes.set(\n key,\n MutableDocument.newInvalidDocument(key).setReadTime(readTime)\n );\n }\n\n /**\n * Looks up an entry in the cache. The buffered changes will first be checked,\n * and if no buffered change applies, this will forward to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document or an invalid document if we have nothing\n * cached.\n */\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MutableDocument> {\n this.assertNotApplied();\n const bufferedEntry = this.changes.get(documentKey);\n if (bufferedEntry !== undefined) {\n return PersistencePromise.resolve(bufferedEntry);\n } else {\n return this.getFromCache(transaction, documentKey);\n }\n }\n\n /**\n * Looks up several entries in the cache, forwarding to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKeys - The keys of the entries to look up.\n * @returns A map of cached documents, indexed by key. If an entry cannot be\n * found, the corresponding key will be mapped to an invalid document.\n */\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<MutableDocumentMap> {\n return this.getAllFromCache(transaction, documentKeys);\n }\n\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */\n apply(transaction: PersistenceTransaction): PersistencePromise<void> {\n this.assertNotApplied();\n this.changesApplied = true;\n return this.applyChanges(transaction);\n }\n\n /** Helper to assert this.changes is not null */\n protected assertNotApplied(): void {\n debugAssert(!this.changesApplied, 'Changes have already been applied.');\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { FieldMask } from '../model/field_mask';\n\n/**\n * Represents a local view (overlay) of a document, and the fields that are\n * locally mutated.\n */\nexport class OverlayedDocument {\n constructor(\n readonly overlayedDocument: Document,\n\n /**\n * The fields that are locally mutated by patch mutations.\n *\n * If the overlayed\tdocument is from set or delete mutations, this is `null`.\n * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.\n */\n readonly mutatedFields: FieldMask | null\n ) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n asCollectionQueryAtPath,\n isCollectionGroupQuery,\n isDocumentQuery,\n Query,\n queryMatches\n} from '../core/query';\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n DocumentKeySet,\n OverlayMap,\n DocumentMap,\n MutableDocumentMap,\n newDocumentKeyMap,\n newMutationMap,\n newOverlayMap,\n documentMap,\n mutableDocumentMap,\n documentKeySet,\n DocumentKeyMap,\n convertOverlayedDocumentMapToDocumentMap,\n OverlayedDocumentMap,\n newOverlayedDocumentMap\n} from '../model/collections';\nimport { Document, MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexOffset, INITIAL_LARGEST_BATCH_ID } from '../model/field_index';\nimport { FieldMask } from '../model/field_mask';\nimport {\n calculateOverlayMutation,\n mutationApplyToLocalView,\n PatchMutation\n} from '../model/mutation';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { LocalWriteResult } from './local_store_impl';\nimport { MutationQueue } from './mutation_queue';\nimport { OverlayedDocument } from './overlayed_document';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { RemoteDocumentCache } from './remote_document_cache';\n\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */\nexport class LocalDocumentsView {\n constructor(\n readonly remoteDocumentCache: RemoteDocumentCache,\n readonly mutationQueue: MutationQueue,\n readonly documentOverlayCache: DocumentOverlayCache,\n readonly indexManager: IndexManager\n ) {}\n\n /**\n * Get the local view of the document identified by `key`.\n *\n * @returns Local view of the document or null if we don't have any cached\n * state for it.\n */\n getDocument(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<Document> {\n let overlay: Overlay | null = null;\n return this.documentOverlayCache\n .getOverlay(transaction, key)\n .next(value => {\n overlay = value;\n return this.remoteDocumentCache.getEntry(transaction, key);\n })\n .next(document => {\n if (overlay !== null) {\n mutationApplyToLocalView(\n overlay.mutation,\n document,\n FieldMask.empty(),\n Timestamp.now()\n );\n }\n return document as Document;\n });\n }\n\n /**\n * Gets the local view of the documents identified by `keys`.\n *\n * If we don't have cached state for a document in `keys`, a NoDocument will\n * be stored for that key in the resulting set.\n */\n getDocuments(\n transaction: PersistenceTransaction,\n keys: DocumentKeySet\n ): PersistencePromise<DocumentMap> {\n return this.remoteDocumentCache\n .getEntries(transaction, keys)\n .next(docs =>\n this.getLocalViewOfDocuments(transaction, docs, documentKeySet()).next(\n () => docs as DocumentMap\n )\n );\n }\n\n /**\n * Similar to `getDocuments`, but creates the local view from the given\n * `baseDocs` without retrieving documents from the local store.\n *\n * @param transaction - The transaction this operation is scoped to.\n * @param docs - The documents to apply local mutations to get the local views.\n * @param existenceStateChanged - The set of document keys whose existence state\n * is changed. This is useful to determine if some documents overlay needs\n * to be recalculated.\n */\n getLocalViewOfDocuments(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap,\n existenceStateChanged: DocumentKeySet = documentKeySet()\n ): PersistencePromise<DocumentMap> {\n const overlays = newOverlayMap();\n return this.populateOverlays(transaction, overlays, docs).next(() => {\n return this.computeViews(\n transaction,\n docs,\n overlays,\n existenceStateChanged\n ).next(computeViewsResult => {\n let result = documentMap();\n computeViewsResult.forEach((documentKey, overlayedDocument) => {\n result = result.insert(\n documentKey,\n overlayedDocument.overlayedDocument\n );\n });\n return result;\n });\n });\n }\n\n /**\n * Gets the overlayed documents for the given document map, which will include\n * the local view of those documents and a `FieldMask` indicating which fields\n * are mutated locally, `null` if overlay is a Set or Delete mutation.\n */\n getOverlayedDocuments(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap\n ): PersistencePromise<OverlayedDocumentMap> {\n const overlays = newOverlayMap();\n return this.populateOverlays(transaction, overlays, docs).next(() =>\n this.computeViews(transaction, docs, overlays, documentKeySet())\n );\n }\n\n /**\n * Fetches the overlays for {@code docs} and adds them to provided overlay map\n * if the map does not already contain an entry for the given document key.\n */\n private populateOverlays(\n transaction: PersistenceTransaction,\n overlays: OverlayMap,\n docs: MutableDocumentMap\n ): PersistencePromise<void> {\n const missingOverlays: DocumentKey[] = [];\n docs.forEach(key => {\n if (!overlays.has(key)) {\n missingOverlays.push(key);\n }\n });\n return this.documentOverlayCache\n .getOverlays(transaction, missingOverlays)\n .next(result => {\n result.forEach((key, val) => {\n overlays.set(key, val);\n });\n });\n }\n\n /**\n * Computes the local view for the given documents.\n *\n * @param docs - The documents to compute views for. It also has the base\n * version of the documents.\n * @param overlays - The overlays that need to be applied to the given base\n * version of the documents.\n * @param existenceStateChanged - A set of documents whose existence states\n * might have changed. This is used to determine if we need to re-calculate\n * overlays from mutation queues.\n * @return A map represents the local documents view.\n */\n computeViews(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap,\n overlays: OverlayMap,\n existenceStateChanged: DocumentKeySet\n ): PersistencePromise<OverlayedDocumentMap> {\n let recalculateDocuments = mutableDocumentMap();\n const mutatedFields = newDocumentKeyMap<FieldMask | null>();\n const results = newOverlayedDocumentMap();\n docs.forEach((_, doc) => {\n const overlay = overlays.get(doc.key);\n // Recalculate an overlay if the document's existence state changed due to\n // a remote event *and* the overlay is a PatchMutation. This is because\n // document existence state can change if some patch mutation's\n // preconditions are met.\n // NOTE: we recalculate when `overlay` is undefined as well, because there\n // might be a patch mutation whose precondition does not match before the\n // change (hence overlay is undefined), but would now match.\n if (\n existenceStateChanged.has(doc.key) &&\n (overlay === undefined || overlay.mutation instanceof PatchMutation)\n ) {\n recalculateDocuments = recalculateDocuments.insert(doc.key, doc);\n } else if (overlay !== undefined) {\n mutatedFields.set(doc.key, overlay.mutation.getFieldMask());\n mutationApplyToLocalView(\n overlay.mutation,\n doc,\n overlay.mutation.getFieldMask(),\n Timestamp.now()\n );\n } else {\n // no overlay exists\n // Using EMPTY to indicate there is no overlay for the document.\n mutatedFields.set(doc.key, FieldMask.empty());\n }\n });\n\n return this.recalculateAndSaveOverlays(\n transaction,\n recalculateDocuments\n ).next(recalculatedFields => {\n recalculatedFields.forEach((documentKey, mask) =>\n mutatedFields.set(documentKey, mask)\n );\n docs.forEach((documentKey, document) =>\n results.set(\n documentKey,\n new OverlayedDocument(\n document,\n mutatedFields.get(documentKey) ?? null\n )\n )\n );\n return results;\n });\n }\n\n private recalculateAndSaveOverlays(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap\n ): PersistencePromise<DocumentKeyMap<FieldMask | null>> {\n const masks = newDocumentKeyMap<FieldMask | null>();\n // A reverse lookup map from batch id to the documents within that batch.\n let documentsByBatchId = new SortedMap<number, DocumentKeySet>(\n (key1: number, key2: number) => key1 - key2\n );\n let processed = documentKeySet();\n return this.mutationQueue\n .getAllMutationBatchesAffectingDocumentKeys(transaction, docs)\n .next(batches => {\n for (const batch of batches) {\n batch.keys().forEach(key => {\n const baseDoc = docs.get(key);\n if (baseDoc === null) {\n return;\n }\n let mask: FieldMask | null = masks.get(key) || FieldMask.empty();\n mask = batch.applyToLocalView(baseDoc, mask);\n masks.set(key, mask);\n const newSet = (\n documentsByBatchId.get(batch.batchId) || documentKeySet()\n ).add(key);\n documentsByBatchId = documentsByBatchId.insert(\n batch.batchId,\n newSet\n );\n });\n }\n })\n .next(() => {\n const promises: Array<PersistencePromise<void>> = [];\n // Iterate in descending order of batch IDs, and skip documents that are\n // already saved.\n const iter = documentsByBatchId.getReverseIterator();\n while (iter.hasNext()) {\n const entry = iter.getNext();\n const batchId = entry.key;\n const keys = entry.value;\n const overlays = newMutationMap();\n keys.forEach(key => {\n if (!processed.has(key)) {\n const overlayMutation = calculateOverlayMutation(\n docs.get(key)!,\n masks.get(key)!\n );\n if (overlayMutation !== null) {\n overlays.set(key, overlayMutation);\n }\n processed = processed.add(key);\n }\n });\n promises.push(\n this.documentOverlayCache.saveOverlays(\n transaction,\n batchId,\n overlays\n )\n );\n }\n return PersistencePromise.waitFor(promises);\n })\n .next(() => masks);\n }\n\n /**\n * Recalculates overlays by reading the documents from remote document cache\n * first, and saves them after they are calculated.\n */\n recalculateAndSaveOverlaysForDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<DocumentKeyMap<FieldMask | null>> {\n return this.remoteDocumentCache\n .getEntries(transaction, documentKeys)\n .next(docs => this.recalculateAndSaveOverlays(transaction, docs));\n }\n\n /**\n * Performs a query against the local view of all documents.\n *\n * @param transaction - The persistence transaction.\n * @param query - The query to match documents against.\n * @param offset - Read time and key to start scanning by (exclusive).\n * @param context - A optional tracker to keep a record of important details\n * during database local query execution.\n */\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n context?: QueryContext\n ): PersistencePromise<DocumentMap> {\n if (isDocumentQuery(query)) {\n return this.getDocumentsMatchingDocumentQuery(transaction, query.path);\n } else if (isCollectionGroupQuery(query)) {\n return this.getDocumentsMatchingCollectionGroupQuery(\n transaction,\n query,\n offset,\n context\n );\n } else {\n return this.getDocumentsMatchingCollectionQuery(\n transaction,\n query,\n offset,\n context\n );\n }\n }\n\n /**\n * Given a collection group, returns the next documents that follow the provided offset, along\n * with an updated batch ID.\n *\n * <p>The documents returned by this method are ordered by remote version from the provided\n * offset. If there are no more remote documents after the provided offset, documents with\n * mutations in order of batch id from the offset are returned. Since all documents in a batch are\n * returned together, the total number of documents returned can exceed {@code count}.\n *\n * @param transaction\n * @param collectionGroup The collection group for the documents.\n * @param offset The offset to index into.\n * @param count The number of documents to return\n * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.\n */\n getNextDocuments(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n count: number\n ): PersistencePromise<LocalWriteResult> {\n return this.remoteDocumentCache\n .getAllFromCollectionGroup(transaction, collectionGroup, offset, count)\n .next((originalDocs: MutableDocumentMap) => {\n const overlaysPromise: PersistencePromise<OverlayMap> =\n count - originalDocs.size > 0\n ? this.documentOverlayCache.getOverlaysForCollectionGroup(\n transaction,\n collectionGroup,\n offset.largestBatchId,\n count - originalDocs.size\n )\n : PersistencePromise.resolve(newOverlayMap());\n // The callsite will use the largest batch ID together with the latest read time to create\n // a new index offset. Since we only process batch IDs if all remote documents have been read,\n // no overlay will increase the overall read time. This is why we only need to special case\n // the batch id.\n let largestBatchId = INITIAL_LARGEST_BATCH_ID;\n let modifiedDocs = originalDocs;\n return overlaysPromise.next(overlays => {\n return PersistencePromise.forEach(\n overlays,\n (key: DocumentKey, overlay: Overlay) => {\n if (largestBatchId < overlay.largestBatchId) {\n largestBatchId = overlay.largestBatchId;\n }\n if (originalDocs.get(key)) {\n return PersistencePromise.resolve();\n }\n return this.remoteDocumentCache\n .getEntry(transaction, key)\n .next(doc => {\n modifiedDocs = modifiedDocs.insert(key, doc);\n });\n }\n )\n .next(() =>\n this.populateOverlays(transaction, overlays, originalDocs)\n )\n .next(() =>\n this.computeViews(\n transaction,\n modifiedDocs,\n overlays,\n documentKeySet()\n )\n )\n .next(localDocs => ({\n batchId: largestBatchId,\n changes: convertOverlayedDocumentMapToDocumentMap(localDocs)\n }));\n });\n });\n }\n\n private getDocumentsMatchingDocumentQuery(\n transaction: PersistenceTransaction,\n docPath: ResourcePath\n ): PersistencePromise<DocumentMap> {\n // Just do a simple document lookup.\n return this.getDocument(transaction, new DocumentKey(docPath)).next(\n document => {\n let result = documentMap();\n if (document.isFoundDocument()) {\n result = result.insert(document.key, document);\n }\n return result;\n }\n );\n }\n\n private getDocumentsMatchingCollectionGroupQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n context?: QueryContext\n ): PersistencePromise<DocumentMap> {\n debugAssert(\n query.path.isEmpty(),\n 'Currently we only support collection group queries at the root.'\n );\n const collectionId = query.collectionGroup!;\n let results = documentMap();\n return this.indexManager\n .getCollectionParents(transaction, collectionId)\n .next(parents => {\n // Perform a collection query against each parent that contains the\n // collectionId and aggregate the results.\n return PersistencePromise.forEach(parents, (parent: ResourcePath) => {\n const collectionQuery = asCollectionQueryAtPath(\n query,\n parent.child(collectionId)\n );\n return this.getDocumentsMatchingCollectionQuery(\n transaction,\n collectionQuery,\n offset,\n context\n ).next(r => {\n r.forEach((key, doc) => {\n results = results.insert(key, doc);\n });\n });\n }).next(() => results);\n });\n }\n\n private getDocumentsMatchingCollectionQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n context?: QueryContext\n ): PersistencePromise<DocumentMap> {\n // Query the remote documents and overlay mutations.\n let overlays: OverlayMap;\n return this.documentOverlayCache\n .getOverlaysForCollection(transaction, query.path, offset.largestBatchId)\n .next(result => {\n overlays = result;\n return this.remoteDocumentCache.getDocumentsMatchingQuery(\n transaction,\n query,\n offset,\n overlays,\n context\n );\n })\n .next(remoteDocuments => {\n // As documents might match the query because of their overlay we need to\n // include documents for all overlays in the initial document set.\n overlays.forEach((_, overlay) => {\n const key = overlay.getKey();\n if (remoteDocuments.get(key) === null) {\n remoteDocuments = remoteDocuments.insert(\n key,\n MutableDocument.newInvalidDocument(key)\n );\n }\n });\n\n // Apply the overlays and match against the query.\n let results = documentMap();\n remoteDocuments.forEach((key, document) => {\n const overlay = overlays.get(key);\n if (overlay !== undefined) {\n mutationApplyToLocalView(\n overlay.mutation,\n document,\n FieldMask.empty(),\n Timestamp.now()\n );\n }\n // Finally, insert the documents that still match the query\n if (queryMatches(query, document)) {\n results = results.insert(key, document);\n }\n });\n return results;\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleMetadata, NamedQuery } from '../core/bundle';\nimport {\n NamedQuery as ProtoNamedQuery,\n BundleMetadata as ProtoBundleMetadata\n} from '../protos/firestore_bundle_proto';\n\nimport { BundleCache } from './bundle_cache';\nimport {\n fromBundleMetadata,\n fromProtoNamedQuery,\n LocalSerializer\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\nexport class MemoryBundleCache implements BundleCache {\n private bundles = new Map<string, BundleMetadata>();\n private namedQueries = new Map<string, NamedQuery>();\n\n constructor(private serializer: LocalSerializer) {}\n\n getBundleMetadata(\n transaction: PersistenceTransaction,\n bundleId: string\n ): PersistencePromise<BundleMetadata | undefined> {\n return PersistencePromise.resolve(this.bundles.get(bundleId));\n }\n\n saveBundleMetadata(\n transaction: PersistenceTransaction,\n bundleMetadata: ProtoBundleMetadata\n ): PersistencePromise<void> {\n this.bundles.set(bundleMetadata.id!, fromBundleMetadata(bundleMetadata));\n return PersistencePromise.resolve();\n }\n\n getNamedQuery(\n transaction: PersistenceTransaction,\n queryName: string\n ): PersistencePromise<NamedQuery | undefined> {\n return PersistencePromise.resolve(this.namedQueries.get(queryName));\n }\n\n saveNamedQuery(\n transaction: PersistenceTransaction,\n query: ProtoNamedQuery\n ): PersistencePromise<void> {\n this.namedQueries.set(query.name!, fromProtoNamedQuery(query));\n return PersistencePromise.resolve();\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n documentKeySet,\n DocumentKeySet,\n MutationMap,\n OverlayMap,\n newOverlayMap\n} from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory implementation of DocumentOverlayCache.\n */\nexport class MemoryDocumentOverlayCache implements DocumentOverlayCache {\n // A map sorted by DocumentKey, whose value is a pair of the largest batch id\n // for the overlay and the overlay itself.\n private overlays = new SortedMap<DocumentKey, Overlay>(\n DocumentKey.comparator\n );\n private overlayByBatchId = new Map<number, DocumentKeySet>();\n\n getOverlay(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<Overlay | null> {\n return PersistencePromise.resolve(this.overlays.get(key));\n }\n\n getOverlays(\n transaction: PersistenceTransaction,\n keys: DocumentKey[]\n ): PersistencePromise<OverlayMap> {\n const result = newOverlayMap();\n return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n return this.getOverlay(transaction, key).next(overlay => {\n if (overlay !== null) {\n result.set(key, overlay);\n }\n });\n }).next(() => result);\n }\n\n saveOverlays(\n transaction: PersistenceTransaction,\n largestBatchId: number,\n overlays: MutationMap\n ): PersistencePromise<void> {\n overlays.forEach((_, mutation) => {\n this.saveOverlay(transaction, largestBatchId, mutation);\n });\n return PersistencePromise.resolve();\n }\n\n removeOverlaysForBatchId(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n batchId: number\n ): PersistencePromise<void> {\n const keys = this.overlayByBatchId.get(batchId);\n if (keys !== undefined) {\n keys.forEach(key => (this.overlays = this.overlays.remove(key)));\n this.overlayByBatchId.delete(batchId);\n }\n return PersistencePromise.resolve();\n }\n\n getOverlaysForCollection(\n transaction: PersistenceTransaction,\n collection: ResourcePath,\n sinceBatchId: number\n ): PersistencePromise<OverlayMap> {\n const result = newOverlayMap();\n\n const immediateChildrenPathLength = collection.length + 1;\n const prefix = new DocumentKey(collection.child(''));\n const iter = this.overlays.getIteratorFrom(prefix);\n while (iter.hasNext()) {\n const entry = iter.getNext();\n const overlay = entry.value;\n const key = overlay.getKey();\n if (!collection.isPrefixOf(key.path)) {\n break;\n }\n // Documents from sub-collections\n if (key.path.length !== immediateChildrenPathLength) {\n continue;\n }\n if (overlay.largestBatchId > sinceBatchId) {\n result.set(overlay.getKey(), overlay);\n }\n }\n\n return PersistencePromise.resolve(result);\n }\n\n getOverlaysForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n sinceBatchId: number,\n count: number\n ): PersistencePromise<OverlayMap> {\n let batchIdToOverlays = new SortedMap<number, OverlayMap>(\n (key1: number, key2: number) => key1 - key2\n );\n\n const iter = this.overlays.getIterator();\n while (iter.hasNext()) {\n const entry = iter.getNext();\n const overlay = entry.value;\n const key = overlay.getKey();\n if (key.getCollectionGroup() !== collectionGroup) {\n continue;\n }\n if (overlay.largestBatchId > sinceBatchId) {\n let overlaysForBatchId = batchIdToOverlays.get(overlay.largestBatchId);\n if (overlaysForBatchId === null) {\n overlaysForBatchId = newOverlayMap();\n batchIdToOverlays = batchIdToOverlays.insert(\n overlay.largestBatchId,\n overlaysForBatchId\n );\n }\n overlaysForBatchId.set(overlay.getKey(), overlay);\n }\n }\n\n const result = newOverlayMap();\n const batchIter = batchIdToOverlays.getIterator();\n while (batchIter.hasNext()) {\n const entry = batchIter.getNext();\n const overlays = entry.value;\n overlays.forEach((key, overlay) => result.set(key, overlay));\n if (result.size() >= count) {\n break;\n }\n }\n return PersistencePromise.resolve(result);\n }\n\n private saveOverlay(\n transaction: PersistenceTransaction,\n largestBatchId: number,\n mutation: Mutation\n ): void {\n // Remove the association of the overlay to its batch id.\n const existing = this.overlays.get(mutation.key);\n if (existing !== null) {\n const newSet = this.overlayByBatchId\n .get(existing.largestBatchId)!\n .delete(mutation.key);\n this.overlayByBatchId.set(existing.largestBatchId, newSet);\n }\n\n this.overlays = this.overlays.insert(\n mutation.key,\n new Overlay(largestBatchId, mutation)\n );\n\n // Create the association of this overlay to the given largestBatchId.\n let batch = this.overlayByBatchId.get(largestBatchId);\n if (batch === undefined) {\n batch = documentKeySet();\n this.overlayByBatchId.set(largestBatchId, batch);\n }\n this.overlayByBatchId.set(largestBatchId, batch.add(mutation.key));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchId, TargetId } from '../core/types';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\n/**\n * A collection of references to a document from some kind of numbered entity\n * (either a target ID or batch ID). As references are added to or removed from\n * the set corresponding events are emitted to a registered garbage collector.\n *\n * Each reference is represented by a DocumentReference object. Each of them\n * contains enough information to uniquely identify the reference. They are all\n * stored primarily in a set sorted by key. A document is considered garbage if\n * there's no references in that set (this can be efficiently checked thanks to\n * sorting by key).\n *\n * ReferenceSet also keeps a secondary set that contains references sorted by\n * IDs. This one is used to efficiently implement removal of all references by\n * some target ID.\n */\nexport class ReferenceSet {\n // A set of outstanding references to a document sorted by key.\n private refsByKey = new SortedSet(DocReference.compareByKey);\n\n // A set of outstanding references to a document sorted by target id.\n private refsByTarget = new SortedSet(DocReference.compareByTargetId);\n\n /** Returns true if the reference set contains no references. */\n isEmpty(): boolean {\n return this.refsByKey.isEmpty();\n }\n\n /** Adds a reference to the given document key for the given ID. */\n addReference(key: DocumentKey, id: TargetId | BatchId): void {\n const ref = new DocReference(key, id);\n this.refsByKey = this.refsByKey.add(ref);\n this.refsByTarget = this.refsByTarget.add(ref);\n }\n\n /** Add references to the given document keys for the given ID. */\n addReferences(keys: DocumentKeySet, id: TargetId | BatchId): void {\n keys.forEach(key => this.addReference(key, id));\n }\n\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */\n removeReference(key: DocumentKey, id: TargetId | BatchId): void {\n this.removeRef(new DocReference(key, id));\n }\n\n removeReferences(keys: DocumentKeySet, id: TargetId | BatchId): void {\n keys.forEach(key => this.removeReference(key, id));\n }\n\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */\n removeReferencesForId(id: TargetId | BatchId): DocumentKey[] {\n const emptyKey = new DocumentKey(new ResourcePath([]));\n const startRef = new DocReference(emptyKey, id);\n const endRef = new DocReference(emptyKey, id + 1);\n const keys: DocumentKey[] = [];\n this.refsByTarget.forEachInRange([startRef, endRef], ref => {\n this.removeRef(ref);\n keys.push(ref.key);\n });\n return keys;\n }\n\n removeAllReferences(): void {\n this.refsByKey.forEach(ref => this.removeRef(ref));\n }\n\n private removeRef(ref: DocReference): void {\n this.refsByKey = this.refsByKey.delete(ref);\n this.refsByTarget = this.refsByTarget.delete(ref);\n }\n\n referencesForId(id: TargetId | BatchId): DocumentKeySet {\n const emptyKey = new DocumentKey(new ResourcePath([]));\n const startRef = new DocReference(emptyKey, id);\n const endRef = new DocReference(emptyKey, id + 1);\n let keys = documentKeySet();\n this.refsByTarget.forEachInRange([startRef, endRef], ref => {\n keys = keys.add(ref.key);\n });\n return keys;\n }\n\n containsKey(key: DocumentKey): boolean {\n const ref = new DocReference(key, 0);\n const firstRef = this.refsByKey.firstAfterOrEqual(ref);\n return firstRef !== null && key.isEqual(firstRef.key);\n }\n}\n\nexport class DocReference {\n constructor(\n public key: DocumentKey,\n public targetOrBatchId: TargetId | BatchId\n ) {}\n\n /** Compare by key then by ID */\n static compareByKey(left: DocReference, right: DocReference): number {\n return (\n DocumentKey.comparator(left.key, right.key) ||\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId)\n );\n }\n\n /** Compare by ID then by key */\n static compareByTargetId(left: DocReference, right: DocReference): number {\n return (\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId) ||\n DocumentKey.comparator(left.key, right.key)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isCollectionGroupQuery, Query } from '../core/query';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { IndexManager } from './index_manager';\nimport { MutationQueue } from './mutation_queue';\nimport { ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { DocReference } from './reference_set';\n\nexport class MemoryMutationQueue implements MutationQueue {\n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n private mutationQueue: MutationBatch[] = [];\n\n /** Next value to use when assigning sequential IDs to each mutation batch. */\n private nextBatchId: BatchId = 1;\n\n /** An ordered mapping between documents and the mutations batch IDs. */\n private batchesByDocumentKey = new SortedSet(DocReference.compareByKey);\n\n constructor(\n private readonly indexManager: IndexManager,\n private readonly referenceDelegate: ReferenceDelegate\n ) {}\n\n checkEmpty(transaction: PersistenceTransaction): PersistencePromise<boolean> {\n return PersistencePromise.resolve(this.mutationQueue.length === 0);\n }\n\n addMutationBatch(\n transaction: PersistenceTransaction,\n localWriteTime: Timestamp,\n baseMutations: Mutation[],\n mutations: Mutation[]\n ): PersistencePromise<MutationBatch> {\n debugAssert(mutations.length !== 0, 'Mutation batches should not be empty');\n\n const batchId = this.nextBatchId;\n this.nextBatchId++;\n\n if (this.mutationQueue.length > 0) {\n const prior = this.mutationQueue[this.mutationQueue.length - 1];\n debugAssert(\n prior.batchId < batchId,\n 'Mutation batchIDs must be monotonically increasing order'\n );\n }\n\n const batch = new MutationBatch(\n batchId,\n localWriteTime,\n baseMutations,\n mutations\n );\n this.mutationQueue.push(batch);\n\n // Track references by document key and index collection parents.\n for (const mutation of mutations) {\n this.batchesByDocumentKey = this.batchesByDocumentKey.add(\n new DocReference(mutation.key, batchId)\n );\n\n this.indexManager.addToCollectionParentIndex(\n transaction,\n mutation.key.path.popLast()\n );\n }\n\n return PersistencePromise.resolve(batch);\n }\n\n lookupMutationBatch(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise<MutationBatch | null> {\n return PersistencePromise.resolve(this.findMutationBatch(batchId));\n }\n\n getNextMutationBatchAfterBatchId(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise<MutationBatch | null> {\n const nextBatchId = batchId + 1;\n\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n const rawIndex = this.indexOfBatchId(nextBatchId);\n const index = rawIndex < 0 ? 0 : rawIndex;\n return PersistencePromise.resolve(\n this.mutationQueue.length > index ? this.mutationQueue[index] : null\n );\n }\n\n getHighestUnacknowledgedBatchId(): PersistencePromise<BatchId> {\n return PersistencePromise.resolve(\n this.mutationQueue.length === 0 ? BATCHID_UNKNOWN : this.nextBatchId - 1\n );\n }\n\n getAllMutationBatches(\n transaction: PersistenceTransaction\n ): PersistencePromise<MutationBatch[]> {\n return PersistencePromise.resolve(this.mutationQueue.slice());\n }\n\n getAllMutationBatchesAffectingDocumentKey(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MutationBatch[]> {\n const start = new DocReference(documentKey, 0);\n const end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n const result: MutationBatch[] = [];\n this.batchesByDocumentKey.forEachInRange([start, end], ref => {\n debugAssert(\n documentKey.isEqual(ref.key),\n \"Should only iterate over a single key's batches\"\n );\n const batch = this.findMutationBatch(ref.targetOrBatchId);\n debugAssert(\n batch !== null,\n 'Batches in the index must exist in the main table'\n );\n result.push(batch!);\n });\n\n return PersistencePromise.resolve(result);\n }\n\n getAllMutationBatchesAffectingDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: SortedMap<DocumentKey, unknown>\n ): PersistencePromise<MutationBatch[]> {\n let uniqueBatchIDs = new SortedSet<number>(primitiveComparator);\n\n documentKeys.forEach(documentKey => {\n const start = new DocReference(documentKey, 0);\n const end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n this.batchesByDocumentKey.forEachInRange([start, end], ref => {\n debugAssert(\n documentKey.isEqual(ref.key),\n \"For each key, should only iterate over a single key's batches\"\n );\n\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n });\n });\n\n return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\n }\n\n getAllMutationBatchesAffectingQuery(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise<MutationBatch[]> {\n debugAssert(\n !isCollectionGroupQuery(query),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n // Use the query path as a prefix for testing if a document matches the\n // query.\n const prefix = query.path;\n const immediateChildrenPathLength = prefix.length + 1;\n\n // Construct a document reference for actually scanning the index. Unlike\n // the prefix the document key in this reference must have an even number of\n // segments. The empty segment can be used a suffix of the query path\n // because it precedes all other segments in an ordered traversal.\n let startPath = prefix;\n if (!DocumentKey.isDocumentKey(startPath)) {\n startPath = startPath.child('');\n }\n\n const start = new DocReference(new DocumentKey(startPath), 0);\n\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n let uniqueBatchIDs = new SortedSet<number>(primitiveComparator);\n\n this.batchesByDocumentKey.forEachWhile(ref => {\n const rowKeyPath = ref.key.path;\n if (!prefix.isPrefixOf(rowKeyPath)) {\n return false;\n } else {\n // Rows with document keys more than one segment longer than the query\n // path can't be matches. For example, a query on 'rooms' can't match\n // the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n if (rowKeyPath.length === immediateChildrenPathLength) {\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n }\n return true;\n }\n }, start);\n\n return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\n }\n\n private findMutationBatches(batchIDs: SortedSet<number>): MutationBatch[] {\n // Construct an array of matching batches, sorted by batchID to ensure that\n // multiple mutations affecting the same document key are applied in order.\n const result: MutationBatch[] = [];\n batchIDs.forEach(batchId => {\n const batch = this.findMutationBatch(batchId);\n if (batch !== null) {\n result.push(batch);\n }\n });\n return result;\n }\n\n removeMutationBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch\n ): PersistencePromise<void> {\n // Find the position of the first batch for removal.\n const batchIndex = this.indexOfExistingBatchId(batch.batchId, 'removed');\n hardAssert(\n batchIndex === 0,\n 'Can only remove the first entry of the mutation queue'\n );\n this.mutationQueue.shift();\n\n let references = this.batchesByDocumentKey;\n return PersistencePromise.forEach(batch.mutations, (mutation: Mutation) => {\n const ref = new DocReference(mutation.key, batch.batchId);\n references = references.delete(ref);\n return this.referenceDelegate.markPotentiallyOrphaned(\n transaction,\n mutation.key\n );\n }).next(() => {\n this.batchesByDocumentKey = references;\n });\n }\n\n removeCachedMutationKeys(batchId: BatchId): void {\n // No-op since the memory mutation queue does not maintain a separate cache.\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n const ref = new DocReference(key, 0);\n const firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref);\n return PersistencePromise.resolve(key.isEqual(firstRef && firstRef.key));\n }\n\n performConsistencyCheck(\n txn: PersistenceTransaction\n ): PersistencePromise<void> {\n if (this.mutationQueue.length === 0) {\n debugAssert(\n this.batchesByDocumentKey.isEmpty(),\n 'Document leak -- detected dangling mutation references when queue is empty.'\n );\n }\n return PersistencePromise.resolve();\n }\n\n /**\n * Finds the index of the given batchId in the mutation queue and asserts that\n * the resulting index is within the bounds of the queue.\n *\n * @param batchId - The batchId to search for\n * @param action - A description of what the caller is doing, phrased in passive\n * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\n */\n private indexOfExistingBatchId(batchId: BatchId, action: string): number {\n const index = this.indexOfBatchId(batchId);\n debugAssert(\n index >= 0 && index < this.mutationQueue.length,\n 'Batches must exist to be ' + action\n );\n return index;\n }\n\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @returns The computed index of the batch with the given batchId, based on\n * the state of the queue. Note this index can be negative if the requested\n * batchId has already been remvoed from the queue or past the end of the\n * queue if the batchId is larger than the last added batch.\n */\n private indexOfBatchId(batchId: BatchId): number {\n if (this.mutationQueue.length === 0) {\n // As an index this is past the end of the queue\n return 0;\n }\n\n // Examine the front of the queue to figure out the difference between the\n // batchId and indexes in the array. Note that since the queue is ordered\n // by batchId, if the first batch has a larger batchId then the requested\n // batchId doesn't exist in the queue.\n const firstBatchId = this.mutationQueue[0].batchId;\n return batchId - firstBatchId;\n }\n\n /**\n * A version of lookupMutationBatch that doesn't return a promise, this makes\n * other functions that uses this code easier to read and more efficent.\n */\n private findMutationBatch(batchId: BatchId): MutationBatch | null {\n const index = this.indexOfBatchId(batchId);\n if (index < 0 || index >= this.mutationQueue.length) {\n return null;\n }\n\n const batch = this.mutationQueue[index];\n debugAssert(batch.batchId === batchId, 'If found batch must match');\n return batch;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Query, queryMatches } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n DocumentKeySet,\n MutableDocumentMap,\n mutableDocumentMap,\n OverlayMap\n} from '../model/collections';\nimport { Document, MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n IndexOffset,\n indexOffsetComparator,\n newIndexOffsetFromDocument\n} from '../model/field_index';\nimport { debugAssert, fail } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { IndexManager } from './index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\n\nexport type DocumentSizer = (doc: Document) => number;\n\n/** Miscellaneous collection types / constants. */\ninterface MemoryRemoteDocumentCacheEntry {\n document: Document;\n size: number;\n}\n\ntype DocumentEntryMap = SortedMap<DocumentKey, MemoryRemoteDocumentCacheEntry>;\nfunction documentEntryMap(): DocumentEntryMap {\n return new SortedMap<DocumentKey, MemoryRemoteDocumentCacheEntry>(\n DocumentKey.comparator\n );\n}\n\nexport interface MemoryRemoteDocumentCache extends RemoteDocumentCache {\n forEachDocumentKey(\n transaction: PersistenceTransaction,\n f: (key: DocumentKey) => PersistencePromise<void>\n ): PersistencePromise<void>;\n}\n\n/**\n * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newMemoryRemoteDocumentCache()`.\n */\nclass MemoryRemoteDocumentCacheImpl implements MemoryRemoteDocumentCache {\n /** Underlying cache of documents and their read times. */\n private docs = documentEntryMap();\n private indexManager!: IndexManager;\n\n /** Size of all cached documents. */\n private size = 0;\n\n /**\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n constructor(private readonly sizer: DocumentSizer) {}\n\n setIndexManager(indexManager: IndexManager): void {\n this.indexManager = indexManager;\n }\n\n /**\n * Adds the supplied entry to the cache and updates the cache size as appropriate.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */\n addEntry(\n transaction: PersistenceTransaction,\n doc: MutableDocument\n ): PersistencePromise<void> {\n debugAssert(\n !doc.readTime.isEqual(SnapshotVersion.min()),\n 'Cannot add a document with a read time of zero'\n );\n\n const key = doc.key;\n const entry = this.docs.get(key);\n const previousSize = entry ? entry.size : 0;\n const currentSize = this.sizer(doc);\n\n this.docs = this.docs.insert(key, {\n document: doc.mutableCopy(),\n size: currentSize\n });\n\n this.size += currentSize - previousSize;\n\n return this.indexManager.addToCollectionParentIndex(\n transaction,\n key.path.popLast()\n );\n }\n\n /**\n * Removes the specified entry from the cache and updates the cache size as appropriate.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */\n removeEntry(documentKey: DocumentKey): void {\n const entry = this.docs.get(documentKey);\n if (entry) {\n this.docs = this.docs.remove(documentKey);\n this.size -= entry.size;\n }\n }\n\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MutableDocument> {\n const entry = this.docs.get(documentKey);\n return PersistencePromise.resolve(\n entry\n ? entry.document.mutableCopy()\n : MutableDocument.newInvalidDocument(documentKey)\n );\n }\n\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<MutableDocumentMap> {\n let results = mutableDocumentMap();\n documentKeys.forEach(documentKey => {\n const entry = this.docs.get(documentKey);\n results = results.insert(\n documentKey,\n entry\n ? entry.document.mutableCopy()\n : MutableDocument.newInvalidDocument(documentKey)\n );\n });\n return PersistencePromise.resolve(results);\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n mutatedDocs: OverlayMap\n ): PersistencePromise<MutableDocumentMap> {\n let results = mutableDocumentMap();\n\n // Documents are ordered by key, so we can use a prefix scan to narrow down\n // the documents we need to match the query against.\n const collectionPath = query.path;\n const prefix = new DocumentKey(collectionPath.child(''));\n const iterator = this.docs.getIteratorFrom(prefix);\n while (iterator.hasNext()) {\n const {\n key,\n value: { document }\n } = iterator.getNext();\n if (!collectionPath.isPrefixOf(key.path)) {\n break;\n }\n if (key.path.length > collectionPath.length + 1) {\n // Exclude entries from subcollections.\n continue;\n }\n if (\n indexOffsetComparator(newIndexOffsetFromDocument(document), offset) <= 0\n ) {\n // The document sorts before the offset.\n continue;\n }\n if (!mutatedDocs.has(document.key) && !queryMatches(query, document)) {\n // The document cannot possibly match the query.\n continue;\n }\n\n results = results.insert(document.key, document.mutableCopy());\n }\n return PersistencePromise.resolve(results);\n }\n\n getAllFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n limti: number\n ): PersistencePromise<MutableDocumentMap> {\n // This method should only be called from the IndexBackfiller if persistence\n // is enabled.\n fail('getAllFromCollectionGroup() is not supported.');\n }\n\n forEachDocumentKey(\n transaction: PersistenceTransaction,\n f: (key: DocumentKey) => PersistencePromise<void>\n ): PersistencePromise<void> {\n return PersistencePromise.forEach(this.docs, (key: DocumentKey) => f(key));\n }\n\n newChangeBuffer(options?: {\n trackRemovals: boolean;\n }): RemoteDocumentChangeBuffer {\n // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps\n // a separate changelog and does not need special handling for removals.\n return new MemoryRemoteDocumentChangeBuffer(this);\n }\n\n getSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return PersistencePromise.resolve(this.size);\n }\n}\n\n/**\n * Creates a new memory-only RemoteDocumentCache.\n *\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\nexport function newMemoryRemoteDocumentCache(\n sizer: DocumentSizer\n): MemoryRemoteDocumentCache {\n return new MemoryRemoteDocumentCacheImpl(sizer);\n}\n\n/**\n * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.\n */\nclass MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n constructor(private readonly documentCache: MemoryRemoteDocumentCacheImpl) {\n super();\n }\n\n protected applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise<void> {\n const promises: Array<PersistencePromise<void>> = [];\n this.changes.forEach((key, doc) => {\n if (doc.isValidDocument()) {\n promises.push(this.documentCache.addEntry(transaction, doc));\n } else {\n this.documentCache.removeEntry(key);\n }\n });\n return PersistencePromise.waitFor(promises);\n }\n\n protected getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MutableDocument> {\n return this.documentCache.getEntry(transaction, documentKey);\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<MutableDocumentMap> {\n return this.documentCache.getEntries(transaction, documentKeys);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { ReferenceSet } from './reference_set';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\n\nexport class MemoryTargetCache implements TargetCache {\n /**\n * Maps a target to the data about that target\n */\n private targets = new ObjectMap<Target, TargetData>(\n t => canonifyTarget(t),\n targetEquals\n );\n\n /** The last received snapshot version. */\n private lastRemoteSnapshotVersion = SnapshotVersion.min();\n /** The highest numbered target ID encountered. */\n private highestTargetId: TargetId = 0;\n /** The highest sequence number encountered. */\n private highestSequenceNumber: ListenSequenceNumber = 0;\n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n private references = new ReferenceSet();\n\n private targetCount = 0;\n\n private targetIdGenerator = TargetIdGenerator.forTargetCache();\n\n constructor(private readonly persistence: Persistence) {}\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise<void> {\n this.targets.forEach((_, targetData) => f(targetData));\n return PersistencePromise.resolve();\n }\n\n getLastRemoteSnapshotVersion(\n transaction: PersistenceTransaction\n ): PersistencePromise<SnapshotVersion> {\n return PersistencePromise.resolve(this.lastRemoteSnapshotVersion);\n }\n\n getHighestSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise<ListenSequenceNumber> {\n return PersistencePromise.resolve(this.highestSequenceNumber);\n }\n\n allocateTargetId(\n transaction: PersistenceTransaction\n ): PersistencePromise<TargetId> {\n this.highestTargetId = this.targetIdGenerator.next();\n return PersistencePromise.resolve(this.highestTargetId);\n }\n\n setTargetsMetadata(\n transaction: PersistenceTransaction,\n highestListenSequenceNumber: number,\n lastRemoteSnapshotVersion?: SnapshotVersion\n ): PersistencePromise<void> {\n if (lastRemoteSnapshotVersion) {\n this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\n }\n if (highestListenSequenceNumber > this.highestSequenceNumber) {\n this.highestSequenceNumber = highestListenSequenceNumber;\n }\n return PersistencePromise.resolve();\n }\n\n private saveTargetData(targetData: TargetData): void {\n this.targets.set(targetData.target, targetData);\n const targetId = targetData.targetId;\n if (targetId > this.highestTargetId) {\n this.targetIdGenerator = new TargetIdGenerator(targetId);\n this.highestTargetId = targetId;\n }\n if (targetData.sequenceNumber > this.highestSequenceNumber) {\n this.highestSequenceNumber = targetData.sequenceNumber;\n }\n }\n\n addTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n debugAssert(\n !this.targets.has(targetData.target),\n 'Adding a target that already exists'\n );\n this.saveTargetData(targetData);\n this.targetCount += 1;\n return PersistencePromise.resolve();\n }\n\n updateTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n debugAssert(\n this.targets.has(targetData.target),\n 'Updating a non-existent target'\n );\n this.saveTargetData(targetData);\n return PersistencePromise.resolve();\n }\n\n removeTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n debugAssert(this.targetCount > 0, 'Removing a target from an empty cache');\n debugAssert(\n this.targets.has(targetData.target),\n 'Removing a non-existent target from the cache'\n );\n this.targets.delete(targetData.target);\n this.references.removeReferencesForId(targetData.targetId);\n this.targetCount -= 1;\n return PersistencePromise.resolve();\n }\n\n removeTargets(\n transaction: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n let count = 0;\n const removals: Array<PersistencePromise<void>> = [];\n this.targets.forEach((key, targetData) => {\n if (\n targetData.sequenceNumber <= upperBound &&\n activeTargetIds.get(targetData.targetId) === null\n ) {\n this.targets.delete(key);\n removals.push(\n this.removeMatchingKeysForTargetId(transaction, targetData.targetId)\n );\n count++;\n }\n });\n return PersistencePromise.waitFor(removals).next(() => count);\n }\n\n getTargetCount(\n transaction: PersistenceTransaction\n ): PersistencePromise<number> {\n return PersistencePromise.resolve(this.targetCount);\n }\n\n getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<TargetData | null> {\n const targetData = this.targets.get(target) || null;\n return PersistencePromise.resolve(targetData);\n }\n\n addMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise<void> {\n this.references.addReferences(keys, targetId);\n return PersistencePromise.resolve();\n }\n\n removeMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise<void> {\n this.references.removeReferences(keys, targetId);\n const referenceDelegate = this.persistence.referenceDelegate;\n const promises: Array<PersistencePromise<void>> = [];\n if (referenceDelegate) {\n keys.forEach(key => {\n promises.push(referenceDelegate.markPotentiallyOrphaned(txn, key));\n });\n }\n return PersistencePromise.waitFor(promises);\n }\n\n removeMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise<void> {\n this.references.removeReferencesForId(targetId);\n return PersistencePromise.resolve();\n }\n\n getMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise<DocumentKeySet> {\n const matchingKeys = this.references.referencesForId(targetId);\n return PersistencePromise.resolve(matchingKeys);\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n return PersistencePromise.resolve(this.references.containsKey(key));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { estimateByteSize } from '../model/values';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { fail } from '../util/assert';\nimport { logDebug } from '../util/log';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { encodeResourcePath } from './encoded_resource_path';\nimport { IndexManager } from './index_manager';\nimport { LocalSerializer } from './local_serializer';\nimport {\n ActiveTargets,\n LruDelegate,\n LruGarbageCollector,\n LruParams\n} from './lru_garbage_collector';\nimport { newLruGarbageCollector } from './lru_garbage_collector_impl';\nimport { MemoryBundleCache } from './memory_bundle_cache';\nimport { MemoryDocumentOverlayCache } from './memory_document_overlay_cache';\nimport { MemoryIndexManager } from './memory_index_manager';\nimport { MemoryMutationQueue } from './memory_mutation_queue';\nimport {\n MemoryRemoteDocumentCache,\n newMemoryRemoteDocumentCache\n} from './memory_remote_document_cache';\nimport { MemoryTargetCache } from './memory_target_cache';\nimport { MutationQueue } from './mutation_queue';\nimport { Persistence, ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport {\n PersistenceTransaction,\n PersistenceTransactionMode\n} from './persistence_transaction';\nimport { ReferenceSet } from './reference_set';\nimport { TargetData } from './target_data';\n\nconst LOG_TAG = 'MemoryPersistence';\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nexport class MemoryPersistence implements Persistence {\n /**\n * Note that these are retained here to make it easier to write tests\n * affecting both the in-memory and IndexedDB-backed persistence layers. Tests\n * can create a new LocalStore wrapping this Persistence instance and this\n * will make the in-memory persistence layer behave as if it were actually\n * persisting values.\n */\n private readonly indexManager: MemoryIndexManager;\n private mutationQueues: { [user: string]: MemoryMutationQueue } = {};\n private overlays: { [user: string]: MemoryDocumentOverlayCache } = {};\n private readonly remoteDocumentCache: MemoryRemoteDocumentCache;\n private readonly targetCache: MemoryTargetCache;\n private readonly bundleCache: MemoryBundleCache;\n private readonly listenSequence = new ListenSequence(0);\n private serializer: LocalSerializer;\n\n private _started = false;\n\n readonly referenceDelegate: MemoryReferenceDelegate;\n\n /**\n * The constructor accepts a factory for creating a reference delegate. This\n * allows both the delegate and this instance to have strong references to\n * each other without having nullable fields that would then need to be\n * checked or asserted on every access.\n */\n constructor(\n referenceDelegateFactory: (p: MemoryPersistence) => MemoryReferenceDelegate,\n serializer: JsonProtoSerializer\n ) {\n this._started = true;\n this.referenceDelegate = referenceDelegateFactory(this);\n this.targetCache = new MemoryTargetCache(this);\n const sizer = (doc: Document): number =>\n this.referenceDelegate.documentSize(doc);\n this.indexManager = new MemoryIndexManager();\n this.remoteDocumentCache = newMemoryRemoteDocumentCache(sizer);\n this.serializer = new LocalSerializer(serializer);\n this.bundleCache = new MemoryBundleCache(this.serializer);\n }\n\n start(): Promise<void> {\n return Promise.resolve();\n }\n\n shutdown(): Promise<void> {\n // No durable state to ensure is closed on shutdown.\n this._started = false;\n return Promise.resolve();\n }\n\n get started(): boolean {\n return this._started;\n }\n\n setDatabaseDeletedListener(): void {\n // No op.\n }\n\n setNetworkEnabled(): void {\n // No op.\n }\n\n getIndexManager(user: User): MemoryIndexManager {\n // We do not currently support indices for memory persistence, so we can\n // return the same shared instance of the memory index manager.\n return this.indexManager;\n }\n\n getDocumentOverlayCache(user: User): DocumentOverlayCache {\n let overlay = this.overlays[user.toKey()];\n if (!overlay) {\n overlay = new MemoryDocumentOverlayCache();\n this.overlays[user.toKey()] = overlay;\n }\n return overlay;\n }\n\n getMutationQueue(user: User, indexManager: IndexManager): MutationQueue {\n let queue = this.mutationQueues[user.toKey()];\n if (!queue) {\n queue = new MemoryMutationQueue(indexManager, this.referenceDelegate);\n this.mutationQueues[user.toKey()] = queue;\n }\n return queue;\n }\n\n getTargetCache(): MemoryTargetCache {\n return this.targetCache;\n }\n\n getRemoteDocumentCache(): MemoryRemoteDocumentCache {\n return this.remoteDocumentCache;\n }\n\n getBundleCache(): MemoryBundleCache {\n return this.bundleCache;\n }\n\n runTransaction<T>(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise<T>\n ): Promise<T> {\n logDebug(LOG_TAG, 'Starting transaction:', action);\n const txn = new MemoryTransaction(this.listenSequence.next());\n this.referenceDelegate.onTransactionStarted();\n return transactionOperation(txn)\n .next(result => {\n return this.referenceDelegate\n .onTransactionCommitted(txn)\n .next(() => result);\n })\n .toPromise()\n .then(result => {\n txn.raiseOnCommittedEvent();\n return result;\n });\n }\n\n mutationQueuesContainKey(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n return PersistencePromise.or(\n Object.values(this.mutationQueues).map(\n queue => () => queue.containsKey(transaction, key)\n )\n );\n }\n}\n\n/**\n * Memory persistence is not actually transactional, but future implementations\n * may have transaction-scoped state.\n */\nexport class MemoryTransaction extends PersistenceTransaction {\n constructor(readonly currentSequenceNumber: ListenSequenceNumber) {\n super();\n }\n}\n\nexport interface MemoryReferenceDelegate extends ReferenceDelegate {\n documentSize(doc: Document): number;\n onTransactionStarted(): void;\n onTransactionCommitted(txn: PersistenceTransaction): PersistencePromise<void>;\n}\n\nexport class MemoryEagerDelegate implements MemoryReferenceDelegate {\n /** Tracks all documents that are active in Query views. */\n private localViewReferences: ReferenceSet = new ReferenceSet();\n /** The list of documents that are potentially GCed after each transaction. */\n private _orphanedDocuments: Set</* path= */ string> | null = null;\n\n private constructor(private readonly persistence: MemoryPersistence) {}\n\n static factory(persistence: MemoryPersistence): MemoryEagerDelegate {\n return new MemoryEagerDelegate(persistence);\n }\n\n private get orphanedDocuments(): Set<string> {\n if (!this._orphanedDocuments) {\n throw fail('orphanedDocuments is only valid during a transaction.');\n } else {\n return this._orphanedDocuments;\n }\n }\n\n addReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.localViewReferences.addReference(key, targetId);\n this.orphanedDocuments.delete(key.toString());\n return PersistencePromise.resolve();\n }\n\n removeReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.localViewReferences.removeReference(key, targetId);\n this.orphanedDocuments.add(key.toString());\n return PersistencePromise.resolve();\n }\n\n markPotentiallyOrphaned(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedDocuments.add(key.toString());\n return PersistencePromise.resolve();\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n const orphaned = this.localViewReferences.removeReferencesForId(\n targetData.targetId\n );\n orphaned.forEach(key => this.orphanedDocuments.add(key.toString()));\n const cache = this.persistence.getTargetCache();\n return cache\n .getMatchingKeysForTargetId(txn, targetData.targetId)\n .next(keys => {\n keys.forEach(key => this.orphanedDocuments.add(key.toString()));\n })\n .next(() => cache.removeTargetData(txn, targetData));\n }\n\n onTransactionStarted(): void {\n this._orphanedDocuments = new Set<string>();\n }\n\n onTransactionCommitted(\n txn: PersistenceTransaction\n ): PersistencePromise<void> {\n // Remove newly orphaned documents.\n const cache = this.persistence.getRemoteDocumentCache();\n const changeBuffer = cache.newChangeBuffer();\n return PersistencePromise.forEach(\n this.orphanedDocuments,\n (path: string) => {\n const key = DocumentKey.fromPath(path);\n return this.isReferenced(txn, key).next(isReferenced => {\n if (!isReferenced) {\n changeBuffer.removeEntry(key, SnapshotVersion.min());\n }\n });\n }\n ).next(() => {\n this._orphanedDocuments = null;\n return changeBuffer.apply(txn);\n });\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n return this.isReferenced(txn, key).next(isReferenced => {\n if (isReferenced) {\n this.orphanedDocuments.delete(key.toString());\n } else {\n this.orphanedDocuments.add(key.toString());\n }\n });\n }\n\n documentSize(doc: Document): number {\n // For eager GC, we don't care about the document size, there are no size thresholds.\n return 0;\n }\n\n private isReferenced(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n return PersistencePromise.or([\n () =>\n PersistencePromise.resolve(this.localViewReferences.containsKey(key)),\n () => this.persistence.getTargetCache().containsKey(txn, key),\n () => this.persistence.mutationQueuesContainKey(txn, key)\n ]);\n }\n}\n\nexport class MemoryLruDelegate implements ReferenceDelegate, LruDelegate {\n private orphanedSequenceNumbers: ObjectMap<\n DocumentKey,\n ListenSequenceNumber\n > = new ObjectMap(\n k => encodeResourcePath(k.path),\n (l, r) => l.isEqual(r)\n );\n\n readonly garbageCollector: LruGarbageCollector;\n\n constructor(\n private readonly persistence: MemoryPersistence,\n lruParams: LruParams\n ) {\n this.garbageCollector = newLruGarbageCollector(this, lruParams);\n }\n\n static factory(\n persistence: MemoryPersistence,\n lruParams: LruParams\n ): MemoryLruDelegate {\n return new MemoryLruDelegate(persistence, lruParams);\n }\n\n // No-ops, present so memory persistence doesn't have to care which delegate\n // it has.\n onTransactionStarted(): void {}\n\n onTransactionCommitted(\n txn: PersistenceTransaction\n ): PersistencePromise<void> {\n return PersistencePromise.resolve();\n }\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise<void> {\n return this.persistence.getTargetCache().forEachTarget(txn, f);\n }\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number> {\n const docCountPromise = this.orphanedDocumentCount(txn);\n const targetCountPromise = this.persistence\n .getTargetCache()\n .getTargetCount(txn);\n return targetCountPromise.next(targetCount =>\n docCountPromise.next(docCount => targetCount + docCount)\n );\n }\n\n private orphanedDocumentCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number> {\n let orphanedCount = 0;\n return this.forEachOrphanedDocumentSequenceNumber(txn, _ => {\n orphanedCount++;\n }).next(() => orphanedCount);\n }\n\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise<void> {\n return PersistencePromise.forEach(\n this.orphanedSequenceNumbers,\n (key, sequenceNumber) => {\n // Pass in the exact sequence number as the upper bound so we know it won't be pinned by\n // being too recent.\n return this.isPinned(txn, key, sequenceNumber).next(isPinned => {\n if (!isPinned) {\n return f(sequenceNumber);\n } else {\n return PersistencePromise.resolve();\n }\n });\n }\n );\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n return this.persistence\n .getTargetCache()\n .removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number> {\n let count = 0;\n const cache = this.persistence.getRemoteDocumentCache();\n const changeBuffer = cache.newChangeBuffer();\n const p = cache.forEachDocumentKey(txn, key => {\n return this.isPinned(txn, key, upperBound).next(isPinned => {\n if (!isPinned) {\n count++;\n changeBuffer.removeEntry(key, SnapshotVersion.min());\n }\n });\n });\n return p.next(() => changeBuffer.apply(txn)).next(() => count);\n }\n\n markPotentiallyOrphaned(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n const updated = targetData.withSequenceNumber(txn.currentSequenceNumber);\n return this.persistence.getTargetCache().updateTargetData(txn, updated);\n }\n\n addReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n removeReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n documentSize(document: Document): number {\n let documentSize = document.key.toString().length;\n if (document.isFoundDocument()) {\n documentSize += estimateByteSize(document.data.value);\n }\n return documentSize;\n }\n\n private isPinned(\n txn: PersistenceTransaction,\n key: DocumentKey,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<boolean> {\n return PersistencePromise.or([\n () => this.persistence.mutationQueuesContainKey(txn, key),\n () => this.persistence.getTargetCache().containsKey(txn, key),\n () => {\n const orphanedAt = this.orphanedSequenceNumbers.get(key);\n return PersistencePromise.resolve(\n orphanedAt !== undefined && orphanedAt > upperBound\n );\n }\n ]);\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return this.persistence.getRemoteDocumentCache().getSize(txn);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TargetId } from '../core/types';\nimport { ChangeType, ViewSnapshot } from '../core/view_snapshot';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\n\n/**\n * A set of changes to what documents are currently in view and out of view for\n * a given query. These changes are sent to the LocalStore by the View (via\n * the SyncEngine) and are used to pin / unpin documents as appropriate.\n */\nexport class LocalViewChanges {\n constructor(\n readonly targetId: TargetId,\n readonly fromCache: boolean,\n readonly addedKeys: DocumentKeySet,\n readonly removedKeys: DocumentKeySet\n ) {}\n\n static fromSnapshot(\n targetId: TargetId,\n viewSnapshot: ViewSnapshot\n ): LocalViewChanges {\n let addedKeys = documentKeySet();\n let removedKeys = documentKeySet();\n\n for (const docChange of viewSnapshot.docChanges) {\n switch (docChange.type) {\n case ChangeType.Added:\n addedKeys = addedKeys.add(docChange.doc.key);\n break;\n case ChangeType.Removed:\n removedKeys = removedKeys.add(docChange.doc.key);\n break;\n default:\n // do nothing\n }\n }\n\n return new LocalViewChanges(\n targetId,\n viewSnapshot.fromCache,\n addedKeys,\n removedKeys\n );\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A tracker to keep a record of important details during database local query\n * execution.\n */\nexport class QueryContext {\n /**\n * Counts the number of documents passed through during local query execution.\n */\n private _documentReadCount = 0;\n\n get documentReadCount(): number {\n return this._documentReadCount;\n }\n\n incrementDocumentReadCount(amount: number): void {\n this._documentReadCount += amount;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n LimitType,\n newQueryComparator,\n Query,\n queryMatches,\n queryMatchesAllDocuments,\n queryToTarget,\n queryWithLimit,\n stringifyQuery\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n documentKeySet,\n DocumentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport {\n IndexOffset,\n INITIAL_LARGEST_BATCH_ID,\n newIndexOffsetSuccessorFromReadTime\n} from '../model/field_index';\nimport { debugAssert } from '../util/assert';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { Iterable } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager, IndexType } from './index_manager';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\n\nconst DEFAULT_INDEX_AUTO_CREATION_MIN_COLLECTION_SIZE = 100;\n\n/**\n * This cost represents the evaluation result of\n * (([index, docKey] + [docKey, docContent]) per document in the result set)\n * / ([docKey, docContent] per documents in full collection scan) coming from\n * experiment [enter PR experiment URL here].\n * TODO(b/299284287) Choose a value appropriate for the browser/OS combination,\n * as determined by more data points from running the experiment.\n */\nconst DEFAULT_RELATIVE_INDEX_READ_COST_PER_DOCUMENT = 8;\n\n/**\n * The Firestore query engine.\n *\n * Firestore queries can be executed in three modes. The Query Engine determines\n * what mode to use based on what data is persisted. The mode only determines\n * the runtime complexity of the query - the result set is equivalent across all\n * implementations.\n *\n * The Query engine will use indexed-based execution if a user has configured\n * any index that can be used to execute query (via `setIndexConfiguration()`).\n * Otherwise, the engine will try to optimize the query by re-using a previously\n * persisted query result. If that is not possible, the query will be executed\n * via a full collection scan.\n *\n * Index-based execution is the default when available. The query engine\n * supports partial indexed execution and merges the result from the index\n * lookup with documents that have not yet been indexed. The index evaluation\n * matches the backend's format and as such, the SDK can use indexing for all\n * queries that the backend supports.\n *\n * If no index exists, the query engine tries to take advantage of the target\n * document mapping in the TargetCache. These mappings exists for all queries\n * that have been synced with the backend at least once and allow the query\n * engine to only read documents that previously matched a query plus any\n * documents that were edited after the query was last listened to.\n *\n * There are some cases when this optimization is not guaranteed to produce\n * the same results as full collection scans. In these cases, query\n * processing falls back to full scans. These cases are:\n *\n * - Limit queries where a document that matched the query previously no longer\n * matches the query.\n *\n * - Limit queries where a document edit may cause the document to sort below\n * another document that is in the local cache.\n *\n * - Queries that have never been CURRENT or free of limbo documents.\n */\nexport class QueryEngine {\n private localDocumentsView!: LocalDocumentsView;\n private indexManager!: IndexManager;\n private initialized = false;\n\n indexAutoCreationEnabled = false;\n\n /**\n * SDK only decides whether it should create index when collection size is\n * larger than this.\n */\n indexAutoCreationMinCollectionSize =\n DEFAULT_INDEX_AUTO_CREATION_MIN_COLLECTION_SIZE;\n\n relativeIndexReadCostPerDocument =\n DEFAULT_RELATIVE_INDEX_READ_COST_PER_DOCUMENT;\n\n /** Sets the document view to query against. */\n initialize(\n localDocuments: LocalDocumentsView,\n indexManager: IndexManager\n ): void {\n this.localDocumentsView = localDocuments;\n this.indexManager = indexManager;\n this.initialized = true;\n }\n\n /** Returns all local documents matching the specified query. */\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n lastLimboFreeSnapshotVersion: SnapshotVersion,\n remoteKeys: DocumentKeySet\n ): PersistencePromise<DocumentMap> {\n debugAssert(this.initialized, 'initialize() not called');\n\n // Stores the result from executing the query; using this object is more\n // convenient than passing the result between steps of the persistence\n // transaction and improves readability comparatively.\n const queryResult: { result: DocumentMap | null } = { result: null };\n\n return this.performQueryUsingIndex(transaction, query)\n .next(result => {\n queryResult.result = result;\n })\n .next(() => {\n if (queryResult.result) {\n return;\n }\n return this.performQueryUsingRemoteKeys(\n transaction,\n query,\n remoteKeys,\n lastLimboFreeSnapshotVersion\n ).next(result => {\n queryResult.result = result;\n });\n })\n .next(() => {\n if (queryResult.result) {\n return;\n }\n const context = new QueryContext();\n return this.executeFullCollectionScan(transaction, query, context).next(\n result => {\n queryResult.result = result;\n if (this.indexAutoCreationEnabled) {\n return this.createCacheIndexes(\n transaction,\n query,\n context,\n result.size\n );\n }\n }\n );\n })\n .next(() => queryResult.result!);\n }\n\n createCacheIndexes(\n transaction: PersistenceTransaction,\n query: Query,\n context: QueryContext,\n resultSize: number\n ): PersistencePromise<void> {\n if (context.documentReadCount < this.indexAutoCreationMinCollectionSize) {\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'SDK will not create cache indexes for query:',\n stringifyQuery(query),\n 'since it only creates cache indexes for collection contains',\n 'more than or equal to',\n this.indexAutoCreationMinCollectionSize,\n 'documents'\n );\n }\n return PersistencePromise.resolve();\n }\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'Query:',\n stringifyQuery(query),\n 'scans',\n context.documentReadCount,\n 'local documents and returns',\n resultSize,\n 'documents as results.'\n );\n }\n\n if (\n context.documentReadCount >\n this.relativeIndexReadCostPerDocument * resultSize\n ) {\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'The SDK decides to create cache indexes for query:',\n stringifyQuery(query),\n 'as using cache indexes may help improve performance.'\n );\n }\n return this.indexManager.createTargetIndexes(\n transaction,\n queryToTarget(query)\n );\n }\n\n return PersistencePromise.resolve();\n }\n\n /**\n * Performs an indexed query that evaluates the query based on a collection's\n * persisted index values. Returns `null` if an index is not available.\n */\n private performQueryUsingIndex(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise<DocumentMap | null> {\n if (queryMatchesAllDocuments(query)) {\n // Queries that match all documents don't benefit from using\n // key-based lookups. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n return PersistencePromise.resolve<DocumentMap | null>(null);\n }\n\n let target = queryToTarget(query);\n return this.indexManager\n .getIndexType(transaction, target)\n .next(indexType => {\n if (indexType === IndexType.NONE) {\n // The target cannot be served from any index.\n return null;\n }\n\n if (query.limit !== null && indexType === IndexType.PARTIAL) {\n // We cannot apply a limit for targets that are served using a partial\n // index. If a partial index will be used to serve the target, the\n // query may return a superset of documents that match the target\n // (e.g. if the index doesn't include all the target's filters), or\n // may return the correct set of documents in the wrong order (e.g. if\n // the index doesn't include a segment for one of the orderBys).\n // Therefore, a limit should not be applied in such cases.\n query = queryWithLimit(query, null, LimitType.First);\n target = queryToTarget(query);\n }\n\n return this.indexManager\n .getDocumentsMatchingTarget(transaction, target)\n .next(keys => {\n debugAssert(\n !!keys,\n 'Index manager must return results for partial and full indexes.'\n );\n const sortedKeys = documentKeySet(...keys);\n return this.localDocumentsView\n .getDocuments(transaction, sortedKeys)\n .next(indexedDocuments => {\n return this.indexManager\n .getMinOffset(transaction, target)\n .next(offset => {\n const previousResults = this.applyQuery(\n query,\n indexedDocuments\n );\n\n if (\n this.needsRefill(\n query,\n previousResults,\n sortedKeys,\n offset.readTime\n )\n ) {\n // A limit query whose boundaries change due to local\n // edits can be re-run against the cache by excluding the\n // limit. This ensures that all documents that match the\n // query's filters are included in the result set. The SDK\n // can then apply the limit once all local edits are\n // incorporated.\n return this.performQueryUsingIndex(\n transaction,\n queryWithLimit(query, null, LimitType.First)\n );\n }\n\n return this.appendRemainingResults(\n transaction,\n previousResults,\n query,\n offset\n ) as PersistencePromise<DocumentMap | null>;\n });\n });\n });\n });\n }\n\n /**\n * Performs a query based on the target's persisted query mapping. Returns\n * `null` if the mapping is not available or cannot be used.\n */\n private performQueryUsingRemoteKeys(\n transaction: PersistenceTransaction,\n query: Query,\n remoteKeys: DocumentKeySet,\n lastLimboFreeSnapshotVersion: SnapshotVersion\n ): PersistencePromise<DocumentMap | null> {\n if (queryMatchesAllDocuments(query)) {\n // Queries that match all documents don't benefit from using\n // key-based lookups. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n return PersistencePromise.resolve<DocumentMap | null>(null);\n }\n\n // Queries that have never seen a snapshot without limbo free documents\n // should also be run as a full collection scan.\n if (lastLimboFreeSnapshotVersion.isEqual(SnapshotVersion.min())) {\n return PersistencePromise.resolve<DocumentMap | null>(null);\n }\n\n return this.localDocumentsView!.getDocuments(transaction, remoteKeys).next(\n documents => {\n const previousResults = this.applyQuery(query, documents);\n\n if (\n this.needsRefill(\n query,\n previousResults,\n remoteKeys,\n lastLimboFreeSnapshotVersion\n )\n ) {\n return PersistencePromise.resolve<DocumentMap | null>(null);\n }\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'Re-using previous result from %s to execute query: %s',\n lastLimboFreeSnapshotVersion.toString(),\n stringifyQuery(query)\n );\n }\n\n // Retrieve all results for documents that were updated since the last\n // limbo-document free remote snapshot.\n return this.appendRemainingResults(\n transaction,\n previousResults,\n query,\n newIndexOffsetSuccessorFromReadTime(\n lastLimboFreeSnapshotVersion,\n INITIAL_LARGEST_BATCH_ID\n )\n ).next<DocumentMap | null>(results => results);\n }\n );\n }\n\n /** Applies the query filter and sorting to the provided documents. */\n private applyQuery(\n query: Query,\n documents: DocumentMap\n ): SortedSet<Document> {\n // Sort the documents and re-apply the query filter since previously\n // matching documents do not necessarily still match the query.\n let queryResults = new SortedSet<Document>(newQueryComparator(query));\n documents.forEach((_, maybeDoc) => {\n if (queryMatches(query, maybeDoc)) {\n queryResults = queryResults.add(maybeDoc);\n }\n });\n return queryResults;\n }\n\n /**\n * Determines if a limit query needs to be refilled from cache, making it\n * ineligible for index-free execution.\n *\n * @param query - The query.\n * @param sortedPreviousResults - The documents that matched the query when it\n * was last synchronized, sorted by the query's comparator.\n * @param remoteKeys - The document keys that matched the query at the last\n * snapshot.\n * @param limboFreeSnapshotVersion - The version of the snapshot when the\n * query was last synchronized.\n */\n private needsRefill(\n query: Query,\n sortedPreviousResults: SortedSet<Document>,\n remoteKeys: DocumentKeySet,\n limboFreeSnapshotVersion: SnapshotVersion\n ): boolean {\n if (query.limit === null) {\n // Queries without limits do not need to be refilled.\n return false;\n }\n\n if (remoteKeys.size !== sortedPreviousResults.size) {\n // The query needs to be refilled if a previously matching document no\n // longer matches.\n return true;\n }\n\n // Limit queries are not eligible for index-free query execution if there is\n // a potential that an older document from cache now sorts before a document\n // that was previously part of the limit. This, however, can only happen if\n // the document at the edge of the limit goes out of limit.\n // If a document that is not the limit boundary sorts differently,\n // the boundary of the limit itself did not change and documents from cache\n // will continue to be \"rejected\" by this boundary. Therefore, we can ignore\n // any modifications that don't affect the last document.\n const docAtLimitEdge =\n query.limitType === LimitType.First\n ? sortedPreviousResults.last()\n : sortedPreviousResults.first();\n if (!docAtLimitEdge) {\n // We don't need to refill the query if there were already no documents.\n return false;\n }\n return (\n docAtLimitEdge.hasPendingWrites ||\n docAtLimitEdge.version.compareTo(limboFreeSnapshotVersion) > 0\n );\n }\n\n private executeFullCollectionScan(\n transaction: PersistenceTransaction,\n query: Query,\n context: QueryContext\n ): PersistencePromise<DocumentMap> {\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'Using full collection scan to execute query:',\n stringifyQuery(query)\n );\n }\n\n return this.localDocumentsView!.getDocumentsMatchingQuery(\n transaction,\n query,\n IndexOffset.min(),\n context\n );\n }\n\n /**\n * Combines the results from an indexed execution with the remaining documents\n * that have not yet been indexed.\n */\n private appendRemainingResults(\n transaction: PersistenceTransaction,\n indexedResults: Iterable<Document>,\n query: Query,\n offset: IndexOffset\n ): PersistencePromise<DocumentMap> {\n // Retrieve all results for documents that were updated since the offset.\n return this.localDocumentsView\n .getDocumentsMatchingQuery(transaction, query, offset)\n .next(remainingResults => {\n // Merge with existing results\n indexedResults.forEach(d => {\n remainingResults = remainingResults.insert(d.key, d);\n });\n return remainingResults;\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { BundleConverter, BundledDocuments, NamedQuery } from '../core/bundle';\nimport {\n newQueryForPath,\n Query,\n queryCollectionGroup,\n queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\nimport { BatchId, TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n convertOverlayedDocumentMapToDocumentMap,\n documentKeySet,\n DocumentKeySet,\n DocumentMap,\n mutableDocumentMap,\n MutableDocumentMap,\n OverlayedDocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexSemanticComparator,\n INITIAL_LARGEST_BATCH_ID,\n newIndexOffsetSuccessorFromReadTime\n} from '../model/field_index';\nimport {\n mutationExtractBaseValue,\n Mutation,\n PatchMutation,\n Precondition\n} from '../model/mutation';\nimport { MutationBatch, MutationBatchResult } from '../model/mutation_batch';\nimport { extractFieldMask } from '../model/object_value';\nimport { ResourcePath } from '../model/path';\nimport {\n BundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { RemoteEvent, TargetChange } from '../remote/remote_event';\nimport { fromVersion, JsonProtoSerializer } from '../remote/serializer';\nimport { diffArrays } from '../util/array';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logDebug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { BundleCache } from './bundle_cache';\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport { IndexedDbPersistence } from './indexeddb_persistence';\nimport { IndexedDbTargetCache } from './indexeddb_target_cache';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { fromBundledQuery } from './local_serializer';\nimport { LocalStore } from './local_store';\nimport { LocalViewChanges } from './local_view_changes';\nimport { LruGarbageCollector, LruResults } from './lru_garbage_collector';\nimport { MutationQueue } from './mutation_queue';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryEngine } from './query_engine';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { ClientId } from './shared_client_state';\nimport { isIndexedDbTransactionError } from './simple_db';\nimport { TargetCache } from './target_cache';\nimport { TargetData, TargetPurpose } from './target_data';\n\nexport const LOG_TAG = 'LocalStore';\n\n/**\n * The maximum time to leave a resume token buffered without writing it out.\n * This value is arbitrary: it's long enough to avoid several writes\n * (possibly indefinitely if updates come more frequently than this) but\n * short enough that restarting after crashing will still have a pretty\n * recent resume token.\n */\nconst RESUME_TOKEN_MAX_AGE_MICROS = 5 * 60 * 1e6;\n\n/** The result of a write to the local store. */\nexport interface LocalWriteResult {\n batchId: BatchId;\n changes: DocumentMap;\n}\n\n/** The result of a user-change operation in the local store. */\nexport interface UserChangeResult {\n readonly affectedDocuments: DocumentMap;\n readonly removedBatchIds: BatchId[];\n readonly addedBatchIds: BatchId[];\n}\n\n/** The result of executing a query against the local store. */\nexport interface QueryResult {\n readonly documents: DocumentMap;\n readonly remoteKeys: DocumentKeySet;\n}\n\n/**\n * Implements `LocalStore` interface.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass LocalStoreImpl implements LocalStore {\n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n mutationQueue!: MutationQueue;\n\n /**\n * The overlays that can be used to short circuit applying all mutations from\n * mutation queue.\n */\n documentOverlayCache!: DocumentOverlayCache;\n\n /** The set of all cached remote documents. */\n remoteDocuments: RemoteDocumentCache;\n\n /**\n * The \"local\" view of all documents (layering mutationQueue on top of\n * remoteDocumentCache).\n */\n localDocuments!: LocalDocumentsView;\n\n /** Manages the list of active field and collection indices. */\n indexManager!: IndexManager;\n\n /** The set of all cached bundle metadata and named queries. */\n bundleCache: BundleCache;\n\n /** Maps a target to its `TargetData`. */\n targetCache: TargetCache;\n\n /**\n * Maps a targetID to data about its target.\n *\n * PORTING NOTE: We are using an immutable data structure on Web to make re-runs\n * of `applyRemoteEvent()` idempotent.\n */\n targetDataByTarget = new SortedMap<TargetId, TargetData>(primitiveComparator);\n\n /** Maps a target to its targetID. */\n // TODO(wuandy): Evaluate if TargetId can be part of Target.\n targetIdByTarget = new ObjectMap<Target, TargetId>(\n t => canonifyTarget(t),\n targetEquals\n );\n\n /**\n * A per collection group index of the last read time processed by\n * `getNewDocumentChanges()`.\n *\n * PORTING NOTE: This is only used for multi-tab synchronization.\n */\n collectionGroupReadTime = new Map<string, SnapshotVersion>();\n\n constructor(\n /** Manages our in-memory or durable persistence. */\n readonly persistence: Persistence,\n readonly queryEngine: QueryEngine,\n initialUser: User,\n readonly serializer: JsonProtoSerializer\n ) {\n debugAssert(\n persistence.started,\n 'LocalStore was passed an unstarted persistence implementation'\n );\n this.remoteDocuments = persistence.getRemoteDocumentCache();\n this.targetCache = persistence.getTargetCache();\n this.bundleCache = persistence.getBundleCache();\n\n this.initializeUserComponents(initialUser);\n }\n\n initializeUserComponents(user: User): void {\n // TODO(indexing): Add spec tests that test these components change after a\n // user change\n this.documentOverlayCache = this.persistence.getDocumentOverlayCache(user);\n this.indexManager = this.persistence.getIndexManager(user);\n this.mutationQueue = this.persistence.getMutationQueue(\n user,\n this.indexManager\n );\n this.localDocuments = new LocalDocumentsView(\n this.remoteDocuments,\n this.mutationQueue,\n this.documentOverlayCache,\n this.indexManager\n );\n this.remoteDocuments.setIndexManager(this.indexManager);\n this.queryEngine.initialize(this.localDocuments, this.indexManager);\n }\n\n collectGarbage(garbageCollector: LruGarbageCollector): Promise<LruResults> {\n return this.persistence.runTransaction(\n 'Collect garbage',\n 'readwrite-primary',\n txn => garbageCollector.collect(txn, this.targetDataByTarget)\n );\n }\n}\n\ninterface DocumentChangeResult {\n changedDocuments: MutableDocumentMap;\n existenceChangedKeys: DocumentKeySet;\n}\n\nexport function newLocalStore(\n /** Manages our in-memory or durable persistence. */\n persistence: Persistence,\n queryEngine: QueryEngine,\n initialUser: User,\n serializer: JsonProtoSerializer\n): LocalStore {\n return new LocalStoreImpl(persistence, queryEngine, initialUser, serializer);\n}\n\n/**\n * Tells the LocalStore that the currently authenticated user has changed.\n *\n * In response the local store switches the mutation queue to the new user and\n * returns any resulting document changes.\n */\n// PORTING NOTE: Android and iOS only return the documents affected by the\n// change.\nexport async function localStoreHandleUserChange(\n localStore: LocalStore,\n user: User\n): Promise<UserChangeResult> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n\n const result = await localStoreImpl.persistence.runTransaction(\n 'Handle user change',\n 'readonly',\n txn => {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n let oldBatches: MutationBatch[];\n return localStoreImpl.mutationQueue\n .getAllMutationBatches(txn)\n .next(promisedOldBatches => {\n oldBatches = promisedOldBatches;\n localStoreImpl.initializeUserComponents(user);\n return localStoreImpl.mutationQueue.getAllMutationBatches(txn);\n })\n .next(newBatches => {\n const removedBatchIds: BatchId[] = [];\n const addedBatchIds: BatchId[] = [];\n\n // Union the old/new changed keys.\n let changedKeys = documentKeySet();\n\n for (const batch of oldBatches) {\n removedBatchIds.push(batch.batchId);\n for (const mutation of batch.mutations) {\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n\n for (const batch of newBatches) {\n addedBatchIds.push(batch.batchId);\n for (const mutation of batch.mutations) {\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n\n // Return the set of all (potentially) changed documents and the list\n // of mutation batch IDs that were affected by change.\n return localStoreImpl.localDocuments\n .getDocuments(txn, changedKeys)\n .next(affectedDocuments => {\n return {\n affectedDocuments,\n removedBatchIds,\n addedBatchIds\n };\n });\n });\n }\n );\n\n return result;\n}\n\n/* Accepts locally generated Mutations and commit them to storage. */\nexport function localStoreWriteLocally(\n localStore: LocalStore,\n mutations: Mutation[]\n): Promise<LocalWriteResult> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const localWriteTime = Timestamp.now();\n const keys = mutations.reduce((keys, m) => keys.add(m.key), documentKeySet());\n\n let overlayedDocuments: OverlayedDocumentMap;\n let mutationBatch: MutationBatch;\n\n return localStoreImpl.persistence\n .runTransaction('Locally write mutations', 'readwrite', txn => {\n // Figure out which keys do not have a remote version in the cache, this\n // is needed to create the right overlay mutation: if no remote version\n // presents, we do not need to create overlays as patch mutations.\n // TODO(Overlay): Is there a better way to determine this? Using the\n // document version does not work because local mutations set them back\n // to 0.\n let remoteDocs = mutableDocumentMap();\n let docsWithoutRemoteVersion = documentKeySet();\n return localStoreImpl.remoteDocuments\n .getEntries(txn, keys)\n .next(docs => {\n remoteDocs = docs;\n remoteDocs.forEach((key, doc) => {\n if (!doc.isValidDocument()) {\n docsWithoutRemoteVersion = docsWithoutRemoteVersion.add(key);\n }\n });\n })\n .next(() => {\n // Load and apply all existing mutations. This lets us compute the\n // current base state for all non-idempotent transforms before applying\n // any additional user-provided writes.\n return localStoreImpl.localDocuments.getOverlayedDocuments(\n txn,\n remoteDocs\n );\n })\n .next((docs: OverlayedDocumentMap) => {\n overlayedDocuments = docs;\n\n // For non-idempotent mutations (such as `FieldValue.increment()`),\n // we record the base state in a separate patch mutation. This is\n // later used to guarantee consistent values and prevents flicker\n // even if the backend sends us an update that already includes our\n // transform.\n const baseMutations: Mutation[] = [];\n\n for (const mutation of mutations) {\n const baseValue = mutationExtractBaseValue(\n mutation,\n overlayedDocuments.get(mutation.key)!.overlayedDocument\n );\n if (baseValue != null) {\n // NOTE: The base state should only be applied if there's some\n // existing document to override, so use a Precondition of\n // exists=true\n baseMutations.push(\n new PatchMutation(\n mutation.key,\n baseValue,\n extractFieldMask(baseValue.value.mapValue),\n Precondition.exists(true)\n )\n );\n }\n }\n\n return localStoreImpl.mutationQueue.addMutationBatch(\n txn,\n localWriteTime,\n baseMutations,\n mutations\n );\n })\n .next(batch => {\n mutationBatch = batch;\n const overlays = batch.applyToLocalDocumentSet(\n overlayedDocuments,\n docsWithoutRemoteVersion\n );\n return localStoreImpl.documentOverlayCache.saveOverlays(\n txn,\n batch.batchId,\n overlays\n );\n });\n })\n .then(() => ({\n batchId: mutationBatch.batchId,\n changes: convertOverlayedDocumentMapToDocumentMap(overlayedDocuments)\n }));\n}\n\n/**\n * Acknowledges the given batch.\n *\n * On the happy path when a batch is acknowledged, the local store will\n *\n * + remove the batch from the mutation queue;\n * + apply the changes to the remote document cache;\n * + recalculate the latency compensated view implied by those changes (there\n * may be mutations in the queue that affect the documents but haven't been\n * acknowledged yet); and\n * + give the changed documents back the sync engine\n *\n * @returns The resulting (modified) documents.\n */\nexport function localStoreAcknowledgeBatch(\n localStore: LocalStore,\n batchResult: MutationBatchResult\n): Promise<DocumentMap> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Acknowledge batch',\n 'readwrite-primary',\n txn => {\n const affected = batchResult.batch.keys();\n const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n return applyWriteToRemoteDocuments(\n localStoreImpl,\n txn,\n batchResult,\n documentBuffer\n )\n .next(() => documentBuffer.apply(txn))\n .next(() => localStoreImpl.mutationQueue.performConsistencyCheck(txn))\n .next(() =>\n localStoreImpl.documentOverlayCache.removeOverlaysForBatchId(\n txn,\n affected,\n batchResult.batch.batchId\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(\n txn,\n getKeysWithTransformResults(batchResult)\n )\n )\n .next(() => localStoreImpl.localDocuments.getDocuments(txn, affected));\n }\n );\n}\n\nfunction getKeysWithTransformResults(\n batchResult: MutationBatchResult\n): DocumentKeySet {\n let result = documentKeySet();\n\n for (let i = 0; i < batchResult.mutationResults.length; ++i) {\n const mutationResult = batchResult.mutationResults[i];\n if (mutationResult.transformResults.length > 0) {\n result = result.add(batchResult.batch.mutations[i].key);\n }\n }\n return result;\n}\n\n/**\n * Removes mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */\nexport function localStoreRejectBatch(\n localStore: LocalStore,\n batchId: BatchId\n): Promise<DocumentMap> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Reject batch',\n 'readwrite-primary',\n txn => {\n let affectedKeys: DocumentKeySet;\n return localStoreImpl.mutationQueue\n .lookupMutationBatch(txn, batchId)\n .next((batch: MutationBatch | null) => {\n hardAssert(batch !== null, 'Attempt to reject nonexistent batch!');\n affectedKeys = batch.keys();\n return localStoreImpl.mutationQueue.removeMutationBatch(txn, batch);\n })\n .next(() => localStoreImpl.mutationQueue.performConsistencyCheck(txn))\n .next(() =>\n localStoreImpl.documentOverlayCache.removeOverlaysForBatchId(\n txn,\n affectedKeys,\n batchId\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(\n txn,\n affectedKeys\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.getDocuments(txn, affectedKeys)\n );\n }\n );\n}\n\n/**\n * Returns the largest (latest) batch id in mutation queue that is pending\n * server response.\n *\n * Returns `BATCHID_UNKNOWN` if the queue is empty.\n */\nexport function localStoreGetHighestUnacknowledgedBatchId(\n localStore: LocalStore\n): Promise<BatchId> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get highest unacknowledged batch id',\n 'readonly',\n txn => localStoreImpl.mutationQueue.getHighestUnacknowledgedBatchId(txn)\n );\n}\n\n/**\n * Returns the last consistent snapshot processed (used by the RemoteStore to\n * determine whether to buffer incoming snapshots from the backend).\n */\nexport function localStoreGetLastRemoteSnapshotVersion(\n localStore: LocalStore\n): Promise<SnapshotVersion> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get last remote snapshot version',\n 'readonly',\n txn => localStoreImpl.targetCache.getLastRemoteSnapshotVersion(txn)\n );\n}\n\n/**\n * Updates the \"ground-state\" (remote) documents. We assume that the remote\n * event reflects any write batches that have been acknowledged or rejected\n * (i.e. we do not re-apply local mutations to updates from this event).\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nexport function localStoreApplyRemoteEventToLocalCache(\n localStore: LocalStore,\n remoteEvent: RemoteEvent\n): Promise<DocumentMap> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const remoteVersion = remoteEvent.snapshotVersion;\n let newTargetDataByTargetMap = localStoreImpl.targetDataByTarget;\n\n return localStoreImpl.persistence\n .runTransaction('Apply remote event', 'readwrite-primary', txn => {\n const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n\n // Reset newTargetDataByTargetMap in case this transaction gets re-run.\n newTargetDataByTargetMap = localStoreImpl.targetDataByTarget;\n\n const promises = [] as Array<PersistencePromise<void>>;\n remoteEvent.targetChanges.forEach((change, targetId) => {\n const oldTargetData = newTargetDataByTargetMap.get(targetId);\n if (!oldTargetData) {\n return;\n }\n\n // Only update the remote keys if the target is still active. This\n // ensures that we can persist the updated target data along with\n // the updated assignment.\n promises.push(\n localStoreImpl.targetCache\n .removeMatchingKeys(txn, change.removedDocuments, targetId)\n .next(() => {\n return localStoreImpl.targetCache.addMatchingKeys(\n txn,\n change.addedDocuments,\n targetId\n );\n })\n );\n\n let newTargetData = oldTargetData.withSequenceNumber(\n txn.currentSequenceNumber\n );\n if (remoteEvent.targetMismatches.get(targetId) !== null) {\n newTargetData = newTargetData\n .withResumeToken(\n ByteString.EMPTY_BYTE_STRING,\n SnapshotVersion.min()\n )\n .withLastLimboFreeSnapshotVersion(SnapshotVersion.min());\n } else if (change.resumeToken.approximateByteSize() > 0) {\n newTargetData = newTargetData.withResumeToken(\n change.resumeToken,\n remoteVersion\n );\n }\n\n newTargetDataByTargetMap = newTargetDataByTargetMap.insert(\n targetId,\n newTargetData\n );\n\n // Update the target data if there are target changes (or if\n // sufficient time has passed since the last update).\n if (shouldPersistTargetData(oldTargetData, newTargetData, change)) {\n promises.push(\n localStoreImpl.targetCache.updateTargetData(txn, newTargetData)\n );\n }\n });\n\n let changedDocs = mutableDocumentMap();\n let existenceChangedKeys = documentKeySet();\n remoteEvent.documentUpdates.forEach(key => {\n if (remoteEvent.resolvedLimboDocuments.has(key)) {\n promises.push(\n localStoreImpl.persistence.referenceDelegate.updateLimboDocument(\n txn,\n key\n )\n );\n }\n });\n\n // Each loop iteration only affects its \"own\" doc, so it's safe to get all\n // the remote documents in advance in a single call.\n promises.push(\n populateDocumentChangeBuffer(\n txn,\n documentBuffer,\n remoteEvent.documentUpdates\n ).next(result => {\n changedDocs = result.changedDocuments;\n existenceChangedKeys = result.existenceChangedKeys;\n })\n );\n\n // HACK: The only reason we allow a null snapshot version is so that we\n // can synthesize remote events when we get permission denied errors while\n // trying to resolve the state of a locally cached document that is in\n // limbo.\n if (!remoteVersion.isEqual(SnapshotVersion.min())) {\n const updateRemoteVersion = localStoreImpl.targetCache\n .getLastRemoteSnapshotVersion(txn)\n .next(lastRemoteSnapshotVersion => {\n debugAssert(\n remoteVersion.compareTo(lastRemoteSnapshotVersion) >= 0,\n 'Watch stream reverted to previous snapshot?? ' +\n remoteVersion +\n ' < ' +\n lastRemoteSnapshotVersion\n );\n return localStoreImpl.targetCache.setTargetsMetadata(\n txn,\n txn.currentSequenceNumber,\n remoteVersion\n );\n });\n promises.push(updateRemoteVersion);\n }\n\n return PersistencePromise.waitFor(promises)\n .next(() => documentBuffer.apply(txn))\n .next(() =>\n localStoreImpl.localDocuments.getLocalViewOfDocuments(\n txn,\n changedDocs,\n existenceChangedKeys\n )\n )\n .next(() => changedDocs);\n })\n .then(changedDocs => {\n localStoreImpl.targetDataByTarget = newTargetDataByTargetMap;\n return changedDocs;\n });\n}\n\n/**\n * Populates document change buffer with documents from backend or a bundle.\n * Returns the document changes resulting from applying those documents, and\n * also a set of documents whose existence state are changed as a result.\n *\n * @param txn - Transaction to use to read existing documents from storage.\n * @param documentBuffer - Document buffer to collect the resulted changes to be\n * applied to storage.\n * @param documents - Documents to be applied.\n */\nfunction populateDocumentChangeBuffer(\n txn: PersistenceTransaction,\n documentBuffer: RemoteDocumentChangeBuffer,\n documents: MutableDocumentMap\n): PersistencePromise<DocumentChangeResult> {\n let updatedKeys = documentKeySet();\n let existenceChangedKeys = documentKeySet();\n documents.forEach(k => (updatedKeys = updatedKeys.add(k)));\n return documentBuffer.getEntries(txn, updatedKeys).next(existingDocs => {\n let changedDocuments = mutableDocumentMap();\n documents.forEach((key, doc) => {\n const existingDoc = existingDocs.get(key)!;\n\n // Check if see if there is a existence state change for this document.\n if (doc.isFoundDocument() !== existingDoc.isFoundDocument()) {\n existenceChangedKeys = existenceChangedKeys.add(key);\n }\n\n // Note: The order of the steps below is important, since we want\n // to ensure that rejected limbo resolutions (which fabricate\n // NoDocuments with SnapshotVersion.min()) never add documents to\n // cache.\n if (doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min())) {\n // NoDocuments with SnapshotVersion.min() are used in manufactured\n // events. We remove these documents from cache since we lost\n // access.\n documentBuffer.removeEntry(key, doc.readTime);\n changedDocuments = changedDocuments.insert(key, doc);\n } else if (\n !existingDoc.isValidDocument() ||\n doc.version.compareTo(existingDoc.version) > 0 ||\n (doc.version.compareTo(existingDoc.version) === 0 &&\n existingDoc.hasPendingWrites)\n ) {\n debugAssert(\n !SnapshotVersion.min().isEqual(doc.readTime),\n 'Cannot add a document when the remote version is zero'\n );\n documentBuffer.addEntry(doc);\n changedDocuments = changedDocuments.insert(key, doc);\n } else {\n logDebug(\n LOG_TAG,\n 'Ignoring outdated watch update for ',\n key,\n '. Current version:',\n existingDoc.version,\n ' Watch version:',\n doc.version\n );\n }\n });\n return { changedDocuments, existenceChangedKeys };\n });\n}\n\n/**\n * Returns true if the newTargetData should be persisted during an update of\n * an active target. TargetData should always be persisted when a target is\n * being released and should not call this function.\n *\n * While the target is active, TargetData updates can be omitted when nothing\n * about the target has changed except metadata like the resume token or\n * snapshot version. Occasionally it's worth the extra write to prevent these\n * values from getting too stale after a crash, but this doesn't have to be\n * too frequent.\n */\nfunction shouldPersistTargetData(\n oldTargetData: TargetData,\n newTargetData: TargetData,\n change: TargetChange\n): boolean {\n // Always persist target data if we don't already have a resume token.\n if (oldTargetData.resumeToken.approximateByteSize() === 0) {\n return true;\n }\n\n // Don't allow resume token changes to be buffered indefinitely. This\n // allows us to be reasonably up-to-date after a crash and avoids needing\n // to loop over all active queries on shutdown. Especially in the browser\n // we may not get time to do anything interesting while the current tab is\n // closing.\n const timeDelta =\n newTargetData.snapshotVersion.toMicroseconds() -\n oldTargetData.snapshotVersion.toMicroseconds();\n if (timeDelta >= RESUME_TOKEN_MAX_AGE_MICROS) {\n return true;\n }\n\n // Otherwise if the only thing that has changed about a target is its resume\n // token it's not worth persisting. Note that the RemoteStore keeps an\n // in-memory view of the currently active targets which includes the current\n // resume token, so stream failure or user changes will still use an\n // up-to-date resume token regardless of what we do here.\n const changes =\n change.addedDocuments.size +\n change.modifiedDocuments.size +\n change.removedDocuments.size;\n return changes > 0;\n}\n\n/**\n * Notifies local store of the changed views to locally pin documents.\n */\nexport async function localStoreNotifyLocalViewChanges(\n localStore: LocalStore,\n viewChanges: LocalViewChanges[]\n): Promise<void> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n try {\n await localStoreImpl.persistence.runTransaction(\n 'notifyLocalViewChanges',\n 'readwrite',\n txn => {\n return PersistencePromise.forEach(\n viewChanges,\n (viewChange: LocalViewChanges) => {\n return PersistencePromise.forEach(\n viewChange.addedKeys,\n (key: DocumentKey) =>\n localStoreImpl.persistence.referenceDelegate.addReference(\n txn,\n viewChange.targetId,\n key\n )\n ).next(() =>\n PersistencePromise.forEach(\n viewChange.removedKeys,\n (key: DocumentKey) =>\n localStoreImpl.persistence.referenceDelegate.removeReference(\n txn,\n viewChange.targetId,\n key\n )\n )\n );\n }\n );\n }\n );\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n // If `notifyLocalViewChanges` fails, we did not advance the sequence\n // number for the documents that were included in this transaction.\n // This might trigger them to be deleted earlier than they otherwise\n // would have, but it should not invalidate the integrity of the data.\n logDebug(LOG_TAG, 'Failed to update sequence numbers: ' + e);\n } else {\n throw e;\n }\n }\n\n for (const viewChange of viewChanges) {\n const targetId = viewChange.targetId;\n\n if (!viewChange.fromCache) {\n const targetData = localStoreImpl.targetDataByTarget.get(targetId);\n debugAssert(\n targetData !== null,\n `Can't set limbo-free snapshot version for unknown target: ${targetId}`\n );\n\n // Advance the last limbo free snapshot version\n const lastLimboFreeSnapshotVersion = targetData.snapshotVersion;\n const updatedTargetData = targetData.withLastLimboFreeSnapshotVersion(\n lastLimboFreeSnapshotVersion\n );\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.insert(targetId, updatedTargetData);\n\n // TODO(b/272564316): Apply the optimization done on other platforms.\n // This is a problem for web because saving the updated targetData from\n // non-primary client conflicts with what primary client saved.\n }\n }\n}\n\n/**\n * Gets the mutation batch after the passed in batchId in the mutation queue\n * or null if empty.\n * @param afterBatchId - If provided, the batch to search after.\n * @returns The next mutation or null if there wasn't one.\n */\nexport function localStoreGetNextMutationBatch(\n localStore: LocalStore,\n afterBatchId?: BatchId\n): Promise<MutationBatch | null> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get next mutation batch',\n 'readonly',\n txn => {\n if (afterBatchId === undefined) {\n afterBatchId = BATCHID_UNKNOWN;\n }\n return localStoreImpl.mutationQueue.getNextMutationBatchAfterBatchId(\n txn,\n afterBatchId\n );\n }\n );\n}\n\n/**\n * Reads the current value of a Document with a given key or null if not\n * found - used for testing.\n */\nexport function localStoreReadDocument(\n localStore: LocalStore,\n key: DocumentKey\n): Promise<Document> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'read document',\n 'readonly',\n txn => localStoreImpl.localDocuments.getDocument(txn, key)\n );\n}\n\n/**\n * Assigns the given target an internal ID so that its results can be pinned so\n * they don't get GC'd. A target must be allocated in the local store before\n * the store can be used to manage its view.\n *\n * Allocating an already allocated `Target` will return the existing `TargetData`\n * for that `Target`.\n */\nexport function localStoreAllocateTarget(\n localStore: LocalStore,\n target: Target\n): Promise<TargetData> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence\n .runTransaction('Allocate target', 'readwrite', txn => {\n let targetData: TargetData;\n return localStoreImpl.targetCache\n .getTargetData(txn, target)\n .next((cached: TargetData | null) => {\n if (cached) {\n // This target has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n targetData = cached;\n return PersistencePromise.resolve(targetData);\n } else {\n return localStoreImpl.targetCache\n .allocateTargetId(txn)\n .next(targetId => {\n targetData = new TargetData(\n target,\n targetId,\n TargetPurpose.Listen,\n txn.currentSequenceNumber\n );\n return localStoreImpl.targetCache\n .addTargetData(txn, targetData)\n .next(() => targetData);\n });\n }\n });\n })\n .then(targetData => {\n // If Multi-Tab is enabled, the existing target data may be newer than\n // the in-memory data\n const cachedTargetData = localStoreImpl.targetDataByTarget.get(\n targetData.targetId\n );\n if (\n cachedTargetData === null ||\n targetData.snapshotVersion.compareTo(cachedTargetData.snapshotVersion) >\n 0\n ) {\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.insert(\n targetData.targetId,\n targetData\n );\n localStoreImpl.targetIdByTarget.set(target, targetData.targetId);\n }\n return targetData;\n });\n}\n\n/**\n * Returns the TargetData as seen by the LocalStore, including updates that may\n * have not yet been persisted to the TargetCache.\n */\n// Visible for testing.\nexport function localStoreGetTargetData(\n localStore: LocalStore,\n transaction: PersistenceTransaction,\n target: Target\n): PersistencePromise<TargetData | null> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const targetId = localStoreImpl.targetIdByTarget.get(target);\n if (targetId !== undefined) {\n return PersistencePromise.resolve<TargetData | null>(\n localStoreImpl.targetDataByTarget.get(targetId)\n );\n } else {\n return localStoreImpl.targetCache.getTargetData(transaction, target);\n }\n}\n\n/**\n * Unpins all the documents associated with the given target. If\n * `keepPersistedTargetData` is set to false and Eager GC enabled, the method\n * directly removes the associated target data from the target cache.\n *\n * Releasing a non-existing `Target` is a no-op.\n */\n// PORTING NOTE: `keepPersistedTargetData` is multi-tab only.\nexport async function localStoreReleaseTarget(\n localStore: LocalStore,\n targetId: number,\n keepPersistedTargetData: boolean\n): Promise<void> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const targetData = localStoreImpl.targetDataByTarget.get(targetId);\n debugAssert(\n targetData !== null,\n `Tried to release nonexistent target: ${targetId}`\n );\n\n const mode = keepPersistedTargetData ? 'readwrite' : 'readwrite-primary';\n\n try {\n if (!keepPersistedTargetData) {\n await localStoreImpl.persistence.runTransaction(\n 'Release target',\n mode,\n txn => {\n return localStoreImpl.persistence.referenceDelegate.removeTarget(\n txn,\n targetData!\n );\n }\n );\n }\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n // All `releaseTarget` does is record the final metadata state for the\n // target, but we've been recording this periodically during target\n // activity. If we lose this write this could cause a very slight\n // difference in the order of target deletion during GC, but we\n // don't define exact LRU semantics so this is acceptable.\n logDebug(\n LOG_TAG,\n `Failed to update sequence numbers for target ${targetId}: ${e}`\n );\n } else {\n throw e;\n }\n }\n\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.remove(targetId);\n localStoreImpl.targetIdByTarget.delete(targetData!.target);\n}\n\n/**\n * Runs the specified query against the local store and returns the results,\n * potentially taking advantage of query data from previous executions (such\n * as the set of remote keys).\n *\n * @param usePreviousResults - Whether results from previous executions can\n * be used to optimize this query execution.\n */\nexport function localStoreExecuteQuery(\n localStore: LocalStore,\n query: Query,\n usePreviousResults: boolean\n): Promise<QueryResult> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n let lastLimboFreeSnapshotVersion = SnapshotVersion.min();\n let remoteKeys = documentKeySet();\n\n return localStoreImpl.persistence.runTransaction(\n 'Execute query',\n 'readwrite', // Use readwrite instead of readonly so indexes can be created\n txn => {\n return localStoreGetTargetData(localStoreImpl, txn, queryToTarget(query))\n .next(targetData => {\n if (targetData) {\n lastLimboFreeSnapshotVersion =\n targetData.lastLimboFreeSnapshotVersion;\n return localStoreImpl.targetCache\n .getMatchingKeysForTargetId(txn, targetData.targetId)\n .next(result => {\n remoteKeys = result;\n });\n }\n })\n .next(() =>\n localStoreImpl.queryEngine.getDocumentsMatchingQuery(\n txn,\n query,\n usePreviousResults\n ? lastLimboFreeSnapshotVersion\n : SnapshotVersion.min(),\n usePreviousResults ? remoteKeys : documentKeySet()\n )\n )\n .next(documents => {\n setMaxReadTime(\n localStoreImpl,\n queryCollectionGroup(query),\n documents\n );\n return { documents, remoteKeys };\n });\n }\n );\n}\n\nfunction applyWriteToRemoteDocuments(\n localStoreImpl: LocalStoreImpl,\n txn: PersistenceTransaction,\n batchResult: MutationBatchResult,\n documentBuffer: RemoteDocumentChangeBuffer\n): PersistencePromise<void> {\n const batch = batchResult.batch;\n const docKeys = batch.keys();\n let promiseChain = PersistencePromise.resolve();\n docKeys.forEach(docKey => {\n promiseChain = promiseChain\n .next(() => documentBuffer.getEntry(txn, docKey))\n .next(doc => {\n const ackVersion = batchResult.docVersions.get(docKey);\n hardAssert(\n ackVersion !== null,\n 'ackVersions should contain every doc in the write.'\n );\n if (doc.version.compareTo(ackVersion!) < 0) {\n batch.applyToRemoteDocument(doc, batchResult);\n if (doc.isValidDocument()) {\n // We use the commitVersion as the readTime rather than the\n // document's updateTime since the updateTime is not advanced\n // for updates that do not modify the underlying document.\n doc.setReadTime(batchResult.commitVersion);\n documentBuffer.addEntry(doc);\n }\n }\n });\n });\n return promiseChain.next(() =>\n localStoreImpl.mutationQueue.removeMutationBatch(txn, batch)\n );\n}\n\n/** Returns the local view of the documents affected by a mutation batch. */\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreLookupMutationDocuments(\n localStore: LocalStore,\n batchId: BatchId\n): Promise<DocumentMap | null> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const mutationQueueImpl = debugCast(\n localStoreImpl.mutationQueue,\n IndexedDbMutationQueue // We only support IndexedDb in multi-tab mode.\n );\n return localStoreImpl.persistence.runTransaction(\n 'Lookup mutation documents',\n 'readonly',\n txn => {\n return mutationQueueImpl.lookupMutationKeys(txn, batchId).next(keys => {\n if (keys) {\n return localStoreImpl.localDocuments.getDocuments(\n txn,\n keys\n ) as PersistencePromise<DocumentMap | null>;\n } else {\n return PersistencePromise.resolve<DocumentMap | null>(null);\n }\n });\n }\n );\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreRemoveCachedMutationBatchMetadata(\n localStore: LocalStore,\n batchId: BatchId\n): void {\n const mutationQueueImpl = debugCast(\n debugCast(localStore, LocalStoreImpl).mutationQueue,\n IndexedDbMutationQueue // We only support IndexedDb in multi-tab mode.\n );\n mutationQueueImpl.removeCachedMutationKeys(batchId);\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetActiveClients(\n localStore: LocalStore\n): Promise<ClientId[]> {\n const persistenceImpl = debugCast(\n debugCast(localStore, LocalStoreImpl).persistence,\n IndexedDbPersistence // We only support IndexedDb in multi-tab mode.\n );\n return persistenceImpl.getActiveClients();\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetCachedTarget(\n localStore: LocalStore,\n targetId: TargetId\n): Promise<Target | null> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const targetCacheImpl = debugCast(\n localStoreImpl.targetCache,\n IndexedDbTargetCache // We only support IndexedDb in multi-tab mode.\n );\n const cachedTargetData = localStoreImpl.targetDataByTarget.get(targetId);\n if (cachedTargetData) {\n return Promise.resolve(cachedTargetData.target);\n } else {\n return localStoreImpl.persistence.runTransaction(\n 'Get target data',\n 'readonly',\n txn => {\n return targetCacheImpl\n .getTargetDataForTarget(txn, targetId)\n .next(targetData => (targetData ? targetData.target : null));\n }\n );\n }\n}\n\n/**\n * Returns the set of documents that have been updated since the last call.\n * If this is the first call, returns the set of changes since client\n * initialization. Further invocations will return document that have changed\n * since the prior call.\n */\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetNewDocumentChanges(\n localStore: LocalStore,\n collectionGroup: string\n): Promise<DocumentMap> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n\n // Get the current maximum read time for the collection. This should always\n // exist, but to reduce the chance for regressions we default to\n // SnapshotVersion.Min()\n // TODO(indexing): Consider removing the default value.\n const readTime =\n localStoreImpl.collectionGroupReadTime.get(collectionGroup) ||\n SnapshotVersion.min();\n\n return localStoreImpl.persistence\n .runTransaction('Get new document changes', 'readonly', txn =>\n localStoreImpl.remoteDocuments.getAllFromCollectionGroup(\n txn,\n collectionGroup,\n newIndexOffsetSuccessorFromReadTime(readTime, INITIAL_LARGEST_BATCH_ID),\n /* limit= */ Number.MAX_SAFE_INTEGER\n )\n )\n .then(changedDocs => {\n setMaxReadTime(localStoreImpl, collectionGroup, changedDocs);\n return changedDocs;\n });\n}\n\n/** Sets the collection group's maximum read time from the given documents. */\n// PORTING NOTE: Multi-Tab only.\nfunction setMaxReadTime(\n localStoreImpl: LocalStoreImpl,\n collectionGroup: string,\n changedDocs: SortedMap<DocumentKey, Document>\n): void {\n let readTime =\n localStoreImpl.collectionGroupReadTime.get(collectionGroup) ||\n SnapshotVersion.min();\n changedDocs.forEach((_, doc) => {\n if (doc.readTime.compareTo(readTime) > 0) {\n readTime = doc.readTime;\n }\n });\n localStoreImpl.collectionGroupReadTime.set(collectionGroup, readTime);\n}\n\n/**\n * Creates a new target using the given bundle name, which will be used to\n * hold the keys of all documents from the bundle in query-document mappings.\n * This ensures that the loaded documents do not get garbage collected\n * right away.\n */\nfunction umbrellaTarget(bundleName: string): Target {\n // It is OK that the path used for the query is not valid, because this will\n // not be read and queried.\n return queryToTarget(\n newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${bundleName}`))\n );\n}\n\n/**\n * Applies the documents from a bundle to the \"ground-state\" (remote)\n * documents.\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nexport async function localStoreApplyBundledDocuments(\n localStore: LocalStore,\n bundleConverter: BundleConverter,\n documents: BundledDocuments,\n bundleName: string\n): Promise<DocumentMap> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n let documentKeys = documentKeySet();\n let documentMap = mutableDocumentMap();\n for (const bundleDoc of documents) {\n const documentKey = bundleConverter.toDocumentKey(bundleDoc.metadata.name!);\n if (bundleDoc.document) {\n documentKeys = documentKeys.add(documentKey);\n }\n const doc = bundleConverter.toMutableDocument(bundleDoc);\n doc.setReadTime(\n bundleConverter.toSnapshotVersion(bundleDoc.metadata.readTime!)\n );\n documentMap = documentMap.insert(documentKey, doc);\n }\n\n const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n\n // Allocates a target to hold all document keys from the bundle, such that\n // they will not get garbage collected right away.\n const umbrellaTargetData = await localStoreAllocateTarget(\n localStoreImpl,\n umbrellaTarget(bundleName)\n );\n return localStoreImpl.persistence.runTransaction(\n 'Apply bundle documents',\n 'readwrite',\n txn => {\n return populateDocumentChangeBuffer(txn, documentBuffer, documentMap)\n .next(documentChangeResult => {\n documentBuffer.apply(txn);\n return documentChangeResult;\n })\n .next(documentChangeResult => {\n return localStoreImpl.targetCache\n .removeMatchingKeysForTargetId(txn, umbrellaTargetData.targetId)\n .next(() =>\n localStoreImpl.targetCache.addMatchingKeys(\n txn,\n documentKeys,\n umbrellaTargetData.targetId\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.getLocalViewOfDocuments(\n txn,\n documentChangeResult.changedDocuments,\n documentChangeResult.existenceChangedKeys\n )\n )\n .next(() => documentChangeResult.changedDocuments);\n });\n }\n );\n}\n\n/**\n * Returns a promise of a boolean to indicate if the given bundle has already\n * been loaded and the create time is newer than the current loading bundle.\n */\nexport function localStoreHasNewerBundle(\n localStore: LocalStore,\n bundleMetadata: BundleMetadata\n): Promise<boolean> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const currentReadTime = fromVersion(bundleMetadata.createTime!);\n return localStoreImpl.persistence\n .runTransaction('hasNewerBundle', 'readonly', transaction => {\n return localStoreImpl.bundleCache.getBundleMetadata(\n transaction,\n bundleMetadata.id!\n );\n })\n .then(cached => {\n return !!cached && cached.createTime!.compareTo(currentReadTime) >= 0;\n });\n}\n\n/**\n * Saves the given `BundleMetadata` to local persistence.\n */\nexport function localStoreSaveBundle(\n localStore: LocalStore,\n bundleMetadata: BundleMetadata\n): Promise<void> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Save bundle',\n 'readwrite',\n transaction => {\n return localStoreImpl.bundleCache.saveBundleMetadata(\n transaction,\n bundleMetadata\n );\n }\n );\n}\n\n/**\n * Returns a promise of a `NamedQuery` associated with given query name. Promise\n * resolves to undefined if no persisted data can be found.\n */\nexport function localStoreGetNamedQuery(\n localStore: LocalStore,\n queryName: string\n): Promise<NamedQuery | undefined> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get named query',\n 'readonly',\n transaction =>\n localStoreImpl.bundleCache.getNamedQuery(transaction, queryName)\n );\n}\n\n/**\n * Saves the given `NamedQuery` to local persistence.\n */\nexport async function localStoreSaveNamedQuery(\n localStore: LocalStore,\n query: ProtoNamedQuery,\n documents: DocumentKeySet = documentKeySet()\n): Promise<void> {\n // Allocate a target for the named query such that it can be resumed\n // from associated read time if users use it to listen.\n // NOTE: this also means if no corresponding target exists, the new target\n // will remain active and will not get collected, unless users happen to\n // unlisten the query somehow.\n const allocated = await localStoreAllocateTarget(\n localStore,\n queryToTarget(fromBundledQuery(query.bundledQuery!))\n );\n\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Save named query',\n 'readwrite',\n transaction => {\n const readTime = fromVersion(query.readTime!);\n // Simply save the query itself if it is older than what the SDK already\n // has.\n if (allocated.snapshotVersion.compareTo(readTime) >= 0) {\n return localStoreImpl.bundleCache.saveNamedQuery(transaction, query);\n }\n\n // Update existing target data because the query from the bundle is newer.\n const newTargetData = allocated.withResumeToken(\n ByteString.EMPTY_BYTE_STRING,\n readTime\n );\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.insert(\n newTargetData.targetId,\n newTargetData\n );\n return localStoreImpl.targetCache\n .updateTargetData(transaction, newTargetData)\n .next(() =>\n localStoreImpl.targetCache.removeMatchingKeysForTargetId(\n transaction,\n allocated.targetId\n )\n )\n .next(() =>\n localStoreImpl.targetCache.addMatchingKeys(\n transaction,\n documents,\n allocated.targetId\n )\n )\n .next(() =>\n localStoreImpl.bundleCache.saveNamedQuery(transaction, query)\n );\n }\n );\n}\n\nexport async function localStoreConfigureFieldIndexes(\n localStore: LocalStore,\n newFieldIndexes: FieldIndex[]\n): Promise<void> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const indexManager = localStoreImpl.indexManager;\n const promises: Array<PersistencePromise<void>> = [];\n return localStoreImpl.persistence.runTransaction(\n 'Configure indexes',\n 'readwrite',\n transaction =>\n indexManager\n .getFieldIndexes(transaction)\n .next(oldFieldIndexes =>\n diffArrays(\n oldFieldIndexes,\n newFieldIndexes,\n fieldIndexSemanticComparator,\n fieldIndex => {\n promises.push(\n indexManager.addFieldIndex(transaction, fieldIndex)\n );\n },\n fieldIndex => {\n promises.push(\n indexManager.deleteFieldIndex(transaction, fieldIndex)\n );\n }\n )\n )\n .next(() => PersistencePromise.waitFor(promises))\n );\n}\n\nexport function localStoreSetIndexAutoCreationEnabled(\n localStore: LocalStore,\n isEnabled: boolean\n): void {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n localStoreImpl.queryEngine.indexAutoCreationEnabled = isEnabled;\n}\n\nexport function localStoreDeleteAllFieldIndexes(\n localStore: LocalStore\n): Promise<void> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const indexManager = localStoreImpl.indexManager;\n return localStoreImpl.persistence.runTransaction(\n 'Delete All Indexes',\n 'readwrite',\n transaction => indexManager.deleteAllFieldIndexes(transaction)\n );\n}\n\n/**\n * Test-only hooks into the SDK for use exclusively by tests.\n */\nexport class TestingHooks {\n private constructor() {\n throw new Error('creating instances is not supported');\n }\n\n static setIndexAutoCreationSettings(\n localStore: LocalStore,\n settings: {\n indexAutoCreationMinCollectionSize?: number;\n relativeIndexReadCostPerDocument?: number;\n }\n ): void {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n if (settings.indexAutoCreationMinCollectionSize !== undefined) {\n localStoreImpl.queryEngine.indexAutoCreationMinCollectionSize =\n settings.indexAutoCreationMinCollectionSize;\n }\n if (settings.relativeIndexReadCostPerDocument !== undefined) {\n localStoreImpl.queryEngine.relativeIndexReadCostPerDocument =\n settings.relativeIndexReadCostPerDocument;\n }\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport {\n BatchId,\n ListenSequenceNumber,\n MutationBatchState,\n OnlineState,\n TargetId\n} from '../core/types';\nimport { TargetIdSet, targetIdSet } from '../model/collections';\nimport { hardAssert, debugAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logError, logDebug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { isSafeInteger, WindowLike } from '../util/types';\n\nimport {\n CLIENT_STATE_KEY_PREFIX,\n ClientStateSchema,\n createBundleLoadedKey,\n createWebStorageClientStateKey,\n createWebStorageMutationBatchKey,\n createWebStorageOnlineStateKey,\n createWebStorageQueryTargetMetadataKey,\n createWebStorageSequenceNumberKey,\n MUTATION_BATCH_KEY_PREFIX,\n MutationMetadataSchema,\n QUERY_TARGET_KEY_PREFIX,\n QueryTargetStateSchema,\n SharedOnlineStateSchema\n} from './shared_client_state_schema';\nimport {\n QueryTargetState,\n SharedClientStateSyncer\n} from './shared_client_state_syncer';\n\nconst LOG_TAG = 'SharedClientState';\n\n/**\n * A randomly-generated key assigned to each Firestore instance at startup.\n */\nexport type ClientId = string;\n\n/**\n * A `SharedClientState` keeps track of the global state of the mutations\n * and query targets for all active clients with the same persistence key (i.e.\n * project ID and FirebaseApp name). It relays local changes to other clients\n * and updates its local state as new state is observed.\n *\n * `SharedClientState` is primarily used for synchronization in Multi-Tab\n * environments. Each tab is responsible for registering its active query\n * targets and mutations. `SharedClientState` will then notify the listener\n * assigned to `.syncEngine` for updates to mutations and queries that\n * originated in other clients.\n *\n * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be\n * assigned before calling `start()`.\n */\nexport interface SharedClientState {\n onlineStateHandler: ((onlineState: OnlineState) => void) | null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n\n /** Registers the Mutation Batch ID of a newly pending mutation. */\n addPendingMutation(batchId: BatchId): void;\n\n /**\n * Records that a pending mutation has been acknowledged or rejected.\n * Called by the primary client to notify secondary clients of mutation\n * results as they come back from the backend.\n */\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void;\n\n /**\n * Associates a new Query Target ID with the local Firestore client. Returns\n * the new query state for the query (which can be 'current' if the query is\n * already associated with another tab).\n *\n * If the target id is already associated with local client, the method simply\n * returns its `QueryTargetState`.\n */\n addLocalQueryTarget(targetId: TargetId): QueryTargetState;\n\n /** Removes the Query Target ID association from the local client. */\n removeLocalQueryTarget(targetId: TargetId): void;\n\n /** Checks whether the target is associated with the local client. */\n isLocalQueryTarget(targetId: TargetId): boolean;\n\n /**\n * Processes an update to a query target.\n *\n * Called by the primary client to notify secondary clients of document\n * changes or state transitions that affect the provided query target.\n */\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void;\n\n /**\n * Removes the target's metadata entry.\n *\n * Called by the primary client when all clients stopped listening to a query\n * target.\n */\n clearQueryState(targetId: TargetId): void;\n\n /**\n * Gets the active Query Targets IDs for all active clients.\n *\n * The implementation for this may require O(n) runtime, where 'n' is the size\n * of the result set.\n */\n // Visible for testing\n getAllActiveQueryTargets(): SortedSet<TargetId>;\n\n /**\n * Checks whether the provided target ID is currently being listened to by\n * any of the active clients.\n *\n * The implementation may require O(n*log m) runtime, where 'n' is the number\n * of clients and 'm' the number of targets.\n */\n isActiveQueryTarget(targetId: TargetId): boolean;\n\n /**\n * Starts the SharedClientState, reads existing client data and registers\n * listeners for updates to new and existing clients.\n */\n start(): Promise<void>;\n\n /** Shuts down the `SharedClientState` and its listeners. */\n shutdown(): void;\n\n /**\n * Changes the active user and removes all existing user-specific data. The\n * user change does not call back into SyncEngine (for example, no mutations\n * will be marked as removed).\n */\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void;\n\n /** Changes the shared online state of all clients. */\n setOnlineState(onlineState: OnlineState): void;\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n\n /**\n * Notifies other clients when remote documents have changed due to loading\n * a bundle.\n *\n * @param collectionGroups The collection groups affected by this bundle.\n */\n notifyBundleLoaded(collectionGroups: Set<string>): void;\n}\n\n/**\n * Holds the state of a mutation batch, including its user ID, batch ID and\n * whether the batch is 'pending', 'acknowledged' or 'rejected'.\n */\n// Visible for testing\nexport class MutationMetadata {\n constructor(\n readonly user: User,\n readonly batchId: BatchId,\n readonly state: MutationBatchState,\n readonly error?: FirestoreError\n ) {\n debugAssert(\n (error !== undefined) === (state === 'rejected'),\n `MutationMetadata must contain an error iff state is 'rejected'`\n );\n }\n\n /**\n * Parses a MutationMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(\n user: User,\n batchId: BatchId,\n value: string\n ): MutationMetadata | null {\n const mutationBatch = JSON.parse(value) as MutationMetadataSchema;\n\n let validData =\n typeof mutationBatch === 'object' &&\n ['pending', 'acknowledged', 'rejected'].indexOf(mutationBatch.state) !==\n -1 &&\n (mutationBatch.error === undefined ||\n typeof mutationBatch.error === 'object');\n\n let firestoreError: FirestoreError | undefined = undefined;\n\n if (validData && mutationBatch.error) {\n validData =\n typeof mutationBatch.error.message === 'string' &&\n typeof mutationBatch.error.code === 'string';\n if (validData) {\n firestoreError = new FirestoreError(\n mutationBatch.error.code as Code,\n mutationBatch.error.message\n );\n }\n }\n\n if (validData) {\n return new MutationMetadata(\n user,\n batchId,\n mutationBatch.state,\n firestoreError\n );\n } else {\n logError(\n LOG_TAG,\n `Failed to parse mutation state for ID '${batchId}': ${value}`\n );\n return null;\n }\n }\n\n toWebStorageJSON(): string {\n const batchMetadata: MutationMetadataSchema = {\n state: this.state,\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n\n if (this.error) {\n batchMetadata.error = {\n code: this.error.code,\n message: this.error.message\n };\n }\n\n return JSON.stringify(batchMetadata);\n }\n}\n\n/**\n * Holds the state of a query target, including its target ID and whether the\n * target is 'not-current', 'current' or 'rejected'.\n */\n// Visible for testing\nexport class QueryTargetMetadata {\n constructor(\n readonly targetId: TargetId,\n readonly state: QueryTargetState,\n readonly error?: FirestoreError\n ) {\n debugAssert(\n (error !== undefined) === (state === 'rejected'),\n `QueryTargetMetadata must contain an error iff state is 'rejected'`\n );\n }\n\n /**\n * Parses a QueryTargetMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(\n targetId: TargetId,\n value: string\n ): QueryTargetMetadata | null {\n const targetState = JSON.parse(value) as QueryTargetStateSchema;\n\n let validData =\n typeof targetState === 'object' &&\n ['not-current', 'current', 'rejected'].indexOf(targetState.state) !==\n -1 &&\n (targetState.error === undefined ||\n typeof targetState.error === 'object');\n\n let firestoreError: FirestoreError | undefined = undefined;\n\n if (validData && targetState.error) {\n validData =\n typeof targetState.error.message === 'string' &&\n typeof targetState.error.code === 'string';\n if (validData) {\n firestoreError = new FirestoreError(\n targetState.error.code as Code,\n targetState.error.message\n );\n }\n }\n\n if (validData) {\n return new QueryTargetMetadata(\n targetId,\n targetState.state,\n firestoreError\n );\n } else {\n logError(\n LOG_TAG,\n `Failed to parse target state for ID '${targetId}': ${value}`\n );\n return null;\n }\n }\n\n toWebStorageJSON(): string {\n const targetState: QueryTargetStateSchema = {\n state: this.state,\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n\n if (this.error) {\n targetState.error = {\n code: this.error.code,\n message: this.error.message\n };\n }\n\n return JSON.stringify(targetState);\n }\n}\n\n/**\n * Metadata state of a single client denoting the query targets it is actively\n * listening to.\n */\n// Visible for testing.\nexport interface ClientState {\n readonly activeTargetIds: TargetIdSet;\n}\n\n/**\n * This class represents the immutable ClientState for a client read from\n * WebStorage, containing the list of active query targets.\n */\nclass RemoteClientState implements ClientState {\n private constructor(\n readonly clientId: ClientId,\n readonly activeTargetIds: TargetIdSet\n ) {}\n\n /**\n * Parses a RemoteClientState from the JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(\n clientId: ClientId,\n value: string\n ): RemoteClientState | null {\n const clientState = JSON.parse(value) as ClientStateSchema;\n\n let validData =\n typeof clientState === 'object' &&\n clientState.activeTargetIds instanceof Array;\n\n let activeTargetIdsSet = targetIdSet();\n\n for (let i = 0; validData && i < clientState.activeTargetIds.length; ++i) {\n validData = isSafeInteger(clientState.activeTargetIds[i]);\n activeTargetIdsSet = activeTargetIdsSet.add(\n clientState.activeTargetIds[i]\n );\n }\n\n if (validData) {\n return new RemoteClientState(clientId, activeTargetIdsSet);\n } else {\n logError(\n LOG_TAG,\n `Failed to parse client data for instance '${clientId}': ${value}`\n );\n return null;\n }\n }\n}\n\n/**\n * This class represents the online state for all clients participating in\n * multi-tab. The online state is only written to by the primary client, and\n * used in secondary clients to update their query views.\n */\nexport class SharedOnlineState {\n constructor(readonly clientId: string, readonly onlineState: OnlineState) {}\n\n /**\n * Parses a SharedOnlineState from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(value: string): SharedOnlineState | null {\n const onlineState = JSON.parse(value) as SharedOnlineStateSchema;\n\n const validData =\n typeof onlineState === 'object' &&\n ['Unknown', 'Online', 'Offline'].indexOf(onlineState.onlineState) !==\n -1 &&\n typeof onlineState.clientId === 'string';\n\n if (validData) {\n return new SharedOnlineState(\n onlineState.clientId,\n onlineState.onlineState as OnlineState\n );\n } else {\n logError(LOG_TAG, `Failed to parse online state: ${value}`);\n return null;\n }\n }\n}\n\n/**\n * Metadata state of the local client. Unlike `RemoteClientState`, this class is\n * mutable and keeps track of all pending mutations, which allows us to\n * update the range of pending mutation batch IDs as new mutations are added or\n * removed.\n *\n * The data in `LocalClientState` is not read from WebStorage and instead\n * updated via its instance methods. The updated state can be serialized via\n * `toWebStorageJSON()`.\n */\n// Visible for testing.\nexport class LocalClientState implements ClientState {\n activeTargetIds = targetIdSet();\n\n addQueryTarget(targetId: TargetId): void {\n this.activeTargetIds = this.activeTargetIds.add(targetId);\n }\n\n removeQueryTarget(targetId: TargetId): void {\n this.activeTargetIds = this.activeTargetIds.delete(targetId);\n }\n\n /**\n * Converts this entry into a JSON-encoded format we can use for WebStorage.\n * Does not encode `clientId` as it is part of the key in WebStorage.\n */\n toWebStorageJSON(): string {\n const data: ClientStateSchema = {\n activeTargetIds: this.activeTargetIds.toArray(),\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n return JSON.stringify(data);\n }\n}\n\n/**\n * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the\n * backing store for the SharedClientState. It keeps track of all active\n * clients and supports modifications of the local client's data.\n */\nexport class WebStorageSharedClientState implements SharedClientState {\n syncEngine: SharedClientStateSyncer | null = null;\n onlineStateHandler: ((onlineState: OnlineState) => void) | null = null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null = null;\n\n private readonly storage: Storage;\n private readonly localClientStorageKey: string;\n private readonly sequenceNumberKey: string;\n private readonly storageListener = this.handleWebStorageEvent.bind(this);\n private readonly onlineStateKey: string;\n private readonly bundleLoadedKey: string;\n private readonly clientStateKeyRe: RegExp;\n private readonly mutationBatchKeyRe: RegExp;\n private readonly queryTargetKeyRe: RegExp;\n private activeClients = new SortedMap<string, ClientState>(\n primitiveComparator\n );\n private started = false;\n private currentUser: User;\n\n /**\n * Captures WebStorage events that occur before `start()` is called. These\n * events are replayed once `WebStorageSharedClientState` is started.\n */\n private earlyEvents: StorageEvent[] = [];\n\n constructor(\n private readonly window: WindowLike,\n private readonly queue: AsyncQueue,\n private readonly persistenceKey: string,\n private readonly localClientId: ClientId,\n initialUser: User\n ) {\n // Escape the special characters mentioned here:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n const escapedPersistenceKey = persistenceKey.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n '\\\\$&'\n );\n\n this.storage = this.window.localStorage;\n this.currentUser = initialUser;\n this.localClientStorageKey = createWebStorageClientStateKey(\n this.persistenceKey,\n this.localClientId\n );\n this.sequenceNumberKey = createWebStorageSequenceNumberKey(\n this.persistenceKey\n );\n this.activeClients = this.activeClients.insert(\n this.localClientId,\n new LocalClientState()\n );\n\n this.clientStateKeyRe = new RegExp(\n `^${CLIENT_STATE_KEY_PREFIX}_${escapedPersistenceKey}_([^_]*)$`\n );\n this.mutationBatchKeyRe = new RegExp(\n `^${MUTATION_BATCH_KEY_PREFIX}_${escapedPersistenceKey}_(\\\\d+)(?:_(.*))?$`\n );\n this.queryTargetKeyRe = new RegExp(\n `^${QUERY_TARGET_KEY_PREFIX}_${escapedPersistenceKey}_(\\\\d+)$`\n );\n\n this.onlineStateKey = createWebStorageOnlineStateKey(this.persistenceKey);\n\n this.bundleLoadedKey = createBundleLoadedKey(this.persistenceKey);\n\n // Rather than adding the storage observer during start(), we add the\n // storage observer during initialization. This ensures that we collect\n // events before other components populate their initial state (during their\n // respective start() calls). Otherwise, we might for example miss a\n // mutation that is added after LocalStore's start() processed the existing\n // mutations but before we observe WebStorage events.\n this.window.addEventListener('storage', this.storageListener);\n }\n\n /** Returns 'true' if WebStorage is available in the current environment. */\n static isAvailable(window: WindowLike | null): window is WindowLike {\n return !!(window && window.localStorage);\n }\n\n async start(): Promise<void> {\n debugAssert(!this.started, 'WebStorageSharedClientState already started');\n debugAssert(\n this.syncEngine !== null,\n 'syncEngine property must be set before calling start()'\n );\n debugAssert(\n this.onlineStateHandler !== null,\n 'onlineStateHandler property must be set before calling start()'\n );\n\n // Retrieve the list of existing clients to backfill the data in\n // SharedClientState.\n const existingClients = await this.syncEngine!.getActiveClients();\n\n for (const clientId of existingClients) {\n if (clientId === this.localClientId) {\n continue;\n }\n\n const storageItem = this.getItem(\n createWebStorageClientStateKey(this.persistenceKey, clientId)\n );\n if (storageItem) {\n const clientState = RemoteClientState.fromWebStorageEntry(\n clientId,\n storageItem\n );\n if (clientState) {\n this.activeClients = this.activeClients.insert(\n clientState.clientId,\n clientState\n );\n }\n }\n }\n\n this.persistClientState();\n\n // Check if there is an existing online state and call the callback handler\n // if applicable.\n const onlineStateJSON = this.storage.getItem(this.onlineStateKey);\n if (onlineStateJSON) {\n const onlineState = this.fromWebStorageOnlineState(onlineStateJSON);\n if (onlineState) {\n this.handleOnlineStateEvent(onlineState);\n }\n }\n\n for (const event of this.earlyEvents) {\n this.handleWebStorageEvent(event);\n }\n\n this.earlyEvents = [];\n\n // Register a window unload hook to remove the client metadata entry from\n // WebStorage even if `shutdown()` was not called.\n this.window.addEventListener('pagehide', () => this.shutdown());\n\n this.started = true;\n }\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void {\n this.setItem(this.sequenceNumberKey, JSON.stringify(sequenceNumber));\n }\n\n getAllActiveQueryTargets(): TargetIdSet {\n return this.extractActiveQueryTargets(this.activeClients);\n }\n\n isActiveQueryTarget(targetId: TargetId): boolean {\n let found = false;\n this.activeClients.forEach((key, value) => {\n if (value.activeTargetIds.has(targetId)) {\n found = true;\n }\n });\n return found;\n }\n\n addPendingMutation(batchId: BatchId): void {\n this.persistMutationState(batchId, 'pending');\n }\n\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void {\n this.persistMutationState(batchId, state, error);\n\n // Once a final mutation result is observed by other clients, they no longer\n // access the mutation's metadata entry. Since WebStorage replays events\n // in order, it is safe to delete the entry right after updating it.\n this.removeMutationState(batchId);\n }\n\n addLocalQueryTarget(targetId: TargetId): QueryTargetState {\n let queryState: QueryTargetState = 'not-current';\n\n // Lookup an existing query state if the target ID was already registered\n // by another tab\n if (this.isActiveQueryTarget(targetId)) {\n const storageItem = this.storage.getItem(\n createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId)\n );\n\n if (storageItem) {\n const metadata = QueryTargetMetadata.fromWebStorageEntry(\n targetId,\n storageItem\n );\n if (metadata) {\n queryState = metadata.state;\n }\n }\n }\n\n this.localClientState.addQueryTarget(targetId);\n this.persistClientState();\n\n return queryState;\n }\n\n removeLocalQueryTarget(targetId: TargetId): void {\n this.localClientState.removeQueryTarget(targetId);\n this.persistClientState();\n }\n\n isLocalQueryTarget(targetId: TargetId): boolean {\n return this.localClientState.activeTargetIds.has(targetId);\n }\n\n clearQueryState(targetId: TargetId): void {\n this.removeItem(\n createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId)\n );\n }\n\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n this.persistQueryTargetState(targetId, state, error);\n }\n\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void {\n removedBatchIds.forEach(batchId => {\n this.removeMutationState(batchId);\n });\n this.currentUser = user;\n addedBatchIds.forEach(batchId => {\n this.addPendingMutation(batchId);\n });\n }\n\n setOnlineState(onlineState: OnlineState): void {\n this.persistOnlineState(onlineState);\n }\n\n notifyBundleLoaded(collectionGroups: Set<string>): void {\n this.persistBundleLoadedState(collectionGroups);\n }\n\n shutdown(): void {\n if (this.started) {\n this.window.removeEventListener('storage', this.storageListener);\n this.removeItem(this.localClientStorageKey);\n this.started = false;\n }\n }\n\n private getItem(key: string): string | null {\n const value = this.storage.getItem(key);\n logDebug(LOG_TAG, 'READ', key, value);\n return value;\n }\n\n private setItem(key: string, value: string): void {\n logDebug(LOG_TAG, 'SET', key, value);\n this.storage.setItem(key, value);\n }\n\n private removeItem(key: string): void {\n logDebug(LOG_TAG, 'REMOVE', key);\n this.storage.removeItem(key);\n }\n\n private handleWebStorageEvent(event: Event): void {\n // Note: The function is typed to take Event to be interface-compatible with\n // `Window.addEventListener`.\n const storageEvent = event as StorageEvent;\n if (storageEvent.storageArea === this.storage) {\n logDebug(LOG_TAG, 'EVENT', storageEvent.key, storageEvent.newValue);\n\n if (storageEvent.key === this.localClientStorageKey) {\n logError(\n 'Received WebStorage notification for local change. Another client might have ' +\n 'garbage-collected our state'\n );\n return;\n }\n\n this.queue.enqueueRetryable(async () => {\n if (!this.started) {\n this.earlyEvents.push(storageEvent);\n return;\n }\n\n if (storageEvent.key === null) {\n return;\n }\n\n if (this.clientStateKeyRe.test(storageEvent.key)) {\n if (storageEvent.newValue != null) {\n const clientState = this.fromWebStorageClientState(\n storageEvent.key,\n storageEvent.newValue\n );\n if (clientState) {\n return this.handleClientStateEvent(\n clientState.clientId,\n clientState\n );\n }\n } else {\n const clientId = this.fromWebStorageClientStateKey(\n storageEvent.key\n )!;\n return this.handleClientStateEvent(clientId, null);\n }\n } else if (this.mutationBatchKeyRe.test(storageEvent.key)) {\n if (storageEvent.newValue !== null) {\n const mutationMetadata = this.fromWebStorageMutationMetadata(\n storageEvent.key,\n storageEvent.newValue\n );\n if (mutationMetadata) {\n return this.handleMutationBatchEvent(mutationMetadata);\n }\n }\n } else if (this.queryTargetKeyRe.test(storageEvent.key)) {\n if (storageEvent.newValue !== null) {\n const queryTargetMetadata = this.fromWebStorageQueryTargetMetadata(\n storageEvent.key,\n storageEvent.newValue\n );\n if (queryTargetMetadata) {\n return this.handleQueryTargetEvent(queryTargetMetadata);\n }\n }\n } else if (storageEvent.key === this.onlineStateKey) {\n if (storageEvent.newValue !== null) {\n const onlineState = this.fromWebStorageOnlineState(\n storageEvent.newValue\n );\n if (onlineState) {\n return this.handleOnlineStateEvent(onlineState);\n }\n }\n } else if (storageEvent.key === this.sequenceNumberKey) {\n debugAssert(\n !!this.sequenceNumberHandler,\n 'Missing sequenceNumberHandler'\n );\n const sequenceNumber = fromWebStorageSequenceNumber(\n storageEvent.newValue\n );\n if (sequenceNumber !== ListenSequence.INVALID) {\n this.sequenceNumberHandler!(sequenceNumber);\n }\n } else if (storageEvent.key === this.bundleLoadedKey) {\n const collectionGroups = this.fromWebStoreBundleLoadedState(\n storageEvent.newValue!\n );\n await Promise.all(\n collectionGroups.map(cg =>\n this.syncEngine!.synchronizeWithChangedDocuments(cg)\n )\n );\n }\n });\n }\n }\n\n private get localClientState(): LocalClientState {\n return this.activeClients.get(this.localClientId) as LocalClientState;\n }\n\n private persistClientState(): void {\n this.setItem(\n this.localClientStorageKey,\n this.localClientState.toWebStorageJSON()\n );\n }\n\n private persistMutationState(\n batchId: BatchId,\n state: MutationBatchState,\n error?: FirestoreError\n ): void {\n const mutationState = new MutationMetadata(\n this.currentUser,\n batchId,\n state,\n error\n );\n const mutationKey = createWebStorageMutationBatchKey(\n this.persistenceKey,\n this.currentUser,\n batchId\n );\n this.setItem(mutationKey, mutationState.toWebStorageJSON());\n }\n\n private removeMutationState(batchId: BatchId): void {\n const mutationKey = createWebStorageMutationBatchKey(\n this.persistenceKey,\n this.currentUser,\n batchId\n );\n this.removeItem(mutationKey);\n }\n\n private persistOnlineState(onlineState: OnlineState): void {\n const entry: SharedOnlineStateSchema = {\n clientId: this.localClientId,\n onlineState\n };\n this.storage.setItem(this.onlineStateKey, JSON.stringify(entry));\n }\n\n private persistQueryTargetState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n const targetKey = createWebStorageQueryTargetMetadataKey(\n this.persistenceKey,\n targetId\n );\n const targetMetadata = new QueryTargetMetadata(targetId, state, error);\n this.setItem(targetKey, targetMetadata.toWebStorageJSON());\n }\n\n private persistBundleLoadedState(collectionGroups: Set<string>): void {\n const json = JSON.stringify(Array.from(collectionGroups));\n this.setItem(this.bundleLoadedKey, json);\n }\n\n /**\n * Parses a client state key in WebStorage. Returns null if the key does not\n * match the expected key format.\n */\n private fromWebStorageClientStateKey(key: string): ClientId | null {\n const match = this.clientStateKeyRe.exec(key);\n return match ? match[1] : null;\n }\n\n /**\n * Parses a client state in WebStorage. Returns 'null' if the value could not\n * be parsed.\n */\n private fromWebStorageClientState(\n key: string,\n value: string\n ): RemoteClientState | null {\n const clientId = this.fromWebStorageClientStateKey(key);\n debugAssert(clientId !== null, `Cannot parse client state key '${key}'`);\n return RemoteClientState.fromWebStorageEntry(clientId, value);\n }\n\n /**\n * Parses a mutation batch state in WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageMutationMetadata(\n key: string,\n value: string\n ): MutationMetadata | null {\n const match = this.mutationBatchKeyRe.exec(key);\n debugAssert(match !== null, `Cannot parse mutation batch key '${key}'`);\n\n const batchId = Number(match[1]);\n const userId = match[2] !== undefined ? match[2] : null;\n return MutationMetadata.fromWebStorageEntry(\n new User(userId),\n batchId,\n value\n );\n }\n\n /**\n * Parses a query target state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageQueryTargetMetadata(\n key: string,\n value: string\n ): QueryTargetMetadata | null {\n const match = this.queryTargetKeyRe.exec(key);\n debugAssert(match !== null, `Cannot parse query target key '${key}'`);\n\n const targetId = Number(match[1]);\n return QueryTargetMetadata.fromWebStorageEntry(targetId, value);\n }\n\n /**\n * Parses an online state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageOnlineState(value: string): SharedOnlineState | null {\n return SharedOnlineState.fromWebStorageEntry(value);\n }\n\n private fromWebStoreBundleLoadedState(value: string): string[] {\n return JSON.parse(value) as string[];\n }\n\n private async handleMutationBatchEvent(\n mutationBatch: MutationMetadata\n ): Promise<void> {\n if (mutationBatch.user.uid !== this.currentUser.uid) {\n logDebug(\n LOG_TAG,\n `Ignoring mutation for non-active user ${mutationBatch.user.uid}`\n );\n return;\n }\n\n return this.syncEngine!.applyBatchState(\n mutationBatch.batchId,\n mutationBatch.state,\n mutationBatch.error\n );\n }\n\n private handleQueryTargetEvent(\n targetMetadata: QueryTargetMetadata\n ): Promise<void> {\n return this.syncEngine!.applyTargetState(\n targetMetadata.targetId,\n targetMetadata.state,\n targetMetadata.error\n );\n }\n\n private handleClientStateEvent(\n clientId: ClientId,\n clientState: RemoteClientState | null\n ): Promise<void> {\n const updatedClients = clientState\n ? this.activeClients.insert(clientId, clientState)\n : this.activeClients.remove(clientId);\n\n const existingTargets = this.extractActiveQueryTargets(this.activeClients);\n const newTargets = this.extractActiveQueryTargets(updatedClients);\n\n const addedTargets: TargetId[] = [];\n const removedTargets: TargetId[] = [];\n\n newTargets.forEach(targetId => {\n if (!existingTargets.has(targetId)) {\n addedTargets.push(targetId);\n }\n });\n\n existingTargets.forEach(targetId => {\n if (!newTargets.has(targetId)) {\n removedTargets.push(targetId);\n }\n });\n\n return this.syncEngine!.applyActiveTargetsChange(\n addedTargets,\n removedTargets\n ).then(() => {\n this.activeClients = updatedClients;\n });\n }\n\n private handleOnlineStateEvent(onlineState: SharedOnlineState): void {\n // We check whether the client that wrote this online state is still active\n // by comparing its client ID to the list of clients kept active in\n // IndexedDb. If a client does not update their IndexedDb client state\n // within 5 seconds, it is considered inactive and we don't emit an online\n // state event.\n if (this.activeClients.get(onlineState.clientId)) {\n this.onlineStateHandler!(onlineState.onlineState);\n }\n }\n\n private extractActiveQueryTargets(\n clients: SortedMap<string, ClientState>\n ): SortedSet<TargetId> {\n let activeTargets = targetIdSet();\n clients.forEach((kev, value) => {\n activeTargets = activeTargets.unionWith(value.activeTargetIds);\n });\n return activeTargets;\n }\n}\n\nfunction fromWebStorageSequenceNumber(\n seqString: string | null\n): ListenSequenceNumber {\n let sequenceNumber = ListenSequence.INVALID;\n if (seqString != null) {\n try {\n const parsed = JSON.parse(seqString);\n hardAssert(\n typeof parsed === 'number',\n 'Found non-numeric sequence number'\n );\n sequenceNumber = parsed;\n } catch (e) {\n logError(LOG_TAG, 'Failed to read sequence number from WebStorage', e);\n }\n }\n return sequenceNumber;\n}\n\n/**\n * `MemorySharedClientState` is a simple implementation of SharedClientState for\n * clients using memory persistence. The state in this class remains fully\n * isolated and no synchronization is performed.\n */\nexport class MemorySharedClientState implements SharedClientState {\n private localState = new LocalClientState();\n private queryState: { [targetId: number]: QueryTargetState } = {};\n onlineStateHandler: ((onlineState: OnlineState) => void) | null = null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null = null;\n\n addPendingMutation(batchId: BatchId): void {\n // No op.\n }\n\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void {\n // No op.\n }\n\n addLocalQueryTarget(targetId: TargetId): QueryTargetState {\n this.localState.addQueryTarget(targetId);\n return this.queryState[targetId] || 'not-current';\n }\n\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n this.queryState[targetId] = state;\n }\n\n removeLocalQueryTarget(targetId: TargetId): void {\n this.localState.removeQueryTarget(targetId);\n }\n\n isLocalQueryTarget(targetId: TargetId): boolean {\n return this.localState.activeTargetIds.has(targetId);\n }\n\n clearQueryState(targetId: TargetId): void {\n delete this.queryState[targetId];\n }\n\n getAllActiveQueryTargets(): TargetIdSet {\n return this.localState.activeTargetIds;\n }\n\n isActiveQueryTarget(targetId: TargetId): boolean {\n return this.localState.activeTargetIds.has(targetId);\n }\n\n start(): Promise<void> {\n this.localState = new LocalClientState();\n return Promise.resolve();\n }\n\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void {\n // No op.\n }\n\n setOnlineState(onlineState: OnlineState): void {\n // No op.\n }\n\n shutdown(): void {}\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void {}\n\n notifyBundleLoaded(collectionGroups: Set<string>): void {\n // No op.\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ConnectivityMonitor, NetworkStatus } from './connectivity_monitor';\n\nexport class NoopConnectivityMonitor implements ConnectivityMonitor {\n addCallback(callback: (status: NetworkStatus) => void): void {\n // No-op.\n }\n\n shutdown(): void {\n // No-op.\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ConnectivityMonitor,\n ConnectivityMonitorCallback,\n NetworkStatus\n} from '../../remote/connectivity_monitor';\nimport { logDebug } from '../../util/log';\n\n// References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()\n/* eslint-disable no-restricted-globals */\n\nconst LOG_TAG = 'ConnectivityMonitor';\n\n/**\n * Browser implementation of ConnectivityMonitor.\n */\nexport class BrowserConnectivityMonitor implements ConnectivityMonitor {\n private readonly networkAvailableListener = (): void =>\n this.onNetworkAvailable();\n private readonly networkUnavailableListener = (): void =>\n this.onNetworkUnavailable();\n private callbacks: ConnectivityMonitorCallback[] = [];\n\n constructor() {\n this.configureNetworkMonitoring();\n }\n\n addCallback(callback: (status: NetworkStatus) => void): void {\n this.callbacks.push(callback);\n }\n\n shutdown(): void {\n window.removeEventListener('online', this.networkAvailableListener);\n window.removeEventListener('offline', this.networkUnavailableListener);\n }\n\n private configureNetworkMonitoring(): void {\n window.addEventListener('online', this.networkAvailableListener);\n window.addEventListener('offline', this.networkUnavailableListener);\n }\n\n private onNetworkAvailable(): void {\n logDebug(LOG_TAG, 'Network connectivity changed: AVAILABLE');\n for (const callback of this.callbacks) {\n callback(NetworkStatus.AVAILABLE);\n }\n }\n\n private onNetworkUnavailable(): void {\n logDebug(LOG_TAG, 'Network connectivity changed: UNAVAILABLE');\n for (const callback of this.callbacks) {\n callback(NetworkStatus.UNAVAILABLE);\n }\n }\n\n // TODO(chenbrian): Consider passing in window either into this component or\n // here for testing via FakeWindow.\n /** Checks that all used attributes of window are available. */\n static isAvailable(): boolean {\n return (\n typeof window !== 'undefined' &&\n window.addEventListener !== undefined &&\n window.removeEventListener !== undefined\n );\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The value returned from the most recent invocation of\n * `generateUniqueDebugId()`, or null if it has never been invoked.\n */\nlet lastUniqueDebugId: number | null = null;\n\n/**\n * Generates and returns an initial value for `lastUniqueDebugId`.\n *\n * The returned value is randomly selected from a range of integers that are\n * represented as 8 hexadecimal digits. This means that (within reason) any\n * numbers generated by incrementing the returned number by 1 will also be\n * represented by 8 hexadecimal digits. This leads to all \"IDs\" having the same\n * length when converted to a hexadecimal string, making reading logs containing\n * these IDs easier to follow. And since the return value is randomly selected\n * it will help to differentiate between logs from different executions.\n */\nfunction generateInitialUniqueDebugId(): number {\n const minResult = 0x10000000;\n const maxResult = 0x90000000;\n const resultRange = maxResult - minResult;\n const resultOffset = Math.round(resultRange * Math.random());\n return minResult + resultOffset;\n}\n\n/**\n * Generates and returns a unique ID as a hexadecimal string.\n *\n * The returned ID is intended to be used in debug logging messages to help\n * correlate log messages that may be spatially separated in the logs, but\n * logically related. For example, a network connection could include the same\n * \"debug ID\" string in all of its log messages to help trace a specific\n * connection over time.\n *\n * @return the 10-character generated ID (e.g. \"0xa1b2c3d4\").\n */\nexport function generateUniqueDebugId(): string {\n if (lastUniqueDebugId === null) {\n lastUniqueDebugId = generateInitialUniqueDebugId();\n } else {\n lastUniqueDebugId++;\n }\n return '0x' + lastUniqueDebugId.toString(16);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../../src/core/version';\nimport { Token } from '../api/credentials';\nimport {\n DatabaseId,\n DatabaseInfo,\n DEFAULT_DATABASE_NAME\n} from '../core/database_info';\nimport { debugAssert } from '../util/assert';\nimport { generateUniqueDebugId } from '../util/debug_uid';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { StringMap } from '../util/types';\n\nimport { Connection, Stream } from './connection';\n\nconst LOG_TAG = 'RestConnection';\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\nconst RPC_NAME_URL_MAPPING: StringMap = {};\n\nRPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet';\nRPC_NAME_URL_MAPPING['Commit'] = 'commit';\nRPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery';\nRPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery';\n\nconst RPC_URL_VERSION = 'v1';\n\n// SDK_VERSION is updated to different value at runtime depending on the entry point,\n// so we need to get its value when we need it in a function.\nfunction getGoogApiClientValue(): string {\n return 'gl-js/ fire/' + SDK_VERSION;\n}\n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nexport abstract class RestConnection implements Connection {\n protected readonly databaseId: DatabaseId;\n protected readonly baseUrl: string;\n private readonly databasePath: string;\n private readonly requestParams: string;\n\n get shouldResourcePathBeIncludedInRequest(): boolean {\n // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n // where to run the query, and expect the `request` to NOT specify the \"path\".\n return false;\n }\n\n constructor(private readonly databaseInfo: DatabaseInfo) {\n this.databaseId = databaseInfo.databaseId;\n const proto = databaseInfo.ssl ? 'https' : 'http';\n const projectId = encodeURIComponent(this.databaseId.projectId);\n const databaseId = encodeURIComponent(this.databaseId.database);\n this.baseUrl = proto + '://' + databaseInfo.host;\n this.databasePath = `projects/${projectId}/databases/${databaseId}`;\n this.requestParams =\n this.databaseId.database === DEFAULT_DATABASE_NAME\n ? `project_id=${projectId}`\n : `project_id=${projectId}&database_id=${databaseId}`;\n }\n\n invokeRPC<Req, Resp>(\n rpcName: string,\n path: string,\n req: Req,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Promise<Resp> {\n const streamId = generateUniqueDebugId();\n const url = this.makeUrl(rpcName, path);\n logDebug(LOG_TAG, `Sending RPC '${rpcName}' ${streamId}:`, url, req);\n\n const headers: StringMap = {\n 'google-cloud-resource-prefix': this.databasePath,\n 'x-goog-request-params': this.requestParams\n };\n this.modifyHeadersForRequest(headers, authToken, appCheckToken);\n\n return this.performRPCRequest<Req, Resp>(rpcName, url, headers, req).then(\n response => {\n logDebug(LOG_TAG, `Received RPC '${rpcName}' ${streamId}: `, response);\n return response;\n },\n (err: FirestoreError) => {\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with error: `,\n err,\n 'url: ',\n url,\n 'request:',\n req\n );\n throw err;\n }\n );\n }\n\n invokeStreamingRPC<Req, Resp>(\n rpcName: string,\n path: string,\n request: Req,\n authToken: Token | null,\n appCheckToken: Token | null,\n expectedResponseCount?: number\n ): Promise<Resp[]> {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.invokeRPC<Req, Resp[]>(\n rpcName,\n path,\n request,\n authToken,\n appCheckToken\n );\n }\n\n abstract openStream<Req, Resp>(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream<Req, Resp>;\n\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n protected modifyHeadersForRequest(\n headers: StringMap,\n authToken: Token | null,\n appCheckToken: Token | null\n ): void {\n headers['X-Goog-Api-Client'] = getGoogApiClientValue();\n\n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the $httpOverwrite\n // parameter supported by ESF to avoid triggering preflight requests.\n headers['Content-Type'] = 'text/plain';\n\n if (this.databaseInfo.appId) {\n headers['X-Firebase-GMPID'] = this.databaseInfo.appId;\n }\n\n if (authToken) {\n authToken.headers.forEach((value, key) => (headers[key] = value));\n }\n if (appCheckToken) {\n appCheckToken.headers.forEach((value, key) => (headers[key] = value));\n }\n }\n\n /**\n * Performs an RPC request using an implementation specific networking layer.\n */\n protected abstract performRPCRequest<Req, Resp>(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req\n ): Promise<Resp>;\n\n private makeUrl(rpcName: string, path: string): string {\n const urlRpcName = RPC_NAME_URL_MAPPING[rpcName];\n debugAssert(\n urlRpcName !== undefined,\n 'Unknown REST mapping for: ' + rpcName\n );\n return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\nimport { FirestoreError } from '../util/error';\n\nimport { Stream } from './connection';\n\n/**\n * Provides a simple helper class that implements the Stream interface to\n * bridge to other implementations that are streams but do not implement the\n * interface. The stream callbacks are invoked with the callOn... methods.\n */\nexport class StreamBridge<I, O> implements Stream<I, O> {\n private wrappedOnOpen: (() => void) | undefined;\n private wrappedOnClose: ((err?: FirestoreError) => void) | undefined;\n private wrappedOnMessage: ((msg: O) => void) | undefined;\n\n private sendFn: (msg: I) => void;\n private closeFn: () => void;\n\n constructor(args: { sendFn: (msg: I) => void; closeFn: () => void }) {\n this.sendFn = args.sendFn;\n this.closeFn = args.closeFn;\n }\n\n onOpen(callback: () => void): void {\n debugAssert(!this.wrappedOnOpen, 'Called onOpen on stream twice!');\n this.wrappedOnOpen = callback;\n }\n\n onClose(callback: (err?: FirestoreError) => void): void {\n debugAssert(!this.wrappedOnClose, 'Called onClose on stream twice!');\n this.wrappedOnClose = callback;\n }\n\n onMessage(callback: (msg: O) => void): void {\n debugAssert(!this.wrappedOnMessage, 'Called onMessage on stream twice!');\n this.wrappedOnMessage = callback;\n }\n\n close(): void {\n this.closeFn();\n }\n\n send(msg: I): void {\n this.sendFn(msg);\n }\n\n callOnOpen(): void {\n debugAssert(\n this.wrappedOnOpen !== undefined,\n 'Cannot call onOpen because no callback was set'\n );\n this.wrappedOnOpen();\n }\n\n callOnClose(err?: FirestoreError): void {\n debugAssert(\n this.wrappedOnClose !== undefined,\n 'Cannot call onClose because no callback was set'\n );\n this.wrappedOnClose(err);\n }\n\n callOnMessage(msg: O): void {\n debugAssert(\n this.wrappedOnMessage !== undefined,\n 'Cannot call onMessage because no callback was set'\n );\n this.wrappedOnMessage(msg);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createWebChannelTransport,\n ErrorCode,\n EventType,\n WebChannel,\n WebChannelError,\n WebChannelOptions,\n XhrIo,\n getStatEventTarget,\n EventTarget,\n StatEvent,\n Event,\n Stat,\n FetchXmlHttpFactory\n} from '@firebase/webchannel-wrapper';\n\nimport { Token } from '../../api/credentials';\nimport { ExperimentalLongPollingOptions } from '../../api/long_polling_options';\nimport { DatabaseInfo } from '../../core/database_info';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport {\n mapCodeFromRpcStatus,\n mapCodeFromHttpResponseErrorStatus\n} from '../../remote/rpc_error';\nimport { StreamBridge } from '../../remote/stream_bridge';\nimport { fail, hardAssert } from '../../util/assert';\nimport { generateUniqueDebugId } from '../../util/debug_uid';\nimport { Code, FirestoreError } from '../../util/error';\nimport { logDebug, logWarn } from '../../util/log';\nimport { Rejecter, Resolver } from '../../util/promise';\nimport { StringMap } from '../../util/types';\n\nconst LOG_TAG = 'WebChannelConnection';\n\nconst RPC_STREAM_SERVICE = 'google.firestore.v1.Firestore';\n\nconst XHR_TIMEOUT_SECS = 15;\n\nexport class WebChannelConnection extends RestConnection {\n private readonly forceLongPolling: boolean;\n private readonly autoDetectLongPolling: boolean;\n private readonly useFetchStreams: boolean;\n private readonly longPollingOptions: ExperimentalLongPollingOptions;\n\n constructor(info: DatabaseInfo) {\n super(info);\n this.forceLongPolling = info.forceLongPolling;\n this.autoDetectLongPolling = info.autoDetectLongPolling;\n this.useFetchStreams = info.useFetchStreams;\n this.longPollingOptions = info.longPollingOptions;\n }\n\n protected performRPCRequest<Req, Resp>(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req\n ): Promise<Resp> {\n const streamId = generateUniqueDebugId();\n return new Promise((resolve: Resolver<Resp>, reject: Rejecter) => {\n const xhr = new XhrIo();\n xhr.setWithCredentials(true);\n xhr.listenOnce(EventType.COMPLETE, () => {\n try {\n switch (xhr.getLastErrorCode()) {\n case ErrorCode.NO_ERROR:\n const json = xhr.getResponseJson() as Resp;\n logDebug(\n LOG_TAG,\n `XHR for RPC '${rpcName}' ${streamId} received:`,\n JSON.stringify(json)\n );\n resolve(json);\n break;\n case ErrorCode.TIMEOUT:\n logDebug(LOG_TAG, `RPC '${rpcName}' ${streamId} timed out`);\n reject(\n new FirestoreError(Code.DEADLINE_EXCEEDED, 'Request time out')\n );\n break;\n case ErrorCode.HTTP_ERROR:\n const status = xhr.getStatus();\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with status:`,\n status,\n 'response text:',\n xhr.getResponseText()\n );\n if (status > 0) {\n let response = xhr.getResponseJson();\n if (Array.isArray(response)) {\n response = response[0];\n }\n const responseError = (response as WebChannelError)?.error;\n if (\n !!responseError &&\n !!responseError.status &&\n !!responseError.message\n ) {\n const firestoreErrorCode = mapCodeFromHttpResponseErrorStatus(\n responseError.status\n );\n reject(\n new FirestoreError(\n firestoreErrorCode,\n responseError.message\n )\n );\n } else {\n reject(\n new FirestoreError(\n Code.UNKNOWN,\n 'Server responded with status ' + xhr.getStatus()\n )\n );\n }\n } else {\n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue\n reject(\n new FirestoreError(Code.UNAVAILABLE, 'Connection failed.')\n );\n }\n break;\n default:\n fail(\n `RPC '${rpcName}' ${streamId} ` +\n 'failed with unanticipated webchannel error: ' +\n xhr.getLastErrorCode() +\n ': ' +\n xhr.getLastError() +\n ', giving up.'\n );\n }\n } finally {\n logDebug(LOG_TAG, `RPC '${rpcName}' ${streamId} completed.`);\n }\n });\n\n const requestString = JSON.stringify(body);\n logDebug(LOG_TAG, `RPC '${rpcName}' ${streamId} sending request:`, body);\n xhr.send(url, 'POST', requestString, headers, XHR_TIMEOUT_SECS);\n });\n }\n\n openStream<Req, Resp>(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream<Req, Resp> {\n const streamId = generateUniqueDebugId();\n const urlParts = [\n this.baseUrl,\n '/',\n RPC_STREAM_SERVICE,\n '/',\n rpcName,\n '/channel'\n ];\n const webchannelTransport = createWebChannelTransport();\n const requestStats = getStatEventTarget();\n const request: WebChannelOptions = {\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: 'gsessionid',\n initMessageHeaders: {},\n messageUrlParams: {\n // This param is used to improve routing and project isolation by the\n // backend and must be included in every request.\n database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`\n },\n sendRawJson: true,\n supportsCrossDomainXhr: true,\n internalChannelParams: {\n // Override the default timeout (randomized between 10-20 seconds) since\n // a large write batch on a slow internet connection may take a long\n // time to send to the backend. Rather than have WebChannel impose a\n // tight timeout which could lead to infinite timeouts and retries, we\n // set it very large (5-10 minutes) and rely on the browser's builtin\n // timeouts to kick in if the request isn't working.\n forwardChannelRequestTimeoutMs: 10 * 60 * 1000\n },\n forceLongPolling: this.forceLongPolling,\n detectBufferingProxy: this.autoDetectLongPolling\n };\n\n const longPollingTimeoutSeconds = this.longPollingOptions.timeoutSeconds;\n if (longPollingTimeoutSeconds !== undefined) {\n request.longPollingTimeout = Math.round(longPollingTimeoutSeconds * 1000);\n }\n\n if (this.useFetchStreams) {\n // TODO(b/307942499): switch to `useFetchStreams` once WebChannel is fixed.\n request.xmlHttpFactory = new FetchXmlHttpFactory({});\n }\n\n this.modifyHeadersForRequest(\n request.initMessageHeaders!,\n authToken,\n appCheckToken\n );\n\n // Sending the custom headers we just added to request.initMessageHeaders\n // (Authorization, etc.) will trigger the browser to make a CORS preflight\n // request because the XHR will no longer meet the criteria for a \"simple\"\n // CORS request:\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests\n //\n // Therefore to avoid the CORS preflight request (an extra network\n // roundtrip), we use the encodeInitMessageHeaders option to specify that\n // the headers should instead be encoded in the request's POST payload,\n // which is recognized by the webchannel backend.\n request.encodeInitMessageHeaders = true;\n\n const url = urlParts.join('');\n logDebug(\n LOG_TAG,\n `Creating RPC '${rpcName}' stream ${streamId}: ${url}`,\n request\n );\n const channel = webchannelTransport.createWebChannel(url, request);\n\n // WebChannel supports sending the first message with the handshake - saving\n // a network round trip. However, it will have to call send in the same\n // JS event loop as open. In order to enforce this, we delay actually\n // opening the WebChannel until send is called. Whether we have called\n // open is tracked with this variable.\n let opened = false;\n\n // A flag to determine whether the stream was closed (by us or through an\n // error/close event) to avoid delivering multiple close events or sending\n // on a closed stream\n let closed = false;\n\n const streamBridge = new StreamBridge<Req, Resp>({\n sendFn: (msg: Req) => {\n if (!closed) {\n if (!opened) {\n logDebug(\n LOG_TAG,\n `Opening RPC '${rpcName}' stream ${streamId} transport.`\n );\n channel.open();\n opened = true;\n }\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} sending:`,\n msg\n );\n channel.send(msg);\n } else {\n logDebug(\n LOG_TAG,\n `Not sending because RPC '${rpcName}' stream ${streamId} ` +\n 'is closed:',\n msg\n );\n }\n },\n closeFn: () => channel.close()\n });\n\n // Closure events are guarded and exceptions are swallowed, so catch any\n // exception and rethrow using a setTimeout so they become visible again.\n // Note that eventually this function could go away if we are confident\n // enough the code is exception free.\n const unguardedEventListen = <T>(\n target: EventTarget,\n type: string | number,\n fn: (param: T) => void\n ): void => {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n target.listen(type, (param: unknown) => {\n try {\n fn(param as T);\n } catch (e) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n });\n };\n\n unguardedEventListen(channel, WebChannel.EventType.OPEN, () => {\n if (!closed) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} transport opened.`\n );\n }\n });\n\n unguardedEventListen(channel, WebChannel.EventType.CLOSE, () => {\n if (!closed) {\n closed = true;\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} transport closed`\n );\n streamBridge.callOnClose();\n }\n });\n\n unguardedEventListen<Error>(channel, WebChannel.EventType.ERROR, err => {\n if (!closed) {\n closed = true;\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} transport errored:`,\n err\n );\n streamBridge.callOnClose(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'The operation could not be completed'\n )\n );\n }\n });\n\n // WebChannel delivers message events as array. If batching is not enabled\n // (it's off by default) each message will be delivered alone, resulting in\n // a single element array.\n interface WebChannelResponse {\n data: Resp[];\n }\n\n unguardedEventListen<WebChannelResponse>(\n channel,\n WebChannel.EventType.MESSAGE,\n msg => {\n if (!closed) {\n const msgData = msg.data[0];\n hardAssert(!!msgData, 'Got a webchannel message without data.');\n // TODO(b/35143891): There is a bug in One Platform that caused errors\n // (and only errors) to be wrapped in an extra array. To be forward\n // compatible with the bug we need to check either condition. The latter\n // can be removed once the fix has been rolled out.\n // Use any because msgData.error is not typed.\n const msgDataOrError: WebChannelError | object = msgData;\n const error =\n msgDataOrError.error ||\n (msgDataOrError as WebChannelError[])[0]?.error;\n if (error) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} received error:`,\n error\n );\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n const status: string = error.status;\n let code = mapCodeFromRpcStatus(status);\n let message = error.message;\n if (code === undefined) {\n code = Code.INTERNAL;\n message =\n 'Unknown error status: ' +\n status +\n ' with message ' +\n error.message;\n }\n // Mark closed so no further events are propagated\n closed = true;\n streamBridge.callOnClose(new FirestoreError(code, message));\n channel.close();\n } else {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} received:`,\n msgData\n );\n streamBridge.callOnMessage(msgData);\n }\n }\n }\n );\n\n unguardedEventListen<StatEvent>(requestStats, Event.STAT_EVENT, event => {\n if (event.stat === Stat.PROXY) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} detected buffering proxy`\n );\n } else if (event.stat === Stat.NOPROXY) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} detected no buffering proxy`\n );\n }\n });\n\n setTimeout(() => {\n // Technically we could/should wait for the WebChannel opened event,\n // but because we want to send the first message with the WebChannel\n // handshake we pretend the channel opened here (asynchronously), and\n // then delay the actual open until the first message is sent.\n streamBridge.callOnOpen();\n }, 0);\n return streamBridge;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The Platform's 'window' implementation or null if not available. */\nexport function getWindow(): Window | null {\n // `window` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' ? window : null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */\nexport function getDocument(): Document | null {\n // `document` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof document !== 'undefined' ? document : null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Return the Platform-specific serializer monitor. */\nimport { DatabaseId } from '../../core/database_info';\nimport { JsonProtoSerializer } from '../../remote/serializer';\n\nexport function newSerializer(databaseId: DatabaseId): JsonProtoSerializer {\n return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nconst LOG_TAG = 'ExponentialBackoff';\n\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nconst DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;\n\nconst DEFAULT_BACKOFF_FACTOR = 1.5;\n\n/** Maximum backoff time in milliseconds */\nconst DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;\n\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nexport class ExponentialBackoff {\n private currentBaseMs: number = 0;\n private timerPromise: DelayedOperation<void> | null = null;\n /** The last backoff attempt, as epoch milliseconds. */\n private lastAttemptTime = Date.now();\n\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n private readonly queue: AsyncQueue,\n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n private readonly timerId: TimerId,\n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n private readonly initialDelayMs: number = DEFAULT_BACKOFF_INITIAL_DELAY_MS,\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n private readonly backoffFactor: number = DEFAULT_BACKOFF_FACTOR,\n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */\n private readonly maxDelayMs: number = DEFAULT_BACKOFF_MAX_DELAY_MS\n ) {\n this.reset();\n }\n\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */\n reset(): void {\n this.currentBaseMs = 0;\n }\n\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n resetToMax(): void {\n this.currentBaseMs = this.maxDelayMs;\n }\n\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts. If there was a pending backoff operation\n * already, it will be canceled.\n */\n backoffAndRun(op: () => Promise<void>): void {\n // Cancel any pending backoff operation.\n this.cancel();\n\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const desiredDelayWithJitterMs = Math.floor(\n this.currentBaseMs + this.jitterDelayMs()\n );\n\n // Guard against lastAttemptTime being in the future due to a clock change.\n const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);\n\n // Guard against the backoff delay already being past.\n const remainingDelayMs = Math.max(\n 0,\n desiredDelayWithJitterMs - delaySoFarMs\n );\n\n if (remainingDelayMs > 0) {\n logDebug(\n LOG_TAG,\n `Backing off for ${remainingDelayMs} ms ` +\n `(base delay: ${this.currentBaseMs} ms, ` +\n `delay with jitter: ${desiredDelayWithJitterMs} ms, ` +\n `last attempt: ${delaySoFarMs} ms ago)`\n );\n }\n\n this.timerPromise = this.queue.enqueueAfterDelay(\n this.timerId,\n remainingDelayMs,\n () => {\n this.lastAttemptTime = Date.now();\n return op();\n }\n );\n\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n }\n\n skipBackoff(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.skipDelay();\n this.timerPromise = null;\n }\n }\n\n cancel(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.cancel();\n this.timerPromise = null;\n }\n }\n\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n private jitterDelayMs(): number {\n return (Math.random() - 0.5) * this.currentBaseMs;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider, Token } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { TargetData } from '../local/target_data';\nimport { Mutation, MutationResult } from '../model/mutation';\nimport {\n ListenRequest as ProtoListenRequest,\n ListenResponse as ProtoListenResponse,\n WriteRequest as ProtoWriteRequest,\n WriteResponse as ProtoWriteResponse\n} from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExponentialBackoff } from './backoff';\nimport { Connection, Stream } from './connection';\nimport {\n fromVersion,\n fromWatchChange,\n fromWriteResults,\n getEncodedDatabaseId,\n JsonProtoSerializer,\n toListenRequestLabels,\n toMutation,\n toTarget,\n versionFromListenResponse\n} from './serializer';\nimport { WatchChange } from './watch_change';\n\nconst LOG_TAG = 'PersistentStream';\n\n// The generated proto interfaces for these class are missing the database\n// field. So we add it here.\n// TODO(b/36015800): Remove this once the api generator is fixed.\ninterface ListenRequest extends ProtoListenRequest {\n database?: string;\n}\nexport interface WriteRequest extends ProtoWriteRequest {\n database?: string;\n}\n/**\n * PersistentStream can be in one of 5 states (each described in detail below)\n * based on the following state transition diagram:\n *\n * start() called auth & connection succeeded\n * INITIAL ----------------> STARTING -----------------------------> OPEN\n * ^ | |\n * | | error occurred |\n * | \\-----------------------------v-----/\n * | |\n * backoff | |\n * elapsed | start() called |\n * \\--- BACKOFF <---------------- ERROR\n *\n * [any state] --------------------------> INITIAL\n * stop() called or\n * idle timer expired\n */\nconst enum PersistentStreamState {\n /**\n * The streaming RPC is not yet running and there's no error condition.\n * Calling start() will start the stream immediately without backoff.\n * While in this state isStarted() will return false.\n */\n Initial,\n\n /**\n * The stream is starting, either waiting for an auth token or for the stream\n * to successfully open. While in this state, isStarted() will return true but\n * isOpen() will return false.\n */\n Starting,\n\n /**\n * The streaming RPC is up and running. Requests and responses can flow\n * freely. Both isStarted() and isOpen() will return true.\n */\n Open,\n\n /**\n * The stream is healthy and has been connected for more than 10 seconds. We\n * therefore assume that the credentials we passed were valid. Both\n * isStarted() and isOpen() will return true.\n */\n Healthy,\n\n /**\n * The stream encountered an error. The next start attempt will back off.\n * While in this state isStarted() will return false.\n */\n Error,\n\n /**\n * An in-between state after an error where the stream is waiting before\n * re-starting. After waiting is complete, the stream will try to open.\n * While in this state isStarted() will return true but isOpen() will return\n * false.\n */\n Backoff\n}\n\n/**\n * Provides a common interface that is shared by the listeners for stream\n * events by the concrete implementation classes.\n */\nexport interface PersistentStreamListener {\n /**\n * Called after the stream was established and can accept outgoing\n * messages\n */\n onOpen: () => Promise<void>;\n /**\n * Called after the stream has closed. If there was an error, the\n * FirestoreError will be set.\n */\n onClose: (err?: FirestoreError) => Promise<void>;\n}\n\n/** The time a stream stays open after it is marked idle. */\nconst IDLE_TIMEOUT_MS = 60 * 1000;\n\n/** The time a stream stays open until we consider it healthy. */\nconst HEALTHY_TIMEOUT_MS = 10 * 1000;\n\n/**\n * A PersistentStream is an abstract base class that represents a streaming RPC\n * to the Firestore backend. It's built on top of the connections own support\n * for streaming RPCs, and adds several critical features for our clients:\n *\n * - Exponential backoff on failure\n * - Authentication via CredentialsProvider\n * - Dispatching all callbacks into the shared worker queue\n * - Closing idle streams after 60 seconds of inactivity\n *\n * Subclasses of PersistentStream implement serialization of models to and\n * from the JSON representation of the protocol buffers for a specific\n * streaming RPC.\n *\n * ## Starting and Stopping\n *\n * Streaming RPCs are stateful and need to be start()ed before messages can\n * be sent and received. The PersistentStream will call the onOpen() function\n * of the listener once the stream is ready to accept requests.\n *\n * Should a start() fail, PersistentStream will call the registered onClose()\n * listener with a FirestoreError indicating what went wrong.\n *\n * A PersistentStream can be started and stopped repeatedly.\n *\n * Generic types:\n * SendType: The type of the outgoing message of the underlying\n * connection stream\n * ReceiveType: The type of the incoming message of the underlying\n * connection stream\n * ListenerType: The type of the listener that will be used for callbacks\n */\nexport abstract class PersistentStream<\n SendType,\n ReceiveType,\n ListenerType extends PersistentStreamListener\n> {\n private state = PersistentStreamState.Initial;\n /**\n * A close count that's incremented every time the stream is closed; used by\n * getCloseGuardedDispatcher() to invalidate callbacks that happen after\n * close.\n */\n private closeCount = 0;\n\n private idleTimer: DelayedOperation<void> | null = null;\n private healthCheck: DelayedOperation<void> | null = null;\n private stream: Stream<SendType, ReceiveType> | null = null;\n\n protected backoff: ExponentialBackoff;\n\n constructor(\n private queue: AsyncQueue,\n connectionTimerId: TimerId,\n private idleTimerId: TimerId,\n private healthTimerId: TimerId,\n protected connection: Connection,\n private authCredentialsProvider: CredentialsProvider<User>,\n private appCheckCredentialsProvider: CredentialsProvider<string>,\n protected listener: ListenerType\n ) {\n this.backoff = new ExponentialBackoff(queue, connectionTimerId);\n }\n\n /**\n * Returns true if start() has been called and no error has occurred. True\n * indicates the stream is open or in the process of opening (which\n * encompasses respecting backoff, getting auth tokens, and starting the\n * actual RPC). Use isOpen() to determine if the stream is open and ready for\n * outbound requests.\n */\n isStarted(): boolean {\n return (\n this.state === PersistentStreamState.Starting ||\n this.state === PersistentStreamState.Backoff ||\n this.isOpen()\n );\n }\n\n /**\n * Returns true if the underlying RPC is open (the onOpen() listener has been\n * called) and the stream is ready for outbound requests.\n */\n isOpen(): boolean {\n return (\n this.state === PersistentStreamState.Open ||\n this.state === PersistentStreamState.Healthy\n );\n }\n\n /**\n * Starts the RPC. Only allowed if isStarted() returns false. The stream is\n * not immediately ready for use: onOpen() will be invoked when the RPC is\n * ready for outbound requests, at which point isOpen() will return true.\n *\n * When start returns, isStarted() will return true.\n */\n start(): void {\n if (this.state === PersistentStreamState.Error) {\n this.performBackoff();\n return;\n }\n\n debugAssert(\n this.state === PersistentStreamState.Initial,\n 'Already started'\n );\n this.auth();\n }\n\n /**\n * Stops the RPC. This call is idempotent and allowed regardless of the\n * current isStarted() state.\n *\n * When stop returns, isStarted() and isOpen() will both return false.\n */\n async stop(): Promise<void> {\n if (this.isStarted()) {\n await this.close(PersistentStreamState.Initial);\n }\n }\n\n /**\n * After an error the stream will usually back off on the next attempt to\n * start it. If the error warrants an immediate restart of the stream, the\n * sender can use this to indicate that the receiver should not back off.\n *\n * Each error will call the onClose() listener. That function can decide to\n * inhibit backoff if required.\n */\n inhibitBackoff(): void {\n debugAssert(\n !this.isStarted(),\n 'Can only inhibit backoff in a stopped state'\n );\n\n this.state = PersistentStreamState.Initial;\n this.backoff.reset();\n }\n\n /**\n * Marks this stream as idle. If no further actions are performed on the\n * stream for one minute, the stream will automatically close itself and\n * notify the stream's onClose() handler with Status.OK. The stream will then\n * be in a !isStarted() state, requiring the caller to start the stream again\n * before further use.\n *\n * Only streams that are in state 'Open' can be marked idle, as all other\n * states imply pending network operations.\n */\n markIdle(): void {\n // Starts the idle time if we are in state 'Open' and are not yet already\n // running a timer (in which case the previous idle timeout still applies).\n if (this.isOpen() && this.idleTimer === null) {\n this.idleTimer = this.queue.enqueueAfterDelay(\n this.idleTimerId,\n IDLE_TIMEOUT_MS,\n () => this.handleIdleCloseTimer()\n );\n }\n }\n\n /** Sends a message to the underlying stream. */\n protected sendRequest(msg: SendType): void {\n this.cancelIdleCheck();\n this.stream!.send(msg);\n }\n\n /** Called by the idle timer when the stream should close due to inactivity. */\n private async handleIdleCloseTimer(): Promise<void> {\n if (this.isOpen()) {\n // When timing out an idle stream there's no reason to force the stream into backoff when\n // it restarts so set the stream state to Initial instead of Error.\n return this.close(PersistentStreamState.Initial);\n }\n }\n\n /** Marks the stream as active again. */\n private cancelIdleCheck(): void {\n if (this.idleTimer) {\n this.idleTimer.cancel();\n this.idleTimer = null;\n }\n }\n\n /** Cancels the health check delayed operation. */\n private cancelHealthCheck(): void {\n if (this.healthCheck) {\n this.healthCheck.cancel();\n this.healthCheck = null;\n }\n }\n\n /**\n * Closes the stream and cleans up as necessary:\n *\n * * closes the underlying GRPC stream;\n * * calls the onClose handler with the given 'error';\n * * sets internal stream state to 'finalState';\n * * adjusts the backoff timer based on the error\n *\n * A new stream can be opened by calling start().\n *\n * @param finalState - the intended state of the stream after closing.\n * @param error - the error the connection was closed with.\n */\n private async close(\n finalState: PersistentStreamState,\n error?: FirestoreError\n ): Promise<void> {\n debugAssert(this.isStarted(), 'Only started streams should be closed.');\n debugAssert(\n finalState === PersistentStreamState.Error || isNullOrUndefined(error),\n \"Can't provide an error when not in an error state.\"\n );\n\n // Cancel any outstanding timers (they're guaranteed not to execute).\n this.cancelIdleCheck();\n this.cancelHealthCheck();\n this.backoff.cancel();\n\n // Invalidates any stream-related callbacks (e.g. from auth or the\n // underlying stream), guaranteeing they won't execute.\n this.closeCount++;\n\n if (finalState !== PersistentStreamState.Error) {\n // If this is an intentional close ensure we don't delay our next connection attempt.\n this.backoff.reset();\n } else if (error && error.code === Code.RESOURCE_EXHAUSTED) {\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n logError(error.toString());\n logError(\n 'Using maximum backoff delay to prevent overloading the backend.'\n );\n this.backoff.resetToMax();\n } else if (\n error &&\n error.code === Code.UNAUTHENTICATED &&\n this.state !== PersistentStreamState.Healthy\n ) {\n // \"unauthenticated\" error means the token was rejected. This should rarely\n // happen since both Auth and AppCheck ensure a sufficient TTL when we\n // request a token. If a user manually resets their system clock this can\n // fail, however. In this case, we should get a Code.UNAUTHENTICATED error\n // before we received the first message and we need to invalidate the token\n // to ensure that we fetch a new token.\n this.authCredentialsProvider.invalidateToken();\n this.appCheckCredentialsProvider.invalidateToken();\n }\n\n // Clean up the underlying stream because we are no longer interested in events.\n if (this.stream !== null) {\n this.tearDown();\n this.stream.close();\n this.stream = null;\n }\n\n // This state must be assigned before calling onClose() to allow the callback to\n // inhibit backoff or otherwise manipulate the state in its non-started state.\n this.state = finalState;\n\n // Notify the listener that the stream closed.\n await this.listener.onClose(error);\n }\n\n /**\n * Can be overridden to perform additional cleanup before the stream is closed.\n * Calling super.tearDown() is not required.\n */\n protected tearDown(): void {}\n\n /**\n * Used by subclasses to start the concrete RPC and return the underlying\n * connection stream.\n */\n protected abstract startRpc(\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream<SendType, ReceiveType>;\n\n /**\n * Called after the stream has received a message. The function will be\n * called on the right queue and must return a Promise.\n * @param message - The message received from the stream.\n */\n protected abstract onMessage(message: ReceiveType): Promise<void>;\n\n private auth(): void {\n debugAssert(\n this.state === PersistentStreamState.Initial,\n 'Must be in initial state to auth'\n );\n\n this.state = PersistentStreamState.Starting;\n\n const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount);\n\n // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.\n const closeCount = this.closeCount;\n\n Promise.all([\n this.authCredentialsProvider.getToken(),\n this.appCheckCredentialsProvider.getToken()\n ]).then(\n ([authToken, appCheckToken]) => {\n // Stream can be stopped while waiting for authentication.\n // TODO(mikelehen): We really should just use dispatchIfNotClosed\n // and let this dispatch onto the queue, but that opened a spec test can\n // of worms that I don't want to deal with in this PR.\n if (this.closeCount === closeCount) {\n // Normally we'd have to schedule the callback on the AsyncQueue.\n // However, the following calls are safe to be called outside the\n // AsyncQueue since they don't chain asynchronous calls\n this.startStream(authToken, appCheckToken);\n }\n },\n (error: Error) => {\n dispatchIfNotClosed(() => {\n const rpcError = new FirestoreError(\n Code.UNKNOWN,\n 'Fetching auth token failed: ' + error.message\n );\n return this.handleStreamClose(rpcError);\n });\n }\n );\n }\n\n private startStream(\n authToken: Token | null,\n appCheckToken: Token | null\n ): void {\n debugAssert(\n this.state === PersistentStreamState.Starting,\n 'Trying to start stream in a non-starting state'\n );\n\n const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount);\n\n this.stream = this.startRpc(authToken, appCheckToken);\n this.stream.onOpen(() => {\n dispatchIfNotClosed(() => {\n debugAssert(\n this.state === PersistentStreamState.Starting,\n 'Expected stream to be in state Starting, but was ' + this.state\n );\n this.state = PersistentStreamState.Open;\n debugAssert(\n this.healthCheck === null,\n 'Expected healthCheck to be null'\n );\n this.healthCheck = this.queue.enqueueAfterDelay(\n this.healthTimerId,\n HEALTHY_TIMEOUT_MS,\n () => {\n if (this.isOpen()) {\n this.state = PersistentStreamState.Healthy;\n }\n return Promise.resolve();\n }\n );\n return this.listener!.onOpen();\n });\n });\n this.stream.onClose((error?: FirestoreError) => {\n dispatchIfNotClosed(() => {\n return this.handleStreamClose(error);\n });\n });\n this.stream.onMessage((msg: ReceiveType) => {\n dispatchIfNotClosed(() => {\n return this.onMessage(msg);\n });\n });\n }\n\n private performBackoff(): void {\n debugAssert(\n this.state === PersistentStreamState.Error,\n 'Should only perform backoff when in Error state'\n );\n this.state = PersistentStreamState.Backoff;\n\n this.backoff.backoffAndRun(async () => {\n debugAssert(\n this.state === PersistentStreamState.Backoff,\n 'Backoff elapsed but state is now: ' + this.state\n );\n\n this.state = PersistentStreamState.Initial;\n this.start();\n debugAssert(this.isStarted(), 'PersistentStream should have started');\n });\n }\n\n // Visible for tests\n handleStreamClose(error?: FirestoreError): Promise<void> {\n debugAssert(\n this.isStarted(),\n \"Can't handle server close on non-started stream\"\n );\n logDebug(LOG_TAG, `close with error: ${error}`);\n\n this.stream = null;\n\n // In theory the stream could close cleanly, however, in our current model\n // we never expect this to happen because if we stop a stream ourselves,\n // this callback will never be called. To prevent cases where we retry\n // without a backoff accidentally, we set the stream to error in all cases.\n return this.close(PersistentStreamState.Error, error);\n }\n\n /**\n * Returns a \"dispatcher\" function that dispatches operations onto the\n * AsyncQueue but only runs them if closeCount remains unchanged. This allows\n * us to turn auth / stream callbacks into no-ops if the stream is closed /\n * re-opened, etc.\n */\n private getCloseGuardedDispatcher(\n startCloseCount: number\n ): (fn: () => Promise<void>) => void {\n return (fn: () => Promise<void>): void => {\n this.queue.enqueueAndForget(() => {\n if (this.closeCount === startCloseCount) {\n return fn();\n } else {\n logDebug(\n LOG_TAG,\n 'stream callback skipped by getCloseGuardedDispatcher.'\n );\n return Promise.resolve();\n }\n });\n };\n }\n}\n\n/** Listener for the PersistentWatchStream */\nexport interface WatchStreamListener extends PersistentStreamListener {\n /**\n * Called on a watchChange. The snapshot parameter will be MIN if the watch\n * change did not have a snapshot associated with it.\n */\n onWatchChange: (\n watchChange: WatchChange,\n snapshot: SnapshotVersion\n ) => Promise<void>;\n}\n\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the onOpen() listener, any number of\n * listen() and unlisten() calls can be made to control what changes will be\n * sent from the server for ListenResponses.\n */\nexport class PersistentListenStream extends PersistentStream<\n ProtoListenRequest,\n ProtoListenResponse,\n WatchStreamListener\n> {\n constructor(\n queue: AsyncQueue,\n connection: Connection,\n authCredentials: CredentialsProvider<User>,\n appCheckCredentials: CredentialsProvider<string>,\n private serializer: JsonProtoSerializer,\n listener: WatchStreamListener\n ) {\n super(\n queue,\n TimerId.ListenStreamConnectionBackoff,\n TimerId.ListenStreamIdle,\n TimerId.HealthCheckTimeout,\n connection,\n authCredentials,\n appCheckCredentials,\n listener\n );\n }\n\n protected startRpc(\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream<ProtoListenRequest, ProtoListenResponse> {\n return this.connection.openStream<ProtoListenRequest, ProtoListenResponse>(\n 'Listen',\n authToken,\n appCheckToken\n );\n }\n\n protected onMessage(watchChangeProto: ProtoListenResponse): Promise<void> {\n // A successful response means the stream is healthy\n this.backoff.reset();\n\n const watchChange = fromWatchChange(this.serializer, watchChangeProto);\n const snapshot = versionFromListenResponse(watchChangeProto);\n return this.listener!.onWatchChange(watchChange, snapshot);\n }\n\n /**\n * Registers interest in the results of the given target. If the target\n * includes a resumeToken it will be included in the request. Results that\n * affect the target will be streamed back as WatchChange messages that\n * reference the targetId.\n */\n watch(targetData: TargetData): void {\n const request: ListenRequest = {};\n request.database = getEncodedDatabaseId(this.serializer);\n request.addTarget = toTarget(this.serializer, targetData);\n\n const labels = toListenRequestLabels(this.serializer, targetData);\n if (labels) {\n request.labels = labels;\n }\n\n this.sendRequest(request);\n }\n\n /**\n * Unregisters interest in the results of the target associated with the\n * given targetId.\n */\n unwatch(targetId: TargetId): void {\n const request: ListenRequest = {};\n request.database = getEncodedDatabaseId(this.serializer);\n request.removeTarget = targetId;\n this.sendRequest(request);\n }\n}\n\n/** Listener for the PersistentWriteStream */\nexport interface WriteStreamListener extends PersistentStreamListener {\n /**\n * Called by the PersistentWriteStream upon a successful handshake response\n * from the server, which is the receiver's cue to send any pending writes.\n */\n onHandshakeComplete: () => Promise<void>;\n\n /**\n * Called by the PersistentWriteStream upon receiving a StreamingWriteResponse\n * from the server that contains a mutation result.\n */\n onMutationResult: (\n commitVersion: SnapshotVersion,\n results: MutationResult[]\n ) => Promise<void>;\n}\n\n/**\n * A Stream that implements the Write RPC.\n *\n * The Write RPC requires the caller to maintain special streamToken\n * state in between calls, to help the server understand which responses the\n * client has processed by the time the next request is made. Every response\n * will contain a streamToken; this value must be passed to the next\n * request.\n *\n * After calling start() on this stream, the next request must be a handshake,\n * containing whatever streamToken is on hand. Once a response to this\n * request is received, all pending mutations may be submitted. When\n * submitting multiple batches of mutations at the same time, it's\n * okay to use the same streamToken for the calls to writeMutations.\n *\n * TODO(b/33271235): Use proto types\n */\nexport class PersistentWriteStream extends PersistentStream<\n ProtoWriteRequest,\n ProtoWriteResponse,\n WriteStreamListener\n> {\n private handshakeComplete_ = false;\n\n constructor(\n queue: AsyncQueue,\n connection: Connection,\n authCredentials: CredentialsProvider<User>,\n appCheckCredentials: CredentialsProvider<string>,\n private serializer: JsonProtoSerializer,\n listener: WriteStreamListener\n ) {\n super(\n queue,\n TimerId.WriteStreamConnectionBackoff,\n TimerId.WriteStreamIdle,\n TimerId.HealthCheckTimeout,\n connection,\n authCredentials,\n appCheckCredentials,\n listener\n );\n }\n\n /**\n * The last received stream token from the server, used to acknowledge which\n * responses the client has processed. Stream tokens are opaque checkpoint\n * markers whose only real value is their inclusion in the next request.\n *\n * PersistentWriteStream manages propagating this value from responses to the\n * next request.\n */\n private lastStreamToken: string | Uint8Array | undefined;\n\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */\n get handshakeComplete(): boolean {\n return this.handshakeComplete_;\n }\n\n // Override of PersistentStream.start\n start(): void {\n this.handshakeComplete_ = false;\n this.lastStreamToken = undefined;\n super.start();\n }\n\n protected tearDown(): void {\n if (this.handshakeComplete_) {\n this.writeMutations([]);\n }\n }\n\n protected startRpc(\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream<ProtoWriteRequest, ProtoWriteResponse> {\n return this.connection.openStream<ProtoWriteRequest, ProtoWriteResponse>(\n 'Write',\n authToken,\n appCheckToken\n );\n }\n\n protected onMessage(responseProto: ProtoWriteResponse): Promise<void> {\n // Always capture the last stream token.\n hardAssert(\n !!responseProto.streamToken,\n 'Got a write response without a stream token'\n );\n this.lastStreamToken = responseProto.streamToken;\n\n if (!this.handshakeComplete_) {\n // The first response is always the handshake response\n hardAssert(\n !responseProto.writeResults || responseProto.writeResults.length === 0,\n 'Got mutation results for handshake'\n );\n this.handshakeComplete_ = true;\n return this.listener!.onHandshakeComplete();\n } else {\n // A successful first write response means the stream is healthy,\n // Note, that we could consider a successful handshake healthy, however,\n // the write itself might be causing an error we want to back off from.\n this.backoff.reset();\n\n const results = fromWriteResults(\n responseProto.writeResults,\n responseProto.commitTime\n );\n const commitVersion = fromVersion(responseProto.commitTime!);\n return this.listener!.onMutationResult(commitVersion, results);\n }\n }\n\n /**\n * Sends an initial streamToken to the server, performing the handshake\n * required to make the StreamingWrite RPC work. Subsequent\n * calls should wait until onHandshakeComplete was called.\n */\n writeHandshake(): void {\n debugAssert(this.isOpen(), 'Writing handshake requires an opened stream');\n debugAssert(!this.handshakeComplete_, 'Handshake already completed');\n debugAssert(\n !this.lastStreamToken,\n 'Stream token should be empty during handshake'\n );\n // TODO(dimond): Support stream resumption. We intentionally do not set the\n // stream token on the handshake, ignoring any stream token we might have.\n const request: WriteRequest = {};\n request.database = getEncodedDatabaseId(this.serializer);\n this.sendRequest(request);\n }\n\n /** Sends a group of mutations to the Firestore backend to apply. */\n writeMutations(mutations: Mutation[]): void {\n debugAssert(this.isOpen(), 'Writing mutations requires an opened stream');\n debugAssert(\n this.handshakeComplete_,\n 'Handshake must be complete before writing mutations'\n );\n debugAssert(\n !!this.lastStreamToken,\n 'Trying to write mutation without a token'\n );\n\n const request: WriteRequest = {\n streamToken: this.lastStreamToken,\n writes: mutations.map(mutation => toMutation(this.serializer, mutation))\n };\n\n this.sendRequest(request);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { Aggregate } from '../core/aggregate';\nimport { queryToAggregateTarget, Query, queryToTarget } from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport {\n ApiClientObjectMap,\n BatchGetDocumentsRequest as ProtoBatchGetDocumentsRequest,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n RunAggregationQueryResponse as ProtoRunAggregationQueryResponse,\n RunQueryRequest as ProtoRunQueryRequest,\n RunQueryResponse as ProtoRunQueryResponse,\n Value\n} from '../protos/firestore_proto_api';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Connection } from './connection';\nimport {\n PersistentListenStream,\n PersistentWriteStream,\n WatchStreamListener,\n WriteStreamListener\n} from './persistent_stream';\nimport {\n fromDocument,\n fromBatchGetDocumentsResponse,\n getEncodedDatabaseId,\n JsonProtoSerializer,\n toMutation,\n toName,\n toQueryTarget,\n toRunAggregationQueryRequest\n} from './serializer';\n\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\nexport abstract class Datastore {\n abstract terminate(): void;\n abstract serializer: JsonProtoSerializer;\n}\n\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass DatastoreImpl extends Datastore {\n terminated = false;\n\n constructor(\n readonly authCredentials: CredentialsProvider<User>,\n readonly appCheckCredentials: CredentialsProvider<string>,\n readonly connection: Connection,\n readonly serializer: JsonProtoSerializer\n ) {\n super();\n }\n\n verifyInitialized(): void {\n debugAssert(!!this.connection, 'Datastore.start() not called');\n if (this.terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n /** Invokes the provided RPC with auth and AppCheck tokens. */\n invokeRPC<Req, Resp>(\n rpcName: string,\n path: string,\n request: Req\n ): Promise<Resp> {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeRPC<Req, Resp>(\n rpcName,\n path,\n request,\n authToken,\n appCheckToken\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */\n invokeStreamingRPC<Req, Resp>(\n rpcName: string,\n path: string,\n request: Req,\n expectedResponseCount?: number\n ): Promise<Resp[]> {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeStreamingRPC<Req, Resp>(\n rpcName,\n path,\n request,\n authToken,\n appCheckToken,\n expectedResponseCount\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n terminate(): void {\n this.terminated = true;\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nexport function newDatastore(\n authCredentials: CredentialsProvider<User>,\n appCheckCredentials: CredentialsProvider<string>,\n connection: Connection,\n serializer: JsonProtoSerializer\n): Datastore {\n return new DatastoreImpl(\n authCredentials,\n appCheckCredentials,\n connection,\n serializer\n );\n}\n\nexport async function invokeCommitRpc(\n datastore: Datastore,\n mutations: Mutation[]\n): Promise<void> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const path = getEncodedDatabaseId(datastoreImpl.serializer) + '/documents';\n const request = {\n writes: mutations.map(m => toMutation(datastoreImpl.serializer, m))\n };\n await datastoreImpl.invokeRPC('Commit', path, request);\n}\n\nexport async function invokeBatchGetDocumentsRpc(\n datastore: Datastore,\n keys: DocumentKey[]\n): Promise<Document[]> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const path = getEncodedDatabaseId(datastoreImpl.serializer) + '/documents';\n const request = {\n documents: keys.map(k => toName(datastoreImpl.serializer, k))\n };\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoBatchGetDocumentsRequest,\n ProtoBatchGetDocumentsResponse\n >('BatchGetDocuments', path, request, keys.length);\n\n const docs = new Map<string, Document>();\n response.forEach(proto => {\n const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto);\n docs.set(doc.key.toString(), doc);\n });\n const result: Document[] = [];\n keys.forEach(key => {\n const doc = docs.get(key.toString());\n hardAssert(!!doc, 'Missing entity in write response for ' + key);\n result.push(doc);\n });\n return result;\n}\n\nexport async function invokeRunQueryRpc(\n datastore: Datastore,\n query: Query\n): Promise<Document[]> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = toQueryTarget(datastoreImpl.serializer, queryToTarget(query));\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunQueryRequest,\n ProtoRunQueryResponse\n >('RunQuery', request.parent!, { structuredQuery: request.structuredQuery });\n return (\n response\n // Omit RunQueryResponses that only contain readTimes.\n .filter(proto => !!proto.document)\n .map(proto =>\n fromDocument(datastoreImpl.serializer, proto.document!, undefined)\n )\n );\n}\n\nexport async function invokeRunAggregationQueryRpc(\n datastore: Datastore,\n query: Query,\n aggregates: Aggregate[]\n): Promise<ApiClientObjectMap<Value>> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { request, aliasMap } = toRunAggregationQueryRequest(\n datastoreImpl.serializer,\n queryToAggregateTarget(query),\n aggregates\n );\n\n const parent = request.parent;\n if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) {\n delete request.parent;\n }\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunAggregationQueryRequest,\n ProtoRunAggregationQueryResponse\n >('RunAggregationQuery', parent!, request, /*expectedResponseCount=*/ 1);\n\n // Omit RunAggregationQueryResponse that only contain readTimes.\n const filteredResult = response.filter(proto => !!proto.result);\n\n hardAssert(\n filteredResult.length === 1,\n 'Aggregation fields are missing from result.'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result),\n 'aggregationQueryResponse.result'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result.aggregateFields),\n 'aggregationQueryResponse.result.aggregateFields'\n );\n\n // Remap the short-form aliases that were sent to the server\n // to the client-side aliases. Users will access the results\n // using the client-side alias.\n const unmappedAggregateFields = filteredResult[0].result?.aggregateFields;\n const remappedFields = Object.keys(unmappedAggregateFields).reduce<\n ApiClientObjectMap<Value>\n >((accumulator, key) => {\n debugAssert(\n !isNullOrUndefined(aliasMap[key]),\n `'${key}' not present in aliasMap result`\n );\n accumulator[aliasMap[key]] = unmappedAggregateFields[key]!;\n return accumulator;\n }, {});\n\n return remappedFields;\n}\n\nexport function newPersistentWriteStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WriteStreamListener\n): PersistentWriteStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentWriteStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n\nexport function newPersistentWatchStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WatchStreamListener\n): PersistentListenStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentListenStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { OnlineState } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { logError, logDebug } from '../util/log';\n\nconst LOG_TAG = 'OnlineStateTracker';\n\n// To deal with transient failures, we allow multiple stream attempts before\n// giving up and transitioning from OnlineState.Unknown to Offline.\n// TODO(mikelehen): This used to be set to 2 as a mitigation for b/66228394.\n// @jdimond thinks that bug is sufficiently fixed so that we can set this back\n// to 1. If that works okay, we could potentially remove this logic entirely.\nconst MAX_WATCH_STREAM_FAILURES = 1;\n\n// To deal with stream attempts that don't succeed or fail in a timely manner,\n// we have a timeout for OnlineState to reach Online or Offline.\n// If the timeout is reached, we transition to Offline rather than waiting\n// indefinitely.\nconst ONLINE_STATE_TIMEOUT_MS = 10 * 1000;\n\n/**\n * A component used by the RemoteStore to track the OnlineState (that is,\n * whether or not the client as a whole should be considered to be online or\n * offline), implementing the appropriate heuristics.\n *\n * In particular, when the client is trying to connect to the backend, we\n * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for\n * a connection to succeed. If we have too many failures or the timeout elapses,\n * then we set the OnlineState to Offline, and the client will behave as if\n * it is offline (get()s will return cached data, etc.).\n */\nexport class OnlineStateTracker {\n /** The current OnlineState. */\n private state = OnlineState.Unknown;\n\n /**\n * A count of consecutive failures to open the stream. If it reaches the\n * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to\n * Offline.\n */\n private watchStreamFailures = 0;\n\n /**\n * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we\n * transition from OnlineState.Unknown to OnlineState.Offline without waiting\n * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).\n */\n private onlineStateTimer: DelayedOperation<void> | null = null;\n\n /**\n * Whether the client should log a warning message if it fails to connect to\n * the backend (initially true, cleared after a successful stream, or if we've\n * logged the message already).\n */\n private shouldWarnClientIsOffline = true;\n\n constructor(\n private asyncQueue: AsyncQueue,\n private onlineStateHandler: (onlineState: OnlineState) => void\n ) {}\n\n /**\n * Called by RemoteStore when a watch stream is started (including on each\n * backoff attempt).\n *\n * If this is the first attempt, it sets the OnlineState to Unknown and starts\n * the onlineStateTimer.\n */\n handleWatchStreamStart(): void {\n if (this.watchStreamFailures === 0) {\n this.setAndBroadcast(OnlineState.Unknown);\n\n debugAssert(\n this.onlineStateTimer === null,\n `onlineStateTimer shouldn't be started yet`\n );\n this.onlineStateTimer = this.asyncQueue.enqueueAfterDelay(\n TimerId.OnlineStateTimeout,\n ONLINE_STATE_TIMEOUT_MS,\n () => {\n this.onlineStateTimer = null;\n debugAssert(\n this.state === OnlineState.Unknown,\n 'Timer should be canceled if we transitioned to a different state.'\n );\n this.logClientOfflineWarningIfNecessary(\n `Backend didn't respond within ${ONLINE_STATE_TIMEOUT_MS / 1000} ` +\n `seconds.`\n );\n this.setAndBroadcast(OnlineState.Offline);\n\n // NOTE: handleWatchStreamFailure() will continue to increment\n // watchStreamFailures even though we are already marked Offline,\n // but this is non-harmful.\n\n return Promise.resolve();\n }\n );\n }\n }\n\n /**\n * Updates our OnlineState as appropriate after the watch stream reports a\n * failure. The first failure moves us to the 'Unknown' state. We then may\n * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we\n * actually transition to the 'Offline' state.\n */\n handleWatchStreamFailure(error: FirestoreError): void {\n if (this.state === OnlineState.Online) {\n this.setAndBroadcast(OnlineState.Unknown);\n\n // To get to OnlineState.Online, set() must have been called which would\n // have reset our heuristics.\n debugAssert(\n this.watchStreamFailures === 0,\n 'watchStreamFailures must be 0'\n );\n debugAssert(\n this.onlineStateTimer === null,\n 'onlineStateTimer must be null'\n );\n } else {\n this.watchStreamFailures++;\n if (this.watchStreamFailures >= MAX_WATCH_STREAM_FAILURES) {\n this.clearOnlineStateTimer();\n\n this.logClientOfflineWarningIfNecessary(\n `Connection failed ${MAX_WATCH_STREAM_FAILURES} ` +\n `times. Most recent error: ${error.toString()}`\n );\n\n this.setAndBroadcast(OnlineState.Offline);\n }\n }\n }\n\n /**\n * Explicitly sets the OnlineState to the specified state.\n *\n * Note that this resets our timers / failure counters, etc. used by our\n * Offline heuristics, so must not be used in place of\n * handleWatchStreamStart() and handleWatchStreamFailure().\n */\n set(newState: OnlineState): void {\n this.clearOnlineStateTimer();\n this.watchStreamFailures = 0;\n\n if (newState === OnlineState.Online) {\n // We've connected to watch at least once. Don't warn the developer\n // about being offline going forward.\n this.shouldWarnClientIsOffline = false;\n }\n\n this.setAndBroadcast(newState);\n }\n\n private setAndBroadcast(newState: OnlineState): void {\n if (newState !== this.state) {\n this.state = newState;\n this.onlineStateHandler(newState);\n }\n }\n\n private logClientOfflineWarningIfNecessary(details: string): void {\n const message =\n `Could not reach Cloud Firestore backend. ${details}\\n` +\n `This typically indicates that your device does not have a healthy ` +\n `Internet connection at the moment. The client will operate in offline ` +\n `mode until it is able to successfully connect to the backend.`;\n if (this.shouldWarnClientIsOffline) {\n logError(message);\n this.shouldWarnClientIsOffline = false;\n } else {\n logDebug(LOG_TAG, message);\n }\n }\n\n private clearOnlineStateTimer(): void {\n if (this.onlineStateTimer !== null) {\n this.onlineStateTimer.cancel();\n this.onlineStateTimer = null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { OnlineState, TargetId } from '../core/types';\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreGetLastRemoteSnapshotVersion,\n localStoreGetNextMutationBatch\n} from '../local/local_store_impl';\nimport { isIndexedDbTransactionError } from '../local/simple_db';\nimport { TargetData } from '../local/target_data';\nimport { MutationResult } from '../model/mutation';\nimport { MutationBatch, MutationBatchResult } from '../model/mutation_batch';\nimport { debugAssert, debugCast } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { ByteString } from '../util/byte_string';\nimport { FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { ConnectivityMonitor, NetworkStatus } from './connectivity_monitor';\nimport {\n Datastore,\n newPersistentWatchStream,\n newPersistentWriteStream\n} from './datastore';\nimport { OnlineStateTracker } from './online_state_tracker';\nimport {\n PersistentListenStream,\n PersistentWriteStream\n} from './persistent_stream';\nimport { RemoteSyncer } from './remote_syncer';\nimport { isPermanentWriteError } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n WatchChange,\n WatchChangeAggregator,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst LOG_TAG = 'RemoteStore';\n\n// TODO(b/35853402): Negotiate this with the stream.\nconst MAX_PENDING_WRITES = 10;\n\n/** Reasons for why the RemoteStore may be offline. */\nconst enum OfflineCause {\n /** The user has explicitly disabled the network (via `disableNetwork()`). */\n UserDisabled,\n /** An IndexedDb failure occurred while persisting a stream update. */\n IndexedDbFailed,\n /** The tab is not the primary tab (only relevant with multi-tab). */\n IsSecondary,\n /** We are restarting the streams due to an Auth credential change. */\n CredentialChange,\n /** The connectivity state of the environment has changed. */\n ConnectivityChange,\n /** The RemoteStore has been shut down. */\n Shutdown\n}\n\n/**\n * RemoteStore - An interface to remotely stored data, basically providing a\n * wrapper around the Datastore that is more reliable for the rest of the\n * system.\n *\n * RemoteStore is responsible for maintaining the connection to the server.\n * - maintaining a list of active listens.\n * - reconnecting when the connection is dropped.\n * - resuming all the active listens on reconnect.\n *\n * RemoteStore handles all incoming events from the Datastore.\n * - listening to the watch stream and repackaging the events as RemoteEvents\n * - notifying SyncEngine of any changes to the active listens.\n *\n * RemoteStore takes writes from other components and handles them reliably.\n * - pulling pending mutations from LocalStore and sending them to Datastore.\n * - retrying mutations that failed because of network problems.\n * - acking mutations to the SyncEngine once they are accepted or rejected.\n */\nexport interface RemoteStore {\n /**\n * SyncEngine to notify of watch and write events. This must be set\n * immediately after construction.\n */\n remoteSyncer: RemoteSyncer;\n}\n\nclass RemoteStoreImpl implements RemoteStore {\n remoteSyncer: RemoteSyncer = {};\n\n /**\n * A list of up to MAX_PENDING_WRITES writes that we have fetched from the\n * LocalStore via fillWritePipeline() and have or will send to the write\n * stream.\n *\n * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or\n * restart the write stream. When the stream is established the writes in the\n * pipeline will be sent in order.\n *\n * Writes remain in writePipeline until they are acknowledged by the backend\n * and thus will automatically be re-sent if the stream is interrupted /\n * restarted before they're acknowledged.\n *\n * Write responses from the backend are linked to their originating request\n * purely based on order, and so we can just shift() writes from the front of\n * the writePipeline as we receive responses.\n */\n writePipeline: MutationBatch[] = [];\n\n /**\n * A mapping of watched targets that the client cares about tracking and the\n * user has explicitly called a 'listen' for this target.\n *\n * These targets may or may not have been sent to or acknowledged by the\n * server. On re-establishing the listen stream, these targets should be sent\n * to the server. The targets removed with unlistens are removed eagerly\n * without waiting for confirmation from the listen stream.\n */\n listenTargets = new Map<TargetId, TargetData>();\n\n connectivityMonitor: ConnectivityMonitor;\n watchStream?: PersistentListenStream;\n writeStream?: PersistentWriteStream;\n watchChangeAggregator?: WatchChangeAggregator;\n\n /**\n * A set of reasons for why the RemoteStore may be offline. If empty, the\n * RemoteStore may start its network connections.\n */\n offlineCauses = new Set<OfflineCause>();\n\n /**\n * Event handlers that get called when the network is disabled or enabled.\n *\n * PORTING NOTE: These functions are used on the Web client to create the\n * underlying streams (to support tree-shakeable streams). On Android and iOS,\n * the streams are created during construction of RemoteStore.\n */\n onNetworkStatusChange: Array<(enabled: boolean) => Promise<void>> = [];\n\n onlineStateTracker: OnlineStateTracker;\n\n constructor(\n /**\n * The local store, used to fill the write pipeline with outbound mutations.\n */\n readonly localStore: LocalStore,\n /** The client-side proxy for interacting with the backend. */\n readonly datastore: Datastore,\n readonly asyncQueue: AsyncQueue,\n onlineStateHandler: (onlineState: OnlineState) => void,\n connectivityMonitor: ConnectivityMonitor\n ) {\n this.connectivityMonitor = connectivityMonitor;\n this.connectivityMonitor.addCallback((_: NetworkStatus) => {\n asyncQueue.enqueueAndForget(async () => {\n // Porting Note: Unlike iOS, `restartNetwork()` is called even when the\n // network becomes unreachable as we don't have any other way to tear\n // down our streams.\n if (canUseNetwork(this)) {\n logDebug(\n LOG_TAG,\n 'Restarting streams for network reachability change.'\n );\n await restartNetwork(this);\n }\n });\n });\n\n this.onlineStateTracker = new OnlineStateTracker(\n asyncQueue,\n onlineStateHandler\n );\n }\n}\n\nexport function newRemoteStore(\n localStore: LocalStore,\n datastore: Datastore,\n asyncQueue: AsyncQueue,\n onlineStateHandler: (onlineState: OnlineState) => void,\n connectivityMonitor: ConnectivityMonitor\n): RemoteStore {\n return new RemoteStoreImpl(\n localStore,\n datastore,\n asyncQueue,\n onlineStateHandler,\n connectivityMonitor\n );\n}\n\n/** Re-enables the network. Idempotent. */\nexport function remoteStoreEnableNetwork(\n remoteStore: RemoteStore\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.offlineCauses.delete(OfflineCause.UserDisabled);\n return enableNetworkInternal(remoteStoreImpl);\n}\n\nasync function enableNetworkInternal(\n remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n if (canUseNetwork(remoteStoreImpl)) {\n for (const networkStatusHandler of remoteStoreImpl.onNetworkStatusChange) {\n await networkStatusHandler(/* enabled= */ true);\n }\n }\n}\n\n/**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */\nexport async function remoteStoreDisableNetwork(\n remoteStore: RemoteStore\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.offlineCauses.add(OfflineCause.UserDisabled);\n await disableNetworkInternal(remoteStoreImpl);\n\n // Set the OnlineState to Offline so get()s return from cache, etc.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Offline);\n}\n\nasync function disableNetworkInternal(\n remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n for (const networkStatusHandler of remoteStoreImpl.onNetworkStatusChange) {\n await networkStatusHandler(/* enabled= */ false);\n }\n}\n\nexport async function remoteStoreShutdown(\n remoteStore: RemoteStore\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n logDebug(LOG_TAG, 'RemoteStore shutting down.');\n remoteStoreImpl.offlineCauses.add(OfflineCause.Shutdown);\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.connectivityMonitor.shutdown();\n\n // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\n // triggering spurious listener events with cached data, etc.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n}\n\n/**\n * Starts new listen for the given target. Uses resume token if provided. It\n * is a no-op if the target of given `TargetData` is already being listened to.\n */\nexport function remoteStoreListen(\n remoteStore: RemoteStore,\n targetData: TargetData\n): void {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n\n if (remoteStoreImpl.listenTargets.has(targetData.targetId)) {\n return;\n }\n\n // Mark this as something the client is currently listening for.\n remoteStoreImpl.listenTargets.set(targetData.targetId, targetData);\n\n if (shouldStartWatchStream(remoteStoreImpl)) {\n // The listen will be sent in onWatchStreamOpen\n startWatchStream(remoteStoreImpl);\n } else if (ensureWatchStream(remoteStoreImpl).isOpen()) {\n sendWatchRequest(remoteStoreImpl, targetData);\n }\n}\n\n/**\n * Removes the listen from server. It is a no-op if the given target id is\n * not being listened to.\n */\nexport function remoteStoreUnlisten(\n remoteStore: RemoteStore,\n targetId: TargetId\n): void {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n const watchStream = ensureWatchStream(remoteStoreImpl);\n\n debugAssert(\n remoteStoreImpl.listenTargets.has(targetId),\n `unlisten called on target no currently watched: ${targetId}`\n );\n\n remoteStoreImpl.listenTargets.delete(targetId);\n if (watchStream.isOpen()) {\n sendUnwatchRequest(remoteStoreImpl, targetId);\n }\n\n if (remoteStoreImpl.listenTargets.size === 0) {\n if (watchStream.isOpen()) {\n watchStream.markIdle();\n } else if (canUseNetwork(remoteStoreImpl)) {\n // Revert to OnlineState.Unknown if the watch stream is not open and we\n // have no listeners, since without any listens to send we cannot\n // confirm if the stream is healthy and upgrade to OnlineState.Online.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n }\n}\n\n/**\n * We need to increment the the expected number of pending responses we're due\n * from watch so we wait for the ack to process any messages from this target.\n */\nfunction sendWatchRequest(\n remoteStoreImpl: RemoteStoreImpl,\n targetData: TargetData\n): void {\n remoteStoreImpl.watchChangeAggregator!.recordPendingTargetRequest(\n targetData.targetId\n );\n\n if (\n targetData.resumeToken.approximateByteSize() > 0 ||\n targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0\n ) {\n const expectedCount = remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget!(\n targetData.targetId\n ).size;\n targetData = targetData.withExpectedCount(expectedCount);\n }\n\n ensureWatchStream(remoteStoreImpl).watch(targetData);\n}\n\n/**\n * We need to increment the expected number of pending responses we're due\n * from watch so we wait for the removal on the server before we process any\n * messages from this target.\n */\nfunction sendUnwatchRequest(\n remoteStoreImpl: RemoteStoreImpl,\n targetId: TargetId\n): void {\n remoteStoreImpl.watchChangeAggregator!.recordPendingTargetRequest(targetId);\n ensureWatchStream(remoteStoreImpl).unwatch(targetId);\n}\n\nfunction startWatchStream(remoteStoreImpl: RemoteStoreImpl): void {\n debugAssert(\n shouldStartWatchStream(remoteStoreImpl),\n 'startWatchStream() called when shouldStartWatchStream() is false.'\n );\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget,\n 'getRemoteKeysForTarget() not set'\n );\n\n remoteStoreImpl.watchChangeAggregator = new WatchChangeAggregator({\n getRemoteKeysForTarget: targetId =>\n remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget!(targetId),\n getTargetDataForTarget: targetId =>\n remoteStoreImpl.listenTargets.get(targetId) || null,\n getDatabaseId: () => remoteStoreImpl.datastore.serializer.databaseId\n });\n ensureWatchStream(remoteStoreImpl).start();\n remoteStoreImpl.onlineStateTracker.handleWatchStreamStart();\n}\n\n/**\n * Returns whether the watch stream should be started because it's necessary\n * and has not yet been started.\n */\nfunction shouldStartWatchStream(remoteStoreImpl: RemoteStoreImpl): boolean {\n return (\n canUseNetwork(remoteStoreImpl) &&\n !ensureWatchStream(remoteStoreImpl).isStarted() &&\n remoteStoreImpl.listenTargets.size > 0\n );\n}\n\nexport function canUseNetwork(remoteStore: RemoteStore): boolean {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n return remoteStoreImpl.offlineCauses.size === 0;\n}\n\nfunction cleanUpWatchStreamState(remoteStoreImpl: RemoteStoreImpl): void {\n remoteStoreImpl.watchChangeAggregator = undefined;\n}\n\nasync function onWatchStreamOpen(\n remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n remoteStoreImpl.listenTargets.forEach((targetData, targetId) => {\n sendWatchRequest(remoteStoreImpl, targetData);\n });\n}\n\nasync function onWatchStreamClose(\n remoteStoreImpl: RemoteStoreImpl,\n error?: FirestoreError\n): Promise<void> {\n if (error === undefined) {\n // Graceful stop (due to stop() or idle timeout). Make sure that's\n // desirable.\n debugAssert(\n !shouldStartWatchStream(remoteStoreImpl),\n 'Watch stream was stopped gracefully while still needed.'\n );\n }\n\n cleanUpWatchStreamState(remoteStoreImpl);\n\n // If we still need the watch stream, retry the connection.\n if (shouldStartWatchStream(remoteStoreImpl)) {\n remoteStoreImpl.onlineStateTracker.handleWatchStreamFailure(error!);\n\n startWatchStream(remoteStoreImpl);\n } else {\n // No need to restart watch stream because there are no active targets.\n // The online state is set to unknown because there is no active attempt\n // at establishing a connection\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n}\n\nasync function onWatchStreamChange(\n remoteStoreImpl: RemoteStoreImpl,\n watchChange: WatchChange,\n snapshotVersion: SnapshotVersion\n): Promise<void> {\n // Mark the client as online since we got a message from the server\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Online);\n\n if (\n watchChange instanceof WatchTargetChange &&\n watchChange.state === WatchTargetChangeState.Removed &&\n watchChange.cause\n ) {\n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n try {\n await handleTargetError(remoteStoreImpl, watchChange);\n } catch (e) {\n logDebug(\n LOG_TAG,\n 'Failed to remove targets %s: %s ',\n watchChange.targetIds.join(','),\n e\n );\n await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n }\n return;\n }\n\n if (watchChange instanceof DocumentWatchChange) {\n remoteStoreImpl.watchChangeAggregator!.handleDocumentChange(watchChange);\n } else if (watchChange instanceof ExistenceFilterChange) {\n remoteStoreImpl.watchChangeAggregator!.handleExistenceFilter(watchChange);\n } else {\n debugAssert(\n watchChange instanceof WatchTargetChange,\n 'Expected watchChange to be an instance of WatchTargetChange'\n );\n remoteStoreImpl.watchChangeAggregator!.handleTargetChange(watchChange);\n }\n\n if (!snapshotVersion.isEqual(SnapshotVersion.min())) {\n try {\n const lastRemoteSnapshotVersion =\n await localStoreGetLastRemoteSnapshotVersion(\n remoteStoreImpl.localStore\n );\n if (snapshotVersion.compareTo(lastRemoteSnapshotVersion) >= 0) {\n // We have received a target change with a global snapshot if the snapshot\n // version is not equal to SnapshotVersion.min().\n await raiseWatchSnapshot(remoteStoreImpl, snapshotVersion);\n }\n } catch (e) {\n logDebug(LOG_TAG, 'Failed to raise snapshot:', e);\n await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n }\n }\n}\n\n/**\n * Recovery logic for IndexedDB errors that takes the network offline until\n * `op` succeeds. Retries are scheduled with backoff using\n * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is\n * validated via a generic operation.\n *\n * The returned Promise is resolved once the network is disabled and before\n * any retry attempt.\n */\nasync function disableNetworkUntilRecovery(\n remoteStoreImpl: RemoteStoreImpl,\n e: FirestoreError,\n op?: () => Promise<unknown>\n): Promise<void> {\n if (isIndexedDbTransactionError(e)) {\n debugAssert(\n !remoteStoreImpl.offlineCauses.has(OfflineCause.IndexedDbFailed),\n 'Unexpected network event when IndexedDB was marked failed.'\n );\n remoteStoreImpl.offlineCauses.add(OfflineCause.IndexedDbFailed);\n\n // Disable network and raise offline snapshots\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Offline);\n\n if (!op) {\n // Use a simple read operation to determine if IndexedDB recovered.\n // Ideally, we would expose a health check directly on SimpleDb, but\n // RemoteStore only has access to persistence through LocalStore.\n op = () =>\n localStoreGetLastRemoteSnapshotVersion(remoteStoreImpl.localStore);\n }\n\n // Probe IndexedDB periodically and re-enable network\n remoteStoreImpl.asyncQueue.enqueueRetryable(async () => {\n logDebug(LOG_TAG, 'Retrying IndexedDB access');\n await op!();\n remoteStoreImpl.offlineCauses.delete(OfflineCause.IndexedDbFailed);\n await enableNetworkInternal(remoteStoreImpl);\n });\n } else {\n throw e;\n }\n}\n\n/**\n * Executes `op`. If `op` fails, takes the network offline until `op`\n * succeeds. Returns after the first attempt.\n */\nfunction executeWithRecovery(\n remoteStoreImpl: RemoteStoreImpl,\n op: () => Promise<void>\n): Promise<void> {\n return op().catch(e => disableNetworkUntilRecovery(remoteStoreImpl, e, op));\n}\n\n/**\n * Takes a batch of changes from the Datastore, repackages them as a\n * RemoteEvent, and passes that on to the listener, which is typically the\n * SyncEngine.\n */\nfunction raiseWatchSnapshot(\n remoteStoreImpl: RemoteStoreImpl,\n snapshotVersion: SnapshotVersion\n): Promise<void> {\n debugAssert(\n !snapshotVersion.isEqual(SnapshotVersion.min()),\n \"Can't raise event for unknown SnapshotVersion\"\n );\n const remoteEvent =\n remoteStoreImpl.watchChangeAggregator!.createRemoteEvent(snapshotVersion);\n\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n remoteEvent.targetChanges.forEach((change, targetId) => {\n if (change.resumeToken.approximateByteSize() > 0) {\n const targetData = remoteStoreImpl.listenTargets.get(targetId);\n // A watched target might have been removed already.\n if (targetData) {\n remoteStoreImpl.listenTargets.set(\n targetId,\n targetData.withResumeToken(change.resumeToken, snapshotVersion)\n );\n }\n }\n });\n\n // Re-establish listens for the targets that have been invalidated by\n // existence filter mismatches.\n remoteEvent.targetMismatches.forEach((targetId, targetPurpose) => {\n const targetData = remoteStoreImpl.listenTargets.get(targetId);\n if (!targetData) {\n // A watched target might have been removed already.\n return;\n }\n\n // Clear the resume token for the target, since we're in a known mismatch\n // state.\n remoteStoreImpl.listenTargets.set(\n targetId,\n targetData.withResumeToken(\n ByteString.EMPTY_BYTE_STRING,\n targetData.snapshotVersion\n )\n );\n\n // Cause a hard reset by unwatching and rewatching immediately, but\n // deliberately don't send a resume token so that we get a full update.\n sendUnwatchRequest(remoteStoreImpl, targetId);\n\n // Mark the target we send as being on behalf of an existence filter\n // mismatch, but don't actually retain that in listenTargets. This ensures\n // that we flag the first re-listen this way without impacting future\n // listens of this target (that might happen e.g. on reconnect).\n const requestTargetData = new TargetData(\n targetData.target,\n targetId,\n targetPurpose,\n targetData.sequenceNumber\n );\n sendWatchRequest(remoteStoreImpl, requestTargetData);\n });\n\n // Finally raise remote event\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.applyRemoteEvent,\n 'applyRemoteEvent() not set'\n );\n return remoteStoreImpl.remoteSyncer.applyRemoteEvent(remoteEvent);\n}\n\n/** Handles an error on a target */\nasync function handleTargetError(\n remoteStoreImpl: RemoteStoreImpl,\n watchChange: WatchTargetChange\n): Promise<void> {\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.rejectListen,\n 'rejectListen() not set'\n );\n debugAssert(!!watchChange.cause, 'Handling target error without a cause');\n const error = watchChange.cause!;\n for (const targetId of watchChange.targetIds) {\n // A watched target might have been removed already.\n if (remoteStoreImpl.listenTargets.has(targetId)) {\n await remoteStoreImpl.remoteSyncer.rejectListen(targetId, error);\n remoteStoreImpl.listenTargets.delete(targetId);\n remoteStoreImpl.watchChangeAggregator!.removeTarget(targetId);\n }\n }\n}\n\n/**\n * Attempts to fill our write pipeline with writes from the LocalStore.\n *\n * Called internally to bootstrap or refill the write pipeline and by\n * SyncEngine whenever there are new mutations to process.\n *\n * Starts the write stream if necessary.\n */\nexport async function fillWritePipeline(\n remoteStore: RemoteStore\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n const writeStream = ensureWriteStream(remoteStoreImpl);\n\n let lastBatchIdRetrieved =\n remoteStoreImpl.writePipeline.length > 0\n ? remoteStoreImpl.writePipeline[remoteStoreImpl.writePipeline.length - 1]\n .batchId\n : BATCHID_UNKNOWN;\n\n while (canAddToWritePipeline(remoteStoreImpl)) {\n try {\n const batch = await localStoreGetNextMutationBatch(\n remoteStoreImpl.localStore,\n lastBatchIdRetrieved\n );\n\n if (batch === null) {\n if (remoteStoreImpl.writePipeline.length === 0) {\n writeStream.markIdle();\n }\n break;\n } else {\n lastBatchIdRetrieved = batch.batchId;\n addToWritePipeline(remoteStoreImpl, batch);\n }\n } catch (e) {\n await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n }\n }\n\n if (shouldStartWriteStream(remoteStoreImpl)) {\n startWriteStream(remoteStoreImpl);\n }\n}\n\n/**\n * Returns true if we can add to the write pipeline (i.e. the network is\n * enabled and the write pipeline is not full).\n */\nfunction canAddToWritePipeline(remoteStoreImpl: RemoteStoreImpl): boolean {\n return (\n canUseNetwork(remoteStoreImpl) &&\n remoteStoreImpl.writePipeline.length < MAX_PENDING_WRITES\n );\n}\n\n// For testing\nexport function outstandingWrites(remoteStore: RemoteStore): number {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n return remoteStoreImpl.writePipeline.length;\n}\n\n/**\n * Queues additional writes to be sent to the write stream, sending them\n * immediately if the write stream is established.\n */\nfunction addToWritePipeline(\n remoteStoreImpl: RemoteStoreImpl,\n batch: MutationBatch\n): void {\n debugAssert(\n canAddToWritePipeline(remoteStoreImpl),\n 'addToWritePipeline called when pipeline is full'\n );\n remoteStoreImpl.writePipeline.push(batch);\n\n const writeStream = ensureWriteStream(remoteStoreImpl);\n if (writeStream.isOpen() && writeStream.handshakeComplete) {\n writeStream.writeMutations(batch.mutations);\n }\n}\n\nfunction shouldStartWriteStream(remoteStoreImpl: RemoteStoreImpl): boolean {\n return (\n canUseNetwork(remoteStoreImpl) &&\n !ensureWriteStream(remoteStoreImpl).isStarted() &&\n remoteStoreImpl.writePipeline.length > 0\n );\n}\n\nfunction startWriteStream(remoteStoreImpl: RemoteStoreImpl): void {\n debugAssert(\n shouldStartWriteStream(remoteStoreImpl),\n 'startWriteStream() called when shouldStartWriteStream() is false.'\n );\n ensureWriteStream(remoteStoreImpl).start();\n}\n\nasync function onWriteStreamOpen(\n remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n ensureWriteStream(remoteStoreImpl).writeHandshake();\n}\n\nasync function onWriteHandshakeComplete(\n remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n const writeStream = ensureWriteStream(remoteStoreImpl);\n // Send the write pipeline now that the stream is established.\n for (const batch of remoteStoreImpl.writePipeline) {\n writeStream.writeMutations(batch.mutations);\n }\n}\n\nasync function onMutationResult(\n remoteStoreImpl: RemoteStoreImpl,\n commitVersion: SnapshotVersion,\n results: MutationResult[]\n): Promise<void> {\n // This is a response to a write containing mutations and should be\n // correlated to the first write in our write pipeline.\n debugAssert(\n remoteStoreImpl.writePipeline.length > 0,\n 'Got result for empty write pipeline'\n );\n const batch = remoteStoreImpl.writePipeline.shift()!;\n const success = MutationBatchResult.from(batch, commitVersion, results);\n\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.applySuccessfulWrite,\n 'applySuccessfulWrite() not set'\n );\n await executeWithRecovery(remoteStoreImpl, () =>\n remoteStoreImpl.remoteSyncer.applySuccessfulWrite!(success)\n );\n\n // It's possible that with the completion of this mutation another\n // slot has freed up.\n await fillWritePipeline(remoteStoreImpl);\n}\n\nasync function onWriteStreamClose(\n remoteStoreImpl: RemoteStoreImpl,\n error?: FirestoreError\n): Promise<void> {\n if (error === undefined) {\n // Graceful stop (due to stop() or idle timeout). Make sure that's\n // desirable.\n debugAssert(\n !shouldStartWriteStream(remoteStoreImpl),\n 'Write stream was stopped gracefully while still needed.'\n );\n }\n\n // If the write stream closed after the write handshake completes, a write\n // operation failed and we fail the pending operation.\n if (error && ensureWriteStream(remoteStoreImpl).handshakeComplete) {\n // This error affects the actual write.\n await handleWriteError(remoteStoreImpl, error!);\n }\n\n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n if (shouldStartWriteStream(remoteStoreImpl)) {\n startWriteStream(remoteStoreImpl);\n }\n}\n\nasync function handleWriteError(\n remoteStoreImpl: RemoteStoreImpl,\n error: FirestoreError\n): Promise<void> {\n // Only handle permanent errors here. If it's transient, just let the retry\n // logic kick in.\n if (isPermanentWriteError(error.code)) {\n // This was a permanent error, the request itself was the problem\n // so it's not going to succeed if we resend it.\n const batch = remoteStoreImpl.writePipeline.shift()!;\n\n // In this case it's also unlikely that the server itself is melting\n // down -- this was just a bad request so inhibit backoff on the next\n // restart.\n ensureWriteStream(remoteStoreImpl).inhibitBackoff();\n\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.rejectFailedWrite,\n 'rejectFailedWrite() not set'\n );\n await executeWithRecovery(remoteStoreImpl, () =>\n remoteStoreImpl.remoteSyncer.rejectFailedWrite!(batch.batchId, error)\n );\n\n // It's possible that with the completion of this mutation\n // another slot has freed up.\n await fillWritePipeline(remoteStoreImpl);\n } else {\n // Transient error, just let the retry logic kick in.\n }\n}\n\nasync function restartNetwork(remoteStore: RemoteStore): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.offlineCauses.add(OfflineCause.ConnectivityChange);\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n remoteStoreImpl.offlineCauses.delete(OfflineCause.ConnectivityChange);\n await enableNetworkInternal(remoteStoreImpl);\n}\n\nexport async function remoteStoreHandleCredentialChange(\n remoteStore: RemoteStore,\n user: User\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.asyncQueue.verifyOperationInProgress();\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.handleCredentialChange,\n 'handleCredentialChange() not set'\n );\n\n logDebug(LOG_TAG, 'RemoteStore received new credentials');\n const usesNetwork = canUseNetwork(remoteStoreImpl);\n\n // Tear down and re-create our network streams. This will ensure we get a\n // fresh auth token for the new user and re-fill the write pipeline with\n // new mutations from the LocalStore (since mutations are per-user).\n remoteStoreImpl.offlineCauses.add(OfflineCause.CredentialChange);\n await disableNetworkInternal(remoteStoreImpl);\n if (usesNetwork) {\n // Don't set the network status to Unknown if we are offline.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n await remoteStoreImpl.remoteSyncer.handleCredentialChange(user);\n remoteStoreImpl.offlineCauses.delete(OfflineCause.CredentialChange);\n await enableNetworkInternal(remoteStoreImpl);\n}\n\n/**\n * Toggles the network state when the client gains or loses its primary lease.\n */\nexport async function remoteStoreApplyPrimaryState(\n remoteStore: RemoteStore,\n isPrimary: boolean\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n if (isPrimary) {\n remoteStoreImpl.offlineCauses.delete(OfflineCause.IsSecondary);\n await enableNetworkInternal(remoteStoreImpl);\n } else if (!isPrimary) {\n remoteStoreImpl.offlineCauses.add(OfflineCause.IsSecondary);\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n}\n\n/**\n * If not yet initialized, registers the WatchStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */\nfunction ensureWatchStream(\n remoteStoreImpl: RemoteStoreImpl\n): PersistentListenStream {\n if (!remoteStoreImpl.watchStream) {\n // Create stream (but note that it is not started yet).\n remoteStoreImpl.watchStream = newPersistentWatchStream(\n remoteStoreImpl.datastore,\n remoteStoreImpl.asyncQueue,\n {\n onOpen: onWatchStreamOpen.bind(null, remoteStoreImpl),\n onClose: onWatchStreamClose.bind(null, remoteStoreImpl),\n onWatchChange: onWatchStreamChange.bind(null, remoteStoreImpl)\n }\n );\n\n remoteStoreImpl.onNetworkStatusChange.push(async enabled => {\n if (enabled) {\n remoteStoreImpl.watchStream!.inhibitBackoff();\n if (shouldStartWatchStream(remoteStoreImpl)) {\n startWatchStream(remoteStoreImpl);\n } else {\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n } else {\n await remoteStoreImpl.watchStream!.stop();\n cleanUpWatchStreamState(remoteStoreImpl);\n }\n });\n }\n\n return remoteStoreImpl.watchStream;\n}\n\n/**\n * If not yet initialized, registers the WriteStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */\nfunction ensureWriteStream(\n remoteStoreImpl: RemoteStoreImpl\n): PersistentWriteStream {\n if (!remoteStoreImpl.writeStream) {\n debugAssert(\n remoteStoreImpl.writePipeline.length === 0,\n 'Should not issue writes before WriteStream is enabled'\n );\n\n // Create stream (but note that it is not started yet).\n remoteStoreImpl.writeStream = newPersistentWriteStream(\n remoteStoreImpl.datastore,\n remoteStoreImpl.asyncQueue,\n {\n onOpen: onWriteStreamOpen.bind(null, remoteStoreImpl),\n onClose: onWriteStreamClose.bind(null, remoteStoreImpl),\n onHandshakeComplete: onWriteHandshakeComplete.bind(\n null,\n remoteStoreImpl\n ),\n onMutationResult: onMutationResult.bind(null, remoteStoreImpl)\n }\n );\n\n remoteStoreImpl.onNetworkStatusChange.push(async enabled => {\n if (enabled) {\n remoteStoreImpl.writeStream!.inhibitBackoff();\n\n // This will start the write stream if necessary.\n await fillWritePipeline(remoteStoreImpl);\n } else {\n await remoteStoreImpl.writeStream!.stop();\n\n if (remoteStoreImpl.writePipeline.length > 0) {\n logDebug(\n LOG_TAG,\n `Stopping write stream with ${remoteStoreImpl.writePipeline.length} pending writes`\n );\n remoteStoreImpl.writePipeline = [];\n }\n }\n });\n }\n\n return remoteStoreImpl.writeStream;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\n\nimport { Code, FirestoreError } from './error';\nimport { logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TimerHandle = any;\n\n/**\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\n * AsyncQueue. These IDs can then be used from tests to check for the presence\n * of operations or to run them early.\n *\n * The string values are used when encoding these timer IDs in JSON spec tests.\n */\nexport const enum TimerId {\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\n All = 'all',\n\n /**\n * The following 5 timers are used in persistent_stream.ts for the listen and\n * write streams. The \"Idle\" timer is used to close the stream due to\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\n * the appropriate backoff delay has elapsed. The health check is used to mark\n * a stream healthy if it has not received an error during its initial setup.\n */\n ListenStreamIdle = 'listen_stream_idle',\n ListenStreamConnectionBackoff = 'listen_stream_connection_backoff',\n WriteStreamIdle = 'write_stream_idle',\n WriteStreamConnectionBackoff = 'write_stream_connection_backoff',\n HealthCheckTimeout = 'health_check_timeout',\n\n /**\n * A timer used in online_state_tracker.ts to transition from\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\n * indefinitely for success or failure.\n */\n OnlineStateTimeout = 'online_state_timeout',\n\n /**\n * A timer used to update the client metadata in IndexedDb, which is used\n * to determine the primary leaseholder.\n */\n ClientMetadataRefresh = 'client_metadata_refresh',\n\n /** A timer used to periodically attempt LRU Garbage collection */\n LruGarbageCollection = 'lru_garbage_collection',\n\n /**\n * A timer used to retry transactions. Since there can be multiple concurrent\n * transactions, multiple of these may be in the queue at a given time.\n */\n TransactionRetry = 'transaction_retry',\n\n /**\n * A timer used to retry operations scheduled via retryable AsyncQueue\n * operations.\n */\n AsyncQueueRetry = 'async_queue_retry',\n\n /**\n * A timer used to periodically attempt index backfill.\n */\n IndexBackfill = 'index_backfill'\n}\n\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nexport class DelayedOperation<T extends unknown> implements PromiseLike<T> {\n // handle for use with clearTimeout(), or null if the operation has been\n // executed or canceled already.\n private timerHandle: TimerHandle | null;\n\n private readonly deferred = new Deferred<T>();\n\n private constructor(\n private readonly asyncQueue: AsyncQueue,\n readonly timerId: TimerId,\n readonly targetTimeMs: number,\n private readonly op: () => Promise<T>,\n private readonly removalCallback: (op: DelayedOperation<T>) => void\n ) {\n // It's normal for the deferred promise to be canceled (due to cancellation)\n // and so we attach a dummy catch callback to avoid\n // 'UnhandledPromiseRejectionWarning' log spam.\n this.deferred.promise.catch(err => {});\n }\n\n get promise(): Promise<T> {\n return this.deferred.promise;\n }\n\n /**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue - The queue to schedule the operation on.\n * @param id - A Timer ID identifying the type of operation this is.\n * @param delayMs - The delay (ms) before the operation should be scheduled.\n * @param op - The operation to run.\n * @param removalCallback - A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */\n static createAndSchedule<R extends unknown>(\n asyncQueue: AsyncQueue,\n timerId: TimerId,\n delayMs: number,\n op: () => Promise<R>,\n removalCallback: (op: DelayedOperation<R>) => void\n ): DelayedOperation<R> {\n const targetTime = Date.now() + delayMs;\n const delayedOp = new DelayedOperation(\n asyncQueue,\n timerId,\n targetTime,\n op,\n removalCallback\n );\n delayedOp.start(delayMs);\n return delayedOp;\n }\n\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */\n private start(delayMs: number): void {\n this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs);\n }\n\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */\n skipDelay(): void {\n return this.handleDelayElapsed();\n }\n\n /**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */\n cancel(reason?: string): void {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n this.deferred.reject(\n new FirestoreError(\n Code.CANCELLED,\n 'Operation cancelled' + (reason ? ': ' + reason : '')\n )\n );\n }\n }\n\n then = this.deferred.promise.then.bind(this.deferred.promise);\n\n private handleDelayElapsed(): void {\n this.asyncQueue.enqueueAndForget(() => {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n return this.op().then(result => {\n return this.deferred.resolve(result);\n });\n } else {\n return Promise.resolve();\n }\n });\n }\n\n private clearTimeout(): void {\n if (this.timerHandle !== null) {\n this.removalCallback(this);\n clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n }\n}\n\nexport interface AsyncQueue {\n // Is this AsyncQueue being shut down? If true, this instance will not enqueue\n // any new operations, Promises from enqueue requests will not resolve.\n readonly isShuttingDown: boolean;\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget<T extends unknown>(op: () => Promise<T>): void;\n\n /**\n * Regardless if the queue has initialized shutdown, adds a new operation to the\n * queue without waiting for it to complete (i.e. we ignore the Promise result).\n */\n enqueueAndForgetEvenWhileRestricted<T extends unknown>(\n op: () => Promise<T>\n ): void;\n\n /**\n * Initialize the shutdown of this queue. Once this method is called, the\n * only possible way to request running an operation is through\n * `enqueueEvenWhileRestricted()`.\n *\n * @param purgeExistingTasks Whether already enqueued tasked should be\n * rejected (unless enqueued wih `enqueueEvenWhileRestricted()`). Defaults\n * to false.\n */\n enterRestrictedMode(purgeExistingTasks?: boolean): void;\n\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n */\n enqueue<T extends unknown>(op: () => Promise<T>): Promise<T>;\n\n /**\n * Enqueue a retryable operation.\n *\n * A retryable operation is rescheduled with backoff if it fails with a\n * IndexedDbTransactionError (the error type used by SimpleDb). All\n * retryable operations are executed in order and only run if all prior\n * operations were retried successfully.\n */\n enqueueRetryable(op: () => Promise<void>): void;\n\n /**\n * Schedules an operation to be queued on the AsyncQueue once the specified\n * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel\n * or fast-forward the operation prior to its running.\n */\n enqueueAfterDelay<T extends unknown>(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise<T>\n ): DelayedOperation<T>;\n\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n verifyOperationInProgress(): void;\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */\nexport function wrapInUserErrorIfRecoverable(\n e: Error,\n msg: string\n): FirestoreError {\n logError(LOG_TAG, `${msg}: ${e}`);\n if (isIndexedDbTransactionError(e)) {\n return new FirestoreError(Code.UNAVAILABLE, `${msg}: ${e}`);\n } else {\n throw e;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap } from '../util/sorted_map';\n\nimport { documentMap } from './collections';\nimport { Document } from './document';\nimport { DocumentComparator } from './document_comparator';\nimport { DocumentKey } from './document_key';\n\n/**\n * DocumentSet is an immutable (copy-on-write) collection that holds documents\n * in order specified by the provided comparator. We always add a document key\n * comparator on top of what is provided to guarantee document equality based on\n * the key.\n */\n\nexport class DocumentSet {\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */\n static emptySet(oldSet: DocumentSet): DocumentSet {\n return new DocumentSet(oldSet.comparator);\n }\n\n private comparator: DocumentComparator;\n private keyedMap: SortedMap<DocumentKey, Document>;\n private sortedSet: SortedMap<Document, null>;\n\n /** The default ordering is by key if the comparator is omitted */\n constructor(comp?: DocumentComparator) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n if (comp) {\n this.comparator = (d1: Document, d2: Document) =>\n comp(d1, d2) || DocumentKey.comparator(d1.key, d2.key);\n } else {\n this.comparator = (d1: Document, d2: Document) =>\n DocumentKey.comparator(d1.key, d2.key);\n }\n\n this.keyedMap = documentMap();\n this.sortedSet = new SortedMap<Document, null>(this.comparator);\n }\n\n has(key: DocumentKey): boolean {\n return this.keyedMap.get(key) != null;\n }\n\n get(key: DocumentKey): Document | null {\n return this.keyedMap.get(key);\n }\n\n first(): Document | null {\n return this.sortedSet.minKey();\n }\n\n last(): Document | null {\n return this.sortedSet.maxKey();\n }\n\n isEmpty(): boolean {\n return this.sortedSet.isEmpty();\n }\n\n /**\n * Returns the index of the provided key in the document set, or -1 if the\n * document key is not present in the set;\n */\n indexOf(key: DocumentKey): number {\n const doc = this.keyedMap.get(key);\n return doc ? this.sortedSet.indexOf(doc) : -1;\n }\n\n get size(): number {\n return this.sortedSet.size;\n }\n\n /** Iterates documents in order defined by \"comparator\" */\n forEach(cb: (doc: Document) => void): void {\n this.sortedSet.inorderTraversal((k, v) => {\n cb(k);\n return false;\n });\n }\n\n /** Inserts or updates a document with the same key */\n add(doc: Document): DocumentSet {\n // First remove the element if we have it.\n const set = this.delete(doc.key);\n return set.copy(\n set.keyedMap.insert(doc.key, doc),\n set.sortedSet.insert(doc, null)\n );\n }\n\n /** Deletes a document with a given key */\n delete(key: DocumentKey): DocumentSet {\n const doc = this.get(key);\n if (!doc) {\n return this;\n }\n\n return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc));\n }\n\n isEqual(other: DocumentSet | null | undefined): boolean {\n if (!(other instanceof DocumentSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.sortedSet.getIterator();\n const otherIt = other.sortedSet.getIterator();\n while (thisIt.hasNext()) {\n const thisDoc = thisIt.getNext().key;\n const otherDoc = otherIt.getNext().key;\n if (!thisDoc.isEqual(otherDoc)) {\n return false;\n }\n }\n return true;\n }\n\n toString(): string {\n const docStrings: string[] = [];\n this.forEach(doc => {\n docStrings.push(doc.toString());\n });\n if (docStrings.length === 0) {\n return 'DocumentSet ()';\n } else {\n return 'DocumentSet (\\n ' + docStrings.join(' \\n') + '\\n)';\n }\n }\n\n private copy(\n keyedMap: SortedMap<DocumentKey, Document>,\n sortedSet: SortedMap<Document, null>\n ): DocumentSet {\n const newSet = new DocumentSet();\n newSet.comparator = this.comparator;\n newSet.keyedMap = keyedMap;\n newSet.sortedSet = sortedSet;\n return newSet;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKeySet } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { fail } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { Query, queryEquals } from './query';\n\nexport const enum ChangeType {\n Added,\n Removed,\n Modified,\n Metadata\n}\n\nexport interface DocumentViewChange {\n type: ChangeType;\n doc: Document;\n}\n\nexport const enum SyncState {\n Local,\n Synced\n}\n\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */\nexport class DocumentChangeSet {\n private changeMap = new SortedMap<DocumentKey, DocumentViewChange>(\n DocumentKey.comparator\n );\n\n track(change: DocumentViewChange): void {\n const key = change.doc.key;\n const oldChange = this.changeMap.get(key);\n if (!oldChange) {\n this.changeMap = this.changeMap.insert(key, change);\n return;\n }\n\n // Merge the new change with the existing change.\n if (\n change.type !== ChangeType.Added &&\n oldChange.type === ChangeType.Metadata\n ) {\n this.changeMap = this.changeMap.insert(key, change);\n } else if (\n change.type === ChangeType.Metadata &&\n oldChange.type !== ChangeType.Removed\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: oldChange.type,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Modified\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Added\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Added,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Added\n ) {\n this.changeMap = this.changeMap.remove(key);\n } else if (\n change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Modified\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Removed,\n doc: oldChange.doc\n });\n } else if (\n change.type === ChangeType.Added &&\n oldChange.type === ChangeType.Removed\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n } else {\n // This includes these cases, which don't make sense:\n // Added->Added\n // Removed->Removed\n // Modified->Added\n // Removed->Modified\n // Metadata->Added\n // Removed->Metadata\n fail(\n 'unsupported combination of changes: ' +\n JSON.stringify(change) +\n ' after ' +\n JSON.stringify(oldChange)\n );\n }\n }\n\n getChanges(): DocumentViewChange[] {\n const changes: DocumentViewChange[] = [];\n this.changeMap.inorderTraversal(\n (key: DocumentKey, change: DocumentViewChange) => {\n changes.push(change);\n }\n );\n return changes;\n }\n}\n\nexport class ViewSnapshot {\n constructor(\n readonly query: Query,\n readonly docs: DocumentSet,\n readonly oldDocs: DocumentSet,\n readonly docChanges: DocumentViewChange[],\n readonly mutatedKeys: DocumentKeySet,\n readonly fromCache: boolean,\n readonly syncStateChanged: boolean,\n readonly excludesMetadataChanges: boolean,\n readonly hasCachedResults: boolean\n ) {}\n\n /** Returns a view snapshot as if all documents in the snapshot were added. */\n static fromInitialDocuments(\n query: Query,\n documents: DocumentSet,\n mutatedKeys: DocumentKeySet,\n fromCache: boolean,\n hasCachedResults: boolean\n ): ViewSnapshot {\n const changes: DocumentViewChange[] = [];\n documents.forEach(doc => {\n changes.push({ type: ChangeType.Added, doc });\n });\n\n return new ViewSnapshot(\n query,\n documents,\n DocumentSet.emptySet(documents),\n changes,\n mutatedKeys,\n fromCache,\n /* syncStateChanged= */ true,\n /* excludesMetadataChanges= */ false,\n hasCachedResults\n );\n }\n\n get hasPendingWrites(): boolean {\n return !this.mutatedKeys.isEmpty();\n }\n\n isEqual(other: ViewSnapshot): boolean {\n if (\n this.fromCache !== other.fromCache ||\n this.hasCachedResults !== other.hasCachedResults ||\n this.syncStateChanged !== other.syncStateChanged ||\n !this.mutatedKeys.isEqual(other.mutatedKeys) ||\n !queryEquals(this.query, other.query) ||\n !this.docs.isEqual(other.docs) ||\n !this.oldDocs.isEqual(other.oldDocs)\n ) {\n return false;\n }\n const changes: DocumentViewChange[] = this.docChanges;\n const otherChanges: DocumentViewChange[] = other.docChanges;\n if (changes.length !== otherChanges.length) {\n return false;\n }\n for (let i = 0; i < changes.length; i++) {\n if (\n changes[i].type !== otherChanges[i].type ||\n !changes[i].doc.isEqual(otherChanges[i].doc)\n ) {\n return false;\n }\n }\n return true;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, debugCast } from '../util/assert';\nimport { wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { EventHandler } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { canonifyQuery, Query, queryEquals, stringifyQuery } from './query';\nimport { OnlineState } from './types';\nimport { ChangeType, DocumentViewChange, ViewSnapshot } from './view_snapshot';\n\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */\nclass QueryListenersInfo {\n viewSnap: ViewSnapshot | undefined = undefined;\n listeners: QueryListener[] = [];\n}\n\n/**\n * Interface for handling events from the EventManager.\n */\nexport interface Observer<T> {\n next: EventHandler<T>;\n error: EventHandler<FirestoreError>;\n}\n\n/**\n * EventManager is responsible for mapping queries to query event emitters.\n * It handles \"fan-out\". -- Identical queries will re-use the same watch on the\n * backend.\n *\n * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be\n * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This\n * allows users to tree-shake the Watch logic.\n */\nexport interface EventManager {\n onListen?: (query: Query) => Promise<ViewSnapshot>;\n onUnlisten?: (query: Query) => Promise<void>;\n}\n\nexport function newEventManager(): EventManager {\n return new EventManagerImpl();\n}\n\nexport class EventManagerImpl implements EventManager {\n queries = new ObjectMap<Query, QueryListenersInfo>(\n q => canonifyQuery(q),\n queryEquals\n );\n\n onlineState = OnlineState.Unknown;\n\n snapshotsInSyncListeners: Set<Observer<void>> = new Set();\n\n /** Callback invoked when a Query is first listen to. */\n onListen?: (query: Query) => Promise<ViewSnapshot>;\n /** Callback invoked once all listeners to a Query are removed. */\n onUnlisten?: (query: Query) => Promise<void>;\n}\n\nexport async function eventManagerListen(\n eventManager: EventManager,\n listener: QueryListener\n): Promise<void> {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n debugAssert(!!eventManagerImpl.onListen, 'onListen not set');\n const query = listener.query;\n let firstListen = false;\n\n let queryInfo = eventManagerImpl.queries.get(query);\n if (!queryInfo) {\n firstListen = true;\n queryInfo = new QueryListenersInfo();\n }\n\n if (firstListen) {\n try {\n queryInfo.viewSnap = await eventManagerImpl.onListen(query);\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Initialization of query '${stringifyQuery(listener.query)}' failed`\n );\n listener.onError(firestoreError);\n return;\n }\n }\n\n eventManagerImpl.queries.set(query, queryInfo);\n queryInfo.listeners.push(listener);\n\n // Run global snapshot listeners if a consistent snapshot has been emitted.\n const raisedEvent = listener.applyOnlineStateChange(\n eventManagerImpl.onlineState\n );\n debugAssert(\n !raisedEvent,\n \"applyOnlineStateChange() shouldn't raise an event for brand-new listeners.\"\n );\n\n if (queryInfo.viewSnap) {\n const raisedEvent = listener.onViewSnapshot(queryInfo.viewSnap);\n if (raisedEvent) {\n raiseSnapshotsInSyncEvent(eventManagerImpl);\n }\n }\n}\n\nexport async function eventManagerUnlisten(\n eventManager: EventManager,\n listener: QueryListener\n): Promise<void> {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n debugAssert(!!eventManagerImpl.onUnlisten, 'onUnlisten not set');\n const query = listener.query;\n let lastListen = false;\n\n const queryInfo = eventManagerImpl.queries.get(query);\n if (queryInfo) {\n const i = queryInfo.listeners.indexOf(listener);\n if (i >= 0) {\n queryInfo.listeners.splice(i, 1);\n lastListen = queryInfo.listeners.length === 0;\n }\n }\n\n if (lastListen) {\n eventManagerImpl.queries.delete(query);\n return eventManagerImpl.onUnlisten(query);\n }\n}\n\nexport function eventManagerOnWatchChange(\n eventManager: EventManager,\n viewSnaps: ViewSnapshot[]\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n let raisedEvent = false;\n for (const viewSnap of viewSnaps) {\n const query = viewSnap.query;\n const queryInfo = eventManagerImpl.queries.get(query);\n if (queryInfo) {\n for (const listener of queryInfo.listeners) {\n if (listener.onViewSnapshot(viewSnap)) {\n raisedEvent = true;\n }\n }\n queryInfo.viewSnap = viewSnap;\n }\n }\n if (raisedEvent) {\n raiseSnapshotsInSyncEvent(eventManagerImpl);\n }\n}\n\nexport function eventManagerOnWatchError(\n eventManager: EventManager,\n query: Query,\n error: FirestoreError\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n const queryInfo = eventManagerImpl.queries.get(query);\n if (queryInfo) {\n for (const listener of queryInfo.listeners) {\n listener.onError(error);\n }\n }\n\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n eventManagerImpl.queries.delete(query);\n}\n\nexport function eventManagerOnOnlineStateChange(\n eventManager: EventManager,\n onlineState: OnlineState\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n eventManagerImpl.onlineState = onlineState;\n let raisedEvent = false;\n eventManagerImpl.queries.forEach((_, queryInfo) => {\n for (const listener of queryInfo.listeners) {\n // Run global snapshot listeners if a consistent snapshot has been emitted.\n if (listener.applyOnlineStateChange(onlineState)) {\n raisedEvent = true;\n }\n }\n });\n if (raisedEvent) {\n raiseSnapshotsInSyncEvent(eventManagerImpl);\n }\n}\n\nexport function addSnapshotsInSyncListener(\n eventManager: EventManager,\n observer: Observer<void>\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n eventManagerImpl.snapshotsInSyncListeners.add(observer);\n // Immediately fire an initial event, indicating all existing listeners\n // are in-sync.\n observer.next();\n}\n\nexport function removeSnapshotsInSyncListener(\n eventManager: EventManager,\n observer: Observer<void>\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n eventManagerImpl.snapshotsInSyncListeners.delete(observer);\n}\n\n// Call all global snapshot listeners that have been set.\nfunction raiseSnapshotsInSyncEvent(eventManagerImpl: EventManagerImpl): void {\n eventManagerImpl.snapshotsInSyncListeners.forEach(observer => {\n observer.next();\n });\n}\n\nexport interface ListenOptions {\n /** Raise events even when only the metadata changes */\n readonly includeMetadataChanges?: boolean;\n\n /**\n * Wait for a sync with the server when online, but still raise events while\n * offline.\n */\n readonly waitForSyncWhenOnline?: boolean;\n}\n\n/**\n * QueryListener takes a series of internal view snapshots and determines\n * when to raise the event.\n *\n * It uses an Observer to dispatch events.\n */\nexport class QueryListener {\n /**\n * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\n * observer. This flag is set to true once we've actually raised an event.\n */\n private raisedInitialEvent = false;\n\n private options: ListenOptions;\n\n private snap: ViewSnapshot | null = null;\n\n private onlineState = OnlineState.Unknown;\n\n constructor(\n readonly query: Query,\n private queryObserver: Observer<ViewSnapshot>,\n options?: ListenOptions\n ) {\n this.options = options || {};\n }\n\n /**\n * Applies the new ViewSnapshot to this listener, raising a user-facing event\n * if applicable (depending on what changed, whether the user has opted into\n * metadata-only changes, etc.). Returns true if a user-facing event was\n * indeed raised.\n */\n onViewSnapshot(snap: ViewSnapshot): boolean {\n debugAssert(\n snap.docChanges.length > 0 || snap.syncStateChanged,\n 'We got a new snapshot with no changes?'\n );\n\n if (!this.options.includeMetadataChanges) {\n // Remove the metadata only changes.\n const docChanges: DocumentViewChange[] = [];\n for (const docChange of snap.docChanges) {\n if (docChange.type !== ChangeType.Metadata) {\n docChanges.push(docChange);\n }\n }\n snap = new ViewSnapshot(\n snap.query,\n snap.docs,\n snap.oldDocs,\n docChanges,\n snap.mutatedKeys,\n snap.fromCache,\n snap.syncStateChanged,\n /* excludesMetadataChanges= */ true,\n snap.hasCachedResults\n );\n }\n let raisedEvent = false;\n if (!this.raisedInitialEvent) {\n if (this.shouldRaiseInitialEvent(snap, this.onlineState)) {\n this.raiseInitialEvent(snap);\n raisedEvent = true;\n }\n } else if (this.shouldRaiseEvent(snap)) {\n this.queryObserver.next(snap);\n raisedEvent = true;\n }\n\n this.snap = snap;\n return raisedEvent;\n }\n\n onError(error: FirestoreError): void {\n this.queryObserver.error(error);\n }\n\n /** Returns whether a snapshot was raised. */\n applyOnlineStateChange(onlineState: OnlineState): boolean {\n this.onlineState = onlineState;\n let raisedEvent = false;\n if (\n this.snap &&\n !this.raisedInitialEvent &&\n this.shouldRaiseInitialEvent(this.snap, onlineState)\n ) {\n this.raiseInitialEvent(this.snap);\n raisedEvent = true;\n }\n return raisedEvent;\n }\n\n private shouldRaiseInitialEvent(\n snap: ViewSnapshot,\n onlineState: OnlineState\n ): boolean {\n debugAssert(\n !this.raisedInitialEvent,\n 'Determining whether to raise first event but already had first event'\n );\n\n // Always raise the first event when we're synced\n if (!snap.fromCache) {\n return true;\n }\n\n // NOTE: We consider OnlineState.Unknown as online (it should become Offline\n // or Online if we wait long enough).\n const maybeOnline = onlineState !== OnlineState.Offline;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n if (this.options.waitForSyncWhenOnline && maybeOnline) {\n debugAssert(\n snap.fromCache,\n 'Waiting for sync, but snapshot is not from cache'\n );\n return false;\n }\n\n // Raise data from cache if we have any documents, have cached results before,\n // or we are offline.\n return (\n !snap.docs.isEmpty() ||\n snap.hasCachedResults ||\n onlineState === OnlineState.Offline\n );\n }\n\n private shouldRaiseEvent(snap: ViewSnapshot): boolean {\n // We don't need to handle includeDocumentMetadataChanges here because\n // the Metadata only changes have already been stripped out if needed.\n // At this point the only changes we will see are the ones we should\n // propagate.\n if (snap.docChanges.length > 0) {\n return true;\n }\n\n const hasPendingWritesChanged =\n this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites;\n if (snap.syncStateChanged || hasPendingWritesChanged) {\n return this.options.includeMetadataChanges === true;\n }\n\n // Generally we should have hit one of the cases above, but it's possible\n // to get here if there were only metadata docChanges and they got\n // stripped out.\n return false;\n }\n\n private raiseInitialEvent(snap: ViewSnapshot): void {\n debugAssert(\n !this.raisedInitialEvent,\n 'Trying to raise initial events for second time'\n );\n snap = ViewSnapshot.fromInitialDocuments(\n snap.query,\n snap.docs,\n snap.mutatedKeys,\n snap.fromCache,\n snap.hasCachedResults\n );\n this.raisedInitialEvent = true;\n this.queryObserver.next(snap);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryResult } from '../local/local_store_impl';\nimport {\n documentKeySet,\n DocumentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { TargetChange } from '../remote/remote_event';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { LimitType, newQueryComparator, Query, queryMatches } from './query';\nimport { OnlineState } from './types';\nimport {\n ChangeType,\n DocumentChangeSet,\n SyncState,\n ViewSnapshot\n} from './view_snapshot';\n\nexport type LimboDocumentChange = AddedLimboDocument | RemovedLimboDocument;\nexport class AddedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\nexport class RemovedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\n\n/** The result of applying a set of doc changes to a view. */\nexport interface ViewDocumentChanges {\n /** The new set of docs that should be in the view. */\n documentSet: DocumentSet;\n /** The diff of these docs with the previous set of docs. */\n changeSet: DocumentChangeSet;\n /**\n * Whether the set of documents passed in was not sufficient to calculate the\n * new state of the view and there needs to be another pass based on the\n * local cache.\n */\n needsRefill: boolean;\n\n mutatedKeys: DocumentKeySet;\n}\n\nexport interface ViewChange {\n snapshot?: ViewSnapshot;\n limboChanges: LimboDocumentChange[];\n}\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */\nexport class View {\n private syncState: SyncState | null = null;\n private hasCachedResults: boolean = false;\n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n private current = false;\n private documentSet: DocumentSet;\n /** Documents in the view but not in the remote target */\n private limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n private mutatedKeys = documentKeySet();\n /** Query comparator that defines the document order in this view. */\n private docComparator: (d1: Document, d2: Document) => number;\n\n constructor(\n private query: Query,\n /** Documents included in the remote target */\n private _syncedDocuments: DocumentKeySet\n ) {\n this.docComparator = newQueryComparator(query);\n this.documentSet = new DocumentSet(this.docComparator);\n }\n\n /**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */\n get syncedDocuments(): DocumentKeySet {\n return this._syncedDocuments;\n }\n\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges - The doc changes to apply to this view.\n * @param previousChanges - If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @returns a new set of docs, changes, and refill flag.\n */\n computeDocChanges(\n docChanges: DocumentMap,\n previousChanges?: ViewDocumentChanges\n ): ViewDocumentChanges {\n const changeSet = previousChanges\n ? previousChanges.changeSet\n : new DocumentChangeSet();\n const oldDocumentSet = previousChanges\n ? previousChanges.documentSet\n : this.documentSet;\n let newMutatedKeys = previousChanges\n ? previousChanges.mutatedKeys\n : this.mutatedKeys;\n let newDocumentSet = oldDocumentSet;\n let needsRefill = false;\n\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n //\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n const lastDocInLimit =\n this.query.limitType === LimitType.First &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n const firstDocInLimit =\n this.query.limitType === LimitType.Last &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.first()\n : null;\n\n docChanges.inorderTraversal((key, entry) => {\n const oldDoc = oldDocumentSet.get(key);\n const newDoc = queryMatches(this.query, entry) ? entry : null;\n\n const oldDocHadPendingMutations = oldDoc\n ? this.mutatedKeys.has(oldDoc.key)\n : false;\n const newDocHasPendingMutations = newDoc\n ? newDoc.hasLocalMutations ||\n // We only consider committed mutations for documents that were\n // mutated during the lifetime of the view.\n (this.mutatedKeys.has(newDoc.key) && newDoc.hasCommittedMutations)\n : false;\n\n let changeApplied = false;\n\n // Calculate change\n if (oldDoc && newDoc) {\n const docsEqual = oldDoc.data.isEqual(newDoc.data);\n if (!docsEqual) {\n if (!this.shouldWaitForSyncedDocument(oldDoc, newDoc)) {\n changeSet.track({\n type: ChangeType.Modified,\n doc: newDoc\n });\n changeApplied = true;\n\n if (\n (lastDocInLimit &&\n this.docComparator(newDoc, lastDocInLimit) > 0) ||\n (firstDocInLimit &&\n this.docComparator(newDoc, firstDocInLimit) < 0)\n ) {\n // This doc moved from inside the limit to outside the limit.\n // That means there may be some other doc in the local cache\n // that should be included instead.\n needsRefill = true;\n }\n }\n } else if (oldDocHadPendingMutations !== newDocHasPendingMutations) {\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\n changeApplied = true;\n }\n } else if (!oldDoc && newDoc) {\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\n changeApplied = true;\n } else if (oldDoc && !newDoc) {\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n changeApplied = true;\n\n if (lastDocInLimit || firstDocInLimit) {\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n needsRefill = true;\n }\n }\n\n if (changeApplied) {\n if (newDoc) {\n newDocumentSet = newDocumentSet.add(newDoc);\n if (newDocHasPendingMutations) {\n newMutatedKeys = newMutatedKeys.add(key);\n } else {\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n } else {\n newDocumentSet = newDocumentSet.delete(key);\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n }\n });\n\n // Drop documents out to meet limit/limitToLast requirement.\n if (this.query.limit !== null) {\n while (newDocumentSet.size > this.query.limit!) {\n const oldDoc =\n this.query.limitType === LimitType.First\n ? newDocumentSet.last()\n : newDocumentSet.first();\n newDocumentSet = newDocumentSet.delete(oldDoc!.key);\n newMutatedKeys = newMutatedKeys.delete(oldDoc!.key);\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc! });\n }\n }\n\n debugAssert(\n !needsRefill || !previousChanges,\n 'View was refilled using docs that themselves needed refilling.'\n );\n return {\n documentSet: newDocumentSet,\n changeSet,\n needsRefill,\n mutatedKeys: newMutatedKeys\n };\n }\n\n private shouldWaitForSyncedDocument(\n oldDoc: Document,\n newDoc: Document\n ): boolean {\n // We suppress the initial change event for documents that were modified as\n // part of a write acknowledgment (e.g. when the value of a server transform\n // is applied) as Watch will send us the same document again.\n // By suppressing the event, we only raise two user visible events (one with\n // `hasPendingWrites` and the final state of the document) instead of three\n // (one with `hasPendingWrites`, the modified document with\n // `hasPendingWrites` and the final state of the document).\n return (\n oldDoc.hasLocalMutations &&\n newDoc.hasCommittedMutations &&\n !newDoc.hasLocalMutations\n );\n }\n\n /**\n * Updates the view with the given ViewDocumentChanges and optionally updates\n * limbo docs and sync state from the provided target change.\n * @param docChanges - The set of changes to make to the view's docs.\n * @param updateLimboDocuments - Whether to update limbo documents based on\n * this change.\n * @param targetChange - A target change to apply for computing limbo docs and\n * sync state.\n * @returns A new ViewChange with the given docs, changes, and sync state.\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n applyChanges(\n docChanges: ViewDocumentChanges,\n updateLimboDocuments: boolean,\n targetChange?: TargetChange\n ): ViewChange {\n debugAssert(\n !docChanges.needsRefill,\n 'Cannot apply changes that need a refill'\n );\n const oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys;\n // Sort changes based on type and query comparator\n const changes = docChanges.changeSet.getChanges();\n changes.sort((c1, c2) => {\n return (\n compareChangeType(c1.type, c2.type) ||\n this.docComparator(c1.doc, c2.doc)\n );\n });\n\n this.applyTargetChange(targetChange);\n const limboChanges = updateLimboDocuments\n ? this.updateLimboDocuments()\n : [];\n const synced = this.limboDocuments.size === 0 && this.current;\n const newSyncState = synced ? SyncState.Synced : SyncState.Local;\n const syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return { limboChanges };\n } else {\n const snap: ViewSnapshot = new ViewSnapshot(\n this.query,\n docChanges.documentSet,\n oldDocs,\n changes,\n docChanges.mutatedKeys,\n newSyncState === SyncState.Local,\n syncStateChanged,\n /* excludesMetadataChanges= */ false,\n targetChange\n ? targetChange.resumeToken.approximateByteSize() > 0\n : false\n );\n return {\n snapshot: snap,\n limboChanges\n };\n }\n }\n\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */\n applyOnlineStateChange(onlineState: OnlineState): ViewChange {\n if (this.current && onlineState === OnlineState.Offline) {\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = false;\n return this.applyChanges(\n {\n documentSet: this.documentSet,\n changeSet: new DocumentChangeSet(),\n mutatedKeys: this.mutatedKeys,\n needsRefill: false\n },\n /* updateLimboDocuments= */ false\n );\n } else {\n // No effect, just return a no-op ViewChange.\n return { limboChanges: [] };\n }\n }\n\n /**\n * Returns whether the doc for the given key should be in limbo.\n */\n private shouldBeInLimbo(key: DocumentKey): boolean {\n // If the remote end says it's part of this query, it's not in limbo.\n if (this._syncedDocuments.has(key)) {\n return false;\n }\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n if (!this.documentSet.has(key)) {\n return false;\n }\n // If there are local changes to the doc, they might explain why the server\n // doesn't know that it's part of the query. So don't put it in limbo.\n // TODO(klimt): Ideally, we would only consider changes that might actually\n // affect this specific query.\n if (this.documentSet.get(key)!.hasLocalMutations) {\n return false;\n }\n // Everything else is in limbo.\n return true;\n }\n\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */\n private applyTargetChange(targetChange?: TargetChange): void {\n if (targetChange) {\n targetChange.addedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.add(key))\n );\n targetChange.modifiedDocuments.forEach(key => {\n debugAssert(\n this._syncedDocuments.has(key),\n `Modified document ${key} not found in view.`\n );\n });\n targetChange.removedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.delete(key))\n );\n this.current = targetChange.current;\n }\n }\n\n private updateLimboDocuments(): LimboDocumentChange[] {\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) {\n return [];\n }\n\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n const oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n this.documentSet.forEach(doc => {\n if (this.shouldBeInLimbo(doc.key)) {\n this.limboDocuments = this.limboDocuments.add(doc.key);\n }\n });\n\n // Diff the new limbo docs with the old limbo docs.\n const changes: LimboDocumentChange[] = [];\n oldLimboDocuments.forEach(key => {\n if (!this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(key => {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n }\n\n /**\n * Update the in-memory state of the current view with the state read from\n * persistence.\n *\n * We update the query view whenever a client's primary status changes:\n * - When a client transitions from primary to secondary, it can miss\n * LocalStorage updates and its query views may temporarily not be\n * synchronized with the state on disk.\n * - For secondary to primary transitions, the client needs to update the list\n * of `syncedDocuments` since secondary clients update their query views\n * based purely on synthesized RemoteEvents.\n *\n * @param queryResult.documents - The documents that match the query according\n * to the LocalStore.\n * @param queryResult.remoteKeys - The keys of the documents that match the\n * query according to the backend.\n *\n * @returns The ViewChange that resulted from this synchronization.\n */\n // PORTING NOTE: Multi-tab only.\n synchronizeWithPersistedState(queryResult: QueryResult): ViewChange {\n this._syncedDocuments = queryResult.remoteKeys;\n this.limboDocuments = documentKeySet();\n const docChanges = this.computeDocChanges(queryResult.documents);\n return this.applyChanges(docChanges, /*updateLimboDocuments=*/ true);\n }\n\n /**\n * Returns a view snapshot as if this query was just listened to. Contains\n * a document add for every existing document and the `fromCache` and\n * `hasPendingWrites` status of the already established view.\n */\n // PORTING NOTE: Multi-tab only.\n computeInitialSnapshot(): ViewSnapshot {\n return ViewSnapshot.fromInitialDocuments(\n this.query,\n this.documentSet,\n this.mutatedKeys,\n this.syncState === SyncState.Local,\n this.hasCachedResults\n );\n }\n}\n\nfunction compareChangeType(c1: ChangeType, c2: ChangeType): number {\n const order = (change: ChangeType): 0 | 1 | 2 => {\n switch (change) {\n case ChangeType.Added:\n return 1;\n case ChangeType.Modified:\n return 2;\n case ChangeType.Metadata:\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n case ChangeType.Removed:\n return 0;\n default:\n return fail('Unknown ChangeType: ' + change);\n }\n };\n\n return order(c1) - order(c2);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LoadBundleTask } from '../api/bundle';\nimport { User } from '../auth/user';\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from '../local/local_store';\nimport {\n localStoreAcknowledgeBatch,\n localStoreAllocateTarget,\n localStoreApplyRemoteEventToLocalCache,\n localStoreExecuteQuery,\n localStoreGetActiveClients,\n localStoreGetCachedTarget,\n localStoreGetHighestUnacknowledgedBatchId,\n localStoreGetNewDocumentChanges,\n localStoreHandleUserChange,\n localStoreHasNewerBundle,\n localStoreLookupMutationDocuments,\n localStoreNotifyLocalViewChanges,\n localStoreRejectBatch,\n localStoreReleaseTarget,\n localStoreRemoveCachedMutationBatchMetadata,\n localStoreSaveBundle,\n localStoreWriteLocally\n} from '../local/local_store_impl';\nimport { LocalViewChanges } from '../local/local_view_changes';\nimport { ReferenceSet } from '../local/reference_set';\nimport { ClientId, SharedClientState } from '../local/shared_client_state';\nimport { QueryTargetState } from '../local/shared_client_state_syncer';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport {\n DocumentKeySet,\n documentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatchResult } from '../model/mutation_batch';\nimport { ResourcePath } from '../model/path';\nimport { RemoteEvent, TargetChange } from '../remote/remote_event';\nimport {\n canUseNetwork,\n fillWritePipeline,\n RemoteStore,\n remoteStoreApplyPrimaryState,\n remoteStoreListen,\n remoteStoreUnlisten\n} from '../remote/remote_store';\nimport { debugAssert, debugCast, fail, hardAssert } from '../util/assert';\nimport { wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { BundleReader } from '../util/bundle_reader';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { Deferred } from '../util/promise';\nimport { SortedMap } from '../util/sorted_map';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport {\n bundleInitialProgress,\n BundleLoader,\n bundleSuccessProgress\n} from './bundle_impl';\nimport {\n EventManager,\n eventManagerOnOnlineStateChange,\n eventManagerOnWatchChange,\n eventManagerOnWatchError\n} from './event_manager';\nimport { ListenSequence } from './listen_sequence';\nimport {\n canonifyQuery,\n LimitType,\n newQuery,\n newQueryForPath,\n Query,\n queryEquals,\n queryCollectionGroup,\n queryToTarget,\n stringifyQuery\n} from './query';\nimport { SnapshotVersion } from './snapshot_version';\nimport { SyncEngine } from './sync_engine';\nimport { Target } from './target';\nimport { TargetIdGenerator } from './target_id_generator';\nimport {\n BatchId,\n MutationBatchState,\n OnlineState,\n OnlineStateSource,\n TargetId\n} from './types';\nimport {\n AddedLimboDocument,\n LimboDocumentChange,\n RemovedLimboDocument,\n View,\n ViewChange\n} from './view';\nimport { ViewSnapshot } from './view_snapshot';\n\nconst LOG_TAG = 'SyncEngine';\n\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nclass QueryView {\n constructor(\n /**\n * The query itself.\n */\n public query: Query,\n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n public targetId: TargetId,\n /**\n * The view is responsible for computing the final merged truth of what\n * docs are in the query. It gets notified of local and remote changes,\n * and applies the query filters and limits to determine the most correct\n * possible results.\n */\n public view: View\n ) {}\n}\n\n/** Tracks a limbo resolution. */\nclass LimboResolution {\n constructor(public key: DocumentKey) {}\n\n /**\n * Set to true once we've received a document. This is used in\n * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to\n * decide whether it needs to manufacture a delete event for the target once\n * the target is CURRENT.\n */\n receivedDocument: boolean = false;\n}\n\n/**\n * A function that updates a QueryView with a set of document changes (and a\n * remote event if applicable).\n */\ntype ApplyDocChangesHandler = (\n queryView: QueryView,\n changes: DocumentMap,\n remoteEvent?: RemoteEvent\n) => Promise<ViewSnapshot | undefined>;\n\n/**\n * Callbacks implemented by EventManager to handle notifications from\n * SyncEngine.\n */\ninterface SyncEngineListener {\n /** Handles new view snapshots. */\n onWatchChange?(snapshots: ViewSnapshot[]): void;\n\n /** Handles the failure of a query. */\n onWatchError?(query: Query, error: FirestoreError): void;\n}\n\n/**\n * An implementation of `SyncEngine` coordinating with other parts of SDK.\n *\n * The parts of SyncEngine that act as a callback to RemoteStore need to be\n * registered individually. This is done in `syncEngineWrite()` and\n * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods\n * serve as entry points to RemoteStore's functionality.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass SyncEngineImpl implements SyncEngine {\n syncEngineListener: SyncEngineListener = {};\n\n /**\n * A callback that updates the QueryView based on the provided change.\n *\n * PORTING NOTE: On other platforms, this logic lives in\n * `emitNewSnapshotsAndNotifyLocalStore()`, but on Web it is extracted to\n * ensure that all view logic only exists in bundles that include views.\n */\n applyDocChanges?: ApplyDocChangesHandler;\n\n queryViewsByQuery = new ObjectMap<Query, QueryView>(\n q => canonifyQuery(q),\n queryEquals\n );\n queriesByTarget = new Map<TargetId, Query[]>();\n /**\n * The keys of documents that are in limbo for which we haven't yet started a\n * limbo resolution query. The strings in this set are the result of calling\n * `key.path.canonicalString()` where `key` is a `DocumentKey` object.\n *\n * The `Set` type was chosen because it provides efficient lookup and removal\n * of arbitrary elements and it also maintains insertion order, providing the\n * desired queue-like FIFO semantics.\n */\n enqueuedLimboResolutions = new Set<string>();\n /**\n * Keeps track of the target ID for each document that is in limbo with an\n * active target.\n */\n activeLimboTargetsByKey = new SortedMap<DocumentKey, TargetId>(\n DocumentKey.comparator\n );\n /**\n * Keeps track of the information about an active limbo resolution for each\n * active target ID that was started for the purpose of limbo resolution.\n */\n activeLimboResolutionsByTarget = new Map<TargetId, LimboResolution>();\n limboDocumentRefs = new ReferenceSet();\n /** Stores user completion handlers, indexed by User and BatchId. */\n mutationUserCallbacks = {} as {\n [uidKey: string]: SortedMap<BatchId, Deferred<void>>;\n };\n /** Stores user callbacks waiting for all pending writes to be acknowledged. */\n pendingWritesCallbacks = new Map<BatchId, Array<Deferred<void>>>();\n limboTargetIdGenerator = TargetIdGenerator.forSyncEngine();\n\n onlineState = OnlineState.Unknown;\n\n // The primary state is set to `true` or `false` immediately after Firestore\n // startup. In the interim, a client should only be considered primary if\n // `isPrimary` is true.\n _isPrimaryClient: undefined | boolean = undefined;\n\n constructor(\n readonly localStore: LocalStore,\n readonly remoteStore: RemoteStore,\n readonly eventManager: EventManager,\n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n readonly sharedClientState: SharedClientState,\n public currentUser: User,\n readonly maxConcurrentLimboResolutions: number\n ) {}\n\n get isPrimaryClient(): boolean {\n return this._isPrimaryClient === true;\n }\n}\n\nexport function newSyncEngine(\n localStore: LocalStore,\n remoteStore: RemoteStore,\n eventManager: EventManager,\n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n sharedClientState: SharedClientState,\n currentUser: User,\n maxConcurrentLimboResolutions: number,\n isPrimary: boolean\n): SyncEngine {\n const syncEngine = new SyncEngineImpl(\n localStore,\n remoteStore,\n eventManager,\n sharedClientState,\n currentUser,\n maxConcurrentLimboResolutions\n );\n if (isPrimary) {\n syncEngine._isPrimaryClient = true;\n }\n return syncEngine;\n}\n\n/**\n * Initiates the new listen, resolves promise when listen enqueued to the\n * server. All the subsequent view snapshots or errors are sent to the\n * subscribed handlers. Returns the initial snapshot.\n */\nexport async function syncEngineListen(\n syncEngine: SyncEngine,\n query: Query\n): Promise<ViewSnapshot> {\n const syncEngineImpl = ensureWatchCallbacks(syncEngine);\n\n let targetId;\n let viewSnapshot;\n\n const queryView = syncEngineImpl.queryViewsByQuery.get(query);\n if (queryView) {\n // PORTING NOTE: With Multi-Tab Web, it is possible that a query view\n // already exists when EventManager calls us for the first time. This\n // happens when the primary tab is already listening to this query on\n // behalf of another tab and the user of the primary also starts listening\n // to the query. EventManager will not have an assigned target ID in this\n // case and calls `listen` to obtain this ID.\n targetId = queryView.targetId;\n syncEngineImpl.sharedClientState.addLocalQueryTarget(targetId);\n viewSnapshot = queryView.view.computeInitialSnapshot();\n } else {\n const targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n queryToTarget(query)\n );\n\n const status = syncEngineImpl.sharedClientState.addLocalQueryTarget(\n targetData.targetId\n );\n targetId = targetData.targetId;\n viewSnapshot = await initializeViewAndComputeSnapshot(\n syncEngineImpl,\n query,\n targetId,\n status === 'current',\n targetData.resumeToken\n );\n\n if (syncEngineImpl.isPrimaryClient) {\n remoteStoreListen(syncEngineImpl.remoteStore, targetData);\n }\n }\n\n return viewSnapshot;\n}\n\n/**\n * Registers a view for a previously unknown query and computes its initial\n * snapshot.\n */\nasync function initializeViewAndComputeSnapshot(\n syncEngineImpl: SyncEngineImpl,\n query: Query,\n targetId: TargetId,\n current: boolean,\n resumeToken: ByteString\n): Promise<ViewSnapshot> {\n // PORTING NOTE: On Web only, we inject the code that registers new Limbo\n // targets based on view changes. This allows us to only depend on Limbo\n // changes when user code includes queries.\n syncEngineImpl.applyDocChanges = (queryView, changes, remoteEvent) =>\n applyDocChanges(syncEngineImpl, queryView, changes, remoteEvent);\n\n const queryResult = await localStoreExecuteQuery(\n syncEngineImpl.localStore,\n query,\n /* usePreviousResults= */ true\n );\n const view = new View(query, queryResult.remoteKeys);\n const viewDocChanges = view.computeDocChanges(queryResult.documents);\n const synthesizedTargetChange =\n TargetChange.createSynthesizedTargetChangeForCurrentChange(\n targetId,\n current && syncEngineImpl.onlineState !== OnlineState.Offline,\n resumeToken\n );\n const viewChange = view.applyChanges(\n viewDocChanges,\n /* updateLimboDocuments= */ syncEngineImpl.isPrimaryClient,\n synthesizedTargetChange\n );\n updateTrackedLimbos(syncEngineImpl, targetId, viewChange.limboChanges);\n\n debugAssert(\n !!viewChange.snapshot,\n 'applyChanges for new view should always return a snapshot'\n );\n\n const data = new QueryView(query, targetId, view);\n\n syncEngineImpl.queryViewsByQuery.set(query, data);\n if (syncEngineImpl.queriesByTarget.has(targetId)) {\n syncEngineImpl.queriesByTarget.get(targetId)!.push(query);\n } else {\n syncEngineImpl.queriesByTarget.set(targetId, [query]);\n }\n\n return viewChange.snapshot;\n}\n\n/** Stops listening to the query. */\nexport async function syncEngineUnlisten(\n syncEngine: SyncEngine,\n query: Query\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const queryView = syncEngineImpl.queryViewsByQuery.get(query)!;\n debugAssert(\n !!queryView,\n 'Trying to unlisten on query not found:' + stringifyQuery(query)\n );\n\n // Only clean up the query view and target if this is the only query mapped\n // to the target.\n const queries = syncEngineImpl.queriesByTarget.get(queryView.targetId)!;\n if (queries.length > 1) {\n syncEngineImpl.queriesByTarget.set(\n queryView.targetId,\n queries.filter(q => !queryEquals(q, query))\n );\n syncEngineImpl.queryViewsByQuery.delete(query);\n return;\n }\n\n // No other queries are mapped to the target, clean up the query and the target.\n if (syncEngineImpl.isPrimaryClient) {\n // We need to remove the local query target first to allow us to verify\n // whether any other client is still interested in this target.\n syncEngineImpl.sharedClientState.removeLocalQueryTarget(queryView.targetId);\n const targetRemainsActive =\n syncEngineImpl.sharedClientState.isActiveQueryTarget(queryView.targetId);\n\n if (!targetRemainsActive) {\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n queryView.targetId,\n /*keepPersistedTargetData=*/ false\n )\n .then(() => {\n syncEngineImpl.sharedClientState.clearQueryState(queryView.targetId);\n remoteStoreUnlisten(syncEngineImpl.remoteStore, queryView.targetId);\n removeAndCleanupTarget(syncEngineImpl, queryView.targetId);\n })\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n } else {\n removeAndCleanupTarget(syncEngineImpl, queryView.targetId);\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n queryView.targetId,\n /*keepPersistedTargetData=*/ true\n );\n }\n}\n\n/**\n * Initiates the write of local mutation batch which involves adding the\n * writes to the mutation queue, notifying the remote store about new\n * mutations and raising events for any changes this write caused.\n *\n * The promise returned by this call is resolved when the above steps\n * have completed, *not* when the write was acked by the backend. The\n * userCallback is resolved once the write was acked/rejected by the\n * backend (or failed locally for any other reason).\n */\nexport async function syncEngineWrite(\n syncEngine: SyncEngine,\n batch: Mutation[],\n userCallback: Deferred<void>\n): Promise<void> {\n const syncEngineImpl = syncEngineEnsureWriteCallbacks(syncEngine);\n\n try {\n const result = await localStoreWriteLocally(\n syncEngineImpl.localStore,\n batch\n );\n syncEngineImpl.sharedClientState.addPendingMutation(result.batchId);\n addMutationCallback(syncEngineImpl, result.batchId, userCallback);\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n result.changes\n );\n await fillWritePipeline(syncEngineImpl.remoteStore);\n } catch (e) {\n // If we can't persist the mutation, we reject the user callback and\n // don't send the mutation. The user can then retry the write.\n const error = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to persist write`\n );\n userCallback.reject(error);\n }\n}\n\n/**\n * Applies one remote event to the sync engine, notifying any views of the\n * changes, and releasing any pending mutation batches that would become\n * visible because of the snapshot version the remote event contains.\n */\nexport async function syncEngineApplyRemoteEvent(\n syncEngine: SyncEngine,\n remoteEvent: RemoteEvent\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n try {\n const changes = await localStoreApplyRemoteEventToLocalCache(\n syncEngineImpl.localStore,\n remoteEvent\n );\n // Update `receivedDocument` as appropriate for any limbo targets.\n remoteEvent.targetChanges.forEach((targetChange, targetId) => {\n const limboResolution =\n syncEngineImpl.activeLimboResolutionsByTarget.get(targetId);\n if (limboResolution) {\n // Since this is a limbo resolution lookup, it's for a single document\n // and it could be added, modified, or removed, but not a combination.\n hardAssert(\n targetChange.addedDocuments.size +\n targetChange.modifiedDocuments.size +\n targetChange.removedDocuments.size <=\n 1,\n 'Limbo resolution for single document contains multiple changes.'\n );\n if (targetChange.addedDocuments.size > 0) {\n limboResolution.receivedDocument = true;\n } else if (targetChange.modifiedDocuments.size > 0) {\n hardAssert(\n limboResolution.receivedDocument,\n 'Received change for limbo target document without add.'\n );\n } else if (targetChange.removedDocuments.size > 0) {\n hardAssert(\n limboResolution.receivedDocument,\n 'Received remove for limbo target document without add.'\n );\n limboResolution.receivedDocument = false;\n } else {\n // This was probably just a CURRENT targetChange or similar.\n }\n }\n });\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n changes,\n remoteEvent\n );\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error as FirestoreError);\n }\n}\n\n/**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */\nexport function syncEngineApplyOnlineStateChange(\n syncEngine: SyncEngine,\n onlineState: OnlineState,\n source: OnlineStateSource\n): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n // If we are the secondary client, we explicitly ignore the remote store's\n // online state (the local client may go offline, even though the primary\n // tab remains online) and only apply the primary tab's online state from\n // SharedClientState.\n if (\n (syncEngineImpl.isPrimaryClient &&\n source === OnlineStateSource.RemoteStore) ||\n (!syncEngineImpl.isPrimaryClient &&\n source === OnlineStateSource.SharedClientState)\n ) {\n const newViewSnapshots = [] as ViewSnapshot[];\n syncEngineImpl.queryViewsByQuery.forEach((query, queryView) => {\n const viewChange = queryView.view.applyOnlineStateChange(onlineState);\n debugAssert(\n viewChange.limboChanges.length === 0,\n 'OnlineState should not affect limbo documents.'\n );\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n });\n\n eventManagerOnOnlineStateChange(syncEngineImpl.eventManager, onlineState);\n\n if (newViewSnapshots.length) {\n debugAssert(\n !!syncEngineImpl.syncEngineListener.onWatchChange,\n 'Active views but EventManager callbacks are not assigned'\n );\n syncEngineImpl.syncEngineListener.onWatchChange(newViewSnapshots);\n }\n\n syncEngineImpl.onlineState = onlineState;\n if (syncEngineImpl.isPrimaryClient) {\n syncEngineImpl.sharedClientState.setOnlineState(onlineState);\n }\n }\n}\n\n/**\n * Rejects the listen for the given targetID. This can be triggered by the\n * backend for any active target.\n *\n * @param syncEngine - The sync engine implementation.\n * @param targetId - The targetID corresponds to one previously initiated by the\n * user as part of TargetData passed to listen() on RemoteStore.\n * @param err - A description of the condition that has forced the rejection.\n * Nearly always this will be an indication that the user is no longer\n * authorized to see the data matching the target.\n */\nexport async function syncEngineRejectListen(\n syncEngine: SyncEngine,\n targetId: TargetId,\n err: FirestoreError\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n // PORTING NOTE: Multi-tab only.\n syncEngineImpl.sharedClientState.updateQueryState(targetId, 'rejected', err);\n\n const limboResolution =\n syncEngineImpl.activeLimboResolutionsByTarget.get(targetId);\n const limboKey = limboResolution && limboResolution.key;\n if (limboKey) {\n // TODO(klimt): We really only should do the following on permission\n // denied errors, but we don't have the cause code here.\n\n // It's a limbo doc. Create a synthetic event saying it was deleted.\n // This is kind of a hack. Ideally, we would have a method in the local\n // store to purge a document. However, it would be tricky to keep all of\n // the local store's invariants with another method.\n let documentUpdates = new SortedMap<DocumentKey, MutableDocument>(\n DocumentKey.comparator\n );\n // TODO(b/217189216): This limbo document should ideally have a read time,\n // so that it is picked up by any read-time based scans. The backend,\n // however, does not send a read time for target removals.\n documentUpdates = documentUpdates.insert(\n limboKey,\n MutableDocument.newNoDocument(limboKey, SnapshotVersion.min())\n );\n const resolvedLimboDocuments = documentKeySet().add(limboKey);\n const event = new RemoteEvent(\n SnapshotVersion.min(),\n /* targetChanges= */ new Map<TargetId, TargetChange>(),\n /* targetMismatches= */ new SortedMap<TargetId, TargetPurpose>(\n primitiveComparator\n ),\n documentUpdates,\n resolvedLimboDocuments\n );\n\n await syncEngineApplyRemoteEvent(syncEngineImpl, event);\n\n // Since this query failed, we won't want to manually unlisten to it.\n // We only remove it from bookkeeping after we successfully applied the\n // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to\n // this query when the RemoteStore restarts the Watch stream, which should\n // re-trigger the target failure.\n syncEngineImpl.activeLimboTargetsByKey =\n syncEngineImpl.activeLimboTargetsByKey.remove(limboKey);\n syncEngineImpl.activeLimboResolutionsByTarget.delete(targetId);\n pumpEnqueuedLimboResolutions(syncEngineImpl);\n } else {\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /* keepPersistedTargetData */ false\n )\n .then(() => removeAndCleanupTarget(syncEngineImpl, targetId, err))\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n}\n\nexport async function syncEngineApplySuccessfulWrite(\n syncEngine: SyncEngine,\n mutationBatchResult: MutationBatchResult\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const batchId = mutationBatchResult.batch.batchId;\n\n try {\n const changes = await localStoreAcknowledgeBatch(\n syncEngineImpl.localStore,\n mutationBatchResult\n );\n\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught\n // up), so we raise user callbacks first so that they consistently happen\n // before listen events.\n processUserCallback(syncEngineImpl, batchId, /*error=*/ null);\n triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n\n syncEngineImpl.sharedClientState.updateMutationState(\n batchId,\n 'acknowledged'\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes);\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error as FirestoreError);\n }\n}\n\nexport async function syncEngineRejectFailedWrite(\n syncEngine: SyncEngine,\n batchId: BatchId,\n error: FirestoreError\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n try {\n const changes = await localStoreRejectBatch(\n syncEngineImpl.localStore,\n batchId\n );\n\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught up),\n // so we raise user callbacks first so that they consistently happen before\n // listen events.\n processUserCallback(syncEngineImpl, batchId, error);\n triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n\n syncEngineImpl.sharedClientState.updateMutationState(\n batchId,\n 'rejected',\n error\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes);\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error as FirestoreError);\n }\n}\n\n/**\n * Registers a user callback that resolves when all pending mutations at the moment of calling\n * are acknowledged .\n */\nexport async function syncEngineRegisterPendingWritesCallback(\n syncEngine: SyncEngine,\n callback: Deferred<void>\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n if (!canUseNetwork(syncEngineImpl.remoteStore)) {\n logDebug(\n LOG_TAG,\n 'The network is disabled. The task returned by ' +\n \"'awaitPendingWrites()' will not complete until the network is enabled.\"\n );\n }\n\n try {\n const highestBatchId = await localStoreGetHighestUnacknowledgedBatchId(\n syncEngineImpl.localStore\n );\n if (highestBatchId === BATCHID_UNKNOWN) {\n // Trigger the callback right away if there is no pending writes at the moment.\n callback.resolve();\n return;\n }\n\n const callbacks =\n syncEngineImpl.pendingWritesCallbacks.get(highestBatchId) || [];\n callbacks.push(callback);\n syncEngineImpl.pendingWritesCallbacks.set(highestBatchId, callbacks);\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n 'Initialization of waitForPendingWrites() operation failed'\n );\n callback.reject(firestoreError);\n }\n}\n\n/**\n * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,\n * if there are any.\n */\nfunction triggerPendingWritesCallbacks(\n syncEngineImpl: SyncEngineImpl,\n batchId: BatchId\n): void {\n (syncEngineImpl.pendingWritesCallbacks.get(batchId) || []).forEach(\n callback => {\n callback.resolve();\n }\n );\n\n syncEngineImpl.pendingWritesCallbacks.delete(batchId);\n}\n\n/** Reject all outstanding callbacks waiting for pending writes to complete. */\nfunction rejectOutstandingPendingWritesCallbacks(\n syncEngineImpl: SyncEngineImpl,\n errorMessage: string\n): void {\n syncEngineImpl.pendingWritesCallbacks.forEach(callbacks => {\n callbacks.forEach(callback => {\n callback.reject(new FirestoreError(Code.CANCELLED, errorMessage));\n });\n });\n\n syncEngineImpl.pendingWritesCallbacks.clear();\n}\n\nfunction addMutationCallback(\n syncEngineImpl: SyncEngineImpl,\n batchId: BatchId,\n callback: Deferred<void>\n): void {\n let newCallbacks =\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()];\n if (!newCallbacks) {\n newCallbacks = new SortedMap<BatchId, Deferred<void>>(primitiveComparator);\n }\n newCallbacks = newCallbacks.insert(batchId, callback);\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()] =\n newCallbacks;\n}\n\n/**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */\nfunction processUserCallback(\n syncEngine: SyncEngine,\n batchId: BatchId,\n error: FirestoreError | null\n): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n let newCallbacks =\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()];\n\n // NOTE: Mutations restored from persistence won't have callbacks, so it's\n // okay for there to be no callback for this ID.\n if (newCallbacks) {\n const callback = newCallbacks.get(batchId);\n if (callback) {\n debugAssert(\n batchId === newCallbacks.minKey(),\n 'Mutation callbacks processed out-of-order?'\n );\n if (error) {\n callback.reject(error);\n } else {\n callback.resolve();\n }\n newCallbacks = newCallbacks.remove(batchId);\n }\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()] =\n newCallbacks;\n }\n}\n\nfunction removeAndCleanupTarget(\n syncEngineImpl: SyncEngineImpl,\n targetId: number,\n error: FirestoreError | null = null\n): void {\n syncEngineImpl.sharedClientState.removeLocalQueryTarget(targetId);\n\n debugAssert(\n syncEngineImpl.queriesByTarget.has(targetId) &&\n syncEngineImpl.queriesByTarget.get(targetId)!.length !== 0,\n `There are no queries mapped to target id ${targetId}`\n );\n\n for (const query of syncEngineImpl.queriesByTarget.get(targetId)!) {\n syncEngineImpl.queryViewsByQuery.delete(query);\n if (error) {\n syncEngineImpl.syncEngineListener.onWatchError!(query, error);\n }\n }\n\n syncEngineImpl.queriesByTarget.delete(targetId);\n\n if (syncEngineImpl.isPrimaryClient) {\n const limboKeys =\n syncEngineImpl.limboDocumentRefs.removeReferencesForId(targetId);\n limboKeys.forEach(limboKey => {\n const isReferenced =\n syncEngineImpl.limboDocumentRefs.containsKey(limboKey);\n if (!isReferenced) {\n // We removed the last reference for this key\n removeLimboTarget(syncEngineImpl, limboKey);\n }\n });\n }\n}\n\nfunction removeLimboTarget(\n syncEngineImpl: SyncEngineImpl,\n key: DocumentKey\n): void {\n syncEngineImpl.enqueuedLimboResolutions.delete(key.path.canonicalString());\n\n // It's possible that the target already got removed because the query failed. In that case,\n // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.\n const limboTargetId = syncEngineImpl.activeLimboTargetsByKey.get(key);\n if (limboTargetId === null) {\n // This target already got removed, because the query failed.\n return;\n }\n\n remoteStoreUnlisten(syncEngineImpl.remoteStore, limboTargetId);\n syncEngineImpl.activeLimboTargetsByKey =\n syncEngineImpl.activeLimboTargetsByKey.remove(key);\n syncEngineImpl.activeLimboResolutionsByTarget.delete(limboTargetId);\n pumpEnqueuedLimboResolutions(syncEngineImpl);\n}\n\nfunction updateTrackedLimbos(\n syncEngineImpl: SyncEngineImpl,\n targetId: TargetId,\n limboChanges: LimboDocumentChange[]\n): void {\n for (const limboChange of limboChanges) {\n if (limboChange instanceof AddedLimboDocument) {\n syncEngineImpl.limboDocumentRefs.addReference(limboChange.key, targetId);\n trackLimboChange(syncEngineImpl, limboChange);\n } else if (limboChange instanceof RemovedLimboDocument) {\n logDebug(LOG_TAG, 'Document no longer in limbo: ' + limboChange.key);\n syncEngineImpl.limboDocumentRefs.removeReference(\n limboChange.key,\n targetId\n );\n const isReferenced = syncEngineImpl.limboDocumentRefs.containsKey(\n limboChange.key\n );\n if (!isReferenced) {\n // We removed the last reference for this key\n removeLimboTarget(syncEngineImpl, limboChange.key);\n }\n } else {\n fail('Unknown limbo change: ' + JSON.stringify(limboChange));\n }\n }\n}\n\nfunction trackLimboChange(\n syncEngineImpl: SyncEngineImpl,\n limboChange: AddedLimboDocument\n): void {\n const key = limboChange.key;\n const keyString = key.path.canonicalString();\n if (\n !syncEngineImpl.activeLimboTargetsByKey.get(key) &&\n !syncEngineImpl.enqueuedLimboResolutions.has(keyString)\n ) {\n logDebug(LOG_TAG, 'New document in limbo: ' + key);\n syncEngineImpl.enqueuedLimboResolutions.add(keyString);\n pumpEnqueuedLimboResolutions(syncEngineImpl);\n }\n}\n\n/**\n * Starts listens for documents in limbo that are enqueued for resolution,\n * subject to a maximum number of concurrent resolutions.\n *\n * Without bounding the number of concurrent resolutions, the server can fail\n * with \"resource exhausted\" errors which can lead to pathological client\n * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.\n */\nfunction pumpEnqueuedLimboResolutions(syncEngineImpl: SyncEngineImpl): void {\n while (\n syncEngineImpl.enqueuedLimboResolutions.size > 0 &&\n syncEngineImpl.activeLimboTargetsByKey.size <\n syncEngineImpl.maxConcurrentLimboResolutions\n ) {\n const keyString = syncEngineImpl.enqueuedLimboResolutions\n .values()\n .next().value;\n syncEngineImpl.enqueuedLimboResolutions.delete(keyString);\n const key = new DocumentKey(ResourcePath.fromString(keyString));\n const limboTargetId = syncEngineImpl.limboTargetIdGenerator.next();\n syncEngineImpl.activeLimboResolutionsByTarget.set(\n limboTargetId,\n new LimboResolution(key)\n );\n syncEngineImpl.activeLimboTargetsByKey =\n syncEngineImpl.activeLimboTargetsByKey.insert(key, limboTargetId);\n remoteStoreListen(\n syncEngineImpl.remoteStore,\n new TargetData(\n queryToTarget(newQueryForPath(key.path)),\n limboTargetId,\n TargetPurpose.LimboResolution,\n ListenSequence.INVALID\n )\n );\n }\n}\n\n// Visible for testing\nexport function syncEngineGetActiveLimboDocumentResolutions(\n syncEngine: SyncEngine\n): SortedMap<DocumentKey, TargetId> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n return syncEngineImpl.activeLimboTargetsByKey;\n}\n\n// Visible for testing\nexport function syncEngineGetEnqueuedLimboDocumentResolutions(\n syncEngine: SyncEngine\n): Set<string> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n return syncEngineImpl.enqueuedLimboResolutions;\n}\n\nexport async function syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngine: SyncEngine,\n changes: DocumentMap,\n remoteEvent?: RemoteEvent\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const newSnaps: ViewSnapshot[] = [];\n const docChangesInAllViews: LocalViewChanges[] = [];\n const queriesProcessed: Array<Promise<void>> = [];\n\n if (syncEngineImpl.queryViewsByQuery.isEmpty()) {\n // Return early since `onWatchChange()` might not have been assigned yet.\n return;\n }\n\n syncEngineImpl.queryViewsByQuery.forEach((_, queryView) => {\n debugAssert(\n !!syncEngineImpl.applyDocChanges,\n 'ApplyDocChangesHandler not set'\n );\n queriesProcessed.push(\n syncEngineImpl\n .applyDocChanges(queryView, changes, remoteEvent)\n .then(viewSnapshot => {\n // If there are changes, or we are handling a global snapshot, notify\n // secondary clients to update query state.\n if (viewSnapshot || remoteEvent) {\n if (syncEngineImpl.isPrimaryClient) {\n syncEngineImpl.sharedClientState.updateQueryState(\n queryView.targetId,\n viewSnapshot?.fromCache ? 'not-current' : 'current'\n );\n }\n }\n\n // Update views if there are actual changes.\n if (!!viewSnapshot) {\n newSnaps.push(viewSnapshot);\n const docChanges = LocalViewChanges.fromSnapshot(\n queryView.targetId,\n viewSnapshot\n );\n docChangesInAllViews.push(docChanges);\n }\n })\n );\n });\n\n await Promise.all(queriesProcessed);\n syncEngineImpl.syncEngineListener.onWatchChange!(newSnaps);\n await localStoreNotifyLocalViewChanges(\n syncEngineImpl.localStore,\n docChangesInAllViews\n );\n}\n\nasync function applyDocChanges(\n syncEngineImpl: SyncEngineImpl,\n queryView: QueryView,\n changes: DocumentMap,\n remoteEvent?: RemoteEvent\n): Promise<ViewSnapshot | undefined> {\n let viewDocChanges = queryView.view.computeDocChanges(changes);\n if (viewDocChanges.needsRefill) {\n // The query has a limit and some docs were removed, so we need\n // to re-run the query against the local store to make sure we\n // didn't lose any good docs that had been past the limit.\n viewDocChanges = await localStoreExecuteQuery(\n syncEngineImpl.localStore,\n queryView.query,\n /* usePreviousResults= */ false\n ).then(({ documents }) => {\n return queryView.view.computeDocChanges(documents, viewDocChanges);\n });\n }\n\n const targetChange =\n remoteEvent && remoteEvent.targetChanges.get(queryView.targetId);\n const viewChange = queryView.view.applyChanges(\n viewDocChanges,\n /* updateLimboDocuments= */ syncEngineImpl.isPrimaryClient,\n targetChange\n );\n updateTrackedLimbos(\n syncEngineImpl,\n queryView.targetId,\n viewChange.limboChanges\n );\n return viewChange.snapshot;\n}\n\nexport async function syncEngineHandleCredentialChange(\n syncEngine: SyncEngine,\n user: User\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const userChanged = !syncEngineImpl.currentUser.isEqual(user);\n\n if (userChanged) {\n logDebug(LOG_TAG, 'User change. New user:', user.toKey());\n\n const result = await localStoreHandleUserChange(\n syncEngineImpl.localStore,\n user\n );\n syncEngineImpl.currentUser = user;\n\n // Fails tasks waiting for pending writes requested by previous user.\n rejectOutstandingPendingWritesCallbacks(\n syncEngineImpl,\n \"'waitForPendingWrites' promise is rejected due to a user change.\"\n );\n // TODO(b/114226417): Consider calling this only in the primary tab.\n syncEngineImpl.sharedClientState.handleUserChange(\n user,\n result.removedBatchIds,\n result.addedBatchIds\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n result.affectedDocuments\n );\n }\n}\n\nexport function syncEngineGetRemoteKeysForTarget(\n syncEngine: SyncEngine,\n targetId: TargetId\n): DocumentKeySet {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const limboResolution =\n syncEngineImpl.activeLimboResolutionsByTarget.get(targetId);\n if (limboResolution && limboResolution.receivedDocument) {\n return documentKeySet().add(limboResolution.key);\n } else {\n let keySet = documentKeySet();\n const queries = syncEngineImpl.queriesByTarget.get(targetId);\n if (!queries) {\n return keySet;\n }\n for (const query of queries) {\n const queryView = syncEngineImpl.queryViewsByQuery.get(query);\n debugAssert(\n !!queryView,\n `No query view found for ${stringifyQuery(query)}`\n );\n keySet = keySet.unionWith(queryView.view.syncedDocuments);\n }\n return keySet;\n }\n}\n\n/**\n * Reconcile the list of synced documents in an existing view with those\n * from persistence.\n */\nasync function synchronizeViewAndComputeSnapshot(\n syncEngine: SyncEngine,\n queryView: QueryView\n): Promise<ViewChange> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const queryResult = await localStoreExecuteQuery(\n syncEngineImpl.localStore,\n queryView.query,\n /* usePreviousResults= */ true\n );\n const viewSnapshot =\n queryView.view.synchronizeWithPersistedState(queryResult);\n if (syncEngineImpl.isPrimaryClient) {\n updateTrackedLimbos(\n syncEngineImpl,\n queryView.targetId,\n viewSnapshot.limboChanges\n );\n }\n return viewSnapshot;\n}\n\n/**\n * Retrieves newly changed documents from remote document cache and raises\n * snapshots if needed.\n */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineSynchronizeWithChangedDocuments(\n syncEngine: SyncEngine,\n collectionGroup: string\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n return localStoreGetNewDocumentChanges(\n syncEngineImpl.localStore,\n collectionGroup\n ).then(changes =>\n syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes)\n );\n}\n\n/** Applies a mutation state to an existing batch. */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineApplyBatchState(\n syncEngine: SyncEngine,\n batchId: BatchId,\n batchState: MutationBatchState,\n error?: FirestoreError\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const documents = await localStoreLookupMutationDocuments(\n syncEngineImpl.localStore,\n batchId\n );\n\n if (documents === null) {\n // A throttled tab may not have seen the mutation before it was completed\n // and removed from the mutation queue, in which case we won't have cached\n // the affected documents. In this case we can safely ignore the update\n // since that means we didn't apply the mutation locally at all (if we\n // had, we would have cached the affected documents), and so we will just\n // see any resulting document changes via normal remote document updates\n // as applicable.\n logDebug(LOG_TAG, 'Cannot apply mutation batch with id: ' + batchId);\n return;\n }\n\n if (batchState === 'pending') {\n // If we are the primary client, we need to send this write to the\n // backend. Secondary clients will ignore these writes since their remote\n // connection is disabled.\n await fillWritePipeline(syncEngineImpl.remoteStore);\n } else if (batchState === 'acknowledged' || batchState === 'rejected') {\n // NOTE: Both these methods are no-ops for batches that originated from\n // other clients.\n processUserCallback(syncEngineImpl, batchId, error ? error : null);\n triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n localStoreRemoveCachedMutationBatchMetadata(\n syncEngineImpl.localStore,\n batchId\n );\n } else {\n fail(`Unknown batchState: ${batchState}`);\n }\n\n await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, documents);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineApplyPrimaryState(\n syncEngine: SyncEngine,\n isPrimary: boolean\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n ensureWatchCallbacks(syncEngineImpl);\n syncEngineEnsureWriteCallbacks(syncEngineImpl);\n if (isPrimary === true && syncEngineImpl._isPrimaryClient !== true) {\n // Secondary tabs only maintain Views for their local listeners and the\n // Views internal state may not be 100% populated (in particular\n // secondary tabs don't track syncedDocuments, the set of documents the\n // server considers to be in the target). So when a secondary becomes\n // primary, we need to need to make sure that all views for all targets\n // match the state on disk.\n const activeTargets =\n syncEngineImpl.sharedClientState.getAllActiveQueryTargets();\n const activeQueries = await synchronizeQueryViewsAndRaiseSnapshots(\n syncEngineImpl,\n activeTargets.toArray(),\n /*transitionToPrimary=*/ true\n );\n syncEngineImpl._isPrimaryClient = true;\n await remoteStoreApplyPrimaryState(syncEngineImpl.remoteStore, true);\n for (const targetData of activeQueries) {\n remoteStoreListen(syncEngineImpl.remoteStore, targetData);\n }\n } else if (isPrimary === false && syncEngineImpl._isPrimaryClient !== false) {\n const activeTargets: TargetId[] = [];\n\n let p = Promise.resolve();\n syncEngineImpl.queriesByTarget.forEach((_, targetId) => {\n if (syncEngineImpl.sharedClientState.isLocalQueryTarget(targetId)) {\n activeTargets.push(targetId);\n } else {\n p = p.then(() => {\n removeAndCleanupTarget(syncEngineImpl, targetId);\n return localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /*keepPersistedTargetData=*/ true\n );\n });\n }\n remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId);\n });\n await p;\n\n await synchronizeQueryViewsAndRaiseSnapshots(\n syncEngineImpl,\n activeTargets,\n /*transitionToPrimary=*/ false\n );\n resetLimboDocuments(syncEngineImpl);\n syncEngineImpl._isPrimaryClient = false;\n await remoteStoreApplyPrimaryState(syncEngineImpl.remoteStore, false);\n }\n}\n\n// PORTING NOTE: Multi-Tab only.\nfunction resetLimboDocuments(syncEngine: SyncEngine): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n syncEngineImpl.activeLimboResolutionsByTarget.forEach((_, targetId) => {\n remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId);\n });\n syncEngineImpl.limboDocumentRefs.removeAllReferences();\n syncEngineImpl.activeLimboResolutionsByTarget = new Map<\n TargetId,\n LimboResolution\n >();\n syncEngineImpl.activeLimboTargetsByKey = new SortedMap<DocumentKey, TargetId>(\n DocumentKey.comparator\n );\n}\n\n/**\n * Reconcile the query views of the provided query targets with the state from\n * persistence. Raises snapshots for any changes that affect the local\n * client and returns the updated state of all target's query data.\n *\n * @param syncEngine - The sync engine implementation\n * @param targets - the list of targets with views that need to be recomputed\n * @param transitionToPrimary - `true` iff the tab transitions from a secondary\n * tab to a primary tab\n */\n// PORTING NOTE: Multi-Tab only.\nasync function synchronizeQueryViewsAndRaiseSnapshots(\n syncEngine: SyncEngine,\n targets: TargetId[],\n transitionToPrimary: boolean\n): Promise<TargetData[]> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const activeQueries: TargetData[] = [];\n const newViewSnapshots: ViewSnapshot[] = [];\n for (const targetId of targets) {\n let targetData: TargetData;\n const queries = syncEngineImpl.queriesByTarget.get(targetId);\n\n if (queries && queries.length !== 0) {\n // For queries that have a local View, we fetch their current state\n // from LocalStore (as the resume token and the snapshot version\n // might have changed) and reconcile their views with the persisted\n // state (the list of syncedDocuments may have gotten out of sync).\n targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n queryToTarget(queries[0])\n );\n\n for (const query of queries) {\n const queryView = syncEngineImpl.queryViewsByQuery.get(query);\n debugAssert(\n !!queryView,\n `No query view found for ${stringifyQuery(query)}`\n );\n\n const viewChange = await synchronizeViewAndComputeSnapshot(\n syncEngineImpl,\n queryView\n );\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n }\n } else {\n debugAssert(\n transitionToPrimary,\n 'A secondary tab should never have an active view without an active target.'\n );\n // For queries that never executed on this client, we need to\n // allocate the target in LocalStore and initialize a new View.\n const target = await localStoreGetCachedTarget(\n syncEngineImpl.localStore,\n targetId\n );\n debugAssert(!!target, `Target for id ${targetId} not found`);\n targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n target\n );\n await initializeViewAndComputeSnapshot(\n syncEngineImpl,\n synthesizeTargetToQuery(target!),\n targetId,\n /*current=*/ false,\n targetData.resumeToken\n );\n }\n\n activeQueries.push(targetData!);\n }\n\n syncEngineImpl.syncEngineListener.onWatchChange!(newViewSnapshots);\n return activeQueries;\n}\n\n/**\n * Creates a `Query` object from the specified `Target`. There is no way to\n * obtain the original `Query`, so we synthesize a `Query` from the `Target`\n * object.\n *\n * The synthesized result might be different from the original `Query`, but\n * since the synthesized `Query` should return the same results as the\n * original one (only the presentation of results might differ), the potential\n * difference will not cause issues.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction synthesizeTargetToQuery(target: Target): Query {\n return newQuery(\n target.path,\n target.collectionGroup,\n target.orderBy,\n target.filters,\n target.limit,\n LimitType.First,\n target.startAt,\n target.endAt\n );\n}\n\n/** Returns the IDs of the clients that are currently active. */\n// PORTING NOTE: Multi-Tab only.\nexport function syncEngineGetActiveClients(\n syncEngine: SyncEngine\n): Promise<ClientId[]> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n return localStoreGetActiveClients(syncEngineImpl.localStore);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineApplyTargetState(\n syncEngine: SyncEngine,\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n if (syncEngineImpl._isPrimaryClient) {\n // If we receive a target state notification via WebStorage, we are\n // either already secondary or another tab has taken the primary lease.\n logDebug(LOG_TAG, 'Ignoring unexpected query state notification.');\n return;\n }\n\n const query = syncEngineImpl.queriesByTarget.get(targetId);\n if (query && query.length > 0) {\n switch (state) {\n case 'current':\n case 'not-current': {\n const changes = await localStoreGetNewDocumentChanges(\n syncEngineImpl.localStore,\n queryCollectionGroup(query[0])\n );\n const synthesizedRemoteEvent =\n RemoteEvent.createSynthesizedRemoteEventForCurrentChange(\n targetId,\n state === 'current',\n ByteString.EMPTY_BYTE_STRING\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n changes,\n synthesizedRemoteEvent\n );\n break;\n }\n case 'rejected': {\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /* keepPersistedTargetData */ true\n );\n removeAndCleanupTarget(syncEngineImpl, targetId, error);\n break;\n }\n default:\n fail('Unexpected target state: ' + state);\n }\n }\n}\n\n/** Adds or removes Watch targets for queries from different tabs. */\nexport async function syncEngineApplyActiveTargetsChange(\n syncEngine: SyncEngine,\n added: TargetId[],\n removed: TargetId[]\n): Promise<void> {\n const syncEngineImpl = ensureWatchCallbacks(syncEngine);\n if (!syncEngineImpl._isPrimaryClient) {\n return;\n }\n\n for (const targetId of added) {\n if (syncEngineImpl.queriesByTarget.has(targetId)) {\n // A target might have been added in a previous attempt\n logDebug(LOG_TAG, 'Adding an already active target ' + targetId);\n continue;\n }\n\n const target = await localStoreGetCachedTarget(\n syncEngineImpl.localStore,\n targetId\n );\n debugAssert(!!target, `Query data for active target ${targetId} not found`);\n const targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n target\n );\n await initializeViewAndComputeSnapshot(\n syncEngineImpl,\n synthesizeTargetToQuery(target),\n targetData.targetId,\n /*current=*/ false,\n targetData.resumeToken\n );\n remoteStoreListen(syncEngineImpl.remoteStore, targetData);\n }\n\n for (const targetId of removed) {\n // Check that the target is still active since the target might have been\n // removed if it has been rejected by the backend.\n if (!syncEngineImpl.queriesByTarget.has(targetId)) {\n continue;\n }\n\n // Release queries that are still active.\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /* keepPersistedTargetData */ false\n )\n .then(() => {\n remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId);\n removeAndCleanupTarget(syncEngineImpl, targetId);\n })\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n}\n\nfunction ensureWatchCallbacks(syncEngine: SyncEngine): SyncEngineImpl {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.applyRemoteEvent =\n syncEngineApplyRemoteEvent.bind(null, syncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.getRemoteKeysForTarget =\n syncEngineGetRemoteKeysForTarget.bind(null, syncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.rejectListen =\n syncEngineRejectListen.bind(null, syncEngineImpl);\n syncEngineImpl.syncEngineListener.onWatchChange =\n eventManagerOnWatchChange.bind(null, syncEngineImpl.eventManager);\n syncEngineImpl.syncEngineListener.onWatchError =\n eventManagerOnWatchError.bind(null, syncEngineImpl.eventManager);\n return syncEngineImpl;\n}\n\nexport function syncEngineEnsureWriteCallbacks(\n syncEngine: SyncEngine\n): SyncEngineImpl {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.applySuccessfulWrite =\n syncEngineApplySuccessfulWrite.bind(null, syncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.rejectFailedWrite =\n syncEngineRejectFailedWrite.bind(null, syncEngineImpl);\n return syncEngineImpl;\n}\n\n/**\n * Loads a Firestore bundle into the SDK. The returned promise resolves when\n * the bundle finished loading.\n *\n * @param syncEngine - SyncEngine to use.\n * @param bundleReader - Bundle to load into the SDK.\n * @param task - LoadBundleTask used to update the loading progress to public API.\n */\nexport function syncEngineLoadBundle(\n syncEngine: SyncEngine,\n bundleReader: BundleReader,\n task: LoadBundleTask\n): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n loadBundleImpl(syncEngineImpl, bundleReader, task).then(collectionGroups => {\n syncEngineImpl.sharedClientState.notifyBundleLoaded(collectionGroups);\n });\n}\n\n/** Loads a bundle and returns the list of affected collection groups. */\nasync function loadBundleImpl(\n syncEngine: SyncEngineImpl,\n reader: BundleReader,\n task: LoadBundleTask\n): Promise<Set<string>> {\n try {\n const metadata = await reader.getMetadata();\n const skip = await localStoreHasNewerBundle(\n syncEngine.localStore,\n metadata\n );\n if (skip) {\n await reader.close();\n task._completeWith(bundleSuccessProgress(metadata));\n return Promise.resolve(new Set<string>());\n }\n\n task._updateProgress(bundleInitialProgress(metadata));\n\n const loader = new BundleLoader(\n metadata,\n syncEngine.localStore,\n reader.serializer\n );\n let element = await reader.nextElement();\n while (element) {\n debugAssert(\n !element.payload.metadata,\n 'Unexpected BundleMetadata element.'\n );\n const progress = await loader.addSizedElement(element);\n if (progress) {\n task._updateProgress(progress);\n }\n\n element = await reader.nextElement();\n }\n\n const result = await loader.complete();\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngine,\n result.changedDocs,\n /* remoteEvent */ undefined\n );\n\n // Save metadata, so loading the same bundle will skip.\n await localStoreSaveBundle(syncEngine.localStore, metadata);\n task._completeWith(result.progress);\n return Promise.resolve(result.changedCollectionGroups);\n } catch (e) {\n logWarn(LOG_TAG, `Loading bundle failed with ${e}`);\n task._failWith(e as FirestoreError);\n return Promise.resolve(new Set<string>());\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport {\n IndexBackfiller,\n IndexBackfillerScheduler\n} from '../local/index_backfiller';\nimport {\n indexedDbStoragePrefix,\n IndexedDbPersistence\n} from '../local/indexeddb_persistence';\nimport { LocalStore } from '../local/local_store';\nimport { newLocalStore } from '../local/local_store_impl';\nimport { LruParams } from '../local/lru_garbage_collector';\nimport { LruScheduler } from '../local/lru_garbage_collector_impl';\nimport {\n MemoryEagerDelegate,\n MemoryLruDelegate,\n MemoryPersistence\n} from '../local/memory_persistence';\nimport { Scheduler, Persistence } from '../local/persistence';\nimport { QueryEngine } from '../local/query_engine';\nimport {\n ClientId,\n MemorySharedClientState,\n SharedClientState,\n WebStorageSharedClientState\n} from '../local/shared_client_state';\nimport { newConnection, newConnectivityMonitor } from '../platform/connection';\nimport { getDocument, getWindow } from '../platform/dom';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport {\n fillWritePipeline,\n newRemoteStore,\n RemoteStore,\n remoteStoreApplyPrimaryState,\n remoteStoreShutdown\n} from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { DatabaseInfo } from './database_info';\nimport { EventManager, newEventManager } from './event_manager';\nimport { SyncEngine } from './sync_engine';\nimport {\n newSyncEngine,\n syncEngineApplyActiveTargetsChange,\n syncEngineApplyBatchState,\n syncEngineApplyOnlineStateChange,\n syncEngineApplyPrimaryState,\n syncEngineApplyTargetState,\n syncEngineEnsureWriteCallbacks,\n syncEngineGetActiveClients,\n syncEngineHandleCredentialChange,\n syncEngineSynchronizeWithChangedDocuments\n} from './sync_engine_impl';\nimport { OnlineStateSource } from './types';\n\nexport interface ComponentConfiguration {\n asyncQueue: AsyncQueue;\n databaseInfo: DatabaseInfo;\n authCredentials: CredentialsProvider<User>;\n appCheckCredentials: CredentialsProvider<string>;\n clientId: ClientId;\n initialUser: User;\n maxConcurrentLimboResolutions: number;\n}\n\n/**\n * Initializes and wires components that are needed to interface with the local\n * cache. Implementations override `initialize()` to provide all components.\n */\nexport interface OfflineComponentProvider {\n persistence: Persistence;\n sharedClientState: SharedClientState;\n localStore: LocalStore;\n gcScheduler: Scheduler | null;\n indexBackfillerScheduler: Scheduler | null;\n synchronizeTabs: boolean;\n\n initialize(cfg: ComponentConfiguration): Promise<void>;\n\n terminate(): Promise<void>;\n}\n\n/**\n * Provides all components needed for Firestore with in-memory persistence.\n * Uses EagerGC garbage collection.\n */\nexport class MemoryOfflineComponentProvider\n implements OfflineComponentProvider\n{\n persistence!: Persistence;\n sharedClientState!: SharedClientState;\n localStore!: LocalStore;\n gcScheduler!: Scheduler | null;\n indexBackfillerScheduler!: Scheduler | null;\n synchronizeTabs = false;\n\n serializer!: JsonProtoSerializer;\n\n async initialize(cfg: ComponentConfiguration): Promise<void> {\n this.serializer = newSerializer(cfg.databaseInfo.databaseId);\n this.sharedClientState = this.createSharedClientState(cfg);\n this.persistence = this.createPersistence(cfg);\n await this.persistence.start();\n this.localStore = this.createLocalStore(cfg);\n this.gcScheduler = this.createGarbageCollectionScheduler(\n cfg,\n this.localStore\n );\n this.indexBackfillerScheduler = this.createIndexBackfillerScheduler(\n cfg,\n this.localStore\n );\n }\n\n createGarbageCollectionScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n return null;\n }\n\n createIndexBackfillerScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n return null;\n }\n\n createLocalStore(cfg: ComponentConfiguration): LocalStore {\n return newLocalStore(\n this.persistence,\n new QueryEngine(),\n cfg.initialUser,\n this.serializer\n );\n }\n\n createPersistence(cfg: ComponentConfiguration): Persistence {\n return new MemoryPersistence(MemoryEagerDelegate.factory, this.serializer);\n }\n\n createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n return new MemorySharedClientState();\n }\n\n async terminate(): Promise<void> {\n if (this.gcScheduler) {\n this.gcScheduler.stop();\n }\n await this.sharedClientState.shutdown();\n await this.persistence.shutdown();\n }\n}\n\nexport class LruGcMemoryOfflineComponentProvider extends MemoryOfflineComponentProvider {\n constructor(protected readonly cacheSizeBytes: number | undefined) {\n super();\n }\n\n createGarbageCollectionScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n hardAssert(\n this.persistence.referenceDelegate instanceof MemoryLruDelegate,\n 'referenceDelegate is expected to be an instance of MemoryLruDelegate.'\n );\n\n const garbageCollector =\n this.persistence.referenceDelegate.garbageCollector;\n return new LruScheduler(garbageCollector, cfg.asyncQueue, localStore);\n }\n\n createPersistence(cfg: ComponentConfiguration): Persistence {\n const lruParams =\n this.cacheSizeBytes !== undefined\n ? LruParams.withCacheSize(this.cacheSizeBytes)\n : LruParams.DEFAULT;\n return new MemoryPersistence(\n p => MemoryLruDelegate.factory(p, lruParams),\n this.serializer\n );\n }\n}\n\n/**\n * Provides all components needed for Firestore with IndexedDB persistence.\n */\nexport class IndexedDbOfflineComponentProvider extends MemoryOfflineComponentProvider {\n persistence!: IndexedDbPersistence;\n sharedClientState!: SharedClientState;\n localStore!: LocalStore;\n gcScheduler!: Scheduler | null;\n indexBackfillerScheduler!: Scheduler | null;\n synchronizeTabs = false;\n\n constructor(\n protected readonly onlineComponentProvider: OnlineComponentProvider,\n protected readonly cacheSizeBytes: number | undefined,\n protected readonly forceOwnership: boolean | undefined\n ) {\n super();\n }\n\n async initialize(cfg: ComponentConfiguration): Promise<void> {\n await super.initialize(cfg);\n\n await this.onlineComponentProvider.initialize(this, cfg);\n\n // Enqueue writes from a previous session\n await syncEngineEnsureWriteCallbacks(\n this.onlineComponentProvider.syncEngine\n );\n await fillWritePipeline(this.onlineComponentProvider.remoteStore);\n\n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.setPrimaryStateListener(() => {\n if (this.gcScheduler && !this.gcScheduler.started) {\n this.gcScheduler.start();\n }\n if (\n this.indexBackfillerScheduler &&\n !this.indexBackfillerScheduler.started\n ) {\n this.indexBackfillerScheduler.start();\n }\n return Promise.resolve();\n });\n }\n\n createLocalStore(cfg: ComponentConfiguration): LocalStore {\n return newLocalStore(\n this.persistence,\n new QueryEngine(),\n cfg.initialUser,\n this.serializer\n );\n }\n\n createGarbageCollectionScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n const garbageCollector =\n this.persistence.referenceDelegate.garbageCollector;\n return new LruScheduler(garbageCollector, cfg.asyncQueue, localStore);\n }\n\n createIndexBackfillerScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n const indexBackfiller = new IndexBackfiller(localStore, this.persistence);\n return new IndexBackfillerScheduler(cfg.asyncQueue, indexBackfiller);\n }\n\n createPersistence(cfg: ComponentConfiguration): IndexedDbPersistence {\n const persistenceKey = indexedDbStoragePrefix(\n cfg.databaseInfo.databaseId,\n cfg.databaseInfo.persistenceKey\n );\n const lruParams =\n this.cacheSizeBytes !== undefined\n ? LruParams.withCacheSize(this.cacheSizeBytes)\n : LruParams.DEFAULT;\n\n return new IndexedDbPersistence(\n this.synchronizeTabs,\n persistenceKey,\n cfg.clientId,\n lruParams,\n cfg.asyncQueue,\n getWindow(),\n getDocument(),\n this.serializer,\n this.sharedClientState,\n !!this.forceOwnership\n );\n }\n\n createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n return new MemorySharedClientState();\n }\n}\n\n/**\n * Provides all components needed for Firestore with multi-tab IndexedDB\n * persistence.\n *\n * In the legacy client, this provider is used to provide both multi-tab and\n * non-multi-tab persistence since we cannot tell at build time whether\n * `synchronizeTabs` will be enabled.\n */\nexport class MultiTabOfflineComponentProvider extends IndexedDbOfflineComponentProvider {\n synchronizeTabs = true;\n\n constructor(\n protected readonly onlineComponentProvider: OnlineComponentProvider,\n protected readonly cacheSizeBytes: number | undefined\n ) {\n super(onlineComponentProvider, cacheSizeBytes, /* forceOwnership= */ false);\n }\n\n async initialize(cfg: ComponentConfiguration): Promise<void> {\n await super.initialize(cfg);\n\n const syncEngine = this.onlineComponentProvider.syncEngine;\n\n if (this.sharedClientState instanceof WebStorageSharedClientState) {\n this.sharedClientState.syncEngine = {\n applyBatchState: syncEngineApplyBatchState.bind(null, syncEngine),\n applyTargetState: syncEngineApplyTargetState.bind(null, syncEngine),\n applyActiveTargetsChange: syncEngineApplyActiveTargetsChange.bind(\n null,\n syncEngine\n ),\n getActiveClients: syncEngineGetActiveClients.bind(null, syncEngine),\n synchronizeWithChangedDocuments:\n syncEngineSynchronizeWithChangedDocuments.bind(null, syncEngine)\n };\n await this.sharedClientState.start();\n }\n\n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.setPrimaryStateListener(async isPrimary => {\n await syncEngineApplyPrimaryState(\n this.onlineComponentProvider.syncEngine,\n isPrimary\n );\n if (this.gcScheduler) {\n if (isPrimary && !this.gcScheduler.started) {\n this.gcScheduler.start();\n } else if (!isPrimary) {\n this.gcScheduler.stop();\n }\n }\n if (this.indexBackfillerScheduler) {\n if (isPrimary && !this.indexBackfillerScheduler.started) {\n this.indexBackfillerScheduler.start();\n } else if (!isPrimary) {\n this.indexBackfillerScheduler.stop();\n }\n }\n });\n }\n\n createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n const window = getWindow();\n if (!WebStorageSharedClientState.isAvailable(window)) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'IndexedDB persistence is only available on platforms that support LocalStorage.'\n );\n }\n const persistenceKey = indexedDbStoragePrefix(\n cfg.databaseInfo.databaseId,\n cfg.databaseInfo.persistenceKey\n );\n return new WebStorageSharedClientState(\n window,\n cfg.asyncQueue,\n persistenceKey,\n cfg.clientId,\n cfg.initialUser\n );\n }\n}\n\n/**\n * Initializes and wires the components that are needed to interface with the\n * network.\n */\nexport class OnlineComponentProvider {\n protected localStore!: LocalStore;\n protected sharedClientState!: SharedClientState;\n datastore!: Datastore;\n eventManager!: EventManager;\n remoteStore!: RemoteStore;\n syncEngine!: SyncEngine;\n\n async initialize(\n offlineComponentProvider: OfflineComponentProvider,\n cfg: ComponentConfiguration\n ): Promise<void> {\n if (this.localStore) {\n // OnlineComponentProvider may get initialized multiple times if\n // multi-tab persistence is used.\n return;\n }\n\n this.localStore = offlineComponentProvider.localStore;\n this.sharedClientState = offlineComponentProvider.sharedClientState;\n this.datastore = this.createDatastore(cfg);\n this.remoteStore = this.createRemoteStore(cfg);\n this.eventManager = this.createEventManager(cfg);\n this.syncEngine = this.createSyncEngine(\n cfg,\n /* startAsPrimary=*/ !offlineComponentProvider.synchronizeTabs\n );\n\n this.sharedClientState.onlineStateHandler = onlineState =>\n syncEngineApplyOnlineStateChange(\n this.syncEngine,\n onlineState,\n OnlineStateSource.SharedClientState\n );\n\n this.remoteStore.remoteSyncer.handleCredentialChange =\n syncEngineHandleCredentialChange.bind(null, this.syncEngine);\n\n await remoteStoreApplyPrimaryState(\n this.remoteStore,\n this.syncEngine.isPrimaryClient\n );\n }\n\n createEventManager(cfg: ComponentConfiguration): EventManager {\n return newEventManager();\n }\n\n createDatastore(cfg: ComponentConfiguration): Datastore {\n const serializer = newSerializer(cfg.databaseInfo.databaseId);\n const connection = newConnection(cfg.databaseInfo);\n return newDatastore(\n cfg.authCredentials,\n cfg.appCheckCredentials,\n connection,\n serializer\n );\n }\n\n createRemoteStore(cfg: ComponentConfiguration): RemoteStore {\n return newRemoteStore(\n this.localStore,\n this.datastore,\n cfg.asyncQueue,\n onlineState =>\n syncEngineApplyOnlineStateChange(\n this.syncEngine,\n onlineState,\n OnlineStateSource.RemoteStore\n ),\n newConnectivityMonitor()\n );\n }\n\n createSyncEngine(\n cfg: ComponentConfiguration,\n startAsPrimary: boolean\n ): SyncEngine {\n return newSyncEngine(\n this.localStore,\n this.remoteStore,\n this.eventManager,\n this.sharedClientState,\n cfg.initialUser,\n cfg.maxConcurrentLimboResolutions,\n startAsPrimary\n );\n }\n\n terminate(): Promise<void> {\n return remoteStoreShutdown(this.remoteStore);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseInfo } from '../../core/database_info';\nimport { Connection } from '../../remote/connection';\nimport { ConnectivityMonitor } from '../../remote/connectivity_monitor';\nimport { NoopConnectivityMonitor } from '../../remote/connectivity_monitor_noop';\n\nimport { BrowserConnectivityMonitor } from './connectivity_monitor';\nimport { WebChannelConnection } from './webchannel_connection';\n\n/** Initializes the WebChannelConnection for the browser. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n return new WebChannelConnection(databaseInfo);\n}\n\n/** Return the Platform-specific connectivity monitor. */\nexport function newConnectivityMonitor(): ConnectivityMonitor {\n if (BrowserConnectivityMonitor.isAvailable()) {\n return new BrowserConnectivityMonitor();\n } else {\n return new NoopConnectivityMonitor();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Observer } from '../core/event_manager';\n\nimport { FirestoreError } from './error';\nimport { logError } from './log';\nimport { EventHandler } from './misc';\n\n/*\n * A wrapper implementation of Observer<T> that will dispatch events\n * asynchronously. To allow immediate silencing, a mute call is added which\n * causes events scheduled to no longer be raised.\n */\nexport class AsyncObserver<T> implements Observer<T> {\n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n private muted = false;\n\n constructor(private observer: Partial<Observer<T>>) {}\n\n next(value: T): void {\n if (this.observer.next) {\n this.scheduleEvent(this.observer.next, value);\n }\n }\n\n error(error: FirestoreError): void {\n if (this.observer.error) {\n this.scheduleEvent(this.observer.error, error);\n } else {\n logError('Uncaught Error in snapshot listener:', error.toString());\n }\n }\n\n mute(): void {\n this.muted = true;\n }\n\n private scheduleEvent<E>(eventHandler: EventHandler<E>, event: E): void {\n if (!this.muted) {\n setTimeout(() => {\n if (!this.muted) {\n eventHandler(event);\n }\n }, 0);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GetOptions } from '@firebase/firestore-types';\n\nimport { LoadBundleTask } from '../api/bundle';\nimport {\n CredentialChangeListener,\n CredentialsProvider\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreConfigureFieldIndexes,\n localStoreDeleteAllFieldIndexes,\n localStoreExecuteQuery,\n localStoreGetNamedQuery,\n localStoreHandleUserChange,\n localStoreReadDocument,\n localStoreSetIndexAutoCreationEnabled\n} from '../local/local_store_impl';\nimport { Persistence } from '../local/persistence';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex } from '../model/field_index';\nimport { Mutation } from '../model/mutation';\nimport { toByteStreamReader } from '../platform/byte_stream_reader';\nimport { newSerializer } from '../platform/serializer';\nimport { newTextEncoder } from '../platform/text_serializer';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { Datastore, invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport {\n RemoteStore,\n remoteStoreDisableNetwork,\n remoteStoreEnableNetwork,\n remoteStoreHandleCredentialChange\n} from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncObserver } from '../util/async_observer';\nimport { AsyncQueue, wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { BundleReader } from '../util/bundle_reader';\nimport { newBundleReader } from '../util/bundle_reader_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { AutoId } from '../util/misc';\nimport { Deferred } from '../util/promise';\n\nimport { Aggregate } from './aggregate';\nimport { NamedQuery } from './bundle';\nimport {\n ComponentConfiguration,\n MemoryOfflineComponentProvider,\n OfflineComponentProvider,\n OnlineComponentProvider\n} from './component_provider';\nimport { DatabaseId, DatabaseInfo } from './database_info';\nimport {\n addSnapshotsInSyncListener,\n EventManager,\n eventManagerListen,\n eventManagerUnlisten,\n ListenOptions,\n Observer,\n QueryListener,\n removeSnapshotsInSyncListener\n} from './event_manager';\nimport { newQueryForPath, Query } from './query';\nimport { SyncEngine } from './sync_engine';\nimport {\n syncEngineListen,\n syncEngineLoadBundle,\n syncEngineRegisterPendingWritesCallback,\n syncEngineUnlisten,\n syncEngineWrite\n} from './sync_engine_impl';\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\nimport { TransactionRunner } from './transaction_runner';\nimport { View } from './view';\nimport { ViewSnapshot } from './view_snapshot';\n\nconst LOG_TAG = 'FirestoreClient';\nexport const MAX_CONCURRENT_LIMBO_RESOLUTIONS = 100;\n\n/** DOMException error code constants. */\nconst DOM_EXCEPTION_INVALID_STATE = 11;\nconst DOM_EXCEPTION_ABORTED = 20;\nconst DOM_EXCEPTION_QUOTA_EXCEEDED = 22;\n\n/**\n * FirestoreClient is a top-level class that constructs and owns all of the //\n * pieces of the client SDK architecture. It is responsible for creating the //\n * async queue that is shared by all of the other components in the system. //\n */\nexport class FirestoreClient {\n private user = User.UNAUTHENTICATED;\n private readonly clientId = AutoId.newId();\n private authCredentialListener: CredentialChangeListener<User> = () =>\n Promise.resolve();\n private appCheckCredentialListener: (\n appCheckToken: string,\n user: User\n ) => Promise<void> = () => Promise.resolve();\n _uninitializedComponentsProvider?: {\n _offline: OfflineComponentProvider;\n _offlineKind: 'memory' | 'persistent';\n _online: OnlineComponentProvider;\n };\n\n _offlineComponents?: OfflineComponentProvider;\n _onlineComponents?: OnlineComponentProvider;\n\n constructor(\n private authCredentials: CredentialsProvider<User>,\n private appCheckCredentials: CredentialsProvider<string>,\n /**\n * Asynchronous queue responsible for all of our internal processing. When\n * we get incoming work from the user (via public API) or the network\n * (incoming GRPC messages), we should always schedule onto this queue.\n * This ensures all of our work is properly serialized (e.g. we don't\n * start processing a new operation while the previous one is waiting for\n * an async I/O to complete).\n */\n public asyncQueue: AsyncQueue,\n private databaseInfo: DatabaseInfo\n ) {\n this.authCredentials.start(asyncQueue, async user => {\n logDebug(LOG_TAG, 'Received user=', user.uid);\n await this.authCredentialListener(user);\n this.user = user;\n });\n this.appCheckCredentials.start(asyncQueue, newAppCheckToken => {\n logDebug(LOG_TAG, 'Received new app check token=', newAppCheckToken);\n return this.appCheckCredentialListener(newAppCheckToken, this.user);\n });\n }\n\n async getConfiguration(): Promise<ComponentConfiguration> {\n return {\n asyncQueue: this.asyncQueue,\n databaseInfo: this.databaseInfo,\n clientId: this.clientId,\n authCredentials: this.authCredentials,\n appCheckCredentials: this.appCheckCredentials,\n initialUser: this.user,\n maxConcurrentLimboResolutions: MAX_CONCURRENT_LIMBO_RESOLUTIONS\n };\n }\n\n setCredentialChangeListener(listener: (user: User) => Promise<void>): void {\n this.authCredentialListener = listener;\n }\n\n setAppCheckTokenChangeListener(\n listener: (appCheckToken: string, user: User) => Promise<void>\n ): void {\n this.appCheckCredentialListener = listener;\n }\n\n /**\n * Checks that the client has not been terminated. Ensures that other methods on //\n * this class cannot be called after the client is terminated. //\n */\n verifyNotTerminated(): void {\n if (this.asyncQueue.isShuttingDown) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n terminate(): Promise<void> {\n this.asyncQueue.enterRestrictedMode();\n const deferred = new Deferred();\n this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async () => {\n try {\n if (this._onlineComponents) {\n await this._onlineComponents.terminate();\n }\n if (this._offlineComponents) {\n await this._offlineComponents.terminate();\n }\n\n // The credentials provider must be terminated after shutting down the\n // RemoteStore as it will prevent the RemoteStore from retrieving auth\n // tokens.\n this.authCredentials.shutdown();\n this.appCheckCredentials.shutdown();\n deferred.resolve();\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to shutdown persistence`\n );\n deferred.reject(firestoreError);\n }\n });\n return deferred.promise;\n }\n}\n\nexport async function setOfflineComponentProvider(\n client: FirestoreClient,\n offlineComponentProvider: OfflineComponentProvider\n): Promise<void> {\n client.asyncQueue.verifyOperationInProgress();\n\n logDebug(LOG_TAG, 'Initializing OfflineComponentProvider');\n const configuration = await client.getConfiguration();\n await offlineComponentProvider.initialize(configuration);\n\n let currentUser = configuration.initialUser;\n client.setCredentialChangeListener(async user => {\n if (!currentUser.isEqual(user)) {\n await localStoreHandleUserChange(\n offlineComponentProvider.localStore,\n user\n );\n currentUser = user;\n }\n });\n\n // When a user calls clearPersistence() in one client, all other clients\n // need to be terminated to allow the delete to succeed.\n offlineComponentProvider.persistence.setDatabaseDeletedListener(() =>\n client.terminate()\n );\n\n client._offlineComponents = offlineComponentProvider;\n}\n\nexport async function setOnlineComponentProvider(\n client: FirestoreClient,\n onlineComponentProvider: OnlineComponentProvider\n): Promise<void> {\n client.asyncQueue.verifyOperationInProgress();\n\n const offlineComponentProvider = await ensureOfflineComponents(client);\n\n logDebug(LOG_TAG, 'Initializing OnlineComponentProvider');\n const configuration = await client.getConfiguration();\n await onlineComponentProvider.initialize(\n offlineComponentProvider,\n configuration\n );\n // The CredentialChangeListener of the online component provider takes\n // precedence over the offline component provider.\n client.setCredentialChangeListener(user =>\n remoteStoreHandleCredentialChange(onlineComponentProvider.remoteStore, user)\n );\n client.setAppCheckTokenChangeListener((_, user) =>\n remoteStoreHandleCredentialChange(onlineComponentProvider.remoteStore, user)\n );\n client._onlineComponents = onlineComponentProvider;\n}\n\n/**\n * Decides whether the provided error allows us to gracefully disable\n * persistence (as opposed to crashing the client).\n */\nexport function canFallbackFromIndexedDbError(\n error: FirestoreError | DOMException\n): boolean {\n if (error.name === 'FirebaseError') {\n return (\n error.code === Code.FAILED_PRECONDITION ||\n error.code === Code.UNIMPLEMENTED\n );\n } else if (\n typeof DOMException !== 'undefined' &&\n error instanceof DOMException\n ) {\n // There are a few known circumstances where we can open IndexedDb but\n // trying to read/write will fail (e.g. quota exceeded). For\n // well-understood cases, we attempt to detect these and then gracefully\n // fall back to memory persistence.\n // NOTE: Rather than continue to add to this list, we could decide to\n // always fall back, with the risk that we might accidentally hide errors\n // representing actual SDK bugs.\n return (\n // When the browser is out of quota we could get either quota exceeded\n // or an aborted error depending on whether the error happened during\n // schema migration.\n error.code === DOM_EXCEPTION_QUOTA_EXCEEDED ||\n error.code === DOM_EXCEPTION_ABORTED ||\n // Firefox Private Browsing mode disables IndexedDb and returns\n // INVALID_STATE for any usage.\n error.code === DOM_EXCEPTION_INVALID_STATE\n );\n }\n\n return true;\n}\n\nasync function ensureOfflineComponents(\n client: FirestoreClient\n): Promise<OfflineComponentProvider> {\n if (!client._offlineComponents) {\n if (client._uninitializedComponentsProvider) {\n logDebug(LOG_TAG, 'Using user provided OfflineComponentProvider');\n try {\n await setOfflineComponentProvider(\n client,\n client._uninitializedComponentsProvider._offline\n );\n } catch (e) {\n const error = e as FirestoreError | DOMException;\n if (!canFallbackFromIndexedDbError(error)) {\n throw error;\n }\n logWarn(\n 'Error using user provided cache. Falling back to ' +\n 'memory cache: ' +\n error\n );\n await setOfflineComponentProvider(\n client,\n new MemoryOfflineComponentProvider()\n );\n }\n } else {\n logDebug(LOG_TAG, 'Using default OfflineComponentProvider');\n await setOfflineComponentProvider(\n client,\n new MemoryOfflineComponentProvider()\n );\n }\n }\n\n return client._offlineComponents!;\n}\n\nasync function ensureOnlineComponents(\n client: FirestoreClient\n): Promise<OnlineComponentProvider> {\n if (!client._onlineComponents) {\n if (client._uninitializedComponentsProvider) {\n logDebug(LOG_TAG, 'Using user provided OnlineComponentProvider');\n await setOnlineComponentProvider(\n client,\n client._uninitializedComponentsProvider._online\n );\n } else {\n logDebug(LOG_TAG, 'Using default OnlineComponentProvider');\n await setOnlineComponentProvider(client, new OnlineComponentProvider());\n }\n }\n\n return client._onlineComponents!;\n}\n\nfunction getPersistence(client: FirestoreClient): Promise<Persistence> {\n return ensureOfflineComponents(client).then(c => c.persistence);\n}\n\nexport function getLocalStore(client: FirestoreClient): Promise<LocalStore> {\n return ensureOfflineComponents(client).then(c => c.localStore);\n}\n\nfunction getRemoteStore(client: FirestoreClient): Promise<RemoteStore> {\n return ensureOnlineComponents(client).then(c => c.remoteStore);\n}\n\nexport function getSyncEngine(client: FirestoreClient): Promise<SyncEngine> {\n return ensureOnlineComponents(client).then(c => c.syncEngine);\n}\n\nfunction getDatastore(client: FirestoreClient): Promise<Datastore> {\n return ensureOnlineComponents(client).then(c => c.datastore);\n}\n\nexport async function getEventManager(\n client: FirestoreClient\n): Promise<EventManager> {\n const onlineComponentProvider = await ensureOnlineComponents(client);\n const eventManager = onlineComponentProvider.eventManager;\n eventManager.onListen = syncEngineListen.bind(\n null,\n onlineComponentProvider.syncEngine\n );\n eventManager.onUnlisten = syncEngineUnlisten.bind(\n null,\n onlineComponentProvider.syncEngine\n );\n return eventManager;\n}\n\n/** Enables the network connection and re-enqueues all pending operations. */\nexport function firestoreClientEnableNetwork(\n client: FirestoreClient\n): Promise<void> {\n return client.asyncQueue.enqueue(async () => {\n const persistence = await getPersistence(client);\n const remoteStore = await getRemoteStore(client);\n persistence.setNetworkEnabled(true);\n return remoteStoreEnableNetwork(remoteStore);\n });\n}\n\n/** Disables the network connection. Pending operations will not complete. */\nexport function firestoreClientDisableNetwork(\n client: FirestoreClient\n): Promise<void> {\n return client.asyncQueue.enqueue(async () => {\n const persistence = await getPersistence(client);\n const remoteStore = await getRemoteStore(client);\n persistence.setNetworkEnabled(false);\n return remoteStoreDisableNetwork(remoteStore);\n });\n}\n\n/**\n * Returns a Promise that resolves when all writes that were pending at the time\n * this method was called received server acknowledgement. An acknowledgement\n * can be either acceptance or rejection.\n */\nexport function firestoreClientWaitForPendingWrites(\n client: FirestoreClient\n): Promise<void> {\n const deferred = new Deferred<void>();\n client.asyncQueue.enqueueAndForget(async () => {\n const syncEngine = await getSyncEngine(client);\n return syncEngineRegisterPendingWritesCallback(syncEngine, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientListen(\n client: FirestoreClient,\n query: Query,\n options: ListenOptions,\n observer: Partial<Observer<ViewSnapshot>>\n): () => void {\n const wrappedObserver = new AsyncObserver(observer);\n const listener = new QueryListener(query, wrappedObserver, options);\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return eventManagerListen(eventManager, listener);\n });\n return () => {\n wrappedObserver.mute();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return eventManagerUnlisten(eventManager, listener);\n });\n };\n}\n\nexport function firestoreClientGetDocumentFromLocalCache(\n client: FirestoreClient,\n docKey: DocumentKey\n): Promise<Document | null> {\n const deferred = new Deferred<Document | null>();\n client.asyncQueue.enqueueAndForget(async () => {\n const localStore = await getLocalStore(client);\n return readDocumentFromCache(localStore, docKey, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentViaSnapshotListener(\n client: FirestoreClient,\n key: DocumentKey,\n options: GetOptions = {}\n): Promise<ViewSnapshot> {\n const deferred = new Deferred<ViewSnapshot>();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return readDocumentViaSnapshotListener(\n eventManager,\n client.asyncQueue,\n key,\n options,\n deferred\n );\n });\n return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentsFromLocalCache(\n client: FirestoreClient,\n query: Query\n): Promise<ViewSnapshot> {\n const deferred = new Deferred<ViewSnapshot>();\n client.asyncQueue.enqueueAndForget(async () => {\n const localStore = await getLocalStore(client);\n return executeQueryFromCache(localStore, query, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentsViaSnapshotListener(\n client: FirestoreClient,\n query: Query,\n options: GetOptions = {}\n): Promise<ViewSnapshot> {\n const deferred = new Deferred<ViewSnapshot>();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return executeQueryViaSnapshotListener(\n eventManager,\n client.asyncQueue,\n query,\n options,\n deferred\n );\n });\n return deferred.promise;\n}\n\nexport function firestoreClientRunAggregateQuery(\n client: FirestoreClient,\n query: Query,\n aggregates: Aggregate[]\n): Promise<ApiClientObjectMap<Value>> {\n const deferred = new Deferred<ApiClientObjectMap<Value>>();\n\n client.asyncQueue.enqueueAndForget(async () => {\n // Implement and call executeAggregateQueryViaSnapshotListener, similar\n // to the implementation in firestoreClientGetDocumentsViaSnapshotListener\n // above\n try {\n // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab.\n const datastore = await getDatastore(client);\n deferred.resolve(\n invokeRunAggregationQueryRpc(datastore, query, aggregates)\n );\n } catch (e) {\n deferred.reject(e as Error);\n }\n });\n return deferred.promise;\n}\n\nexport function firestoreClientWrite(\n client: FirestoreClient,\n mutations: Mutation[]\n): Promise<void> {\n const deferred = new Deferred<void>();\n client.asyncQueue.enqueueAndForget(async () => {\n const syncEngine = await getSyncEngine(client);\n return syncEngineWrite(syncEngine, mutations, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientAddSnapshotsInSyncListener(\n client: FirestoreClient,\n observer: Partial<Observer<void>>\n): () => void {\n const wrappedObserver = new AsyncObserver(observer);\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return addSnapshotsInSyncListener(eventManager, wrappedObserver);\n });\n return () => {\n wrappedObserver.mute();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return removeSnapshotsInSyncListener(eventManager, wrappedObserver);\n });\n };\n}\n\n/**\n * Takes an updateFunction in which a set of reads and writes can be performed\n * atomically. In the updateFunction, the client can read and write values\n * using the supplied transaction object. After the updateFunction, all\n * changes will be committed. If a retryable error occurs (ex: some other\n * client has changed any of the data referenced), then the updateFunction\n * will be called again after a backoff. If the updateFunction still fails\n * after all retries, then the transaction will be rejected.\n *\n * The transaction object passed to the updateFunction contains methods for\n * accessing documents and collections. Unlike other datastore access, data\n * accessed with the transaction will not reflect local changes that have not\n * been committed. For this reason, it is required that all reads are\n * performed before any writes. Transactions must be performed while online.\n */\nexport function firestoreClientTransaction<T>(\n client: FirestoreClient,\n updateFunction: (transaction: Transaction) => Promise<T>,\n options: TransactionOptions\n): Promise<T> {\n const deferred = new Deferred<T>();\n client.asyncQueue.enqueueAndForget(async () => {\n const datastore = await getDatastore(client);\n new TransactionRunner<T>(\n client.asyncQueue,\n datastore,\n options,\n updateFunction,\n deferred\n ).run();\n });\n return deferred.promise;\n}\n\nasync function readDocumentFromCache(\n localStore: LocalStore,\n docKey: DocumentKey,\n result: Deferred<Document | null>\n): Promise<void> {\n try {\n const document = await localStoreReadDocument(localStore, docKey);\n if (document.isFoundDocument()) {\n result.resolve(document);\n } else if (document.isNoDocument()) {\n result.resolve(null);\n } else {\n result.reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document from cache. (However, this document may ' +\n \"exist on the server. Run again without setting 'source' in \" +\n 'the GetOptions to attempt to retrieve the document from the ' +\n 'server.)'\n )\n );\n }\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to get document '${docKey} from cache`\n );\n result.reject(firestoreError);\n }\n}\n\n/**\n * Retrieves a latency-compensated document from the backend via a\n * SnapshotListener.\n */\nfunction readDocumentViaSnapshotListener(\n eventManager: EventManager,\n asyncQueue: AsyncQueue,\n key: DocumentKey,\n options: GetOptions,\n result: Deferred<ViewSnapshot>\n): Promise<void> {\n const wrappedObserver = new AsyncObserver({\n next: (snap: ViewSnapshot) => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n asyncQueue.enqueueAndForget(() =>\n eventManagerUnlisten(eventManager, listener)\n );\n\n const exists = snap.docs.has(key);\n if (!exists && snap.fromCache) {\n // TODO(dimond): If we're online and the document doesn't\n // exist then we resolve with a doc.exists set to false. If\n // we're offline however, we reject the Promise in this\n // case. Two options: 1) Cache the negative response from\n // the server so we can deliver that even when you're\n // offline 2) Actually reject the Promise in the online case\n // if the document doesn't exist.\n result.reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document because the client is offline.'\n )\n );\n } else if (\n exists &&\n snap.fromCache &&\n options &&\n options.source === 'server'\n ) {\n result.reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document from server. (However, this ' +\n 'document does exist in the local cache. Run again ' +\n 'without setting source to \"server\" to ' +\n 'retrieve the cached document.)'\n )\n );\n } else {\n debugAssert(\n snap.docs.size <= 1,\n 'Expected zero or a single result on a document-only query'\n );\n result.resolve(snap);\n }\n },\n error: e => result.reject(e)\n });\n\n const listener = new QueryListener(\n newQueryForPath(key.path),\n wrappedObserver,\n {\n includeMetadataChanges: true,\n waitForSyncWhenOnline: true\n }\n );\n return eventManagerListen(eventManager, listener);\n}\n\nasync function executeQueryFromCache(\n localStore: LocalStore,\n query: Query,\n result: Deferred<ViewSnapshot>\n): Promise<void> {\n try {\n const queryResult = await localStoreExecuteQuery(\n localStore,\n query,\n /* usePreviousResults= */ true\n );\n const view = new View(query, queryResult.remoteKeys);\n const viewDocChanges = view.computeDocChanges(queryResult.documents);\n const viewChange = view.applyChanges(\n viewDocChanges,\n /* updateLimboDocuments= */ false\n );\n result.resolve(viewChange.snapshot!);\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to execute query '${query} against cache`\n );\n result.reject(firestoreError);\n }\n}\n\n/**\n * Retrieves a latency-compensated query snapshot from the backend via a\n * SnapshotListener.\n */\nfunction executeQueryViaSnapshotListener(\n eventManager: EventManager,\n asyncQueue: AsyncQueue,\n query: Query,\n options: GetOptions,\n result: Deferred<ViewSnapshot>\n): Promise<void> {\n const wrappedObserver = new AsyncObserver<ViewSnapshot>({\n next: snapshot => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n asyncQueue.enqueueAndForget(() =>\n eventManagerUnlisten(eventManager, listener)\n );\n\n if (snapshot.fromCache && options.source === 'server') {\n result.reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get documents from server. (However, these ' +\n 'documents may exist in the local cache. Run again ' +\n 'without setting source to \"server\" to ' +\n 'retrieve the cached documents.)'\n )\n );\n } else {\n result.resolve(snapshot);\n }\n },\n error: e => result.reject(e)\n });\n\n const listener = new QueryListener(query, wrappedObserver, {\n includeMetadataChanges: true,\n waitForSyncWhenOnline: true\n });\n return eventManagerListen(eventManager, listener);\n}\n\nexport function firestoreClientLoadBundle(\n client: FirestoreClient,\n databaseId: DatabaseId,\n data: ReadableStream<Uint8Array> | ArrayBuffer | string,\n resultTask: LoadBundleTask\n): void {\n const reader = createBundleReader(data, newSerializer(databaseId));\n client.asyncQueue.enqueueAndForget(async () => {\n syncEngineLoadBundle(await getSyncEngine(client), reader, resultTask);\n });\n}\n\nexport function firestoreClientGetNamedQuery(\n client: FirestoreClient,\n queryName: string\n): Promise<NamedQuery | undefined> {\n return client.asyncQueue.enqueue(async () =>\n localStoreGetNamedQuery(await getLocalStore(client), queryName)\n );\n}\n\nfunction createBundleReader(\n data: ReadableStream<Uint8Array> | ArrayBuffer | string,\n serializer: JsonProtoSerializer\n): BundleReader {\n let content: ReadableStream<Uint8Array> | ArrayBuffer;\n if (typeof data === 'string') {\n content = newTextEncoder().encode(data);\n } else {\n content = data;\n }\n return newBundleReader(toByteStreamReader(content), serializer);\n}\n\nexport function firestoreClientSetIndexConfiguration(\n client: FirestoreClient,\n indexes: FieldIndex[]\n): Promise<void> {\n return client.asyncQueue.enqueue(async () => {\n return localStoreConfigureFieldIndexes(\n await getLocalStore(client),\n indexes\n );\n });\n}\n\nexport function firestoreClientSetPersistentCacheIndexAutoCreationEnabled(\n client: FirestoreClient,\n isEnabled: boolean\n): Promise<void> {\n return client.asyncQueue.enqueue(async () => {\n return localStoreSetIndexAutoCreationEnabled(\n await getLocalStore(client),\n isEnabled\n );\n });\n}\n\nexport function firestoreClientDeleteAllFieldIndexes(\n client: FirestoreClient\n): Promise<void> {\n return client.asyncQueue.enqueue(async () => {\n return localStoreDeleteAllFieldIndexes(await getLocalStore(client));\n });\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Options that configure the SDK’s underlying network transport (WebChannel)\n * when long-polling is used.\n *\n * Note: This interface is \"experimental\" and is subject to change.\n *\n * See `FirestoreSettings.experimentalAutoDetectLongPolling`,\n * `FirestoreSettings.experimentalForceLongPolling`, and\n * `FirestoreSettings.experimentalLongPollingOptions`.\n */\nexport interface ExperimentalLongPollingOptions {\n /**\n * The desired maximum timeout interval, in seconds, to complete a\n * long-polling GET response. Valid values are between 5 and 30, inclusive.\n * Floating point values are allowed and will be rounded to the nearest\n * millisecond.\n *\n * By default, when long-polling is used the \"hanging GET\" request sent by\n * the client times out after 30 seconds. To request a different timeout\n * from the server, set this setting with the desired timeout.\n *\n * Changing the default timeout may be useful, for example, if the buffering\n * proxy that necessitated enabling long-polling in the first place has a\n * shorter timeout for hanging GET requests, in which case setting the\n * long-polling timeout to a shorter value, such as 25 seconds, may fix\n * prematurely-closed hanging GET requests.\n * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987.\n */\n timeoutSeconds?: number;\n}\n\n/**\n * Compares two `ExperimentalLongPollingOptions` objects for equality.\n */\nexport function longPollingOptionsEqual(\n options1: ExperimentalLongPollingOptions,\n options2: ExperimentalLongPollingOptions\n): boolean {\n return options1.timeoutSeconds === options2.timeoutSeconds;\n}\n\n/**\n * Creates and returns a new `ExperimentalLongPollingOptions` with the same\n * option values as the given instance.\n */\nexport function cloneLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): ExperimentalLongPollingOptions {\n const clone: ExperimentalLongPollingOptions = {};\n\n if (options.timeoutSeconds !== undefined) {\n clone.timeoutSeconds = options.timeoutSeconds;\n }\n\n return clone;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { _FirebaseService } from '@firebase/app';\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { cloneLongPollingOptions } from '../api/long_polling_options';\nimport { User } from '../auth/user';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { newConnection } from '../platform/connection';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { FirestoreSettingsImpl } from './settings';\n\nexport const LOG_TAG = 'ComponentProvider';\n\n// The components module manages the lifetime of dependencies of the Firestore\n// client. Dependencies can be lazily constructed and only one exists per\n// Firestore instance.\n\n/**\n * An interface implemented by FirebaseFirestore that provides compatibility\n * with the usage in this file.\n *\n * This interface mainly exists to remove a cyclic dependency.\n */\nexport interface FirestoreService extends _FirebaseService {\n _authCredentials: CredentialsProvider<User>;\n _appCheckCredentials: CredentialsProvider<string>;\n _persistenceKey: string;\n _databaseId: DatabaseId;\n _terminated: boolean;\n\n _freezeSettings(): FirestoreSettingsImpl;\n}\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\nconst datastoreInstances = new Map<FirestoreService, Datastore>();\n\n/**\n * Returns an initialized and started Datastore for the given Firestore\n * instance. Callers must invoke removeComponents() when the Firestore\n * instance is terminated.\n */\nexport function getDatastore(firestore: FirestoreService): Datastore {\n if (firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n if (!datastoreInstances.has(firestore)) {\n logDebug(LOG_TAG, 'Initializing Datastore');\n const databaseInfo = makeDatabaseInfo(\n firestore._databaseId,\n firestore.app.options.appId || '',\n firestore._persistenceKey,\n firestore._freezeSettings()\n );\n const connection = newConnection(databaseInfo);\n const serializer = newSerializer(firestore._databaseId);\n const datastore = newDatastore(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n connection,\n serializer\n );\n\n datastoreInstances.set(firestore, datastore);\n }\n return datastoreInstances.get(firestore)!;\n}\n\n/**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\nexport function removeComponents(firestore: FirestoreService): void {\n const datastore = datastoreInstances.get(firestore);\n if (datastore) {\n logDebug(LOG_TAG, 'Removing Datastore');\n datastoreInstances.delete(firestore);\n datastore.terminate();\n }\n}\n\nexport function makeDatabaseInfo(\n databaseId: DatabaseId,\n appId: string,\n persistenceKey: string,\n settings: FirestoreSettingsImpl\n): DatabaseInfo {\n return new DatabaseInfo(\n databaseId,\n appId,\n persistenceKey,\n settings.host,\n settings.ssl,\n settings.experimentalForceLongPolling,\n settings.experimentalAutoDetectLongPolling,\n cloneLongPollingOptions(settings.experimentalLongPollingOptions),\n settings.useFetchStreams\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\n\nimport { fail } from './assert';\nimport { Code, FirestoreError } from './error';\n\n/** Types accepted by validateType() and related methods for validation. */\nexport type ValidationType =\n | 'undefined'\n | 'object'\n | 'function'\n | 'boolean'\n | 'number'\n | 'string'\n | 'non-empty string';\n\nexport function validateNonEmptyArgument(\n functionName: string,\n argumentName: string,\n argument?: string\n): asserts argument is string {\n if (!argument) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() cannot be called with an empty ${argumentName}.`\n );\n }\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */\nexport function validateIsNotUsedTogether(\n optionName1: string,\n argument1: boolean | undefined,\n optionName2: string,\n argument2: boolean | undefined\n): void {\n if (argument1 === true && argument2 === true) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `${optionName1} and ${optionName2} cannot be used together.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */\nexport function validateDocumentPath(path: ResourcePath): void {\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */\nexport function validateCollectionPath(path: ResourcePath): void {\n if (DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nexport function isPlainObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n (Object.getPrototypeOf(input) === Object.prototype ||\n Object.getPrototypeOf(input) === null)\n );\n}\n\n/** Returns a string describing the type / value of the provided input. */\nexport function valueDescription(input: unknown): string {\n if (input === undefined) {\n return 'undefined';\n } else if (input === null) {\n return 'null';\n } else if (typeof input === 'string') {\n if (input.length > 20) {\n input = `${input.substring(0, 20)}...`;\n }\n return JSON.stringify(input);\n } else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n } else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n } else {\n const customObjectName = tryGetCustomObjectType(input!);\n if (customObjectName) {\n return `a custom ${customObjectName} object`;\n } else {\n return 'an object';\n }\n }\n } else if (typeof input === 'function') {\n return 'a function';\n } else {\n return fail('Unknown wrong type: ' + typeof input);\n }\n}\n\n/** try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input: object): string | null {\n if (input.constructor) {\n return input.constructor.name;\n }\n return null;\n}\n\n/**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */\nexport function cast<T>(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n if ('_delegate' in obj) {\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj = (obj as any)._delegate;\n }\n\n if (!(obj instanceof constructor)) {\n if (constructor.name === obj.constructor.name) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Type does not match the expected instance. Did you pass a ' +\n `reference from a different Firestore SDK?`\n );\n } else {\n const description = valueDescription(obj);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Expected type '${constructor.name}', but it was: ${description}`\n );\n }\n }\n return obj as T;\n}\n\nexport function validatePositiveNumber(functionName: string, n: number): void {\n if (n <= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires a positive number, but it was: ${n}.`\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreLocalCache } from '../api/cache_config';\nimport { CredentialsSettings } from '../api/credentials';\nimport {\n ExperimentalLongPollingOptions,\n cloneLongPollingOptions,\n longPollingOptionsEqual\n} from '../api/long_polling_options';\nimport {\n LRU_COLLECTION_DISABLED,\n LRU_DEFAULT_CACHE_SIZE_BYTES\n} from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { validateIsNotUsedTogether } from '../util/input_validation';\n\n// settings() defaults:\nexport const DEFAULT_HOST = 'firestore.googleapis.com';\nexport const DEFAULT_SSL = true;\n\n// The minimum long-polling timeout is hardcoded on the server. The value here\n// should be kept in sync with the value used by the server, as the server will\n// silently ignore a value below the minimum and fall back to the default.\n// Googlers see b/266868871 for relevant discussion.\nconst MIN_LONG_POLLING_TIMEOUT_SECONDS = 5;\n\n// No maximum long-polling timeout is configured in the server, and defaults to\n// 30 seconds, which is what Watch appears to use.\n// Googlers see b/266868871 for relevant discussion.\nconst MAX_LONG_POLLING_TIMEOUT_SECONDS = 30;\n\n// Whether long-polling auto-detected is enabled by default.\nconst DEFAULT_AUTO_DETECT_LONG_POLLING = true;\n\n/**\n * Specifies custom configurations for your Cloud Firestore instance.\n * You must set these before invoking any other methods.\n */\nexport interface FirestoreSettings {\n /** The hostname to connect to. */\n host?: string;\n\n /** Whether to use SSL when connecting. */\n ssl?: boolean;\n\n /**\n * Whether to skip nested properties that are set to `undefined` during\n * object serialization. If set to `true`, these properties are skipped\n * and not written to Firestore. If set to `false` or omitted, the SDK\n * throws an exception when it encounters properties of type `undefined`.\n */\n ignoreUndefinedProperties?: boolean;\n}\n\n/**\n * @internal\n * Undocumented, private additional settings not exposed in our public API.\n */\nexport interface PrivateSettings extends FirestoreSettings {\n // Can be a google-auth-library or gapi client.\n credentials?: CredentialsSettings;\n cacheSizeBytes?: number;\n experimentalForceLongPolling?: boolean;\n experimentalAutoDetectLongPolling?: boolean;\n experimentalLongPollingOptions?: ExperimentalLongPollingOptions;\n useFetchStreams?: boolean;\n\n localCache?: FirestoreLocalCache;\n}\n\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nexport class FirestoreSettingsImpl {\n /** The hostname to connect to. */\n readonly host: string;\n\n /** Whether to use SSL when connecting. */\n readonly ssl: boolean;\n\n readonly cacheSizeBytes: number;\n\n readonly experimentalForceLongPolling: boolean;\n\n readonly experimentalAutoDetectLongPolling: boolean;\n\n readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions;\n\n readonly ignoreUndefinedProperties: boolean;\n\n readonly useFetchStreams: boolean;\n readonly localCache?: FirestoreLocalCache;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '../api';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport {\n ActiveTargets,\n GC_DID_NOT_RUN,\n LRU_COLLECTION_DISABLED,\n LruDelegate,\n LruGarbageCollector,\n LruParams,\n LruResults\n} from './lru_garbage_collector';\nimport { Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'LruGarbageCollector';\n\nexport const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\n\nfunction bufferEntryComparator(\n [aSequence, aIndex]: BufferEntry,\n [bSequence, bIndex]: BufferEntry\n): number {\n const seqCmp = primitiveComparator(aSequence, bSequence);\n if (seqCmp === 0) {\n // This order doesn't matter, but we can bias against churn by sorting\n // entries created earlier as less than newer entries.\n return primitiveComparator(aIndex, bIndex);\n } else {\n return seqCmp;\n }\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */\nclass RollingSequenceNumberBuffer {\n private buffer: SortedSet<BufferEntry> = new SortedSet<BufferEntry>(\n bufferEntryComparator\n );\n\n private previousIndex = 0;\n\n constructor(private readonly maxElements: number) {}\n\n private nextIndex(): number {\n return ++this.previousIndex;\n }\n\n addElement(sequenceNumber: ListenSequenceNumber): void {\n const entry: BufferEntry = [sequenceNumber, this.nextIndex()];\n if (this.buffer.size < this.maxElements) {\n this.buffer = this.buffer.add(entry);\n } else {\n const highestValue = this.buffer.last()!;\n if (bufferEntryComparator(entry, highestValue) < 0) {\n this.buffer = this.buffer.delete(highestValue).add(entry);\n }\n }\n }\n\n get maxValue(): ListenSequenceNumber {\n // Guaranteed to be non-empty. If we decide we are not collecting any\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\n // decided that we are collecting n sequence numbers, it's because n is some\n // percentage of the existing sequence numbers. That means we should never\n // be in a situation where we are collecting sequence numbers but don't\n // actually have any.\n return this.buffer.last()![0];\n }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */\nexport class LruScheduler implements Scheduler {\n private gcTask: DelayedOperation<void> | null;\n\n constructor(\n private readonly garbageCollector: LruGarbageCollector,\n private readonly asyncQueue: AsyncQueue,\n private readonly localStore: LocalStore\n ) {\n this.gcTask = null;\n }\n\n start(): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot start an already started LruScheduler'\n );\n if (\n this.garbageCollector.params.cacheSizeCollectionThreshold !==\n LRU_COLLECTION_DISABLED\n ) {\n this.scheduleGC(INITIAL_GC_DELAY_MS);\n }\n }\n\n stop(): void {\n if (this.gcTask) {\n this.gcTask.cancel();\n this.gcTask = null;\n }\n }\n\n get started(): boolean {\n return this.gcTask !== null;\n }\n\n private scheduleGC(delay: number): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot schedule GC while a task is pending'\n );\n logDebug(LOG_TAG, `Garbage collection scheduled in ${delay}ms`);\n this.gcTask = this.asyncQueue.enqueueAfterDelay(\n TimerId.LruGarbageCollection,\n delay,\n async () => {\n this.gcTask = null;\n try {\n await this.localStore.collectGarbage(this.garbageCollector);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during garbage collection: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.scheduleGC(REGULAR_GC_DELAY_MS);\n }\n );\n }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */\nclass LruGarbageCollectorImpl implements LruGarbageCollector {\n constructor(\n private readonly delegate: LruDelegate,\n readonly params: LruParams\n ) {}\n\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise<number> {\n return this.delegate.getSequenceNumberCount(txn).next(targetCount => {\n return Math.floor((percentile / 100.0) * targetCount);\n });\n }\n\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise<ListenSequenceNumber> {\n if (n === 0) {\n return PersistencePromise.resolve(ListenSequence.INVALID);\n }\n\n const buffer = new RollingSequenceNumberBuffer(n);\n return this.delegate\n .forEachTarget(txn, target => buffer.addElement(target.sequenceNumber))\n .next(() => {\n return this.delegate.forEachOrphanedDocumentSequenceNumber(\n txn,\n sequenceNumber => buffer.addElement(sequenceNumber)\n );\n })\n .next(() => buffer.maxValue);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number> {\n return this.delegate.removeOrphanedDocuments(txn, upperBound);\n }\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<LruResults> {\n if (this.params.cacheSizeCollectionThreshold === LRU_COLLECTION_DISABLED) {\n logDebug('LruGarbageCollector', 'Garbage collection skipped; disabled');\n return PersistencePromise.resolve(GC_DID_NOT_RUN);\n }\n\n return this.getCacheSize(txn).next(cacheSize => {\n if (cacheSize < this.params.cacheSizeCollectionThreshold) {\n logDebug(\n 'LruGarbageCollector',\n `Garbage collection skipped; Cache size ${cacheSize} ` +\n `is lower than threshold ${this.params.cacheSizeCollectionThreshold}`\n );\n return GC_DID_NOT_RUN;\n } else {\n return this.runGarbageCollection(txn, activeTargetIds);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return this.delegate.getCacheSize(txn);\n }\n\n private runGarbageCollection(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<LruResults> {\n let upperBoundSequenceNumber: number;\n let sequenceNumbersToCollect: number, targetsRemoved: number;\n // Timestamps for various pieces of the process\n let countedTargetsTs: number,\n foundUpperBoundTs: number,\n removedTargetsTs: number,\n removedDocumentsTs: number;\n const startTs = Date.now();\n return this.calculateTargetCount(txn, this.params.percentileToCollect)\n .next(sequenceNumbers => {\n // Cap at the configured max\n if (sequenceNumbers > this.params.maximumSequenceNumbersToCollect) {\n logDebug(\n 'LruGarbageCollector',\n 'Capping sequence numbers to collect down ' +\n `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` +\n `from ${sequenceNumbers}`\n );\n sequenceNumbersToCollect =\n this.params.maximumSequenceNumbersToCollect;\n } else {\n sequenceNumbersToCollect = sequenceNumbers;\n }\n countedTargetsTs = Date.now();\n\n return this.nthSequenceNumber(txn, sequenceNumbersToCollect);\n })\n .next(upperBound => {\n upperBoundSequenceNumber = upperBound;\n foundUpperBoundTs = Date.now();\n\n return this.removeTargets(\n txn,\n upperBoundSequenceNumber,\n activeTargetIds\n );\n })\n .next(numTargetsRemoved => {\n targetsRemoved = numTargetsRemoved;\n removedTargetsTs = Date.now();\n\n return this.removeOrphanedDocuments(txn, upperBoundSequenceNumber);\n })\n .next(documentsRemoved => {\n removedDocumentsTs = Date.now();\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n const desc =\n 'LRU Garbage Collection\\n' +\n `\\tCounted targets in ${countedTargetsTs - startTs}ms\\n` +\n `\\tDetermined least recently used ${sequenceNumbersToCollect} in ` +\n `${foundUpperBoundTs - countedTargetsTs}ms\\n` +\n `\\tRemoved ${targetsRemoved} targets in ` +\n `${removedTargetsTs - foundUpperBoundTs}ms\\n` +\n `\\tRemoved ${documentsRemoved} documents in ` +\n `${removedDocumentsTs - removedTargetsTs}ms\\n` +\n `Total Duration: ${removedDocumentsTs - startTs}ms`;\n logDebug('LruGarbageCollector', desc);\n }\n\n return PersistencePromise.resolve<LruResults>({\n didRun: true,\n sequenceNumbersCollected: sequenceNumbersToCollect,\n targetsRemoved,\n documentsRemoved\n });\n });\n }\n}\n\nexport function newLruGarbageCollector(\n delegate: LruDelegate,\n params: LruParams\n): LruGarbageCollector {\n return new LruGarbageCollectorImpl(delegate, params);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort\n} from '@firebase/util';\n\nimport {\n CredentialsProvider,\n EmulatorAuthCredentialsProvider,\n makeAuthCredentialsProvider,\n OAuthToken\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { FirestoreService, removeComponents } from './components';\nimport {\n DEFAULT_HOST,\n FirestoreSettingsImpl,\n PrivateSettings,\n FirestoreSettings\n} from './settings';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore implements FirestoreService {\n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n type: 'firestore-lite' | 'firestore' = 'firestore-lite';\n\n readonly _persistenceKey: string = '(lite)';\n\n private _settings = new FirestoreSettingsImpl({});\n private _settingsFrozen = false;\n\n // A task that is assigned when the terminate() is invoked and resolved when\n // all components have shut down.\n private _terminateTask?: Promise<void>;\n\n /** @hideconstructor */\n constructor(\n public _authCredentials: CredentialsProvider<User>,\n public _appCheckCredentials: CredentialsProvider<string>,\n readonly _databaseId: DatabaseId,\n readonly _app?: FirebaseApp\n ) {}\n\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */\n get app(): FirebaseApp {\n if (!this._app) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available'\n );\n }\n return this._app;\n }\n\n get _initialized(): boolean {\n return this._settingsFrozen;\n }\n\n get _terminated(): boolean {\n return this._terminateTask !== undefined;\n }\n\n _setSettings(settings: PrivateSettings): void {\n if (this._settingsFrozen) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only modify settings before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\n this._settings = new FirestoreSettingsImpl(settings);\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _freezeSettings(): FirestoreSettingsImpl {\n this._settingsFrozen = true;\n return this._settings;\n }\n\n _delete(): Promise<void> {\n if (!this._terminateTask) {\n this._terminateTask = this._terminate();\n }\n return this._terminateTask;\n }\n\n /** Returns a JSON-serializable representation of this `Firestore` instance. */\n toJSON(): object {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\n }\n\n /**\n * Terminates all components used by this client. Subclasses can override\n * this method to clean up their own dependencies, but must also call this\n * method.\n *\n * Only ever called once.\n */\n protected _terminate(): Promise<void> {\n removeComponents(this);\n return Promise.resolve();\n }\n}\n\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @returns A newly initialized `Firestore` instance.\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings\n): Firestore;\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized `Firestore` instance.\n * @beta\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore;\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore {\n if (!databaseId) {\n databaseId = DEFAULT_DATABASE_NAME;\n }\n const provider = _getProvider(app, 'firestore/lite');\n\n if (provider.isInitialized(databaseId)) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore can only be initialized once per app.'\n );\n }\n\n return provider.initialize({\n options: settings,\n instanceIdentifier: databaseId\n });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n appOrDatabaseId?: FirebaseApp | string,\n optionalDatabaseId?: string\n): Firestore {\n const app: FirebaseApp =\n typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n const databaseId =\n typeof appOrDatabaseId === 'string'\n ? appOrDatabaseId\n : optionalDatabaseId || '(default)';\n const db = _getProvider(app, 'firestore/lite').getImmediate({\n identifier: databaseId\n }) as Firestore;\n if (!db._initialized) {\n const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n if (emulator) {\n connectFirestoreEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */\nexport function connectFirestoreEmulator(\n firestore: Firestore,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n firestore = cast(firestore, Firestore);\n const settings = firestore._getSettings();\n const newHostSetting = `${host}:${port}`;\n\n if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) {\n logWarn(\n 'Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' +\n 'will be used.'\n );\n }\n\n firestore._setSettings({\n ...settings,\n host: newHostSetting,\n ssl: false\n });\n\n if (options.mockUserToken) {\n let token: string;\n let user: User;\n if (typeof options.mockUserToken === 'string') {\n token = options.mockUserToken;\n user = User.MOCK_USER;\n } else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n token = createMockUserToken(\n options.mockUserToken,\n firestore._app?.options.projectId\n );\n const uid = options.mockUserToken.sub || options.mockUserToken.user_id;\n if (!uid) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"mockUserToken must contain 'sub' or 'user_id' field!\"\n );\n }\n user = new User(uid);\n }\n\n firestore._authCredentials = new EmulatorAuthCredentialsProvider(\n new OAuthToken(token, user)\n );\n }\n}\n\n/**\n * Terminates the provided `Firestore` instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` functions\n * may be used. Any other function will throw a `FirestoreError`. Termination\n * does not cancel any pending writes, and any promises that are awaiting a\n * response from the server will not be resolved.\n *\n * To restart after termination, create a new instance of `Firestore` with\n * {@link (getFirestore:1)}.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all of\n * its resources or in combination with {@link clearIndexedDbPersistence} to\n * ensure that all local state is destroyed between test runs.\n *\n * @param firestore - The `Firestore` instance to terminate.\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise<void> {\n firestore = cast(firestore, Firestore);\n _removeServiceInstance(firestore.app, 'firestore/lite');\n return firestore._delete();\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64urlEncodeWithoutPadding } from './crypt';\n\n// Firebase Auth tokens contain snake_case claims following the JWT standard / convention.\n/* eslint-disable camelcase */\n\nexport type FirebaseSignInProvider =\n | 'custom'\n | 'email'\n | 'password'\n | 'phone'\n | 'anonymous'\n | 'google.com'\n | 'facebook.com'\n | 'github.com'\n | 'twitter.com'\n | 'microsoft.com'\n | 'apple.com';\n\ninterface FirebaseIdToken {\n // Always set to https://securetoken.google.com/PROJECT_ID\n iss: string;\n\n // Always set to PROJECT_ID\n aud: string;\n\n // The user's unique ID\n sub: string;\n\n // The token issue time, in seconds since epoch\n iat: number;\n\n // The token expiry time, normally 'iat' + 3600\n exp: number;\n\n // The user's unique ID. Must be equal to 'sub'\n user_id: string;\n\n // The time the user authenticated, normally 'iat'\n auth_time: number;\n\n // The sign in provider, only set when the provider is 'anonymous'\n provider_id?: 'anonymous';\n\n // The user's primary email\n email?: string;\n\n // The user's email verification status\n email_verified?: boolean;\n\n // The user's primary phone number\n phone_number?: string;\n\n // The user's display name\n name?: string;\n\n // The user's profile photo URL\n picture?: string;\n\n // Information on all identities linked to this user\n firebase: {\n // The primary sign-in provider\n sign_in_provider: FirebaseSignInProvider;\n\n // A map of providers to the user's list of unique identifiers from\n // each provider\n identities?: { [provider in FirebaseSignInProvider]?: string[] };\n };\n\n // Custom claims set by the developer\n [claim: string]: unknown;\n\n uid?: never; // Try to catch a common mistake of \"uid\" (should be \"sub\" instead).\n}\n\nexport type EmulatorMockTokenOptions = ({ user_id: string } | { sub: string }) &\n Partial<FirebaseIdToken>;\n\nexport function createMockUserToken(\n token: EmulatorMockTokenOptions,\n projectId?: string\n): string {\n if (token.uid) {\n throw new Error(\n 'The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.'\n );\n }\n // Unsecured JWTs use \"none\" as the algorithm.\n const header = {\n alg: 'none',\n type: 'JWT'\n };\n\n const project = projectId || 'demo-project';\n const iat = token.iat || 0;\n const sub = token.sub || token.user_id;\n if (!sub) {\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\n }\n\n const payload: FirebaseIdToken = {\n // Set all required fields to decent defaults\n iss: `https://securetoken.google.com/${project}`,\n aud: project,\n iat,\n exp: iat + 3600,\n auth_time: iat,\n sub,\n user_id: sub,\n firebase: {\n sign_in_provider: 'custom',\n identities: {}\n },\n\n // Override with user options\n ...token\n };\n\n // Unsecured JWTs use the empty string as a signature.\n const signature = '';\n return [\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\n signature\n ].join('.');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport {\n newQueryForCollectionGroup,\n newQueryForPath,\n Query as InternalQuery,\n queryEquals\n} from '../core/query';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n cast,\n validateCollectionPath,\n validateDocumentPath,\n validateNonEmptyArgument\n} from '../util/input_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { FirestoreDataConverter } from './snapshot';\nimport { NestedUpdateFields, Primitive } from './types';\n\n/**\n * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to\n * values.\n */\nexport interface DocumentData {\n /** A mapping between a field and its value. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [field: string]: any;\n}\n\n/**\n * Similar to Typescript's `Partial<T>`, but allows nested fields to be\n * omitted and FieldValues to be passed in as property values.\n */\nexport type PartialWithFieldValue<T> =\n | Partial<T>\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: PartialWithFieldValue<T[K]> | FieldValue }\n : never);\n\n/**\n * Allows FieldValues to be passed in as a property value while maintaining\n * type safety.\n */\nexport type WithFieldValue<T> =\n | T\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]: WithFieldValue<T[K]> | FieldValue }\n : never);\n\n/**\n * Update data (for use with {@link (updateDoc:1)}) that consists of field paths\n * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots\n * reference nested fields within the document. FieldValues can be passed in\n * as property values.\n */\nexport type UpdateData<T> = T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: UpdateData<T[K]> | FieldValue } & NestedUpdateFields<T>\n : Partial<T>;\n/**\n * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link\n * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be\n * configured to perform granular merges instead of overwriting the target\n * documents in their entirety by providing a `SetOptions` with `merge: true`.\n *\n * @param merge - Changes the behavior of a `setDoc()` call to only replace the\n * values specified in its data argument. Fields omitted from the `setDoc()`\n * call remain untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace\n * the specified field paths. Any field path that is not specified is ignored\n * and remains untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n */\nexport type SetOptions =\n | {\n readonly merge?: boolean;\n }\n | {\n readonly mergeFields?: Array<string | FieldPath>;\n };\n\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */\nexport class Query<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type: 'query' | 'collection' = 'query';\n\n /**\n * The `Firestore` instance for the Firestore database (useful for performing\n * transactions, etc.).\n */\n readonly firestore: Firestore;\n\n // This is the lite version of the Query class in the main SDK.\n\n /** @hideconstructor protected */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _query: InternalQuery\n ) {\n this.firestore = firestore;\n }\n\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `Query<DocumentData, DocumentData>` that does not use a\n * converter.\n */\n withConverter(converter: null): Query<DocumentData, DocumentData>;\n /**\n * Applies a custom data converter to this query, allowing you to use your own\n * custom model objects with Firestore. When you call {@link getDocs} with\n * the returned query, the provided converter will convert between Firestore\n * data of type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `Query` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n ): Query<NewAppModelType, NewDbModelType>;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n ): Query<NewAppModelType, NewDbModelType> {\n return new Query<NewAppModelType, NewDbModelType>(\n this.firestore,\n converter,\n this._query\n );\n }\n}\n\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */\nexport class DocumentReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type = 'document';\n\n /**\n * The {@link Firestore} instance the document is in.\n * This is useful for performing transactions, for example.\n */\n readonly firestore: Firestore;\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _key: DocumentKey\n ) {\n this.firestore = firestore;\n }\n\n get _path(): ResourcePath {\n return this._key.path;\n }\n\n /**\n * The document's identifier within its collection.\n */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */\n get path(): string {\n return this._key.path.canonicalString();\n }\n\n /**\n * The collection this `DocumentReference` belongs to.\n */\n get parent(): CollectionReference<AppModelType, DbModelType> {\n return new CollectionReference<AppModelType, DbModelType>(\n this.firestore,\n this.converter,\n this._key.path.popLast()\n );\n }\n\n /**\n * Applies a custom data converter to this `DocumentReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`\n * instance, the provided converter will convert between Firestore data of\n * type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `DocumentReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n ): DocumentReference<NewAppModelType, NewDbModelType>;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `DocumentReference<DocumentData, DocumentData>` that does not\n * use a converter.\n */\n withConverter(converter: null): DocumentReference<DocumentData, DocumentData>;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n ): DocumentReference<NewAppModelType, NewDbModelType> {\n return new DocumentReference<NewAppModelType, NewDbModelType>(\n this.firestore,\n converter,\n this._key\n );\n }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link (query:1)}).\n */\nexport class CollectionReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends Query<AppModelType, DbModelType> {\n /** The type of this Firestore reference. */\n readonly type = 'collection';\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n converter: FirestoreDataConverter<AppModelType, DbModelType> | null,\n readonly _path: ResourcePath\n ) {\n super(firestore, converter, newQueryForPath(_path));\n }\n\n /** The collection's identifier. */\n get id(): string {\n return this._query.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */\n get path(): string {\n return this._query.path.canonicalString();\n }\n\n /**\n * A reference to the containing `DocumentReference` if this is a\n * subcollection. If this isn't a subcollection, the reference is null.\n */\n get parent(): DocumentReference<DocumentData, DocumentData> | null {\n const parentPath = this._path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n } else {\n return new DocumentReference(\n this.firestore,\n /* converter= */ null,\n new DocumentKey(parentPath)\n );\n }\n }\n\n /**\n * Applies a custom data converter to this `CollectionReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * addDoc} with the returned `CollectionReference` instance, the provided\n * converter will convert between Firestore data of type `NewDbModelType` and\n * your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `CollectionReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n ): CollectionReference<NewAppModelType, NewDbModelType>;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `CollectionReference<DocumentData, DocumentData>` that does not\n * use a converter.\n */\n withConverter(\n converter: null\n ): CollectionReference<DocumentData, DocumentData>;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n ): CollectionReference<NewAppModelType, NewDbModelType> {\n return new CollectionReference<NewAppModelType, NewDbModelType>(\n this.firestore,\n converter,\n this._path\n );\n }\n}\n\n/**\n * Gets a `CollectionReference` instance that refers to the collection at\n * the specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the the specified relative path.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n reference: CollectionReference<AppModelType, DbModelType>,\n path: string,\n ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n path: string,\n ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n parent:\n | Firestore\n | DocumentReference<AppModelType, DbModelType>\n | CollectionReference<AppModelType, DbModelType>,\n path: string,\n ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData> {\n parent = getModularInstance(parent);\n\n validateNonEmptyArgument('collection', 'path', path);\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateCollectionPath(absolutePath);\n return new CollectionReference(parent, /* converter= */ null, absolutePath);\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateCollectionPath(absolutePath);\n return new CollectionReference(\n parent.firestore,\n /* converter= */ null,\n absolutePath\n );\n }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */\nexport function collectionGroup(\n firestore: Firestore,\n collectionId: string\n): Query<DocumentData, DocumentData> {\n firestore = cast(firestore, Firestore);\n\n validateNonEmptyArgument('collectionGroup', 'collection id', collectionId);\n if (collectionId.indexOf('/') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection ID '${collectionId}' passed to function ` +\n `collectionGroup(). Collection IDs must not contain '/'.`\n );\n }\n\n return new Query(\n firestore,\n /* converter= */ null,\n newQueryForCollectionGroup(collectionId)\n );\n}\n\n/**\n * Gets a `DocumentReference` instance that refers to the document at the\n * specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): DocumentReference<DocumentData, DocumentData>;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path. If no path is specified, an\n * automatically-generated unique ID will be used for the returned\n * `DocumentReference`.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a document. Has to be omitted to use\n * auto-genrated IDs.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc<AppModelType, DbModelType extends DocumentData>(\n reference: CollectionReference<AppModelType, DbModelType>,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference<AppModelType, DbModelType>;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n path: string,\n ...pathSegments: string[]\n): DocumentReference<DocumentData, DocumentData>;\nexport function doc<AppModelType, DbModelType extends DocumentData>(\n parent:\n | Firestore\n | CollectionReference<AppModelType, DbModelType>\n | DocumentReference<AppModelType, DbModelType>,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference<AppModelType, DbModelType> {\n parent = getModularInstance(parent);\n\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 1) {\n path = AutoId.newId();\n }\n validateNonEmptyArgument('doc', 'path', path);\n\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent,\n /* converter= */ null,\n new DocumentKey(absolutePath)\n );\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateDocumentPath(absolutePath);\n return new DocumentReference<AppModelType, DbModelType>(\n parent.firestore,\n parent instanceof CollectionReference ? parent.converter : null,\n new DocumentKey(absolutePath)\n );\n }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function refEqual<AppModelType, DbModelType extends DocumentData>(\n left:\n | DocumentReference<AppModelType, DbModelType>\n | CollectionReference<AppModelType, DbModelType>,\n right:\n | DocumentReference<AppModelType, DbModelType>\n | CollectionReference<AppModelType, DbModelType>\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (\n (left instanceof DocumentReference ||\n left instanceof CollectionReference) &&\n (right instanceof DocumentReference || right instanceof CollectionReference)\n ) {\n return (\n left.firestore === right.firestore &&\n left.path === right.path &&\n left.converter === right.converter\n );\n }\n return false;\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function queryEqual<AppModelType, DbModelType extends DocumentData>(\n left: Query<AppModelType, DbModelType>,\n right: Query<AppModelType, DbModelType>\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof Query && right instanceof Query) {\n return (\n left.firestore === right.firestore &&\n queryEquals(left._query, right._query) &&\n left.converter === right.converter\n );\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\nimport { getDocument } from '../platform/dom';\nimport { ExponentialBackoff } from '../remote/backoff';\n\nimport { debugAssert, fail } from './assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from './async_queue';\nimport { FirestoreError } from './error';\nimport { logDebug, logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\nexport class AsyncQueueImpl implements AsyncQueue {\n // The last promise in the queue.\n private tail: Promise<unknown> = Promise.resolve();\n\n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n private retryableOps: Array<() => Promise<void>> = [];\n\n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n private _isShuttingDown: boolean = false;\n\n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n private delayedOperations: Array<DelayedOperation<unknown>> = [];\n\n // visible for testing\n failure: FirestoreError | null = null;\n\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n private operationInProgress = false;\n\n // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n private skipNonRestrictedTasks = false;\n\n // List of TimerIds to fast-forward delays for.\n private timerIdsToSkip: TimerId[] = [];\n\n // Backoff timer used to schedule retries for retryable operations\n private backoff = new ExponentialBackoff(this, TimerId.AsyncQueueRetry);\n\n // Visibility handler that triggers an immediate retry of all retryable\n // operations. Meant to speed up recovery when we regain file system access\n // after page comes into foreground.\n private visibilityHandler: () => void = () => {\n const document = getDocument();\n if (document) {\n logDebug(\n LOG_TAG,\n 'Visibility state changed to ' + document.visibilityState\n );\n }\n this.backoff.skipBackoff();\n };\n\n constructor() {\n const document = getDocument();\n if (document && typeof document.addEventListener === 'function') {\n document.addEventListener('visibilitychange', this.visibilityHandler);\n }\n }\n\n get isShuttingDown(): boolean {\n return this._isShuttingDown;\n }\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget<T extends unknown>(op: () => Promise<T>): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(op);\n }\n\n enqueueAndForgetEvenWhileRestricted<T extends unknown>(\n op: () => Promise<T>\n ): void {\n this.verifyNotFailed();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueueInternal(op);\n }\n\n enterRestrictedMode(purgeExistingTasks?: boolean): void {\n if (!this._isShuttingDown) {\n this._isShuttingDown = true;\n this.skipNonRestrictedTasks = purgeExistingTasks || false;\n const document = getDocument();\n if (document && typeof document.removeEventListener === 'function') {\n document.removeEventListener(\n 'visibilitychange',\n this.visibilityHandler\n );\n }\n }\n }\n\n enqueue<T extends unknown>(op: () => Promise<T>): Promise<T> {\n this.verifyNotFailed();\n if (this._isShuttingDown) {\n // Return a Promise which never resolves.\n return new Promise<T>(() => {});\n }\n\n // Create a deferred Promise that we can return to the callee. This\n // allows us to return a \"hanging Promise\" only to the callee and still\n // advance the queue even when the operation is not run.\n const task = new Deferred<T>();\n return this.enqueueInternal<unknown>(() => {\n if (this._isShuttingDown && this.skipNonRestrictedTasks) {\n // We do not resolve 'task'\n return Promise.resolve();\n }\n\n op().then(task.resolve, task.reject);\n return task.promise;\n }).then(() => task.promise);\n }\n\n enqueueRetryable(op: () => Promise<void>): void {\n this.enqueueAndForget(() => {\n this.retryableOps.push(op);\n return this.retryNextOp();\n });\n }\n\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */\n private async retryNextOp(): Promise<void> {\n if (this.retryableOps.length === 0) {\n return;\n }\n\n try {\n await this.retryableOps[0]();\n this.retryableOps.shift();\n this.backoff.reset();\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e);\n } else {\n throw e; // Failure will be handled by AsyncQueue\n }\n }\n\n if (this.retryableOps.length > 0) {\n // If there are additional operations, we re-schedule `retryNextOp()`.\n // This is necessary to run retryable operations that failed during\n // their initial attempt since we don't know whether they are already\n // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n // needs to be re-run, we will run `op1`, `op1`, `op2` using the\n // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n // call scheduled here.\n // Since `backoffAndRun()` cancels an existing backoff and schedules a\n // new backoff on every call, there is only ever a single additional\n // operation in the queue.\n this.backoff.backoffAndRun(() => this.retryNextOp());\n }\n }\n\n private enqueueInternal<T extends unknown>(op: () => Promise<T>): Promise<T> {\n const newTail = this.tail.then(() => {\n this.operationInProgress = true;\n return op()\n .catch((error: FirestoreError) => {\n this.failure = error;\n this.operationInProgress = false;\n const message = getMessageOrStack(error);\n logError('INTERNAL UNHANDLED ERROR: ', message);\n\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw error;\n })\n .then(result => {\n this.operationInProgress = false;\n return result;\n });\n });\n this.tail = newTail;\n return newTail;\n }\n\n enqueueAfterDelay<T extends unknown>(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise<T>\n ): DelayedOperation<T> {\n this.verifyNotFailed();\n\n debugAssert(\n delayMs >= 0,\n `Attempted to schedule an operation with a negative delay of ${delayMs}`\n );\n\n // Fast-forward delays for timerIds that have been overriden.\n if (this.timerIdsToSkip.indexOf(timerId) > -1) {\n delayMs = 0;\n }\n\n const delayedOp = DelayedOperation.createAndSchedule<T>(\n this,\n timerId,\n delayMs,\n op,\n removedOp =>\n this.removeDelayedOperation(removedOp as DelayedOperation<unknown>)\n );\n this.delayedOperations.push(delayedOp as DelayedOperation<unknown>);\n return delayedOp;\n }\n\n private verifyNotFailed(): void {\n if (this.failure) {\n fail('AsyncQueue is already failed: ' + getMessageOrStack(this.failure));\n }\n }\n\n verifyOperationInProgress(): void {\n debugAssert(\n this.operationInProgress,\n 'verifyOpInProgress() called when no op in progress on this queue.'\n );\n }\n\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */\n async drain(): Promise<void> {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let currentTail: Promise<unknown>;\n do {\n currentTail = this.tail;\n await currentTail;\n } while (currentTail !== this.tail);\n }\n\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */\n containsDelayedOperation(timerId: TimerId): boolean {\n for (const op of this.delayedOperations) {\n if (op.timerId === timerId) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId - Delayed operations up to and including this TimerId\n * will be drained. Pass TimerId.All to run all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */\n runAllDelayedOperationsUntil(lastTimerId: TimerId): Promise<void> {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.drain().then(() => {\n // Run ops in the same order they'd run if they ran naturally.\n this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs);\n\n for (const op of this.delayedOperations) {\n op.skipDelay();\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\n break;\n }\n }\n\n return this.drain();\n });\n }\n\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */\n skipDelaysForTimerId(timerId: TimerId): void {\n this.timerIdsToSkip.push(timerId);\n }\n\n /** Called once a DelayedOperation is run or canceled. */\n private removeDelayedOperation(op: DelayedOperation<unknown>): void {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const index = this.delayedOperations.indexOf(op);\n debugAssert(index >= 0, 'Delayed operation not found.');\n this.delayedOperations.splice(index, 1);\n }\n}\n\nexport function newAsyncQueue(): AsyncQueue {\n return new AsyncQueueImpl();\n}\n\n/**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\nfunction getMessageOrStack(error: Error): string {\n let message = error.message || '';\n if (error.stack) {\n if (error.stack.includes(error.message)) {\n message = error.stack;\n } else {\n message = error.message + '\\n' + error.stack;\n }\n }\n return message;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport { deepEqual, getDefaultEmulatorHostnameAndPort } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport {\n IndexedDbOfflineComponentProvider,\n MultiTabOfflineComponentProvider,\n OfflineComponentProvider,\n OnlineComponentProvider\n} from '../core/component_provider';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport {\n canFallbackFromIndexedDbError,\n FirestoreClient,\n firestoreClientDisableNetwork,\n firestoreClientEnableNetwork,\n firestoreClientGetNamedQuery,\n firestoreClientLoadBundle,\n firestoreClientWaitForPendingWrites,\n setOfflineComponentProvider,\n setOnlineComponentProvider\n} from '../core/firestore_client';\nimport { makeDatabaseInfo } from '../lite-api/components';\nimport {\n Firestore as LiteFirestore,\n connectFirestoreEmulator\n} from '../lite-api/database';\nimport { Query } from '../lite-api/reference';\nimport {\n indexedDbClearPersistence,\n indexedDbStoragePrefix\n} from '../local/indexeddb_persistence';\nimport { LRU_COLLECTION_DISABLED } from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\nimport { Deferred } from '../util/promise';\n\nimport { LoadBundleTask } from './bundle';\nimport { CredentialsProvider } from './credentials';\nimport { PersistenceSettings, FirestoreSettings } from './settings';\nexport {\n connectFirestoreEmulator,\n EmulatorMockTokenOptions\n} from '../lite-api/database';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore': Firestore;\n }\n}\n\n/**\n * Constant used to indicate the LRU garbage collection should be disabled.\n * Set this value as the `cacheSizeBytes` on the settings passed to the\n * {@link Firestore} instance.\n */\nexport const CACHE_SIZE_UNLIMITED = LRU_COLLECTION_DISABLED;\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore extends LiteFirestore {\n /**\n * Whether it's a {@link Firestore} or Firestore Lite instance.\n */\n type: 'firestore-lite' | 'firestore' = 'firestore';\n\n readonly _queue: AsyncQueue = newAsyncQueue();\n readonly _persistenceKey: string;\n\n _firestoreClient: FirestoreClient | undefined;\n\n /** @hideconstructor */\n constructor(\n authCredentialsProvider: CredentialsProvider<User>,\n appCheckCredentialsProvider: CredentialsProvider<string>,\n databaseId: DatabaseId,\n app?: FirebaseApp\n ) {\n super(\n authCredentialsProvider,\n appCheckCredentialsProvider,\n databaseId,\n app\n );\n this._persistenceKey = app?.name || '[DEFAULT]';\n }\n\n _terminate(): Promise<void> {\n if (!this._firestoreClient) {\n // The client must be initialized to ensure that all subsequent API\n // usage throws an exception.\n configureFirestore(this);\n }\n return this._firestoreClient!.terminate();\n }\n}\n\n/**\n * Initializes a new instance of {@link Firestore} with the provided settings.\n * Can only be called before any other function, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will\n * be associated.\n * @param settings - A settings object to configure the {@link Firestore} instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized {@link Firestore} instance.\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore {\n if (!databaseId) {\n databaseId = DEFAULT_DATABASE_NAME;\n }\n const provider = _getProvider(app, 'firestore');\n\n if (provider.isInitialized(databaseId)) {\n const existingInstance = provider.getImmediate({\n identifier: databaseId\n });\n const initialSettings = provider.getOptions(\n databaseId\n ) as FirestoreSettings;\n if (deepEqual(initialSettings, settings)) {\n return existingInstance;\n } else {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'initializeFirestore() has already been called with ' +\n 'different options. To avoid this error, call initializeFirestore() with the ' +\n 'same options as when it was originally called, or call getFirestore() to return the' +\n ' already initialized instance.'\n );\n }\n }\n\n if (\n settings.cacheSizeBytes !== undefined &&\n settings.localCache !== undefined\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes will` +\n `be deprecated. Instead, specify the cache size in the cache object`\n );\n }\n\n if (\n settings.cacheSizeBytes !== undefined &&\n settings.cacheSizeBytes !== CACHE_SIZE_UNLIMITED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n }\n\n return provider.initialize({\n options: settings,\n instanceIdentifier: databaseId\n });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The default {@link Firestore} instance of the default app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The default {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing named {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The named {@link Firestore} instance of the default app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing named {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The named {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n appOrDatabaseId?: FirebaseApp | string,\n optionalDatabaseId?: string\n): Firestore {\n const app: FirebaseApp =\n typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n const databaseId =\n typeof appOrDatabaseId === 'string'\n ? appOrDatabaseId\n : optionalDatabaseId || DEFAULT_DATABASE_NAME;\n const db = _getProvider(app, 'firestore').getImmediate({\n identifier: databaseId\n }) as Firestore;\n if (!db._initialized) {\n const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n if (emulator) {\n connectFirestoreEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * @internal\n */\nexport function ensureFirestoreConfigured(\n firestore: Firestore\n): FirestoreClient {\n if (!firestore._firestoreClient) {\n configureFirestore(firestore);\n }\n firestore._firestoreClient!.verifyNotTerminated();\n return firestore._firestoreClient as FirestoreClient;\n}\n\nexport function configureFirestore(firestore: Firestore): void {\n const settings = firestore._freezeSettings();\n debugAssert(!!settings.host, 'FirestoreSettings.host is not set');\n debugAssert(\n !firestore._firestoreClient,\n 'configureFirestore() called multiple times'\n );\n\n const databaseInfo = makeDatabaseInfo(\n firestore._databaseId,\n firestore._app?.options.appId || '',\n firestore._persistenceKey,\n settings\n );\n firestore._firestoreClient = new FirestoreClient(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n firestore._queue,\n databaseInfo\n );\n if (\n settings.localCache?._offlineComponentProvider &&\n settings.localCache?._onlineComponentProvider\n ) {\n firestore._firestoreClient._uninitializedComponentsProvider = {\n _offlineKind: settings.localCache.kind,\n _offline: settings.localCache._offlineComponentProvider,\n _online: settings.localCache._onlineComponentProvider\n };\n }\n}\n\n/**\n * Attempts to enable persistent storage, if possible.\n *\n * Must be called before any other functions (other than\n * {@link initializeFirestore}, {@link (getFirestore:1)} or\n * {@link clearIndexedDbPersistence}.\n *\n * If this fails, `enableIndexedDbPersistence()` will reject the promise it\n * returns. Note that even after this failure, the {@link Firestore} instance will\n * remain usable, however offline persistence will be disabled.\n *\n * There are several reasons why this can fail, which can be identified by\n * the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab.\n * * unimplemented: The browser is incompatible with the offline\n * persistence implementation.\n *\n * Persistence cannot be used in a Node.js environment.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @param persistenceSettings - Optional settings object to configure\n * persistence.\n * @returns A `Promise` that represents successfully enabling persistent storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to\n * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache`\n * is already specified will throw an exception.\n */\nexport function enableIndexedDbPersistence(\n firestore: Firestore,\n persistenceSettings?: PersistenceSettings\n): Promise<void> {\n firestore = cast(firestore, Firestore);\n verifyNotInitialized(firestore);\n\n const client = ensureFirestoreConfigured(firestore);\n if (client._uninitializedComponentsProvider) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'SDK cache is already specified.'\n );\n }\n\n logWarn(\n 'enableIndexedDbPersistence() will be deprecated in the future, ' +\n 'you can use `FirestoreSettings.cache` instead.'\n );\n const settings = firestore._freezeSettings();\n\n const onlineComponentProvider = new OnlineComponentProvider();\n const offlineComponentProvider = new IndexedDbOfflineComponentProvider(\n onlineComponentProvider,\n settings.cacheSizeBytes,\n persistenceSettings?.forceOwnership\n );\n return setPersistenceProviders(\n client,\n onlineComponentProvider,\n offlineComponentProvider\n );\n}\n\n/**\n * Attempts to enable multi-tab persistent storage, if possible. If enabled\n * across all tabs, all operations share access to local persistence, including\n * shared execution of queries and latency-compensated local document updates\n * across all connected instances.\n *\n * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise\n * it returns. Note that even after this failure, the {@link Firestore} instance will\n * remain usable, however offline persistence will be disabled.\n *\n * There are several reasons why this can fail, which can be identified by\n * the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab and\n * multi-tab is not enabled.\n * * unimplemented: The browser is incompatible with the offline\n * persistence implementation.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @returns A `Promise` that represents successfully enabling persistent\n * storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to\n * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache`\n * is already specified will throw an exception.\n */\nexport function enableMultiTabIndexedDbPersistence(\n firestore: Firestore\n): Promise<void> {\n firestore = cast(firestore, Firestore);\n verifyNotInitialized(firestore);\n\n const client = ensureFirestoreConfigured(firestore);\n if (client._uninitializedComponentsProvider) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'SDK cache is already specified.'\n );\n }\n\n logWarn(\n 'enableMultiTabIndexedDbPersistence() will be deprecated in the future, ' +\n 'you can use `FirestoreSettings.cache` instead.'\n );\n const settings = firestore._freezeSettings();\n\n const onlineComponentProvider = new OnlineComponentProvider();\n const offlineComponentProvider = new MultiTabOfflineComponentProvider(\n onlineComponentProvider,\n settings.cacheSizeBytes\n );\n return setPersistenceProviders(\n client,\n onlineComponentProvider,\n offlineComponentProvider\n );\n}\n\n/**\n * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.\n * If the operation fails with a recoverable error (see\n * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected\n * but the client remains usable.\n */\nfunction setPersistenceProviders(\n client: FirestoreClient,\n onlineComponentProvider: OnlineComponentProvider,\n offlineComponentProvider: OfflineComponentProvider\n): Promise<void> {\n const persistenceResult = new Deferred();\n return client.asyncQueue\n .enqueue(async () => {\n try {\n await setOfflineComponentProvider(client, offlineComponentProvider);\n await setOnlineComponentProvider(client, onlineComponentProvider);\n persistenceResult.resolve();\n } catch (e) {\n const error = e as FirestoreError | DOMException;\n if (!canFallbackFromIndexedDbError(error)) {\n throw error;\n }\n logWarn(\n 'Error enabling indexeddb cache. Falling back to ' +\n 'memory cache: ' +\n error\n );\n persistenceResult.reject(error);\n }\n })\n .then(() => persistenceResult.promise);\n}\n\n/**\n * Clears the persistent storage. This includes pending writes and cached\n * documents.\n *\n * Must be called while the {@link Firestore} instance is not started (after the app is\n * terminated or when the app is first initialized). On startup, this function\n * must be called before other functions (other than {@link\n * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}\n * instance is still running, the promise will be rejected with the error code\n * of `failed-precondition`.\n *\n * Note: `clearIndexedDbPersistence()` is primarily intended to help write\n * reliable tests that use Cloud Firestore. It uses an efficient mechanism for\n * dropping existing data but does not attempt to securely overwrite or\n * otherwise make cached data unrecoverable. For applications that are sensitive\n * to the disclosure of cached data in between user sessions, we strongly\n * recommend not enabling persistence at all.\n *\n * @param firestore - The {@link Firestore} instance to clear persistence for.\n * @returns A `Promise` that is resolved when the persistent storage is\n * cleared. Otherwise, the promise is rejected with an error.\n */\nexport function clearIndexedDbPersistence(firestore: Firestore): Promise<void> {\n if (firestore._initialized && !firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Persistence can only be cleared before a Firestore instance is ' +\n 'initialized or after it is terminated.'\n );\n }\n\n const deferred = new Deferred<void>();\n firestore._queue.enqueueAndForgetEvenWhileRestricted(async () => {\n try {\n await indexedDbClearPersistence(\n indexedDbStoragePrefix(firestore._databaseId, firestore._persistenceKey)\n );\n deferred.resolve();\n } catch (e) {\n deferred.reject(e as Error | undefined);\n }\n });\n return deferred.promise;\n}\n\n/**\n * Waits until all currently pending writes for the active user have been\n * acknowledged by the backend.\n *\n * The returned promise resolves immediately if there are no outstanding writes.\n * Otherwise, the promise waits for all previously issued writes (including\n * those written in a previous app session), but it does not wait for writes\n * that were added after the function is called. If you want to wait for\n * additional writes, call `waitForPendingWrites()` again.\n *\n * Any outstanding `waitForPendingWrites()` promises are rejected during user\n * changes.\n *\n * @returns A `Promise` which resolves when all currently pending writes have been\n * acknowledged by the backend.\n */\nexport function waitForPendingWrites(firestore: Firestore): Promise<void> {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientWaitForPendingWrites(client);\n}\n\n/**\n * Re-enables use of the network for this {@link Firestore} instance after a prior\n * call to {@link disableNetwork}.\n *\n * @returns A `Promise` that is resolved once the network has been enabled.\n */\nexport function enableNetwork(firestore: Firestore): Promise<void> {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientEnableNetwork(client);\n}\n\n/**\n * Disables network usage for this instance. It can be re-enabled via {@link\n * enableNetwork}. While the network is disabled, any snapshot listeners,\n * `getDoc()` or `getDocs()` calls will return results from cache, and any write\n * operations will be queued until the network is restored.\n *\n * @returns A `Promise` that is resolved once the network has been disabled.\n */\nexport function disableNetwork(firestore: Firestore): Promise<void> {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientDisableNetwork(client);\n}\n\n/**\n * Terminates the provided {@link Firestore} instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` function\n * may be used. Any other function will throw a `FirestoreError`.\n *\n * To restart after termination, create a new instance of FirebaseFirestore with\n * {@link (getFirestore:1)}.\n *\n * Termination does not cancel any pending writes, and any promises that are\n * awaiting a response from the server will not be resolved. If you have\n * persistence enabled, the next time you start this instance, it will resume\n * sending these writes to the server.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all\n * of its resources or in combination with `clearIndexedDbPersistence()` to\n * ensure that all local state is destroyed between test runs.\n *\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise<void> {\n _removeServiceInstance(\n firestore.app,\n 'firestore',\n firestore._databaseId.database\n );\n return firestore._delete();\n}\n\n/**\n * Loads a Firestore bundle into the local cache.\n *\n * @param firestore - The {@link Firestore} instance to load bundles for.\n * @param bundleData - An object representing the bundle to be loaded. Valid\n * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.\n *\n * @returns A `LoadBundleTask` object, which notifies callers with progress\n * updates, and completion or error events. It can be used as a\n * `Promise<LoadBundleTaskProgress>`.\n */\nexport function loadBundle(\n firestore: Firestore,\n bundleData: ReadableStream<Uint8Array> | ArrayBuffer | string\n): LoadBundleTask {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const resultTask = new LoadBundleTask();\n firestoreClientLoadBundle(\n client,\n firestore._databaseId,\n bundleData,\n resultTask\n );\n return resultTask;\n}\n\n/**\n * Reads a Firestore {@link Query} from local cache, identified by the given\n * name.\n *\n * The named queries are packaged into bundles on the server side (along\n * with resulting documents), and loaded to local cache using `loadBundle`. Once\n * in local cache, use this method to extract a {@link Query} by name.\n *\n * @param firestore - The {@link Firestore} instance to read the query from.\n * @param name - The name of the query.\n * @returns A `Promise` that is resolved with the Query or `null`.\n */\nexport function namedQuery(\n firestore: Firestore,\n name: string\n): Promise<Query | null> {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientGetNamedQuery(client, name).then(namedQuery => {\n if (!namedQuery) {\n return null;\n }\n\n return new Query(firestore, null, namedQuery.query);\n });\n}\n\nfunction verifyNotInitialized(firestore: Firestore): void {\n if (firestore._initialized || firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and persistence can no longer be ' +\n 'enabled. You can only enable persistence before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * An immutable object representing an array of bytes.\n */\nexport class Bytes {\n _byteString: ByteString;\n\n /** @hideconstructor */\n constructor(byteString: ByteString) {\n this._byteString = byteString;\n }\n\n /**\n * Creates a new `Bytes` object from the given Base64 string, converting it to\n * bytes.\n *\n * @param base64 - The Base64 string used to create the `Bytes` object.\n */\n static fromBase64String(base64: string): Bytes {\n try {\n return new Bytes(ByteString.fromBase64String(base64));\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to construct data from Base64 string: ' + e\n );\n }\n }\n\n /**\n * Creates a new `Bytes` object from the given Uint8Array.\n *\n * @param array - The Uint8Array used to create the `Bytes` object.\n */\n static fromUint8Array(array: Uint8Array): Bytes {\n return new Bytes(ByteString.fromUint8Array(array));\n }\n\n /**\n * Returns the underlying bytes as a Base64-encoded string.\n *\n * @returns The Base64-encoded string created from the `Bytes` object.\n */\n toBase64(): string {\n return this._byteString.toBase64();\n }\n\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */\n toUint8Array(): Uint8Array {\n return this._byteString.toUint8Array();\n }\n\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */\n toString(): string {\n return 'Bytes(base64: ' + this.toBase64() + ')';\n }\n\n /**\n * Returns true if this `Bytes` object is equal to the provided one.\n *\n * @param other - The `Bytes` object to compare against.\n * @returns true if this `Bytes` object is equal to the provided one.\n */\n isEqual(other: Bytes): boolean {\n return this._byteString.isEqual(other._byteString);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DOCUMENT_KEY_NAME,\n FieldPath as InternalFieldPath\n} from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */\nexport class FieldPath {\n /** Internal representation of a Firestore field path. */\n readonly _internalPath: InternalFieldPath;\n\n /**\n * Creates a `FieldPath` from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...fieldNames: string[]) {\n for (let i = 0; i < fieldNames.length; ++i) {\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field name at argument $(i + 1). ` +\n 'Field names must not be empty.'\n );\n }\n }\n\n this._internalPath = new InternalFieldPath(fieldNames);\n }\n\n /**\n * Returns true if this `FieldPath` is equal to the provided one.\n *\n * @param other - The `FieldPath` to compare against.\n * @returns true if this `FieldPath` is equal to the provided one.\n */\n isEqual(other: FieldPath): boolean {\n return this._internalPath.isEqual(other._internalPath);\n }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */\nexport function documentId(): FieldPath {\n return new FieldPath(DOCUMENT_KEY_NAME);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParseContext } from '../api/parse_context';\nimport { FieldTransform } from '../model/mutation';\n\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */\nexport abstract class FieldValue {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(public _methodName: string) {}\n\n /** Compares `FieldValue`s for equality. */\n abstract isEqual(other: FieldValue): boolean;\n abstract _toFieldTransform(context: ParseContext): FieldTransform | null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\nimport { primitiveComparator } from '../util/misc';\n\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */\nexport class GeoPoint {\n // Prefix with underscore to signal this is a private variable in JS and\n // prevent it showing up for autocompletion when typing latitude or longitude.\n private _lat: number;\n private _long: number;\n\n /**\n * Creates a new immutable `GeoPoint` object with the provided latitude and\n * longitude values.\n * @param latitude - The latitude as number between -90 and 90.\n * @param longitude - The longitude as number between -180 and 180.\n */\n constructor(latitude: number, longitude: number) {\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Latitude must be a number between -90 and 90, but was: ' + latitude\n );\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Longitude must be a number between -180 and 180, but was: ' + longitude\n );\n }\n\n this._lat = latitude;\n this._long = longitude;\n }\n\n /**\n * The latitude of this `GeoPoint` instance.\n */\n get latitude(): number {\n return this._lat;\n }\n\n /**\n * The longitude of this `GeoPoint` instance.\n */\n get longitude(): number {\n return this._long;\n }\n\n /**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other - The `GeoPoint` to compare against.\n * @returns true if this `GeoPoint` is equal to the provided one.\n */\n isEqual(other: GeoPoint): boolean {\n return this._lat === other._lat && this._long === other._long;\n }\n\n /** Returns a JSON-serializable representation of this GeoPoint. */\n toJSON(): { latitude: number; longitude: number } {\n return { latitude: this._lat, longitude: this._long };\n }\n\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n _compareTo(other: GeoPoint): number {\n return (\n primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport { newSerializer } from '../platform/serializer';\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { toNumber } from '../remote/number_serializer';\nimport {\n JsonProtoSerializer,\n toBytes,\n toResourceName,\n toTimestamp\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { Dict, forEach, isEmpty } from '../util/obj';\n\nimport { Bytes } from './bytes';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { GeoPoint } from './geo_point';\nimport {\n DocumentReference,\n PartialWithFieldValue,\n WithFieldValue\n} from './reference';\nimport { Timestamp } from './timestamp';\n\nconst RESERVED_FIELD_REGEX = /^__.*__$/;\n\n/**\n * An untyped Firestore Data Converter interface that is shared between the\n * lite, firestore-exp and classic SDK.\n */\nexport interface UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n toFirestore(\n modelObject: WithFieldValue<AppModelType>\n ): WithFieldValue<DbModelType>;\n toFirestore(\n modelObject: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n ): PartialWithFieldValue<DbModelType>;\n fromFirestore(snapshot: unknown, options?: unknown): AppModelType;\n}\n\n/** The result of parsing document data (e.g. for a setData call). */\nexport class ParsedSetData {\n constructor(\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask | null,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n if (this.fieldMask !== null) {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n } else {\n return new SetMutation(\n key,\n this.data,\n precondition,\n this.fieldTransforms\n );\n }\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nexport class ParsedUpdateData {\n constructor(\n readonly data: ObjectValue,\n // The fieldMask does not include document transforms.\n readonly fieldMask: FieldMask,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n }\n}\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nexport const enum UserDataSource {\n Set,\n Update,\n MergeSet,\n /**\n * Indicates the source is a where clause, cursor bound, arrayUnion()\n * element, etc. Of note, isWrite(source) will return false.\n */\n Argument,\n /**\n * Indicates that the source is an Argument that may directly contain nested\n * arrays (e.g. the operand of an `in` query).\n */\n ArrayArgument\n}\n\nfunction isWrite(dataSource: UserDataSource): boolean {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.Argument:\n case UserDataSource.ArrayArgument:\n return false;\n default:\n throw fail(`Unexpected case for UserDataSource: ${dataSource}`);\n }\n}\n\n/** Contains the settings that are mutated as we parse user data. */\ninterface ContextSettings {\n /** Indicates what kind of API method this data came from. */\n readonly dataSource: UserDataSource;\n /** The name of the method the user called to create the ParseContext. */\n readonly methodName: string;\n /** The document the user is attempting to modify, if that applies. */\n readonly targetDoc?: DocumentKey;\n /**\n * A path within the object being parsed. This could be an empty path (in\n * which case the context represents the root of the data being parsed), or a\n * nonempty path (indicating the context represents a nested location within\n * the data).\n */\n readonly path?: InternalFieldPath;\n /**\n * Whether or not this context corresponds to an element of an array.\n * If not set, elements are treated as if they were outside of arrays.\n */\n readonly arrayElement?: boolean;\n /**\n * Whether or not a converter was specified in this context. If true, error\n * messages will reference the converter when invalid data is provided.\n */\n readonly hasConverter?: boolean;\n}\n\n/** A \"context\" object passed around while parsing user data. */\nclass ParseContextImpl implements ParseContext {\n readonly fieldTransforms: FieldTransform[];\n readonly fieldMask: InternalFieldPath[];\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings - The settings for the parser.\n * @param databaseId - The database ID of the Firestore instance.\n * @param serializer - The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms - A mutable list of field transforms encountered\n * while parsing the data.\n * @param fieldMask - A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(\n readonly settings: ContextSettings,\n readonly databaseId: DatabaseId,\n readonly serializer: JsonProtoSerializer,\n readonly ignoreUndefinedProperties: boolean,\n fieldTransforms?: FieldTransform[],\n fieldMask?: InternalFieldPath[]\n ) {\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n\n get path(): InternalFieldPath | undefined {\n return this.settings.path;\n }\n\n get dataSource(): UserDataSource {\n return this.settings.dataSource;\n }\n\n /** Returns a new context with the specified settings overwritten. */\n contextWith(configuration: Partial<ContextSettings>): ParseContextImpl {\n return new ParseContextImpl(\n { ...this.settings, ...configuration },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties,\n this.fieldTransforms,\n this.fieldMask\n );\n }\n\n childContextForField(field: string): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePathSegment(field);\n return context;\n }\n\n childContextForFieldPath(field: InternalFieldPath): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePath();\n return context;\n }\n\n childContextForArray(index: number): ParseContextImpl {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.contextWith({ path: undefined, arrayElement: true });\n }\n\n createError(reason: string): FirestoreError {\n return createError(\n reason,\n this.settings.methodName,\n this.settings.hasConverter || false,\n this.path,\n this.settings.targetDoc\n );\n }\n\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\n contains(fieldPath: InternalFieldPath): boolean {\n return (\n this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined ||\n this.fieldTransforms.find(transform =>\n fieldPath.isPrefixOf(transform.field)\n ) !== undefined\n );\n }\n\n private validatePath(): void {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (!this.path) {\n return;\n }\n for (let i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n }\n\n private validatePathSegment(segment: string): void {\n if (segment.length === 0) {\n throw this.createError('Document fields must not be empty');\n }\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with \"__\"');\n }\n }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nexport class UserDataReader {\n private readonly serializer: JsonProtoSerializer;\n\n constructor(\n private readonly databaseId: DatabaseId,\n private readonly ignoreUndefinedProperties: boolean,\n serializer?: JsonProtoSerializer\n ) {\n this.serializer = serializer || newSerializer(databaseId);\n }\n\n /** Creates a new top-level parse context. */\n createContext(\n dataSource: UserDataSource,\n methodName: string,\n targetDoc?: DocumentKey,\n hasConverter = false\n ): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource,\n methodName,\n targetDoc,\n path: InternalFieldPath.emptyPath(),\n arrayElement: false,\n hasConverter\n },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties\n );\n }\n}\n\nexport function newUserDataReader(firestore: Firestore): UserDataReader {\n const settings = firestore._freezeSettings();\n const serializer = newSerializer(firestore._databaseId);\n return new UserDataReader(\n firestore._databaseId,\n !!settings.ignoreUndefinedProperties,\n serializer\n );\n}\n\n/** Parse document data from a set() call. */\nexport function parseSetData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown,\n hasConverter: boolean,\n options: SetOptions = {}\n): ParsedSetData {\n const context = userDataReader.createContext(\n options.merge || options.mergeFields\n ? UserDataSource.MergeSet\n : UserDataSource.Set,\n methodName,\n targetDoc,\n hasConverter\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n const updateData = parseObject(input, context)!;\n\n let fieldMask: FieldMask | null;\n let fieldTransforms: FieldTransform[];\n\n if (options.merge) {\n fieldMask = new FieldMask(context.fieldMask);\n fieldTransforms = context.fieldTransforms;\n } else if (options.mergeFields) {\n const validatedFieldPaths: InternalFieldPath[] = [];\n\n for (const stringOrFieldPath of options.mergeFields) {\n const fieldPath = fieldPathFromArgument(\n methodName,\n stringOrFieldPath,\n targetDoc\n );\n if (!context.contains(fieldPath)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Field '${fieldPath}' is specified in your field mask but missing from your input data.`\n );\n }\n\n if (!fieldMaskContains(validatedFieldPaths, fieldPath)) {\n validatedFieldPaths.push(fieldPath);\n }\n }\n\n fieldMask = new FieldMask(validatedFieldPaths);\n fieldTransforms = context.fieldTransforms.filter(transform =>\n fieldMask!.covers(transform.field)\n );\n } else {\n fieldMask = null;\n fieldTransforms = context.fieldTransforms;\n }\n\n return new ParsedSetData(\n new ObjectValue(updateData),\n fieldMask,\n fieldTransforms\n );\n}\n\nexport class DeleteFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): null {\n if (context.dataSource === UserDataSource.MergeSet) {\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n context.fieldMask.push(context.path!);\n } else if (context.dataSource === UserDataSource.Update) {\n debugAssert(\n context.path!.length > 0,\n `${this._methodName}() at the top level should have already ` +\n 'been handled.'\n );\n throw context.createError(\n `${this._methodName}() can only appear at the top level ` +\n 'of your update data'\n );\n } else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError(\n `${this._methodName}() cannot be used with set() unless you pass ` +\n '{merge:true}'\n );\n }\n return null;\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof DeleteFieldValueImpl;\n }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n * context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */\nfunction createSentinelChildContext(\n fieldValue: FieldValue,\n context: ParseContextImpl,\n arrayElement: boolean\n): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource: UserDataSource.Argument,\n targetDoc: context.settings.targetDoc,\n methodName: fieldValue._methodName,\n arrayElement\n },\n context.databaseId,\n context.serializer,\n context.ignoreUndefinedProperties\n );\n}\n\nexport class ServerTimestampFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n return new FieldTransform(context.path!, new ServerTimestampTransform());\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof ServerTimestampFieldValueImpl;\n }\n}\n\nexport class ArrayUnionFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayUnionTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n // TODO(mrschmidt): Implement isEquals\n return this === other;\n }\n}\n\nexport class ArrayRemoveFieldValueImpl extends FieldValue {\n constructor(methodName: string, readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayRemoveTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n // TODO(mrschmidt): Implement isEquals\n return this === other;\n }\n}\n\nexport class NumericIncrementFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _operand: number) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const numericIncrement = new NumericIncrementTransformOperation(\n context.serializer,\n toNumber(context.serializer, this._operand)\n );\n return new FieldTransform(context.path!, numericIncrement);\n }\n\n isEqual(other: FieldValue): boolean {\n // TODO(mrschmidt): Implement isEquals\n return this === other;\n }\n}\n\n/** Parse update data from an update() call. */\nexport function parseUpdateData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n forEach(input as Dict<unknown>, (key, value) => {\n const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n });\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */\nexport function parseUpdateVarargs(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n field: string | PublicFieldPath | Compat<PublicFieldPath>,\n value: unknown,\n moreFieldsAndValues: unknown[]\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n const keys = [fieldPathFromArgument(methodName, field, targetDoc)];\n const values = [value];\n\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${methodName}() needs to be called with an even number ` +\n 'of arguments that alternate between field names and values.'\n );\n }\n\n for (let i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(\n fieldPathFromArgument(\n methodName,\n moreFieldsAndValues[i] as string | PublicFieldPath\n )\n );\n values.push(moreFieldsAndValues[i + 1]);\n }\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n\n // We iterate in reverse order to pick the last value for a field if the\n // user specified the field multiple times.\n for (let i = keys.length - 1; i >= 0; --i) {\n if (!fieldMaskContains(fieldMaskPaths, keys[i])) {\n const path = keys[i];\n let value = values[i];\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n }\n }\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */\nexport function parseQueryValue(\n userDataReader: UserDataReader,\n methodName: string,\n input: unknown,\n allowArrays = false\n): ProtoValue {\n const context = userDataReader.createContext(\n allowArrays ? UserDataSource.ArrayArgument : UserDataSource.Argument,\n methodName\n );\n const parsed = parseData(input, context);\n debugAssert(parsed != null, 'Parsed data should not be null.');\n debugAssert(\n context.fieldTransforms.length === 0,\n 'Field transforms should have been disallowed.'\n );\n return parsed;\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\nexport function parseData(\n input: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n input = getModularInstance(input);\n\n if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return parseObject(input, context);\n } else if (input instanceof FieldValue) {\n // FieldValues usually parse into transforms (except deleteField())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n parseSentinelFieldValue(input, context);\n return null;\n } else if (input === undefined && context.ignoreUndefinedProperties) {\n // If the input is undefined it can never participate in the fieldMask, so\n // don't handle this below. If `ignoreUndefinedProperties` is false,\n // `parseScalarValue` will reject an undefined value.\n return null;\n } else {\n // If context.path is null we are inside an array and we don't support\n // field mask paths more granular than the top-level array.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n\n if (input instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n // In the case of IN queries, the parsed data is an array (representing\n // the set of values to be included for the IN query) that may directly\n // contain additional arrays (each representing an individual field\n // value), so we disable this validation.\n if (\n context.settings.arrayElement &&\n context.dataSource !== UserDataSource.ArrayArgument\n ) {\n throw context.createError('Nested arrays are not supported');\n }\n return parseArray(input as unknown[], context);\n } else {\n return parseScalarValue(input, context);\n }\n }\n}\n\nfunction parseObject(\n obj: Dict<unknown>,\n context: ParseContextImpl\n): { mapValue: ProtoMapValue } {\n const fields: Dict<ProtoValue> = {};\n\n if (isEmpty(obj)) {\n // If we encounter an empty object, we explicitly add it to the update\n // mask to ensure that the server creates a map entry.\n if (context.path && context.path.length > 0) {\n context.fieldMask.push(context.path);\n }\n } else {\n forEach(obj, (key: string, val: unknown) => {\n const parsedValue = parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n fields[key] = parsedValue;\n }\n });\n }\n\n return { mapValue: { fields } };\n}\n\nfunction parseArray(array: unknown[], context: ParseContextImpl): ProtoValue {\n const values: ProtoValue[] = [];\n let entryIndex = 0;\n for (const entry of array) {\n let parsedEntry = parseData(\n entry,\n context.childContextForArray(entryIndex)\n );\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = { nullValue: 'NULL_VALUE' };\n }\n values.push(parsedEntry);\n entryIndex++;\n }\n return { arrayValue: { values } };\n}\n\n/**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\nfunction parseSentinelFieldValue(\n value: FieldValue,\n context: ParseContextImpl\n): void {\n // Sentinels are only supported with writes, and not within arrays.\n if (!isWrite(context.dataSource)) {\n throw context.createError(\n `${value._methodName}() can only be used with update() and set()`\n );\n }\n if (!context.path) {\n throw context.createError(\n `${value._methodName}() is not currently supported inside arrays`\n );\n }\n\n const fieldTransform = value._toFieldTransform(context);\n if (fieldTransform) {\n context.fieldTransforms.push(fieldTransform);\n }\n}\n\n/**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */\nfunction parseScalarValue(\n value: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n value = getModularInstance(value);\n\n if (value === null) {\n return { nullValue: 'NULL_VALUE' };\n } else if (typeof value === 'number') {\n return toNumber(context.serializer, value);\n } else if (typeof value === 'boolean') {\n return { booleanValue: value };\n } else if (typeof value === 'string') {\n return { stringValue: value };\n } else if (value instanceof Date) {\n const timestamp = Timestamp.fromDate(value);\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof Timestamp) {\n // Firestore backend truncates precision down to microseconds. To ensure\n // offline mode works the same with regards to truncation, perform the\n // truncation immediately without waiting for the backend to do that.\n const timestamp = new Timestamp(\n value.seconds,\n Math.floor(value.nanoseconds / 1000) * 1000\n );\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof GeoPoint) {\n return {\n geoPointValue: {\n latitude: value.latitude,\n longitude: value.longitude\n }\n };\n } else if (value instanceof Bytes) {\n return { bytesValue: toBytes(context.serializer, value._byteString) };\n } else if (value instanceof DocumentReference) {\n const thisDb = context.databaseId;\n const otherDb = value.firestore._databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw context.createError(\n 'Document reference is for database ' +\n `${otherDb.projectId}/${otherDb.database} but should be ` +\n `for database ${thisDb.projectId}/${thisDb.database}`\n );\n }\n return {\n referenceValue: toResourceName(\n value.firestore._databaseId || context.databaseId,\n value._key.path\n )\n };\n } else {\n throw context.createError(\n `Unsupported field value: ${valueDescription(value)}`\n );\n }\n}\n\n/**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */\nfunction looksLikeJsonObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof Timestamp) &&\n !(input instanceof GeoPoint) &&\n !(input instanceof Bytes) &&\n !(input instanceof DocumentReference) &&\n !(input instanceof FieldValue)\n );\n}\n\nfunction validatePlainObject(\n message: string,\n context: ParseContextImpl,\n input: unknown\n): asserts input is Dict<unknown> {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n const description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n } else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n path: string | PublicFieldPath | Compat<PublicFieldPath>,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n // If required, replace the FieldPath Compat class with with the firestore-exp\n // FieldPath.\n path = getModularInstance(path);\n\n if (path instanceof FieldPath) {\n return path._internalPath;\n } else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n } else {\n const message = 'Field path arguments must be of type string or ';\n throw createError(\n message,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nconst FIELD_PATH_RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */\nexport function fieldPathFromDotSeparatedString(\n methodName: string,\n path: string,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n const found = path.search(FIELD_PATH_RESERVED);\n if (found >= 0) {\n throw createError(\n `Invalid field path (${path}). Paths must not contain ` +\n `'~', '*', '/', '[', or ']'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n\n try {\n return new FieldPath(...path.split('.'))._internalPath;\n } catch (e) {\n throw createError(\n `Invalid field path (${path}). Paths must not be empty, ` +\n `begin with '.', end with '.', or contain '..'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\nfunction createError(\n reason: string,\n methodName: string,\n hasConverter: boolean,\n path?: InternalFieldPath,\n targetDoc?: DocumentKey\n): FirestoreError {\n const hasPath = path && !path.isEmpty();\n const hasDocument = targetDoc !== undefined;\n let message = `Function ${methodName}() called with invalid data`;\n if (hasConverter) {\n message += ' (via `toFirestore()`)';\n }\n message += '. ';\n\n let description = '';\n if (hasPath || hasDocument) {\n description += ' (found';\n\n if (hasPath) {\n description += ` in field ${path}`;\n }\n if (hasDocument) {\n description += ` in document ${targetDoc}`;\n }\n description += ')';\n }\n\n return new FirestoreError(\n Code.INVALID_ARGUMENT,\n message + reason + description\n );\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */\nfunction fieldMaskContains(\n haystack: InternalFieldPath[],\n needle: InternalFieldPath\n): boolean {\n return haystack.some(v => v.isEqual(needle));\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { arrayEquals } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n queryEqual,\n SetOptions,\n WithFieldValue\n} from './reference';\nimport {\n fieldPathFromDotSeparatedString,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * @example\n * ```typescript\n * class Post {\n * constructor(readonly title: string, readonly author: string) {}\n *\n * toString(): string {\n * return this.title + ', by ' + this.author;\n * }\n * }\n *\n * interface PostDbModel {\n * title: string;\n * author: string;\n * }\n *\n * const postConverter = {\n * toFirestore(post: WithFieldValue<Post>): PostDbModel {\n * return {title: post.title, author: post.author};\n * },\n * fromFirestore(snapshot: QueryDocumentSnapshot): Post {\n * const data = snapshot.data(options) as PostDbModel;\n * return new Post(data.title, data.author);\n * }\n * };\n *\n * const postSnap = await firebase.firestore()\n * .collection('posts')\n * .withConverter(postConverter)\n * .doc().get();\n * const post = postSnap.data();\n * if (post !== undefined) {\n * post.title; // string\n * post.toString(); // Should be defined\n * post.someNonExistentProperty; // TS error\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain Javascript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)}.\n *\n * The `WithFieldValue<T>` type extends `T` to also allow FieldValues such as\n * {@link (deleteField:1)} to be used as property values.\n */\n toFirestore(\n modelObject: WithFieldValue<AppModelType>\n ): WithFieldValue<DbModelType>;\n\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain Javascript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true`\n * or `mergeFields`.\n *\n * The `PartialWithFieldValue<T>` type extends `Partial<T>` to allow\n * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n * It also supports nested `Partial` by allowing nested fields to be\n * omitted.\n */\n toFirestore(\n modelObject: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n ): PartialWithFieldValue<DbModelType>;\n\n /**\n * Called by the Firestore SDK to convert Firestore data into an object of\n * type `AppModelType`. You can access your data by calling:\n * `snapshot.data()`.\n *\n * Generally, the data returned from `snapshot.data()` can be cast to\n * `DbModelType`; however, this is not guaranteed as writes to the database\n * may have occurred without a type converter enforcing this specific layout.\n *\n * @param snapshot - A `QueryDocumentSnapshot` containing your data and\n * metadata.\n */\n fromFirestore(\n snapshot: QueryDocumentSnapshot<DocumentData, DocumentData>\n ): AppModelType;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get(<field>)` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n // Note: This class is stripped down version of the DocumentSnapshot in\n // the legacy SDK. The changes are:\n // - No support for SnapshotMetadata.\n // - No support for SnapshotOptions.\n\n /** @hideconstructor protected */\n constructor(\n public _firestore: Firestore,\n public _userDataWriter: AbstractUserDataWriter,\n public _key: DocumentKey,\n public _document: Document | null,\n public _converter: UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null\n ) {}\n\n /** Property of the `DocumentSnapshot` that provides the document's ID. */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */\n get ref(): DocumentReference<AppModelType, DbModelType> {\n return new DocumentReference<AppModelType, DbModelType>(\n this._firestore,\n this._converter,\n this._key\n );\n }\n\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */\n exists(): this is QueryDocumentSnapshot<AppModelType, DbModelType> {\n return this._document !== null;\n }\n\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * @returns An `Object` containing all fields in the document or `undefined`\n * if the document doesn't exist.\n */\n data(): AppModelType | undefined {\n if (!this._document) {\n return undefined;\n } else if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n this._key,\n this._document,\n /* converter= */ null\n );\n return this._converter.fromFirestore(snapshot);\n } else {\n return this._userDataWriter.convertValue(\n this._document.data.value\n ) as AppModelType;\n }\n }\n\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(fieldPath: string | FieldPath): any {\n if (this._document) {\n const value = this._document.data.field(\n fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n );\n if (value !== null) {\n return this._userDataWriter.convertValue(value);\n }\n }\n return undefined;\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get(<field>)` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot<AppModelType, DbModelType> {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * @override\n * @returns An `Object` containing all fields in the document.\n */\n data(): AppModelType {\n return super.data() as AppModelType;\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * The query on which you called {@link getDocs} in order to get this\n * `QuerySnapshot`.\n */\n readonly query: Query<AppModelType, DbModelType>;\n\n /** @hideconstructor */\n constructor(\n _query: Query<AppModelType, DbModelType>,\n readonly _docs: Array<QueryDocumentSnapshot<AppModelType, DbModelType>>\n ) {\n this.query = _query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array<QueryDocumentSnapshot<AppModelType, DbModelType>> {\n return [...this._docs];\n }\n\n /** The number of documents in the `QuerySnapshot`. */\n get size(): number {\n return this.docs.length;\n }\n\n /** True if there are no documents in the `QuerySnapshot`. */\n get empty(): boolean {\n return this.docs.length === 0;\n }\n\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */\n forEach(\n callback: (\n result: QueryDocumentSnapshot<AppModelType, DbModelType>\n ) => void,\n thisArg?: unknown\n ): void {\n this._docs.forEach(callback, thisArg);\n }\n}\n\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual<AppModelType, DbModelType extends DocumentData>(\n left:\n | DocumentSnapshot<AppModelType, DbModelType>\n | QuerySnapshot<AppModelType, DbModelType>,\n right:\n | DocumentSnapshot<AppModelType, DbModelType>\n | QuerySnapshot<AppModelType, DbModelType>\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n return (\n left._firestore === right._firestore &&\n left._key.isEqual(right._key) &&\n (left._document === null\n ? right._document === null\n : left._document.isEqual(right._document)) &&\n left._converter === right._converter\n );\n } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n return (\n queryEqual(left.query, right.query) &&\n arrayEquals(left.docs, right.docs, snapshotEqual)\n );\n }\n\n return false;\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n arg: string | FieldPath | Compat<FieldPath>\n): InternalFieldPath {\n if (typeof arg === 'string') {\n return fieldPathFromDotSeparatedString(methodName, arg);\n } else if (arg instanceof FieldPath) {\n return arg._internalPath;\n } else {\n return arg._delegate._internalPath;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n isCollectionGroupQuery,\n LimitType,\n Query as InternalQuery,\n queryNormalizedOrderBy,\n queryWithAddedFilter,\n queryWithAddedOrderBy,\n queryWithEndAt,\n queryWithLimit,\n queryWithStartAt\n} from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath, ResourcePath } from '../model/path';\nimport { isServerTimestamp } from '../model/server_timestamps';\nimport { refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n validatePositiveNumber,\n valueDescription\n} from '../util/input_validation';\n\nimport { FieldPath } from './field_path';\nimport { DocumentData, DocumentReference, Query } from './reference';\nimport { DocumentSnapshot, fieldPathFromArgument } from './snapshot';\nimport {\n newUserDataReader,\n parseQueryValue,\n UserDataReader\n} from './user_data_reader';\n\nexport function validateHasExplicitOrderByForLimitToLast(\n query: InternalQuery\n): void {\n if (\n query.limitType === LimitType.Last &&\n query.explicitOrderBy.length === 0\n ) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'limitToLast() queries require specifying at least one orderBy() clause'\n );\n }\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'where'\n | 'orderBy'\n | 'limit'\n | 'limitToLast'\n | 'startAt'\n | 'startAfter'\n | 'endAt'\n | 'endBefore';\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */\nexport abstract class AppliableConstraint {\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType>;\n}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link\n * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link (query:1)} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint extends AppliableConstraint {\n /** The type of this query constraint */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType>;\n}\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to\n * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or\n * {@link or}.\n * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to\n * apply (e.g. {@link orderBy}, {@link limit}).\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n compositeFilter: QueryCompositeFilterConstraint,\n ...queryConstraints: QueryNonFilterConstraint[]\n): Query<AppModelType, DbModelType>;\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param queryConstraints - The list of {@link QueryConstraint}s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n ...queryConstraints: QueryConstraint[]\n): Query<AppModelType, DbModelType>;\n\nexport function query<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n queryConstraint: QueryCompositeFilterConstraint | QueryConstraint | undefined,\n ...additionalQueryConstraints: Array<\n QueryConstraint | QueryNonFilterConstraint\n >\n): Query<AppModelType, DbModelType> {\n let queryConstraints: AppliableConstraint[] = [];\n\n if (queryConstraint instanceof AppliableConstraint) {\n queryConstraints.push(queryConstraint);\n }\n\n queryConstraints = queryConstraints.concat(additionalQueryConstraints);\n\n validateQueryConstraintArray(queryConstraints);\n\n for (const constraint of queryConstraints) {\n query = constraint._apply(query);\n }\n return query;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link (query:1)} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */\nexport class QueryFieldFilterConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'where';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _op: Operator,\n private _value: unknown\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _op: Operator,\n _value: unknown\n ): QueryFieldFilterConstraint {\n return new QueryFieldFilterConstraint(_field, _op, _value);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const filter = this._parse(query);\n validateNewFieldFilter(query._query, filter);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, filter)\n );\n }\n\n _parse<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): FieldFilter {\n const reader = newUserDataReader(query.firestore);\n const filter = newQueryFilter(\n query._query,\n 'where',\n reader,\n query.firestore._databaseId,\n this._field,\n this._op,\n this._value\n );\n return filter;\n }\n}\n\n/**\n * Filter conditions in a {@link where} clause are specified using the\n * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in',\n * 'array-contains-any', and 'not-in'.\n */\nexport type WhereFilterOp =\n | '<'\n | '<='\n | '=='\n | '!='\n | '>='\n | '>'\n | 'array-contains'\n | 'in'\n | 'array-contains-any'\n | 'not-in';\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"<\", \"<=\", \"==\", \"<\",\n * \"<=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */\nexport function where(\n fieldPath: string | FieldPath,\n opStr: WhereFilterOp,\n value: unknown\n): QueryFieldFilterConstraint {\n const op = opStr as Operator;\n const field = fieldPathFromArgument('where', fieldPath);\n return QueryFieldFilterConstraint._create(field, op, value);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n */\nexport class QueryCompositeFilterConstraint extends AppliableConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'or' | 'and',\n private readonly _queryConstraints: QueryFilterConstraint[]\n ) {\n super();\n }\n\n static _create(\n type: 'or' | 'and',\n _queryConstraints: QueryFilterConstraint[]\n ): QueryCompositeFilterConstraint {\n return new QueryCompositeFilterConstraint(type, _queryConstraints);\n }\n\n _parse<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Filter {\n const parsedFilters = this._queryConstraints\n .map(queryConstraint => {\n return queryConstraint._parse(query);\n })\n .filter(parsedFilter => parsedFilter.getFilters().length > 0);\n\n if (parsedFilters.length === 1) {\n return parsedFilters[0];\n }\n\n return CompositeFilter.create(parsedFilters, this._getOperator());\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const parsedFilter = this._parse(query);\n if (parsedFilter.getFilters().length === 0) {\n // Return the existing query if not adding any more filters (e.g. an empty\n // composite filter).\n return query;\n }\n validateNewFilter(query._query, parsedFilter);\n\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, parsedFilter)\n );\n }\n\n _getQueryConstraints(): readonly AppliableConstraint[] {\n return this._queryConstraints;\n }\n\n _getOperator(): CompositeOperator {\n return this.type === 'and' ? CompositeOperator.AND : CompositeOperator.OR;\n }\n}\n\n/**\n * `QueryNonFilterConstraint` is a helper union type that represents\n * QueryConstraints which are used to narrow or order the set of documents,\n * but that do not explicitly filter on a document field.\n * `QueryNonFilterConstraint`s are created by invoking {@link orderBy},\n * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)},\n * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)}\n * to create a new query instance that also contains the `QueryConstraint`.\n */\nexport type QueryNonFilterConstraint =\n | QueryOrderByConstraint\n | QueryLimitConstraint\n | QueryStartAtConstraint\n | QueryEndAtConstraint;\n\n/**\n * `QueryFilterConstraint` is a helper union type that represents\n * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}.\n */\nexport type QueryFilterConstraint =\n | QueryFieldFilterConstraint\n | QueryCompositeFilterConstraint;\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function or(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('or', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.OR,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function and(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('and', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.AND,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */\nexport class QueryOrderByConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'orderBy';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _direction: Direction\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _direction: Direction\n ): QueryOrderByConstraint {\n return new QueryOrderByConstraint(_field, _direction);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const orderBy = newQueryOrderBy(query._query, this._field, this._direction);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedOrderBy(query._query, orderBy)\n );\n }\n}\n\n/**\n * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc'\n * (descending or ascending).\n */\nexport type OrderByDirection = 'desc' | 'asc';\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */\nexport function orderBy(\n fieldPath: string | FieldPath,\n directionStr: OrderByDirection = 'asc'\n): QueryOrderByConstraint {\n const direction = directionStr as Direction;\n const path = fieldPathFromArgument('orderBy', fieldPath);\n return QueryOrderByConstraint._create(path, direction);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */\nexport class QueryLimitConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'limit' | 'limitToLast',\n private readonly _limit: number,\n private readonly _limitType: LimitType\n ) {\n super();\n }\n\n static _create(\n type: 'limit' | 'limitToLast',\n _limit: number,\n _limitType: LimitType\n ): QueryLimitConstraint {\n return new QueryLimitConstraint(type, _limit, _limitType);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n return new Query(\n query.firestore,\n query.converter,\n queryWithLimit(query._query, this._limit, this._limitType)\n );\n }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limit(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limit', limit);\n return QueryLimitConstraint._create('limit', limit, LimitType.First);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limitToLast(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limitToLast', limit);\n return QueryLimitConstraint._create('limitToLast', limit, LimitType.Last);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */\nexport class QueryStartAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'startAt' | 'startAfter',\n private readonly _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'startAt' | 'startAfter',\n _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n _inclusive: boolean\n ): QueryStartAtConstraint {\n return new QueryStartAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query<AppModelType, DbModelType>(\n query.firestore,\n query.converter,\n queryWithStartAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided document (inclusive). The starting position is relative\n * to the order of the query. The document must contain all of the fields\n * provided in the `orderBy` of this query.\n *\n * @param snapshot - The snapshot of the document to start at.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt<AppModelType, DbModelType extends DocumentData>(\n snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query at, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAt<AppModelType, DbModelType extends DocumentData>(\n ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided document (exclusive). The starting position is\n * relative to the order of the query. The document must contain all of the\n * fields provided in the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to start after.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter<AppModelType, DbModelType extends DocumentData>(\n snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided fields relative to the order of the query. The order\n * of the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query after, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAfter<AppModelType, DbModelType extends DocumentData>(\n ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAfter',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */\nexport class QueryEndAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'endBefore' | 'endAt',\n private readonly _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'endBefore' | 'endAt',\n _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n _inclusive: boolean\n ): QueryEndAtConstraint {\n return new QueryEndAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithEndAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided document (exclusive). The end position is relative to the\n * order of the query. The document must contain all of the fields provided in\n * the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end before.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore<AppModelType, DbModelType extends DocumentData>(\n snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query before, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endBefore<AppModelType, DbModelType extends DocumentData>(\n ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endBefore',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided document (inclusive). The end position is relative to the order\n * of the query. The document must contain all of the fields provided in the\n * orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end at.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt<AppModelType, DbModelType extends DocumentData>(\n snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided fields relative to the order of the query. The order of the field\n * values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query at, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endAt<AppModelType, DbModelType extends DocumentData>(\n ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/** Helper function to create a bound from a document or fields */\nfunction newQueryBoundFromDocOrFields<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query<AppModelType, DbModelType>,\n methodName: string,\n docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>,\n inclusive: boolean\n): Bound {\n docOrFields[0] = getModularInstance(docOrFields[0]);\n\n if (docOrFields[0] instanceof DocumentSnapshot) {\n return newQueryBoundFromDocument(\n query._query,\n query.firestore._databaseId,\n methodName,\n docOrFields[0]._document,\n inclusive\n );\n } else {\n const reader = newUserDataReader(query.firestore);\n return newQueryBoundFromFields(\n query._query,\n query.firestore._databaseId,\n reader,\n methodName,\n docOrFields,\n inclusive\n );\n }\n}\n\nexport function newQueryFilter(\n query: InternalQuery,\n methodName: string,\n dataReader: UserDataReader,\n databaseId: DatabaseId,\n fieldPath: InternalFieldPath,\n op: Operator,\n value: unknown\n): FieldFilter {\n let fieldValue: ProtoValue;\n if (fieldPath.isKeyField()) {\n if (op === Operator.ARRAY_CONTAINS || op === Operator.ARRAY_CONTAINS_ANY) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. You can't perform '${op}' queries on documentId().`\n );\n } else if (op === Operator.IN || op === Operator.NOT_IN) {\n validateDisjunctiveFilterElements(value, op);\n const referenceList: ProtoValue[] = [];\n for (const arrayValue of value as ProtoValue[]) {\n referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue));\n }\n fieldValue = { arrayValue: { values: referenceList } };\n } else {\n fieldValue = parseDocumentIdValue(databaseId, query, value);\n }\n } else {\n if (\n op === Operator.IN ||\n op === Operator.NOT_IN ||\n op === Operator.ARRAY_CONTAINS_ANY\n ) {\n validateDisjunctiveFilterElements(value, op);\n }\n fieldValue = parseQueryValue(\n dataReader,\n methodName,\n value,\n /* allowArrays= */ op === Operator.IN || op === Operator.NOT_IN\n );\n }\n const filter = FieldFilter.create(fieldPath, op, fieldValue);\n return filter;\n}\n\nexport function newQueryOrderBy(\n query: InternalQuery,\n fieldPath: InternalFieldPath,\n direction: Direction\n): OrderBy {\n if (query.startAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call startAt() or startAfter() before ' +\n 'calling orderBy().'\n );\n }\n if (query.endAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call endAt() or endBefore() before ' +\n 'calling orderBy().'\n );\n }\n const orderBy = new OrderBy(fieldPath, direction);\n return orderBy;\n}\n\n/**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */\nexport function newQueryBoundFromDocument(\n query: InternalQuery,\n databaseId: DatabaseId,\n methodName: string,\n doc: Document | null,\n inclusive: boolean\n): Bound {\n if (!doc) {\n throw new FirestoreError(\n Code.NOT_FOUND,\n `Can't use a DocumentSnapshot that doesn't exist for ` +\n `${methodName}().`\n );\n }\n\n const components: ProtoValue[] = [];\n\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n if (orderBy.field.isKeyField()) {\n components.push(refValue(databaseId, doc.key));\n } else {\n const value = doc.data.field(orderBy.field);\n if (isServerTimestamp(value)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You are trying to start or end a query using a ' +\n 'document for which the field \"' +\n orderBy.field +\n '\" is an uncommitted server timestamp. (Since the value of ' +\n 'this field is unknown, you cannot start/end a query with it.)'\n );\n } else if (value !== null) {\n components.push(value);\n } else {\n const field = orderBy.field.canonicalString();\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You are trying to start or end a query using a ` +\n `document for which the field '${field}' (used as the ` +\n `orderBy) does not exist.`\n );\n }\n }\n }\n return new Bound(components, inclusive);\n}\n\n/**\n * Converts a list of field values to a `Bound` for the given query.\n */\nexport function newQueryBoundFromFields(\n query: InternalQuery,\n databaseId: DatabaseId,\n dataReader: UserDataReader,\n methodName: string,\n values: unknown[],\n inclusive: boolean\n): Bound {\n // Use explicit order by's because it has to match the query the user made\n const orderBy = query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Too many arguments provided to ${methodName}(). ` +\n `The number of arguments must be less than or equal to the ` +\n `number of orderBy() clauses`\n );\n }\n\n const components: ProtoValue[] = [];\n for (let i = 0; i < values.length; i++) {\n const rawValue = values[i];\n const orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. Expected a string for document ID in ` +\n `${methodName}(), but got a ${typeof rawValue}`\n );\n }\n if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection and ordering by documentId(), ` +\n `the value passed to ${methodName}() must be a plain document ID, but ` +\n `'${rawValue}' contains a slash.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(rawValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group and ordering by ` +\n `documentId(), the value passed to ${methodName}() must result in a ` +\n `valid document path, but '${path}' is not because it contains an odd number ` +\n `of segments.`\n );\n }\n const key = new DocumentKey(path);\n components.push(refValue(databaseId, key));\n } else {\n const wrapped = parseQueryValue(dataReader, methodName, rawValue);\n components.push(wrapped);\n }\n }\n\n return new Bound(components, inclusive);\n}\n\n/**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */\nfunction parseDocumentIdValue(\n databaseId: DatabaseId,\n query: InternalQuery,\n documentIdValue: unknown\n): ProtoValue {\n documentIdValue = getModularInstance(documentIdValue);\n\n if (typeof documentIdValue === 'string') {\n if (documentIdValue === '') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. When querying with documentId(), you ' +\n 'must provide a valid document ID, but it was an empty string.'\n );\n }\n if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection by ` +\n `documentId(), you must provide a plain document ID, but ` +\n `'${documentIdValue}' contains a '/' character.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(documentIdValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group by ` +\n `documentId(), the value provided must result in a valid document path, ` +\n `but '${path}' is not because it has an odd number of segments (${path.length}).`\n );\n }\n return refValue(databaseId, new DocumentKey(path));\n } else if (documentIdValue instanceof DocumentReference) {\n return refValue(databaseId, documentIdValue._key);\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying with documentId(), you must provide a valid ` +\n `string or a DocumentReference, but it was: ` +\n `${valueDescription(documentIdValue)}.`\n );\n }\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */\nfunction validateDisjunctiveFilterElements(\n value: unknown,\n operator: Operator\n): void {\n if (!Array.isArray(value) || value.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid Query. A non-empty array is required for ' +\n `'${operator.toString()}' filters.`\n );\n }\n}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * This is not a comprehensive check, and this function should be removed in the\n * long term. Validations should occur in the Firestore backend.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one inequality per query.\n * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n */\nfunction conflictingOps(op: Operator): Operator[] {\n switch (op) {\n case Operator.NOT_EQUAL:\n return [Operator.NOT_EQUAL, Operator.NOT_IN];\n case Operator.ARRAY_CONTAINS_ANY:\n case Operator.IN:\n return [Operator.NOT_IN];\n case Operator.NOT_IN:\n return [\n Operator.ARRAY_CONTAINS_ANY,\n Operator.IN,\n Operator.NOT_IN,\n Operator.NOT_EQUAL\n ];\n default:\n return [];\n }\n}\n\nfunction validateNewFieldFilter(\n query: InternalQuery,\n fieldFilter: FieldFilter\n): void {\n const conflictingOp = findOpInsideFilters(\n query.filters,\n conflictingOps(fieldFilter.op)\n );\n if (conflictingOp !== null) {\n // Special case when it's a duplicate op to give a slightly clearer error message.\n if (conflictingOp === fieldFilter.op) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You cannot use more than one ' +\n `'${fieldFilter.op.toString()}' filter.`\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` +\n `with '${conflictingOp.toString()}' filters.`\n );\n }\n }\n}\n\nfunction validateNewFilter(query: InternalQuery, filter: Filter): void {\n let testQuery = query;\n const subFilters = filter.getFlattenedFilters();\n for (const subFilter of subFilters) {\n validateNewFieldFilter(testQuery, subFilter);\n testQuery = queryWithAddedFilter(testQuery, subFilter);\n }\n}\n\n// Checks if any of the provided filter operators are included in the given list of filters and\n// returns the first one that is, or null if none are.\nfunction findOpInsideFilters(\n filters: Filter[],\n operators: Operator[]\n): Operator | null {\n for (const filter of filters) {\n for (const fieldFilter of filter.getFlattenedFilters()) {\n if (operators.indexOf(fieldFilter.op) >= 0) {\n return fieldFilter.op;\n }\n }\n }\n return null;\n}\n\nexport function validateQueryFilterConstraint(\n functionName: string,\n queryConstraint: AppliableConstraint\n): void {\n if (\n !(queryConstraint instanceof QueryFieldFilterConstraint) &&\n !(queryConstraint instanceof QueryCompositeFilterConstraint)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`\n );\n }\n}\n\nfunction validateQueryConstraintArray(\n queryConstraint: AppliableConstraint[]\n): void {\n const compositeFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryCompositeFilterConstraint\n ).length;\n const fieldFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryFieldFilterConstraint\n ).length;\n\n if (\n compositeFilterCount > 1 ||\n (compositeFilterCount > 0 && fieldFilterCount > 0)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'InvalidQuery. When using composite filters, you cannot use ' +\n 'more than one filter at the top level. Consider nesting the multiple ' +\n 'filters within an `and(...)` statement. For example: ' +\n 'change `query(query, where(...), or(...))` to ' +\n '`query(query, and(where(...), or(...)))`.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentData } from '@firebase/firestore-types';\n\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from '../model/normalize';\nimport { ResourcePath } from '../model/path';\nimport {\n getLocalWriteTime,\n getPreviousValue\n} from '../model/server_timestamps';\nimport { TypeOrder } from '../model/type_order';\nimport { typeOrder } from '../model/values';\nimport {\n ApiClientObjectMap,\n ArrayValue as ProtoArrayValue,\n LatLng as ProtoLatLng,\n MapValue as ProtoMapValue,\n Timestamp as ProtoTimestamp,\n Value,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { isValidResourceName } from '../remote/serializer';\nimport { fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logError } from '../util/log';\nimport { forEach } from '../util/obj';\n\nimport { GeoPoint } from './geo_point';\nimport { Timestamp } from './timestamp';\n\nexport type ServerTimestampBehavior = 'estimate' | 'previous' | 'none';\n\n/**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */\nexport abstract class AbstractUserDataWriter {\n convertValue(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): unknown {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return null;\n case TypeOrder.BooleanValue:\n return value.booleanValue!;\n case TypeOrder.NumberValue:\n return normalizeNumber(value.integerValue || value.doubleValue);\n case TypeOrder.TimestampValue:\n return this.convertTimestamp(value.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return this.convertServerTimestamp(value, serverTimestampBehavior);\n case TypeOrder.StringValue:\n return value.stringValue!;\n case TypeOrder.BlobValue:\n return this.convertBytes(normalizeByteString(value.bytesValue!));\n case TypeOrder.RefValue:\n return this.convertReference(value.referenceValue!);\n case TypeOrder.GeoPointValue:\n return this.convertGeoPoint(value.geoPointValue!);\n case TypeOrder.ArrayValue:\n return this.convertArray(value.arrayValue!, serverTimestampBehavior);\n case TypeOrder.ObjectValue:\n return this.convertObject(value.mapValue!, serverTimestampBehavior);\n default:\n throw fail('Invalid value type: ' + JSON.stringify(value));\n }\n }\n\n private convertObject(\n mapValue: ProtoMapValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): DocumentData {\n return this.convertObjectMap(mapValue.fields, serverTimestampBehavior);\n }\n\n /**\n * @internal\n */\n convertObjectMap(\n fields: ApiClientObjectMap<Value> | undefined,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): DocumentData {\n const result: DocumentData = {};\n forEach(fields, (key, value) => {\n result[key] = this.convertValue(value, serverTimestampBehavior);\n });\n return result;\n }\n\n private convertGeoPoint(value: ProtoLatLng): GeoPoint {\n return new GeoPoint(\n normalizeNumber(value.latitude),\n normalizeNumber(value.longitude)\n );\n }\n\n private convertArray(\n arrayValue: ProtoArrayValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown[] {\n return (arrayValue.values || []).map(value =>\n this.convertValue(value, serverTimestampBehavior)\n );\n }\n\n private convertServerTimestamp(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown {\n switch (serverTimestampBehavior) {\n case 'previous':\n const previousValue = getPreviousValue(value);\n if (previousValue == null) {\n return null;\n }\n return this.convertValue(previousValue, serverTimestampBehavior);\n case 'estimate':\n return this.convertTimestamp(getLocalWriteTime(value));\n default:\n return null;\n }\n }\n\n private convertTimestamp(value: ProtoTimestamp): Timestamp {\n const normalizedValue = normalizeTimestamp(value);\n return new Timestamp(normalizedValue.seconds, normalizedValue.nanos);\n }\n\n protected convertDocumentKey(\n name: string,\n expectedDatabaseId: DatabaseId\n ): DocumentKey {\n const resourcePath = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resourcePath),\n 'ReferenceValue is not valid ' + name\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter<T>(\n converter: UntypedFirestoreDataConverter<T> | null,\n value: WithFieldValue<T> | PartialWithFieldValue<T>,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue<T>);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(result.length === 1, 'Expected a single document result');\n const document = result[0];\n return new DocumentSnapshot<AppModelType, DbModelType>(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n query = cast<Query<AppModelType, DbModelType>>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot<AppModelType, DbModelType>(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot<AppModelType, DbModelType>(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n): Promise<void>;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n): Promise<void>;\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options?: SetOptions\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: UpdateData<DbModelType>\n): Promise<void>;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise<void>;\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n fieldOrUpdateData: string | FieldPath | UpdateData<DbModelType>,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc<AppModelType, DbModelType extends DocumentData>(\n reference: CollectionReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n): Promise<DocumentReference<AppModelType, DbModelType>> {\n reference = cast<CollectionReference<AppModelType, DbModelType>>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue<AppModelType>\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { newQueryComparator } from '../core/query';\nimport { ChangeType, ViewSnapshot } from '../core/view_snapshot';\nimport { FieldPath } from '../lite-api/field_path';\nimport {\n DocumentData,\n PartialWithFieldValue,\n Query,\n queryEqual,\n SetOptions,\n WithFieldValue\n} from '../lite-api/reference';\nimport {\n DocumentSnapshot as LiteDocumentSnapshot,\n fieldPathFromArgument,\n FirestoreDataConverter as LiteFirestoreDataConverter\n} from '../lite-api/snapshot';\nimport { UntypedFirestoreDataConverter } from '../lite-api/user_data_reader';\nimport { AbstractUserDataWriter } from '../lite-api/user_data_writer';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { Firestore } from './database';\nimport { SnapshotListenOptions } from './reference_impl';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * @example\n * ```typescript\n * class Post {\n * constructor(readonly title: string, readonly author: string) {}\n *\n * toString(): string {\n * return this.title + ', by ' + this.author;\n * }\n * }\n *\n * interface PostDbModel {\n * title: string;\n * author: string;\n * }\n *\n * const postConverter = {\n * toFirestore(post: WithFieldValue<Post>): PostDbModel {\n * return {title: post.title, author: post.author};\n * },\n * fromFirestore(\n * snapshot: QueryDocumentSnapshot,\n * options: SnapshotOptions\n * ): Post {\n * const data = snapshot.data(options) as PostDbModel;\n * return new Post(data.title, data.author);\n * }\n * };\n *\n * const postSnap = await firebase.firestore()\n * .collection('posts')\n * .withConverter(postConverter)\n * .doc().get();\n * const post = postSnap.data();\n * if (post !== undefined) {\n * post.title; // string\n * post.toString(); // Should be defined\n * post.someNonExistentProperty; // TS error\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> extends LiteFirestoreDataConverter<AppModelType, DbModelType> {\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. To use `set()`\n * with `merge` and `mergeFields`, `toFirestore()` must be defined with\n * `PartialWithFieldValue<AppModelType>`.\n *\n * The `WithFieldValue<T>` type extends `T` to also allow FieldValues such as\n * {@link (deleteField:1)} to be used as property values.\n */\n toFirestore(\n modelObject: WithFieldValue<AppModelType>\n ): WithFieldValue<DbModelType>;\n\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and\n * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`.\n *\n * The `PartialWithFieldValue<T>` type extends `Partial<T>` to allow\n * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n * It also supports nested `Partial` by allowing nested fields to be\n * omitted.\n */\n toFirestore(\n modelObject: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n ): PartialWithFieldValue<DbModelType>;\n\n /**\n * Called by the Firestore SDK to convert Firestore data into an object of\n * type `AppModelType`. You can access your data by calling:\n * `snapshot.data(options)`.\n *\n * Generally, the data returned from `snapshot.data()` can be cast to\n * `DbModelType`; however, this is not guaranteed as writes to the database\n * may have occurred without a type converter enforcing this specific layout.\n *\n * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata.\n * @param options - The `SnapshotOptions` from the initial call to `data()`.\n */\n fromFirestore(\n snapshot: QueryDocumentSnapshot<DocumentData, DocumentData>,\n options?: SnapshotOptions\n ): AppModelType;\n}\n\n/**\n * Options that configure how data is retrieved from a `DocumentSnapshot` (for\n * example the desired behavior for server timestamps that have not yet been set\n * to their final value).\n */\nexport interface SnapshotOptions {\n /**\n * If set, controls the return value for server timestamps that have not yet\n * been set to their final value.\n *\n * By specifying 'estimate', pending server timestamps return an estimate\n * based on the local clock. This estimate will differ from the final value\n * and cause these values to change once the server result becomes available.\n *\n * By specifying 'previous', pending timestamps will be ignored and return\n * their previous value instead.\n *\n * If omitted or set to 'none', `null` will be returned by default until the\n * server value becomes available.\n */\n readonly serverTimestamps?: 'estimate' | 'previous' | 'none';\n}\n\n/**\n * Metadata about a snapshot, describing the state of the snapshot.\n */\nexport class SnapshotMetadata {\n /**\n * True if the snapshot contains the result of local writes (for example\n * `set()` or `update()` calls) that have not yet been committed to the\n * backend. If your listener has opted into metadata updates (via\n * `SnapshotListenOptions`) you will receive another snapshot with\n * `hasPendingWrites` equal to false once the writes have been committed to\n * the backend.\n */\n readonly hasPendingWrites: boolean;\n\n /**\n * True if the snapshot was created from cached data rather than guaranteed\n * up-to-date server data. If your listener has opted into metadata updates\n * (via `SnapshotListenOptions`) you will receive another snapshot with\n * `fromCache` set to false once the client has received up-to-date data from\n * the backend.\n */\n readonly fromCache: boolean;\n\n /** @hideconstructor */\n constructor(hasPendingWrites: boolean, fromCache: boolean) {\n this.hasPendingWrites = hasPendingWrites;\n this.fromCache = fromCache;\n }\n\n /**\n * Returns true if this `SnapshotMetadata` is equal to the provided one.\n *\n * @param other - The `SnapshotMetadata` to compare against.\n * @returns true if this `SnapshotMetadata` is equal to the provided one.\n */\n isEqual(other: SnapshotMetadata): boolean {\n return (\n this.hasPendingWrites === other.hasPendingWrites &&\n this.fromCache === other.fromCache\n );\n }\n}\n\n/**\n * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'.\n */\nexport type DocumentChangeType = 'added' | 'removed' | 'modified';\n\n/**\n * A `DocumentChange` represents a change to the documents matching a query.\n * It contains the document affected and the type of change that occurred.\n */\nexport interface DocumentChange<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of change ('added', 'modified', or 'removed'). */\n readonly type: DocumentChangeType;\n\n /** The document affected by this change. */\n readonly doc: QueryDocumentSnapshot<AppModelType, DbModelType>;\n\n /**\n * The index of the changed document in the result set immediately prior to\n * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects\n * have been applied). Is `-1` for 'added' events.\n */\n readonly oldIndex: number;\n\n /**\n * The index of the changed document in the result set immediately after\n * this `DocumentChange` (i.e. supposing that all prior `DocumentChange`\n * objects and the current `DocumentChange` object have been applied).\n * Is -1 for 'removed' events.\n */\n readonly newIndex: number;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get(<field>)` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends LiteDocumentSnapshot<AppModelType, DbModelType> {\n private readonly _firestoreImpl: Firestore;\n\n /**\n * Metadata about the `DocumentSnapshot`, including information about its\n * source and local modifications.\n */\n readonly metadata: SnapshotMetadata;\n\n /** @hideconstructor protected */\n constructor(\n readonly _firestore: Firestore,\n userDataWriter: AbstractUserDataWriter,\n key: DocumentKey,\n document: Document | null,\n metadata: SnapshotMetadata,\n converter: UntypedFirestoreDataConverter<AppModelType, DbModelType> | null\n ) {\n super(_firestore, userDataWriter, key, document, converter);\n this._firestoreImpl = _firestore;\n this.metadata = metadata;\n }\n\n /**\n * Returns whether or not the data exists. True if the document exists.\n */\n exists(): this is QueryDocumentSnapshot<AppModelType, DbModelType> {\n return super.exists();\n }\n\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document or `undefined` if\n * the document doesn't exist.\n */\n data(options: SnapshotOptions = {}): AppModelType | undefined {\n if (!this._document) {\n return undefined;\n } else if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n this._key,\n this._document,\n this.metadata,\n /* converter= */ null\n );\n return this._converter.fromFirestore(snapshot, options);\n } else {\n return this._userDataWriter.convertValue(\n this._document.data.value,\n options.serverTimestamps\n ) as AppModelType;\n }\n }\n\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * By default, a `serverTimestamp()` that has not yet been set to\n * its final value will be returned as `null`. You can override this by\n * passing an options object.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @param options - An options object to configure how the field is retrieved\n * from the snapshot (for example the desired behavior for server timestamps\n * that have not yet been set to their final value).\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(fieldPath: string | FieldPath, options: SnapshotOptions = {}): any {\n if (this._document) {\n const value = this._document.data.field(\n fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n );\n if (value !== null) {\n return this._userDataWriter.convertValue(\n value,\n options.serverTimestamps\n );\n }\n }\n return undefined;\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get(<field>)` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot<AppModelType, DbModelType> {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @override\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document.\n */\n data(options: SnapshotOptions = {}): AppModelType {\n return super.data(options) as AppModelType;\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * Metadata about this snapshot, concerning its source and if it has local\n * modifications.\n */\n readonly metadata: SnapshotMetadata;\n\n /**\n * The query on which you called `get` or `onSnapshot` in order to get this\n * `QuerySnapshot`.\n */\n readonly query: Query<AppModelType, DbModelType>;\n\n private _cachedChanges?: Array<DocumentChange<AppModelType, DbModelType>>;\n private _cachedChangesIncludeMetadataChanges?: boolean;\n\n /** @hideconstructor */\n constructor(\n readonly _firestore: Firestore,\n readonly _userDataWriter: AbstractUserDataWriter,\n query: Query<AppModelType, DbModelType>,\n readonly _snapshot: ViewSnapshot\n ) {\n this.metadata = new SnapshotMetadata(\n _snapshot.hasPendingWrites,\n _snapshot.fromCache\n );\n this.query = query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array<QueryDocumentSnapshot<AppModelType, DbModelType>> {\n const result: Array<QueryDocumentSnapshot<AppModelType, DbModelType>> = [];\n this.forEach(doc => result.push(doc));\n return result;\n }\n\n /** The number of documents in the `QuerySnapshot`. */\n get size(): number {\n return this._snapshot.docs.size;\n }\n\n /** True if there are no documents in the `QuerySnapshot`. */\n get empty(): boolean {\n return this.size === 0;\n }\n\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */\n forEach(\n callback: (\n result: QueryDocumentSnapshot<AppModelType, DbModelType>\n ) => void,\n thisArg?: unknown\n ): void {\n this._snapshot.docs.forEach(doc => {\n callback.call(\n thisArg,\n new QueryDocumentSnapshot<AppModelType, DbModelType>(\n this._firestore,\n this._userDataWriter,\n doc.key,\n doc,\n new SnapshotMetadata(\n this._snapshot.mutatedKeys.has(doc.key),\n this._snapshot.fromCache\n ),\n this.query.converter\n )\n );\n });\n }\n\n /**\n * Returns an array of the documents changes since the last snapshot. If this\n * is the first snapshot, all documents will be in the list as 'added'\n * changes.\n *\n * @param options - `SnapshotListenOptions` that control whether metadata-only\n * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger\n * snapshot events.\n */\n docChanges(\n options: SnapshotListenOptions = {}\n ): Array<DocumentChange<AppModelType, DbModelType>> {\n const includeMetadataChanges = !!options.includeMetadataChanges;\n\n if (includeMetadataChanges && this._snapshot.excludesMetadataChanges) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'To include metadata changes with your document changes, you must ' +\n 'also pass { includeMetadataChanges:true } to onSnapshot().'\n );\n }\n\n if (\n !this._cachedChanges ||\n this._cachedChangesIncludeMetadataChanges !== includeMetadataChanges\n ) {\n this._cachedChanges = changesFromSnapshot(this, includeMetadataChanges);\n this._cachedChangesIncludeMetadataChanges = includeMetadataChanges;\n }\n\n return this._cachedChanges;\n }\n}\n\n/** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */\nexport function changesFromSnapshot<\n AppModelType,\n DbModelType extends DocumentData\n>(\n querySnapshot: QuerySnapshot<AppModelType, DbModelType>,\n includeMetadataChanges: boolean\n): Array<DocumentChange<AppModelType, DbModelType>> {\n if (querySnapshot._snapshot.oldDocs.isEmpty()) {\n // Special case the first snapshot because index calculation is easy and\n // fast\n let lastDoc: Document;\n let index = 0;\n return querySnapshot._snapshot.docChanges.map(change => {\n debugAssert(\n change.type === ChangeType.Added,\n 'Invalid event type for first snapshot'\n );\n debugAssert(\n !lastDoc ||\n newQueryComparator(querySnapshot._snapshot.query)(\n lastDoc,\n change.doc\n ) < 0,\n 'Got added events in wrong order'\n );\n const doc = new QueryDocumentSnapshot<AppModelType, DbModelType>(\n querySnapshot._firestore,\n querySnapshot._userDataWriter,\n change.doc.key,\n change.doc,\n new SnapshotMetadata(\n querySnapshot._snapshot.mutatedKeys.has(change.doc.key),\n querySnapshot._snapshot.fromCache\n ),\n querySnapshot.query.converter\n );\n lastDoc = change.doc;\n return {\n type: 'added' as DocumentChangeType,\n doc,\n oldIndex: -1,\n newIndex: index++\n };\n });\n } else {\n // A `DocumentSet` that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n let indexTracker = querySnapshot._snapshot.oldDocs;\n return querySnapshot._snapshot.docChanges\n .filter(\n change => includeMetadataChanges || change.type !== ChangeType.Metadata\n )\n .map(change => {\n const doc = new QueryDocumentSnapshot<AppModelType, DbModelType>(\n querySnapshot._firestore,\n querySnapshot._userDataWriter,\n change.doc.key,\n change.doc,\n new SnapshotMetadata(\n querySnapshot._snapshot.mutatedKeys.has(change.doc.key),\n querySnapshot._snapshot.fromCache\n ),\n querySnapshot.query.converter\n );\n let oldIndex = -1;\n let newIndex = -1;\n if (change.type !== ChangeType.Added) {\n oldIndex = indexTracker.indexOf(change.doc.key);\n debugAssert(oldIndex >= 0, 'Index for document not found');\n indexTracker = indexTracker.delete(change.doc.key);\n }\n if (change.type !== ChangeType.Removed) {\n indexTracker = indexTracker.add(change.doc);\n newIndex = indexTracker.indexOf(change.doc.key);\n }\n return {\n type: resultChangeType(change.type),\n doc,\n oldIndex,\n newIndex\n };\n });\n }\n}\n\nexport function resultChangeType(type: ChangeType): DocumentChangeType {\n switch (type) {\n case ChangeType.Added:\n return 'added';\n case ChangeType.Modified:\n case ChangeType.Metadata:\n return 'modified';\n case ChangeType.Removed:\n return 'removed';\n default:\n return fail('Unknown change type: ' + type);\n }\n}\n\n// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot\n// metadata\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual<AppModelType, DbModelType extends DocumentData>(\n left:\n | DocumentSnapshot<AppModelType, DbModelType>\n | QuerySnapshot<AppModelType, DbModelType>,\n right:\n | DocumentSnapshot<AppModelType, DbModelType>\n | QuerySnapshot<AppModelType, DbModelType>\n): boolean {\n if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n return (\n left._firestore === right._firestore &&\n left._key.isEqual(right._key) &&\n (left._document === null\n ? right._document === null\n : left._document.isEqual(right._document)) &&\n left._converter === right._converter\n );\n } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n return (\n left._firestore === right._firestore &&\n queryEqual(left.query, right.query) &&\n left.metadata.isEqual(right.metadata) &&\n left._snapshot.isEqual(right._snapshot)\n );\n }\n\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport {\n CompleteFn,\n ErrorFn,\n isPartialObserver,\n NextFn,\n PartialObserver\n} from '../api/observer';\nimport {\n firestoreClientAddSnapshotsInSyncListener,\n firestoreClientGetDocumentFromLocalCache,\n firestoreClientGetDocumentsFromLocalCache,\n firestoreClientGetDocumentsViaSnapshotListener,\n firestoreClientGetDocumentViaSnapshotListener,\n firestoreClientListen,\n firestoreClientWrite\n} from '../core/firestore_client';\nimport { newQueryForPath, Query as InternalQuery } from '../core/query';\nimport { ViewSnapshot } from '../core/view_snapshot';\nimport { Bytes } from '../lite-api/bytes';\nimport { FieldPath } from '../lite-api/field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from '../lite-api/query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from '../lite-api/reference';\nimport { applyFirestoreDataConverter } from '../lite-api/reference_impl';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs\n} from '../lite-api/user_data_reader';\nimport { AbstractUserDataWriter } from '../lite-api/user_data_writer';\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { DocumentSnapshot, QuerySnapshot, SnapshotMetadata } from './snapshot';\n\n/**\n * An options object that can be passed to {@link (onSnapshot:1)} and {@link\n * QuerySnapshot.docChanges} to control which types of changes to include in the\n * result set.\n */\nexport interface SnapshotListenOptions {\n /**\n * Include a change even if only the metadata of the query or of a document\n * changed. Default is false.\n */\n readonly includeMetadataChanges?: boolean;\n}\n\n/**\n * Reads the document referred to by this `DocumentReference`.\n *\n * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting\n * for data from the server, but it may return cached data or fail if you are\n * offline and the server cannot be reached. To specify this behavior, invoke\n * {@link getDocFromCache} or {@link getDocFromServer}.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */\nexport function getDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n\n return firestoreClientGetDocumentViaSnapshotListener(\n client,\n reference._key\n ).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot));\n}\n\nexport class ExpUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from cache.\n * Returns an error if the document is not currently cached.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */\nexport function getDocFromCache<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n return firestoreClientGetDocumentFromLocalCache(client, reference._key).then(\n doc =>\n new DocumentSnapshot<AppModelType, DbModelType>(\n firestore,\n userDataWriter,\n reference._key,\n doc,\n new SnapshotMetadata(\n doc !== null && doc.hasLocalMutations,\n /* fromCache= */ true\n ),\n reference.converter\n )\n );\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from the server.\n * Returns an error if the network is not available.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */\nexport function getDocFromServer<\n AppModelType,\n DbModelType extends DocumentData\n>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n\n return firestoreClientGetDocumentViaSnapshotListener(client, reference._key, {\n source: 'server'\n }).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot`.\n *\n * Note: `getDocs()` attempts to provide up-to-date data when possible by\n * waiting for data from the server, but it may return cached data or fail if\n * you are offline and the server cannot be reached. To specify this behavior,\n * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */\nexport function getDocs<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n query = cast<Query<AppModelType, DbModelType>>(query, Query);\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n validateHasExplicitOrderByForLimitToLast(query._query);\n return firestoreClientGetDocumentsViaSnapshotListener(\n client,\n query._query\n ).then(\n snapshot =>\n new QuerySnapshot<AppModelType, DbModelType>(\n firestore,\n userDataWriter,\n query,\n snapshot\n )\n );\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from cache.\n * Returns an empty result set if no documents matching the query are currently\n * cached.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */\nexport function getDocsFromCache<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n query = cast<Query<AppModelType, DbModelType>>(query, Query);\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n return firestoreClientGetDocumentsFromLocalCache(client, query._query).then(\n snapshot =>\n new QuerySnapshot<AppModelType, DbModelType>(\n firestore,\n userDataWriter,\n query,\n snapshot\n )\n );\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from the\n * server. Returns an error if the network is not available.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */\nexport function getDocsFromServer<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n query = cast<Query<AppModelType, DbModelType>>(query, Query);\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n return firestoreClientGetDocumentsViaSnapshotListener(client, query._query, {\n source: 'server'\n }).then(\n snapshot => new QuerySnapshot(firestore, userDataWriter, query, snapshot)\n );\n}\n\n/**\n * Writes to the document referred to by this `DocumentReference`. If the\n * document does not yet exist, it will be created.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n): Promise<void>;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @returns A Promise resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n): Promise<void>;\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options?: SetOptions\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as WithFieldValue<AppModelType>,\n options\n );\n const dataReader = newUserDataReader(firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const mutation = parsed.toMutation(reference._key, Precondition.none());\n return executeWrite(firestore, [mutation]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: UpdateData<DbModelType>\n): Promise<void>;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise<void>;\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<unknown>,\n fieldOrUpdateData: string | FieldPath | UpdateData<DbModelType>,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n\n const dataReader = newUserDataReader(firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const mutation = parsed.toMutation(reference._key, Precondition.exists(true));\n return executeWrite(firestore, [mutation]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * @param reference - A reference to the document to delete.\n * @returns A Promise resolved once the document has been successfully\n * deleted from the backend (note that it won't resolve while you're offline).\n */\nexport function deleteDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<void> {\n const firestore = cast(reference.firestore, Firestore);\n const mutations = [new DeleteMutation(reference._key, Precondition.none())];\n return executeWrite(firestore, mutations);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend (Note that it\n * won't resolve while you're offline).\n */\nexport function addDoc<AppModelType, DbModelType extends DocumentData>(\n reference: CollectionReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n): Promise<DocumentReference<AppModelType, DbModelType>> {\n const firestore = cast(reference.firestore, Firestore);\n\n const docRef = doc(reference);\n const convertedValue = applyFirestoreDataConverter(reference.converter, data);\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n reference.converter !== null,\n {}\n );\n\n const mutation = parsed.toMutation(docRef._key, Precondition.exists(false));\n return executeWrite(firestore, [mutation]).then(() => docRef);\n}\n\n/**\n * A function returned by `onSnapshot()` that removes the listener when invoked.\n */\nexport interface Unsubscribe {\n /** Removes the listener when invoked. */\n (): void;\n}\n\n// TODO(firestorexp): Make sure these overloads are tested via the Firestore\n// integration tests\n\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n observer: {\n next?: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n options: SnapshotListenOptions,\n observer: {\n next?: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot`\n * is available.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n onNext: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot`\n * is available.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n options: SnapshotListenOptions,\n onNext: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n observer: {\n next?: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n options: SnapshotListenOptions,\n observer: {\n next?: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param onNext - A callback to be called every time a new `QuerySnapshot`\n * is available.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n onNext: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `QuerySnapshot`\n * is available.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n options: SnapshotListenOptions,\n onNext: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n reference:\n | Query<AppModelType, DbModelType>\n | DocumentReference<AppModelType, DbModelType>,\n ...args: unknown[]\n): Unsubscribe {\n reference = getModularInstance(reference);\n\n let options: SnapshotListenOptions = {\n includeMetadataChanges: false\n };\n let currArg = 0;\n if (typeof args[currArg] === 'object' && !isPartialObserver(args[currArg])) {\n options = args[currArg] as SnapshotListenOptions;\n currArg++;\n }\n\n const internalOptions = {\n includeMetadataChanges: options.includeMetadataChanges\n };\n\n if (isPartialObserver(args[currArg])) {\n const userObserver = args[currArg] as PartialObserver<\n QuerySnapshot<AppModelType, DbModelType>\n >;\n args[currArg] = userObserver.next?.bind(userObserver);\n args[currArg + 1] = userObserver.error?.bind(userObserver);\n args[currArg + 2] = userObserver.complete?.bind(userObserver);\n }\n\n let observer: PartialObserver<ViewSnapshot>;\n let firestore: Firestore;\n let internalQuery: InternalQuery;\n\n if (reference instanceof DocumentReference) {\n firestore = cast(reference.firestore, Firestore);\n internalQuery = newQueryForPath(reference._key.path);\n\n observer = {\n next: snapshot => {\n if (args[currArg]) {\n (\n args[currArg] as NextFn<DocumentSnapshot<AppModelType, DbModelType>>\n )(\n convertToDocSnapshot(\n firestore,\n reference as DocumentReference<AppModelType, DbModelType>,\n snapshot\n )\n );\n }\n },\n error: args[currArg + 1] as ErrorFn,\n complete: args[currArg + 2] as CompleteFn\n };\n } else {\n const query = cast<Query<AppModelType, DbModelType>>(reference, Query);\n firestore = cast(query.firestore, Firestore);\n internalQuery = query._query;\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n observer = {\n next: snapshot => {\n if (args[currArg]) {\n (args[currArg] as NextFn<QuerySnapshot<AppModelType, DbModelType>>)(\n new QuerySnapshot(firestore, userDataWriter, query, snapshot)\n );\n }\n },\n error: args[currArg + 1] as ErrorFn,\n complete: args[currArg + 2] as CompleteFn\n };\n\n validateHasExplicitOrderByForLimitToLast(reference._query);\n }\n\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientListen(\n client,\n internalQuery,\n internalOptions,\n observer\n );\n}\n\n// TODO(firestorexp): Make sure these overloads are tested via the Firestore\n// integration tests\n\n/**\n * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync\n * event indicates that all listeners affected by a given change have fired,\n * even if a single server-generated change affects multiple listeners.\n *\n * NOTE: The snapshots-in-sync event only indicates that listeners are in sync\n * with each other, but does not relate to whether those snapshots are in sync\n * with the server. Use SnapshotMetadata in the individual listeners to\n * determine if a snapshot is from the cache or the server.\n *\n * @param firestore - The instance of Firestore for synchronizing snapshots.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n */\nexport function onSnapshotsInSync(\n firestore: Firestore,\n observer: {\n next?: (value: void) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync\n * event indicates that all listeners affected by a given change have fired,\n * even if a single server-generated change affects multiple listeners.\n *\n * NOTE: The snapshots-in-sync event only indicates that listeners are in sync\n * with each other, but does not relate to whether those snapshots are in sync\n * with the server. Use `SnapshotMetadata` in the individual listeners to\n * determine if a snapshot is from the cache or the server.\n *\n * @param firestore - The `Firestore` instance for synchronizing snapshots.\n * @param onSync - A callback to be called every time all snapshot listeners are\n * in sync with each other.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n */\nexport function onSnapshotsInSync(\n firestore: Firestore,\n onSync: () => void\n): Unsubscribe;\nexport function onSnapshotsInSync(\n firestore: Firestore,\n arg: unknown\n): Unsubscribe {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const observer = isPartialObserver(arg)\n ? (arg as PartialObserver<void>)\n : {\n next: arg as () => void\n };\n\n return firestoreClientAddSnapshotsInSyncListener(client, observer);\n}\n\n/**\n * Locally writes `mutations` on the async queue.\n * @internal\n */\nexport function executeWrite(\n firestore: Firestore,\n mutations: Mutation[]\n): Promise<void> {\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientWrite(client, mutations);\n}\n\n/**\n * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`\n * to a {@link DocumentSnapshot}.\n */\nfunction convertToDocSnapshot<AppModelType, DbModelType extends DocumentData>(\n firestore: Firestore,\n ref: DocumentReference<AppModelType, DbModelType>,\n snapshot: ViewSnapshot\n): DocumentSnapshot<AppModelType, DbModelType> {\n debugAssert(\n snapshot.docs.size <= 1,\n 'Expected zero or a single result on a document-only query'\n );\n const doc = snapshot.docs.get(ref._key);\n\n const userDataWriter = new ExpUserDataWriter(firestore);\n return new DocumentSnapshot<AppModelType, DbModelType>(\n firestore,\n userDataWriter,\n ref._key,\n doc,\n new SnapshotMetadata(snapshot.hasPendingWrites, snapshot.fromCache),\n ref.converter\n );\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n firestoreClientDeleteAllFieldIndexes,\n firestoreClientSetPersistentCacheIndexAutoCreationEnabled,\n FirestoreClient\n} from '../core/firestore_client';\nimport { cast } from '../util/input_validation';\nimport { logDebug, logWarn } from '../util/log';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\n\n/**\n * A `PersistentCacheIndexManager` for configuring persistent cache indexes used\n * for local query execution.\n *\n * To use, call `getPersistentCacheIndexManager()` to get an instance.\n */\nexport class PersistentCacheIndexManager {\n /** A type string to uniquely identify instances of this class. */\n readonly type: 'PersistentCacheIndexManager' = 'PersistentCacheIndexManager';\n\n /** @hideconstructor */\n constructor(readonly _client: FirestoreClient) {}\n}\n\n/**\n * Returns the PersistentCache Index Manager used by the given `Firestore`\n * object.\n *\n * @return The `PersistentCacheIndexManager` instance, or `null` if local\n * persistent storage is not in use.\n */\nexport function getPersistentCacheIndexManager(\n firestore: Firestore\n): PersistentCacheIndexManager | null {\n firestore = cast(firestore, Firestore);\n\n const cachedInstance = persistentCacheIndexManagerByFirestore.get(firestore);\n if (cachedInstance) {\n return cachedInstance;\n }\n\n const client = ensureFirestoreConfigured(firestore);\n if (client._uninitializedComponentsProvider?._offlineKind !== 'persistent') {\n return null;\n }\n\n const instance = new PersistentCacheIndexManager(client);\n persistentCacheIndexManagerByFirestore.set(firestore, instance);\n return instance;\n}\n\n/**\n * Enables the SDK to create persistent cache indexes automatically for local\n * query execution when the SDK believes cache indexes can help improve\n * performance.\n *\n * This feature is disabled by default.\n */\nexport function enablePersistentCacheIndexAutoCreation(\n indexManager: PersistentCacheIndexManager\n): void {\n setPersistentCacheIndexAutoCreationEnabled(indexManager, true);\n}\n\n/**\n * Stops creating persistent cache indexes automatically for local query\n * execution. The indexes which have been created by calling\n * `enablePersistentCacheIndexAutoCreation()` still take effect.\n */\nexport function disablePersistentCacheIndexAutoCreation(\n indexManager: PersistentCacheIndexManager\n): void {\n setPersistentCacheIndexAutoCreationEnabled(indexManager, false);\n}\n\n/**\n * Removes all persistent cache indexes.\n *\n * Please note this function will also deletes indexes generated by\n * `setIndexConfiguration()`, which is deprecated.\n */\nexport function deleteAllPersistentCacheIndexes(\n indexManager: PersistentCacheIndexManager\n): void {\n indexManager._client.verifyNotTerminated();\n\n const promise = firestoreClientDeleteAllFieldIndexes(indexManager._client);\n\n promise\n .then(_ => logDebug('deleting all persistent cache indexes succeeded'))\n .catch(error =>\n logWarn('deleting all persistent cache indexes failed', error)\n );\n}\n\nfunction setPersistentCacheIndexAutoCreationEnabled(\n indexManager: PersistentCacheIndexManager,\n isEnabled: boolean\n): void {\n indexManager._client.verifyNotTerminated();\n\n const promise = firestoreClientSetPersistentCacheIndexAutoCreationEnabled(\n indexManager._client,\n isEnabled\n );\n\n promise\n .then(_ =>\n logDebug(\n `setting persistent cache index auto creation ` +\n `isEnabled=${isEnabled} succeeded`\n )\n )\n .catch(error =>\n logWarn(\n `setting persistent cache index auto creation ` +\n `isEnabled=${isEnabled} failed`,\n error\n )\n );\n}\n\n/**\n * Maps `Firestore` instances to their corresponding\n * `PersistentCacheIndexManager` instances.\n *\n * Use a `WeakMap` so that the mapping will be automatically dropped when the\n * `Firestore` instance is garbage collected. This emulates a private member\n * as described in https://goo.gle/454yvug.\n */\nconst persistentCacheIndexManagerByFirestore = new WeakMap<\n Firestore,\n PersistentCacheIndexManager\n>();\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { name, version } from '../package.json';\nimport {\n FirebaseAppCheckTokenProvider,\n FirebaseAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { setSDKVersion } from '../src/core/version';\n\nimport { Firestore } from './api/database';\nimport { databaseIdFromApp } from './core/database_info';\n\nexport function registerFirestore(\n variant?: string,\n useFetchStreams = true\n): void {\n setSDKVersion(SDK_VERSION);\n _registerComponent(\n new Component(\n 'firestore',\n (container, { instanceIdentifier: databaseId, options: settings }) => {\n const app = container.getProvider('app').getImmediate()!;\n const firestoreInstance = new Firestore(\n new FirebaseAuthCredentialsProvider(\n container.getProvider('auth-internal')\n ),\n new FirebaseAppCheckTokenProvider(\n container.getProvider('app-check-internal')\n ),\n databaseIdFromApp(app, databaseId),\n app\n );\n settings = { useFetchStreams, ...settings };\n firestoreInstance._setSettings(settings);\n return firestoreInstance;\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * Cloud Firestore\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Firestore } from './api/database';\nimport { registerFirestore } from './register';\n\nregisterFirestore();\n\nexport * from './api';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore': Firestore;\n }\n}\n","// Import the functions you need from the SDKs you need\nimport { initializeApp } from \"firebase/app\";\nimport { getAnalytics } from \"firebase/analytics\";\nimport { getAuth} from \"firebase/auth\"\nimport { getFirestore } from \"firebase/firestore\"\n// TODO: Add SDKs for Firebase products that you want to use\n// https://firebase.google.com/docs/web/setup#available-libraries\n\n// Your web app's Firebase configuration\n// For Firebase JS SDK v7.20.0 and later, measurementId is optional\nconst firebaseConfig = {\n apiKey: \"AIzaSyDZjgosQcTQgNfvwAaFC_W6R5Sv0JjjxkM\",\n authDomain: \"friendly-betting-fb47e.firebaseapp.com\",\n projectId: \"friendly-betting-fb47e\",\n storageBucket: \"friendly-betting-fb47e.appspot.com\",\n messagingSenderId: \"897713635691\",\n appId: \"1:897713635691:web:70b530052a319f77e14c2e\",\n measurementId: \"G-74305KF5X4\"\n};\n\n// Initialize Firebase\nconst app = initializeApp(firebaseConfig);\nconst analytics = getAnalytics(app);\n\n\nexport const auth = getAuth(app);\nexport const db = getFirestore(app);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\nimport {\n Auth,\n NextOrObserver,\n Persistence,\n User,\n CompleteFn,\n ErrorFn,\n Unsubscribe,\n PasswordValidationStatus\n} from '../model/public_types';\nimport { _initializeRecaptchaConfig } from '../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { _castAuth } from '../core/auth/auth_impl';\n\nexport {\n debugErrorMap,\n prodErrorMap,\n AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as AuthErrorCodes\n} from './errors';\n\n// Non-optional auth methods.\n/**\n * Changes the type of persistence on the {@link Auth} instance for the currently saved\n * `Auth` session and applies this type of persistence for future sign-in requests, including\n * sign-in with redirect requests.\n *\n * @remarks\n * This makes it easy for a user signing in to specify whether their session should be\n * remembered or not. It also makes it easier to never persist the `Auth` state for applications\n * that are shared by other users or have sensitive data.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * setPersistence(auth, browserSessionPersistence);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param persistence - The {@link Persistence} to use.\n * @returns A `Promise` that resolves once the persistence change has completed\n *\n * @public\n */\nexport function setPersistence(\n auth: Auth,\n persistence: Persistence\n): Promise<void> {\n return getModularInstance(auth).setPersistence(persistence);\n}\n\n/**\n * Loads the reCAPTCHA configuration into the `Auth` instance.\n *\n * @remarks\n * This will load the reCAPTCHA config, which indicates whether the reCAPTCHA\n * verification flow should be triggered for each auth provider, into the\n * current Auth session.\n *\n * If initializeRecaptchaConfig() is not invoked, the auth flow will always start\n * without reCAPTCHA verification. If the provider is configured to require reCAPTCHA\n * verification, the SDK will transparently load the reCAPTCHA config and restart the\n * auth flows.\n *\n * Thus, by calling this optional method, you will reduce the latency of future auth flows.\n * Loading the reCAPTCHA config early will also enhance the signal collected by reCAPTCHA.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * initializeRecaptchaConfig(auth);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport function initializeRecaptchaConfig(auth: Auth): Promise<void> {\n return _initializeRecaptchaConfig(auth);\n}\n\n/**\n * Validates the password against the password policy configured for the project or tenant.\n *\n * @remarks\n * If no tenant ID is set on the `Auth` instance, then this method will use the password\n * policy configured for the project. Otherwise, this method will use the policy configured\n * for the tenant. If a password policy has not been configured, then the default policy\n * configured for all projects will be used.\n *\n * If an auth flow fails because a submitted password does not meet the password policy\n * requirements and this method has previously been called, then this method will use the\n * most recent policy available when called again.\n *\n * @example\n * ```javascript\n * validatePassword(auth, 'some-password');\n * ```\n *\n * @param auth The {@link Auth} instance.\n * @param password The password to validate.\n *\n * @public\n */\nexport async function validatePassword(\n auth: Auth,\n password: string\n): Promise<PasswordValidationStatus> {\n const authInternal = _castAuth(auth);\n return authInternal.validatePassword(password);\n}\n\n/**\n * Adds an observer for changes to the signed-in user's ID token.\n *\n * @remarks\n * This includes sign-in, sign-out, and token refresh events.\n * This will not be triggered automatically upon ID token expiration. Use {@link User.getIdToken} to refresh the ID token.\n *\n * @param auth - The {@link Auth} instance.\n * @param nextOrObserver - callback triggered on change.\n * @param error - Deprecated. This callback is never triggered. Errors\n * on signing in/out can be caught in promises returned from\n * sign-in/sign-out functions.\n * @param completed - Deprecated. This callback is never triggered.\n *\n * @public\n */\nexport function onIdTokenChanged(\n auth: Auth,\n nextOrObserver: NextOrObserver<User>,\n error?: ErrorFn,\n completed?: CompleteFn\n): Unsubscribe {\n return getModularInstance(auth).onIdTokenChanged(\n nextOrObserver,\n error,\n completed\n );\n}\n/**\n * Adds a blocking callback that runs before an auth state change\n * sets a new user.\n *\n * @param auth - The {@link Auth} instance.\n * @param callback - callback triggered before new user value is set.\n * If this throws, it blocks the user from being set.\n * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`\n * callback throws, allowing you to undo any side effects.\n */\nexport function beforeAuthStateChanged(\n auth: Auth,\n callback: (user: User | null) => void | Promise<void>,\n onAbort?: () => void\n): Unsubscribe {\n return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);\n}\n/**\n * Adds an observer for changes to the user's sign-in state.\n *\n * @remarks\n * To keep the old behavior, see {@link onIdTokenChanged}.\n *\n * @param auth - The {@link Auth} instance.\n * @param nextOrObserver - callback triggered on change.\n * @param error - Deprecated. This callback is never triggered. Errors\n * on signing in/out can be caught in promises returned from\n * sign-in/sign-out functions.\n * @param completed - Deprecated. This callback is never triggered.\n *\n * @public\n */\nexport function onAuthStateChanged(\n auth: Auth,\n nextOrObserver: NextOrObserver<User>,\n error?: ErrorFn,\n completed?: CompleteFn\n): Unsubscribe {\n return getModularInstance(auth).onAuthStateChanged(\n nextOrObserver,\n error,\n completed\n );\n}\n/**\n * Sets the current language to the default device/browser preference.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport function useDeviceLanguage(auth: Auth): void {\n getModularInstance(auth).useDeviceLanguage();\n}\n/**\n * Asynchronously sets the provided user as {@link Auth.currentUser} on the\n * {@link Auth} instance.\n *\n * @remarks\n * A new instance copy of the user provided will be made and set as currentUser.\n *\n * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners\n * like other sign in methods.\n *\n * The operation fails with an error if the user to be updated belongs to a different Firebase\n * project.\n *\n * @param auth - The {@link Auth} instance.\n * @param user - The new {@link User}.\n *\n * @public\n */\nexport function updateCurrentUser(\n auth: Auth,\n user: User | null\n): Promise<void> {\n return getModularInstance(auth).updateCurrentUser(user);\n}\n/**\n * Signs out the current user.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport function signOut(auth: Auth): Promise<void> {\n return getModularInstance(auth).signOut();\n}\n\n/**\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\n *\n * @param auth - The {@link Auth} instance.\n * @param token - The Apple OAuth access token.\n *\n * @public\n */\nexport function revokeAccessToken(auth: Auth, token: string): Promise<void> {\n const authInternal = _castAuth(auth);\n return authInternal.revokeAccessToken(token);\n}\n\nexport { initializeAuth } from './auth/initialize';\nexport { connectAuthEmulator } from './auth/emulator';\n\n// credentials\nexport { AuthCredential } from './credentials';\nexport { EmailAuthCredential } from './credentials/email';\nexport { OAuthCredential } from './credentials/oauth';\nexport { PhoneAuthCredential } from './credentials/phone';\n\n// persistence\nexport { inMemoryPersistence } from './persistence/in_memory';\n\n// providers\nexport { EmailAuthProvider } from './providers/email';\nexport { FacebookAuthProvider } from './providers/facebook';\nexport { CustomParameters } from './providers/federated';\nexport { GoogleAuthProvider } from './providers/google';\nexport { GithubAuthProvider } from './providers/github';\nexport { OAuthProvider, OAuthCredentialOptions } from './providers/oauth';\nexport { SAMLAuthProvider } from './providers/saml';\nexport { TwitterAuthProvider } from './providers/twitter';\n\n// strategies\nexport { signInAnonymously } from './strategies/anonymous';\nexport {\n signInWithCredential,\n linkWithCredential,\n reauthenticateWithCredential\n} from './strategies/credential';\nexport { signInWithCustomToken } from './strategies/custom_token';\nexport {\n sendPasswordResetEmail,\n confirmPasswordReset,\n applyActionCode,\n checkActionCode,\n verifyPasswordResetCode,\n createUserWithEmailAndPassword,\n signInWithEmailAndPassword\n} from './strategies/email_and_password';\nexport {\n sendSignInLinkToEmail,\n isSignInWithEmailLink,\n signInWithEmailLink\n} from './strategies/email_link';\nexport {\n fetchSignInMethodsForEmail,\n sendEmailVerification,\n verifyBeforeUpdateEmail\n} from './strategies/email';\n\n// core\nexport { ActionCodeURL, parseActionCodeURL } from './action_code_url';\n\n// user\nexport {\n updateProfile,\n updateEmail,\n updatePassword\n} from './user/account_info';\nexport { getIdToken, getIdTokenResult } from './user/id_token_result';\nexport { unlink } from './user/link_unlink';\nexport { getAdditionalUserInfo } from './user/additional_user_info';\n\n// Non-optional user methods.\nexport { reload } from './user/reload';\n/**\n * Deletes and signs out the user.\n *\n * @remarks\n * Important: this is a security-sensitive operation that requires the user to have recently\n * signed in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n *\n * @public\n */\nexport async function deleteUser(user: User): Promise<void> {\n return getModularInstance(user).delete();\n}\n","////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location<State = any> extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: State;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n\n /**\n * The delta between this location and the former location in the history stack\n */\n delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial<Path>;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n /**\n * The last action that modified the current location. This will always be\n * Action.Pop when a history instance is first created. This value is mutable.\n */\n readonly action: Action;\n\n /**\n * The current location. This value is mutable.\n */\n readonly location: Location;\n\n /**\n * Returns a valid href for the given `to` value that may be used as\n * the value of an <a href> attribute.\n *\n * @param to - The destination URL\n */\n createHref(to: To): string;\n\n /**\n * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial<Location>;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 1 });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route (<Route path=\"*\">) since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant<T>(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\nexport function warning(cond: any, message: string) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly<Location> {\n let location: Readonly<Location> = {\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\",\n ...(typeof to === \"string\" ? parsePath(to) : to),\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: (to && (to as Location).key) || key || createKey(),\n };\n return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial<Path>) {\n if (search && search !== \"?\")\n pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\")\n pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial<Path> {\n let parsedPath: Partial<Path> = {};\n\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n window?: Window;\n v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n createHref: (window: Window, to: To) => string,\n validateLocation: ((location: Location, to: To) => void) | null,\n options: UrlHistoryOptions = {}\n): UrlHistory {\n let { window = document.defaultView!, v5Compat = false } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 1 });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n deferred = \"deferred\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: any;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n type: ResultType.deferred;\n deferredData: DeferredData;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n status: number;\n location: string;\n revalidate: boolean;\n reloadDocument?: boolean;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n type: ResultType.error;\n error: any;\n headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n | SuccessResult\n | DeferredResult\n | RedirectResult\n | ErrorResult;\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;\n\n/**\n * Users can specify either lowercase or uppercase form methods on `<Form>`,\n * useSubmit(), `<fetcher.Form>`, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude<FormMethod, \"get\">;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude<V7_FormMethod, \"GET\">;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"application/json\"\n | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: undefined;\n text: string;\n };\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs<Context> {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs<Context = any>\n extends DataFunctionArgs<Context> {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs<Context = any>\n extends DataFunctionArgs<Context> {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable<unknown> | null;\n\n/**\n * Route loader function signature\n */\nexport interface LoaderFunction<Context = any> {\n (args: LoaderFunctionArgs<Context>):\n | Promise<DataFunctionValue>\n | DataFunctionValue;\n}\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction<Context = any> {\n (args: ActionFunctionArgs<Context>):\n | Promise<DataFunctionValue>\n | DataFunctionValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n text?: Submission[\"text\"];\n formData?: Submission[\"formData\"];\n json?: Submission[\"json\"];\n actionResult?: any;\n defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record<string, any>;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set<ImmutableRouteKey>([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne<T, Key = keyof T> = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit<T, K> & Required<Pick<T, K>> : never;\n }[keyof T],\n undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction<R extends AgnosticRouteObject> {\n (): Promise<RequireOne<Omit<R, ImmutableRouteKey>>>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n caseSensitive?: boolean;\n path?: string;\n id?: string;\n loader?: LoaderFunction;\n action?: ActionFunction;\n hasErrorBoundary?: boolean;\n shouldRevalidate?: ShouldRevalidateFunction;\n handle?: any;\n lazy?: LazyRouteFunction<AgnosticBaseRouteObject>;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record<string, AgnosticDataRouteObject | undefined>;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam<Path extends string> =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam<L> | _PathParam<R>\n : // find params after `:`\n Path extends `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\n : Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam<Path extends string> =\n // check if path is just a wildcard\n Path extends \"*\" | \"/*\"\n ? \"*\"\n : // look for wildcard at the end of the path\n Path extends `${infer Rest}/*`\n ? \"*\" | _PathParam<Rest>\n : // look for params in the absence of wildcards\n _PathParam<Path>;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise, return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey<Segment extends string> =\n // if you could not find path params, fallback to `string`\n [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params<Key extends string = string> = {\n readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params<ParamKey>;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The route object that was used to match.\n */\n route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {}\n\nfunction isIndexRoute(\n route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n routes: AgnosticRouteObject[],\n mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: number[] = [],\n manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, index];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(\n route.index !== true || !route.children,\n `Cannot specify children on an index route`\n );\n invariant(\n !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\n\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial<Location> | string,\n basename = \"/\"\n): AgnosticRouteMatch<string, RouteObjectType>[] | null {\n let location =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n let pathname = stripBasename(location.pathname || \"/\", basename);\n\n if (pathname == null) {\n return null;\n }\n\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n\n let matches = null;\n for (let i = 0; matches == null && i < branches.length; ++i) {\n matches = matchRouteBranch<string, RouteObjectType>(\n branches[i],\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n safelyDecodeURI(pathname)\n );\n }\n\n return matches;\n}\n\nexport interface UIMatch<Data = unknown, Handle = unknown> {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: Data;\n handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UIMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle,\n };\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta<RouteObjectType>[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch<RouteObjectType>[] = [],\n parentsMeta: RouteMeta<RouteObjectType>[] = [],\n parentPath = \"\"\n): RouteBranch<RouteObjectType>[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta<RouteObjectType> = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:\\w+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch<RouteObjectType>,\n pathname: string\n): AgnosticRouteMatch<ParamKey, RouteObjectType>[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch<ParamKey, RouteObjectType>[] = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname =\n matchedPathname === \"/\"\n ? pathname\n : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath(\n { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n remainingPathname\n );\n\n if (!match) return null;\n\n Object.assign(matchedParams, match.params);\n\n let route = meta.route;\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params<ParamKey>,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(\n joinPaths([matchedPathname, match.pathnameBase])\n ),\n route,\n });\n\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n\n return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/utils/generate-path\n */\nexport function generatePath<Path extends string>(\n originalPath: Path,\n params: {\n [key in PathParam<Path>]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const stringify = (p: any) =>\n p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam<Path>;\n // Apply the splat\n return stringify(params[star]);\n }\n\n const keyMatch = segment.match(/^:(\\w+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam<Path>];\n invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n return stringify(param);\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern<Path extends string = string> {\n /**\n * A string to match against a URL pathname. May contain `:id`-style segments\n * to indicate placeholders for dynamic parameters. May also end with `/*` to\n * indicate matching the rest of the URL pathname.\n */\n path: Path;\n /**\n * Should be `true` if the static portions of the `path` should be matched in\n * the same case.\n */\n caseSensitive?: boolean;\n /**\n * Should be `true` if this pattern should match the entire URL pathname.\n */\n end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch<ParamKey extends string = string> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params<ParamKey>;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The pattern that was used to match.\n */\n pattern: PathPattern;\n}\n\ntype Mutable<T> = {\n -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey<Path>,\n Path extends string\n>(\n pattern: PathPattern<Path> | Path,\n pathname: string\n): PathMatch<ParamKey> | null {\n if (typeof pattern === \"string\") {\n pattern = { path: pattern, caseSensitive: false, end: true };\n }\n\n let [matcher, compiledParams] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = compiledParams.reduce<Mutable<Params>>(\n (memo, { paramName, isOptional }, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = safelyDecodeURIComponent(value || \"\", paramName);\n }\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, CompiledPathParam[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let params: CompiledPathParam[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(/\\/:(\\w+)(\\?)?/g, (_: string, paramName: string, isOptional) => {\n params.push({ paramName, isOptional: isOptional != null });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n });\n\n if (path.endsWith(\"*\")) {\n params.push({ paramName: \"*\" });\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, params];\n}\n\nfunction safelyDecodeURI(value: string) {\n try {\n return decodeURI(value);\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\n}\n\nfunction safelyDecodeURIComponent(value: string, paramName: string) {\n try {\n return decodeURIComponent(value);\n } catch (error) {\n warning(\n false,\n `The value for the URL param \"${paramName}\" will not be decoded because` +\n ` the string \"${value}\" is a malformed URL segment. This is probably` +\n ` due to a bad percent encoding (${error}).`\n );\n\n return value;\n }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n pathname: string,\n basename: string\n): string | null {\n if (basename === \"/\") return pathname;\n\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\")\n ? basename.length - 1\n : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n\n return pathname.slice(startIndex) || \"/\";\n}\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\",\n } = typeof to === \"string\" ? parsePath(to) : to;\n\n let pathname = toPathname\n ? toPathname.startsWith(\"/\")\n ? toPathname\n : resolvePathname(toPathname, fromPathname)\n : fromPathname;\n\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash),\n };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n\n relativeSegments.forEach((segment) => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n char: string,\n field: string,\n dest: string,\n path: Partial<Path>\n) {\n return (\n `Cannot include a '${char}' character in a manually specified ` +\n `\\`to.${field}\\` field [${JSON.stringify(\n path\n )}]. Please separate it out to the ` +\n `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n `a string in <Link to=\"...\"> and the router will parse it for you.`\n );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * <Route path=\"/\">\n * <Route path=\"accounts\" element={<Link to=\"..\"}>\n * </Route>\n *\n * <Route path=\"/\">\n * <Route path=\"accounts\">\n * <Route element={<AccountsLayout />}> // <-- Does not contribute\n * <Route index element={<Link to=\"..\"} /> // <-- Does not contribute\n * </Route\n * </Route>\n * </Route>\n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\n );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n // Use the full pathname for the leaf match so we include splat values for \".\" links\n return getPathContributingMatches(matches).map((match, idx) =>\n idx === matches.length - 1 ? match.pathname : match.pathnameBase\n );\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial<Path>;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = { ...toArg };\n\n invariant(\n !to.pathname || !to.pathname.includes(\"?\"),\n getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n );\n invariant(\n !to.pathname || !to.pathname.includes(\"#\"),\n getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n );\n invariant(\n !to.search || !to.search.includes(\"#\"),\n getInvalidPathError(\"#\", \"search\", \"hash\", to)\n );\n }\n\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n let from: string;\n\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `<Link to>` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (toPathname == null) {\n from = locationPathname;\n } else if (isPathRelative) {\n let fromSegments = routePathnames[routePathnames.length - 1]\n .replace(/^\\//, \"\")\n .split(\"/\");\n\n if (toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n // With relative=\"path\", each leading .. segment means \"go up one URL segment\"\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n fromSegments.pop();\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n from = \"/\" + fromSegments.join(\"/\");\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n if (toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how <a href> works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n // If there are more \"..\" segments than parent routes, resolve relative to\n // the root / URL.\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\n}\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n !search || search === \"?\"\n ? \"\"\n : search.startsWith(\"?\")\n ? search\n : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = <Data>(\n data: Data,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n\n return new Response(JSON.stringify(data), {\n ...responseInit,\n headers,\n });\n};\n\nexport interface TrackedPromise extends Promise<any> {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeysSet: Set<string> = new Set<string>();\n private controller: AbortController;\n private abortPromise: Promise<void>;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record<string, unknown>;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record<string, unknown>, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise<unknown> | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record<string, unknown>,\n init?: number | ResponseInit\n) => DeferredData;\n\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n\nexport type ErrorResponse = {\n status: number;\n statusText: string;\n data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n private error?: Error;\n private internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n ActionFunction,\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n AgnosticRouteObject,\n DataResult,\n DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n ImmutableRouteKey,\n LoaderFunction,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\n} from \"./utils\";\nimport {\n ErrorResponseImpl,\n ResultType,\n convertRouteMatchToUiMatch,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n getResolveToMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n resolveTo,\n stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record<string, number>,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): Promise<void>;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher<TData = any>(key: string): Fetcher<TData>;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete the fetcher for a given key\n * @param key\n */\n deleteFetcher(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map<string, AbortController>;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map<string, DeferredData>;\n}\n\n/**\n * State maintained internally by the router. During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n /**\n * The action of the most recent navigation\n */\n historyAction: HistoryAction;\n\n /**\n * The current location reflected by the router\n */\n location: Location;\n\n /**\n * The current set of route matches\n */\n matches: AgnosticDataRouteMatch[];\n\n /**\n * Tracks whether we've completed our initial data load\n */\n initialized: boolean;\n\n /**\n * Current scroll position we should start at for a new view\n * - number -> scroll position to restore to\n * - false -> do not restore scroll at all (used during submissions)\n * - null -> don't have a saved position, scroll to hash or top of page\n */\n restoreScrollPosition: number | false | null;\n\n /**\n * Indicate whether this navigation should skip resetting the scroll position\n * if we are unable to restore the scroll position\n */\n preventScrollReset: boolean;\n\n /**\n * Tracks the state of the current navigation\n */\n navigation: Navigation;\n\n /**\n * Tracks any in-progress revalidations\n */\n revalidation: RevalidationState;\n\n /**\n * Data from the loaders for the current matches\n */\n loaderData: RouteData;\n\n /**\n * Data from the action for the current matches\n */\n actionData: RouteData | null;\n\n /**\n * Errors caught from loaders for the current matches\n */\n errors: RouteData | null;\n\n /**\n * Map of current fetchers\n */\n fetchers: Map<string, Fetcher>;\n\n /**\n * Map of current blockers\n */\n blockers: Map<string, Blocker>;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick<RouterState, \"loaderData\" | \"actionData\" | \"errors\">\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_prependBasename: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial<FutureConfig>;\n hydrationData?: HydrationState;\n window?: Window;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record<string, Headers>;\n actionHeaders: Record<string, Headers>;\n activeDeferreds: Record<string, DeferredData> | null;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(\n request: Request,\n opts?: { requestContext?: unknown }\n ): Promise<StaticHandlerContext | Response>;\n queryRoute(\n request: Request,\n opts?: { routeId?: string; requestContext?: unknown }\n ): Promise<any>;\n}\n\ntype ViewTransitionOpts = {\n currentLocation: Location;\n nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (\n state: RouterState,\n opts: {\n deletedFetchers: string[];\n unstable_viewTransitionOpts?: ViewTransitionOpts;\n unstable_flushSync: boolean;\n }\n ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n unstable_viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n} & (\n | { formData: FormData; body?: undefined }\n | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n json: undefined;\n text: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n text: Submission[\"text\"] | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n text: Submission[\"text\"];\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates<TData = any> = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n text: Submission[\"text\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n text: Submission[\"text\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n data: TData | undefined;\n };\n};\n\nexport type Fetcher<TData = any> =\n FetcherStates<TData>[keyof FetcherStates<TData>];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\ninterface HandleActionResult extends ShortCircuitable {\n /**\n * Error thrown from the current action, keyed by the route containing the\n * error boundary to render the error. To be committed to the state after\n * loaders have completed\n */\n pendingActionError?: RouteData;\n /**\n * Data returned from the current action, keyed by the route owning the action.\n * To be committed to the state after loaders have completed\n */\n pendingActionData?: RouteData;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n /**\n * loaderData returned from the current set of loaders\n */\n loaderData?: RouterState[\"loaderData\"];\n /**\n * errors thrown from the current set of loaders\n */\n errors?: RouterState[\"errors\"];\n}\n\n/**\n * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\n/**\n * Wrapper object to allow us to throw any response out from callLoaderOrAction\n * for queryRouter while preserving whether or not it was thrown or returned\n * from the loader/action\n */\ninterface QueryRouteResponse {\n type: ResultType.data | ResultType.error;\n response: Response;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\nconst validMutationMethods = new Set<MutationFormMethod>(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set<FormMethod>(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n const routerWindow = init.window\n ? init.window\n : typeof window !== \"undefined\"\n ? window\n : undefined;\n const isBrowser =\n typeof routerWindow !== \"undefined\" &&\n typeof routerWindow.document !== \"undefined\" &&\n typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_prependBasename: false,\n ...init.future,\n };\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set<RouterSubscriber>();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record<string, number> | null = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition: GetScrollPositionFunction | null = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from <ScrollRestoration /> until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialErrors: RouteData | null = null;\n\n if (initialMatches == null) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n let initialized =\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n !initialMatches.some((m) => m.route.lazy) &&\n // And we have to either have no loaders or have been provided hydrationData\n (!initialMatches.some((m) => m.route.loader) || init.hydrationData != null);\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n blockers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: HistoryAction = HistoryAction.Pop;\n\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions: Map<string, Set<string>> = new Map<\n string,\n Set<string>\n >();\n\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener: (() => void) | null = null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map<string, AbortController>();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map<string, number>();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set<string>();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map<string, FetchLoadMatch>();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map<string, number>();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set<string>();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map<string, DeferredData>();\n\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map<string, BlockerFunction>();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let ignoreNextHistoryUpdate = false;\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n ignoreNextHistoryUpdate = true;\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked\n init.history.go(delta);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () =>\n persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () =>\n routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location);\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(\n newState: Partial<RouterState>,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach((subscriber) =>\n subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n unstable_viewTransitionOpts: opts.viewTransitionOpts,\n unstable_flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n }\n }\n\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(\n location: Location,\n newState: Partial<Omit<RouterState, \"action\" | \"location\" | \"navigation\">>,\n { flushSync }: { flushSync?: boolean } = {}\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.Replace) {\n init.history.replace(location, location.state);\n }\n\n let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === HistoryAction.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location,\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set<string>([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n }\n\n updateState(\n {\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers,\n },\n {\n viewTransitionOpts,\n flushSync: flushSync === true,\n }\n );\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\n }\n\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(\n to: number | To | null,\n opts?: RouterNavigateOptions\n ): Promise<void> {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n to,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.unstable_viewTransition,\n flushSync,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n { overrideNavigation: state.navigation }\n );\n }\n\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(\n historyAction: HistoryAction,\n location: Location,\n opts?: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponseImpl;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n enableViewTransition?: boolean;\n flushSync?: boolean;\n }\n ): Promise<void> {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n completeNavigation(\n location,\n {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n },\n { flushSync }\n );\n return;\n }\n\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial load will always\n // be \"same hash\". For example, on /page#hash and submit a <Form method=\"post\">\n // which will default to a navigation to /page\n if (\n state.initialized &&\n !isRevalidationRequired &&\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches }, { flushSync });\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let pendingActionData: RouteData | undefined;\n let pendingError: RouteData | undefined;\n\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingError = {\n [findNearestBoundary(matches).route.id]: opts.pendingError,\n };\n } else if (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\n // Call action if we received an action submission\n let actionOutput = await handleAction(\n request,\n location,\n opts.submission,\n matches,\n { replace: opts.replace, flushSync }\n );\n\n if (actionOutput.shortCircuited) {\n return;\n }\n\n pendingActionData = actionOutput.pendingActionData;\n pendingError = actionOutput.pendingActionError;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n\n // Create a GET request for the loaders\n request = new Request(request.url, { signal: request.signal });\n }\n\n // Call loaders\n let { shortCircuited, loaderData, errors } = await handleLoaders(\n request,\n location,\n matches,\n loadingNavigation,\n opts && opts.submission,\n opts && opts.fetcherSubmission,\n opts && opts.replace,\n flushSync,\n pendingActionData,\n pendingError\n );\n\n if (shortCircuited) {\n return;\n }\n\n // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches,\n ...(pendingActionData ? { actionData: pendingActionData } : {}),\n loaderData,\n errors,\n });\n }\n\n // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n async function handleAction(\n request: Request,\n location: Location,\n submission: Submission,\n matches: AgnosticDataRouteMatch[],\n opts: { replace?: boolean; flushSync?: boolean } = {}\n ): Promise<HandleActionResult> {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n replace =\n result.location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(state, result, { submission, replace });\n return { shortCircuited: true };\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n // By default, all submissions are REPLACE navigations, but if the\n // action threw an error that'll be rendered in an errorElement, we fall\n // back to PUSH so that the user can use the back button to get back to\n // the pre-submission form location to try again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n // Send back an empty object we can use to clear out any prior actionData\n pendingActionData: {},\n pendingActionError: { [boundaryMatch.route.id]: result.error },\n };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n return {\n pendingActionData: { [actionMatch.route.id]: result.data },\n };\n }\n\n // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n async function handleLoaders(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n overrideNavigation?: Navigation,\n submission?: Submission,\n fetcherSubmission?: Submission,\n replace?: boolean,\n flushSync?: boolean,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n ): Promise<HandleLoadersResult> {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation =\n overrideNavigation || getLoadingNavigation(location, submission);\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission ||\n fetcherSubmission ||\n getSubmissionFromNavigation(loadingNavigation);\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionData,\n pendingError\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n );\n\n pendingNavigationLoadId = ++incrementingLoadId;\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(\n location,\n {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors: pendingError || null,\n ...(pendingActionData ? { actionData: pendingActionData } : {}),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n },\n { flushSync }\n );\n return { shortCircuited: true };\n }\n\n // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n if (!isUninterruptedRevalidation) {\n revalidatingFetchers.forEach((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n fetcher ? fetcher.data : undefined\n );\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n let actionData = pendingActionData || state.actionData;\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData\n ? Object.keys(actionData).length === 0\n ? { actionData: null }\n : { actionData }\n : {}),\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n revalidatingFetchers.forEach((rf) => {\n if (fetchControllers.has(rf.key)) {\n abortFetcher(rf.key);\n }\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n await startRedirectNavigation(state, redirect.result, { replace });\n return { shortCircuited: true };\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n matchesToLoad,\n loaderResults,\n pendingError,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe((aborted) => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n if (fetchControllers.has(key)) abortFetcher(key);\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath }),\n { flushSync }\n );\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n true,\n normalizedPath,\n opts\n );\n\n if (error) {\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n let match = getTargetMatch(matches, path);\n\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\n submission\n );\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, { routeId, path });\n handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\n submission\n );\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n requestMatches: AgnosticDataRouteMatch[],\n flushSync: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action && !match.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync,\n });\n\n // Call the action for the fetcher\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResult = await callLoaderOrAction(\n \"action\",\n fetchRequest,\n match,\n requestMatches,\n manifest,\n mapRouteProperties,\n basename\n );\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(state, actionResult, {\n fetcherSubmission: submission,\n });\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(\n init.history,\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n { [match.route.id]: actionResult.data },\n undefined // No need to send through errors since we short circuit above\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(staleKey, revalidatingFetcher);\n if (fetchControllers.has(staleKey)) {\n abortFetcher(staleKey);\n }\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n return startRedirectNavigation(state, redirect.result);\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n state.matches,\n matchesToLoad,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n\n abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n fetchers: new Map(state.fetchers),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n flushSync: boolean,\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(\n key,\n getLoadingFetcher(\n submission,\n existingFetcher ? existingFetcher.data : undefined\n ),\n { flushSync }\n );\n\n // Call the loader for this fetcher route match\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let result: DataResult = await callLoaderOrAction(\n \"loader\",\n fetchRequest,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename\n );\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\n\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(state, result);\n return;\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n state: RouterState,\n redirect: RedirectResult,\n {\n submission,\n fetcherSubmission,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n replace?: boolean;\n } = {}\n ) {\n if (redirect.revalidate) {\n isRevalidationRequired = true;\n }\n\n let redirectLocation = createLocation(state.location, redirect.location, {\n _isRedirect: true,\n });\n invariant(\n redirectLocation,\n \"Expected a location on the redirect navigation\"\n );\n\n if (isBrowser) {\n let isDocumentReload = false;\n\n if (redirect.reloadDocument) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(redirect.location)) {\n const url = init.history.createURL(redirect.location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(redirect.location);\n } else {\n routerWindow.location.assign(redirect.location);\n }\n return;\n }\n }\n\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectHistoryAction =\n replace === true ? HistoryAction.Replace : HistoryAction.Push;\n\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let { formMethod, formAction, formEncType } = state.navigation;\n if (\n !submission &&\n !fetcherSubmission &&\n formMethod &&\n formAction &&\n formEncType\n ) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (\n redirectPreserveMethodStatusCodes.has(redirect.status) &&\n activeSubmission &&\n isMutationMethod(activeSubmission.formMethod)\n ) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: redirect.location,\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(\n redirectLocation,\n submission\n );\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n }\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n // Call all navigation loaders and revalidating fetcher loaders in parallel,\n // then slice off the results into separate arrays so we can handle them\n // accordingly\n let results = await Promise.all([\n ...matchesToLoad.map((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename\n )\n ),\n ...fetchersToLoad.map((f) => {\n if (f.matches && f.match && f.controller) {\n return callLoaderOrAction(\n \"loader\",\n createClientSideRequest(init.history, f.path, f.controller.signal),\n f.match,\n f.matches,\n manifest,\n mapRouteProperties,\n basename\n );\n } else {\n let error: ErrorResult = {\n type: ResultType.error,\n error: getInternalRouterError(404, { pathname: f.path }),\n };\n return error;\n }\n }),\n ]);\n let loaderResults = results.slice(0, matchesToLoad.length);\n let fetcherResults = results.slice(matchesToLoad.length);\n\n await Promise.all([\n resolveDeferredResults(\n currentMatches,\n matchesToLoad,\n loaderResults,\n loaderResults.map(() => request.signal),\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map((f) => f.match),\n fetcherResults,\n fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)),\n true\n ),\n ]);\n\n return { results, loaderResults, fetcherResults };\n }\n\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true;\n\n // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.push(key);\n abortFetcher(key);\n }\n });\n }\n\n function updateFetcherState(\n key: string,\n fetcher: Fetcher,\n opts: { flushSync?: boolean } = {}\n ) {\n state.fetchers.set(key, fetcher);\n updateState(\n { fetchers: new Map(state.fetchers) },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function setFetcherError(\n key: string,\n routeId: string,\n error: any,\n opts: { flushSync?: boolean } = {}\n ) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState(\n {\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function getFetcher<TData = any>(key: string): Fetcher<TData> {\n if (future.v7_fetcherPersist) {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n function deleteFetcher(key: string): void {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (\n fetchControllers.has(key) &&\n !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n ) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n deletedFetchers.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n if (future.v7_fetcherPersist) {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n } else {\n activeFetchers.set(key, count);\n }\n } else {\n deleteFetcher(key);\n }\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n invariant(controller, `Expected fetch controller: ${key}`);\n controller.abort();\n fetchControllers.delete(key);\n }\n\n function markFetchersDone(keys: string[]) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({ blockers });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\n }\n\n function cancelActiveDeferreds(\n predicate?: (routeId: string) => boolean\n ): string[] {\n let cancelledRouteIds: string[] = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the <ScrollRestoration> component\n function enableScrollRestoration(\n positions: Record<string, number>,\n getPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || null;\n\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered <ScrollRestoration/>\n // and therefore have no savedScrollPositions available\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({ restoreScrollPosition: y });\n }\n }\n\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n\n function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(\n location,\n matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n );\n return key || location.key;\n }\n return location.key;\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\n );\n }\n\n router = {\n get basename() {\n return basename;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n */\n async function query(\n request: Request,\n { requestContext }: { requestContext?: unknown } = {}\n ): Promise<StaticHandlerContext | Response> {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(request, location, matches, requestContext);\n if (isResponse(result)) {\n return result;\n }\n\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n }: { requestContext?: unknown; routeId?: string } = {}\n ): Promise<any> {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n match\n );\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch\n ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction, we throw\n // it to bail out and then return or throw here based on whether the user\n // returned or threw\n if (isQueryRouteResponse(e)) {\n if (e.type === ResultType.error) {\n throw e.response;\n }\n return e.response;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n isRouteRequest: boolean\n ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n { isStaticRequest: true, isRouteRequest, requestContext }\n );\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(\n `${method}() call aborted: ${request.method} ${request.url}`\n );\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.status,\n headers: {\n Location: result.location,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n let context = await loadRouteData(\n request,\n matches,\n requestContext,\n undefined,\n {\n [boundaryMatch.route.id]: result.error,\n }\n );\n\n // action status codes take precedence over loader status codes\n return {\n ...context,\n statusCode: isRouteErrorResponse(result.error)\n ? result.error.status\n : 500,\n actionData: null,\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n let context = await loadRouteData(loaderRequest, matches, requestContext);\n\n return {\n ...context,\n // action status codes take precedence over loader status codes\n ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n actionData: {\n [actionMatch.route.id]: result.data,\n },\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n async function loadRouteData(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch,\n pendingActionError?: RouteData\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(pendingActionError || {})[0]\n );\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors: pendingActionError || null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let results = await Promise.all([\n ...matchesToLoad.map((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n { isStaticRequest: true, isRouteRequest, requestContext }\n )\n ),\n ]);\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(\n `${method}() call aborted: ${request.method} ${request.url}`\n );\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map<string, DeferredData>();\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionError,\n activeDeferreds\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set<string>(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\n };\n }\n\n return {\n dataRoutes,\n query,\n queryRoute,\n };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n routes: AgnosticDataRouteObject[],\n context: StaticHandlerContext,\n error: any\n) {\n let newContext: StaticHandlerContext = {\n ...context,\n statusCode: 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error,\n },\n };\n return newContext;\n}\n\nfunction isSubmissionNavigation(\n opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n return (\n opts != null &&\n ((\"formData\" in opts && opts.formData != null) ||\n (\"body\" in opts && opts.body !== undefined))\n );\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n prependBasename: boolean,\n to: To | null,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getResolveToMatches(contextualMatches),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Add an ?index param for matched index routes if we don't already have one\n if (\n (to == null || to === \"\" || to === \".\") &&\n activeRouteMatch &&\n activeRouteMatch.route.index &&\n !hasNakedIndexQuery(path.search)\n ) {\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n normalizeFormMethod: boolean,\n isFetcher: boolean,\n path: string,\n opts?: BaseNavigateOrFetchOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponseImpl;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, { type: \"invalid-body\" }),\n });\n\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() as FormMethod);\n let formAction = stripHashFromPath(path);\n\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n let text =\n typeof opts.body === \"string\"\n ? opts.body\n : opts.body instanceof FormData ||\n opts.body instanceof URLSearchParams\n ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce(\n (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n \"\"\n )\n : String(opts.body);\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text,\n },\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n try {\n let json =\n typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined,\n },\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n\n invariant(\n typeof FormData === \"function\",\n \"FormData is not available in this environment\"\n );\n\n let searchParams: URLSearchParams;\n let formData: FormData;\n\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n\n let submission: Submission = {\n formMethod,\n formAction,\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n matches: AgnosticDataRouteMatch[],\n boundaryId?: string\n) {\n let boundaryMatches = matches;\n if (boundaryId) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n boundaryMatches = matches.slice(0, index);\n }\n }\n return boundaryMatches;\n}\n\nfunction getMatchesToLoad(\n history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n deletedFetchers: Set<string>,\n fetchLoadMatches: Map<string, FetchLoadMatch>,\n fetchRedirectIds: Set<string>,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingError\n ? Object.values(pendingError)[0]\n : pendingActionData\n ? Object.values(pendingActionData)[0]\n : undefined;\n\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n\n let navigationMatches = boundaryMatches.filter((match, index) => {\n if (match.route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n if (match.route.loader == null) {\n return false;\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\n return true;\n }\n\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n defaultShouldRevalidate:\n // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n // Clicked the same link, resubmitted a GET form\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate if fetcher won't be present in the subsequent render\n if (\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.has(key)\n ) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.includes(key)) {\n // Always revalidate if the fetcher was cancelled\n shouldRevalidate = true;\n } else if (\n fetcher &&\n fetcher.state !== \"idle\" &&\n fetcher.data === undefined\n ) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n defaultShouldRevalidate: isRevalidationRequired,\n });\n }\n\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: ShouldRevalidateFunctionArgs\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record<string, any> = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n basename: string,\n opts: {\n isStaticRequest?: boolean;\n isRouteRequest?: boolean;\n requestContext?: unknown;\n } = {}\n): Promise<DataResult> {\n let resultType;\n let result;\n let onReject: (() => void) | undefined;\n\n let runHandler = (handler: ActionFunction | LoaderFunction) => {\n // Setup a promise we can race against so that abort signals short circuit\n let reject: () => void;\n let abortPromise = new Promise((_, r) => (reject = r));\n onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n return Promise.race([\n handler({\n request,\n params: match.params,\n context: opts.requestContext,\n }),\n abortPromise,\n ]);\n };\n\n try {\n let handler = match.route[type];\n\n if (match.route.lazy) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let values = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch((e) => {\n handlerError = e;\n }),\n loadLazyRouteModule(match.route, mapRouteProperties, manifest),\n ]);\n if (handlerError) {\n throw handlerError;\n }\n result = values[0];\n } else {\n // Load lazy route module, then run any returned handler\n await loadLazyRouteModule(match.route, mapRouteProperties, manifest);\n\n handler = match.route[type];\n if (handler) {\n // Handler still run even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, data: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n\n invariant(\n result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n resultType = ResultType.error;\n result = e;\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n if (isResponse(result)) {\n let status = result.status;\n\n // Process redirects\n if (redirectStatusCodes.has(status)) {\n let location = result.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n // Support relative routing in internal redirects\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n location = normalizeTo(\n new URL(request.url),\n matches.slice(0, matches.indexOf(match) + 1),\n basename,\n true,\n location\n );\n } else if (!opts.isStaticRequest) {\n // Strip off the protocol+origin for same-origin + same-basename absolute\n // redirects. If this is a static request, we can let it go back to the\n // browser as-is\n let currentUrl = new URL(request.url);\n let url = location.startsWith(\"//\")\n ? new URL(currentUrl.protocol + location)\n : new URL(location);\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n location = url.pathname + url.search + url.hash;\n }\n }\n\n // Don't process redirects in the router during static requests requests.\n // Instead, throw the Response and let the server handle it with an HTTP\n // redirect. We also update the Location header in place in this flow so\n // basename and relative routing is taken into account\n if (opts.isStaticRequest) {\n result.headers.set(\"Location\", location);\n throw result;\n }\n\n return {\n type: ResultType.redirect,\n status,\n location,\n revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null,\n reloadDocument: result.headers.get(\"X-Remix-Reload-Document\") !== null,\n };\n }\n\n // For SSR single-route requests, we want to hand Responses back directly\n // without unwrapping. We do this with the QueryRouteResponse wrapper\n // interface so we can know whether it was returned or thrown\n if (opts.isRouteRequest) {\n let queryRouteResponse: QueryRouteResponse = {\n type:\n resultType === ResultType.error ? ResultType.error : ResultType.data,\n response: result,\n };\n throw queryRouteResponse;\n }\n\n let data: any;\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n data = await result.json();\n } else {\n data = await result.text();\n }\n\n if (resultType === ResultType.error) {\n return {\n type: resultType,\n error: new ErrorResponseImpl(status, result.statusText, data),\n headers: result.headers,\n };\n }\n\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n if (resultType === ResultType.error) {\n return { type: resultType, error: result };\n }\n\n if (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n return { type: ResultType.data, data: result };\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n\n if (formEncType === \"application/json\") {\n init.headers = new Headers({ \"Content-Type\": formEncType });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (\n formEncType === \"application/x-www-form-urlencoded\" &&\n submission.formData\n ) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n\n return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n searchParams: URLSearchParams\n): FormData {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n activeDeferreds: Map<string, DeferredData>\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record<string, Headers>;\n} {\n // Fill in loaderData/errors from our loaders\n let loaderData: RouterState[\"loaderData\"] = {};\n let errors: RouterState[\"errors\"] | null = null;\n let statusCode: number | undefined;\n let foundError = false;\n let loaderHeaders: Record<string, Headers> = {};\n\n // Process loader results into state.loaderData/state.errors\n results.forEach((result, index) => {\n let id = matchesToLoad[index].route.id;\n invariant(\n !isRedirectResult(result),\n \"Cannot handle redirect results in processLoaderData\"\n );\n if (isErrorResult(result)) {\n // Look upwards from the matched route for the closest ancestor\n // error boundary, defaulting to the root match\n let boundaryMatch = findNearestBoundary(matches, id);\n let error = result.error;\n // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n if (pendingError) {\n error = Object.values(pendingError)[0];\n pendingError = undefined;\n }\n\n errors = errors || {};\n\n // Prefer higher error values if lower errors bubble to the same boundary\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n } else {\n loaderData[id] = result.data;\n }\n\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (\n result.statusCode != null &&\n result.statusCode !== 200 &&\n !foundError\n ) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n });\n\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here. Also clear out any loaderData for the\n // throwing route\n if (pendingError) {\n errors = pendingError;\n loaderData[Object.keys(pendingError)[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: DataResult[],\n activeDeferreds: Map<string, DeferredData>\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingError,\n activeDeferreds\n );\n\n // Process results from our revalidating fetchers\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let { key, match, controller } = revalidatingFetchers[index];\n invariant(\n fetcherResults !== undefined && fetcherResults[index] !== undefined,\n \"Did not find corresponding fetcher result\"\n );\n let result = fetcherResults[index];\n\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n continue;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[],\n errors: RouteData | null | undefined\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponseImpl(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n results: DataResult[]\n): { result: RedirectResult; idx: number } | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return { result, idx: i };\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\n}\n\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isQueryRouteResponse(obj: any): obj is QueryRouteResponse {\n return (\n obj &&\n isResponse(obj.response) &&\n (obj.type === ResultType.data || obj.type === ResultType.error)\n );\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: (AgnosticDataRouteMatch | null)[],\n results: DataResult[],\n signals: (AbortSignal | null)[],\n isFetcher: boolean,\n currentLoaderData?: RouteData\n) {\n for (let index = 0; index < results.length; index++) {\n let result = results[index];\n let match = matchesToLoad[index];\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n let signal = signals[index];\n invariant(\n signal,\n \"Expected an AbortSignal for revalidating fetcher deferred result\"\n );\n await resolveDeferredData(result, signal, isFetcher).then((result) => {\n if (result) {\n results[index] = result || results[index];\n }\n });\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise<SuccessResult | ErrorResult | undefined> {\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData,\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e,\n };\n }\n }\n\n return {\n type: ResultType.data,\n data: result.deferredData.data,\n };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n hasNakedIndexQuery(search || \"\")\n ) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n navigation: Navigation\n): Submission | undefined {\n let { formMethod, formAction, formEncType, text, formData, json } =\n navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text,\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined,\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined,\n };\n }\n}\n\nfunction getLoadingNavigation(\n location: Location,\n submission?: Submission\n): NavigationStates[\"Loading\"] {\n if (submission) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n } else {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n };\n return navigation;\n }\n}\n\nfunction getSubmittingNavigation(\n location: Location,\n submission: Submission\n): NavigationStates[\"Submitting\"] {\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n}\n\nfunction getLoadingFetcher(\n submission?: Submission,\n data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n if (submission) {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data,\n };\n return fetcher;\n } else {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n }\n}\n\nfunction getSubmittingFetcher(\n submission: Submission,\n existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined,\n };\n return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n let fetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n _window: Window,\n transitions: Map<string, Set<string>>\n) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(\n TRANSITIONS_STORAGE_KEY\n );\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\n\nfunction persistAppliedTransitions(\n _window: Window,\n transitions: Map<string, Set<string>>\n) {\n if (transitions.size > 0) {\n let json: Record<string, string[]> = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(\n TRANSITIONS_STORAGE_KEY,\n JSON.stringify(json)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save applied view transitions in sessionStorage (${error}).`\n );\n }\n }\n}\n\n//#endregion\n","import * as React from \"react\";\nimport type {\n AgnosticIndexRouteObject,\n AgnosticNonIndexRouteObject,\n AgnosticRouteMatch,\n History,\n LazyRouteFunction,\n Location,\n Action as NavigationType,\n RelativeRoutingType,\n Router,\n StaticHandlerContext,\n To,\n TrackedPromise,\n} from \"@remix-run/router\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticIndexRouteObject[\"path\"];\n id?: AgnosticIndexRouteObject[\"id\"];\n loader?: AgnosticIndexRouteObject[\"loader\"];\n action?: AgnosticIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticIndexRouteObject[\"handle\"];\n index: true;\n children?: undefined;\n element?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport interface NonIndexRouteObject {\n caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticNonIndexRouteObject[\"path\"];\n id?: AgnosticNonIndexRouteObject[\"id\"];\n loader?: AgnosticNonIndexRouteObject[\"loader\"];\n action?: AgnosticNonIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticNonIndexRouteObject[\"handle\"];\n index?: false;\n children?: RouteObject[];\n element?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n children?: DataRouteObject[];\n id: string;\n};\n\nexport interface RouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {}\n\nexport interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}\n\nexport interface DataRouterContextObject extends NavigationContextObject {\n router: Router;\n staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n React.createContext<DataRouterContextObject | null>(null);\nif (__DEV__) {\n DataRouterContext.displayName = \"DataRouter\";\n}\n\nexport const DataRouterStateContext = React.createContext<\n Router[\"state\"] | null\n>(null);\nif (__DEV__) {\n DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nexport const AwaitContext = React.createContext<TrackedPromise | null>(null);\nif (__DEV__) {\n AwaitContext.displayName = \"Await\";\n}\n\nexport interface NavigateOptions {\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n unstable_viewTransition?: boolean;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `<Router>` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n createHref: History[\"createHref\"];\n // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n encodeLocation?: History[\"encodeLocation\"];\n go: History[\"go\"];\n push(to: To, state?: any, opts?: NavigateOptions): void;\n replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n basename: string;\n navigator: Navigator;\n static: boolean;\n}\n\nexport const NavigationContext = React.createContext<NavigationContextObject>(\n null!\n);\n\nif (__DEV__) {\n NavigationContext.displayName = \"Navigation\";\n}\n\ninterface LocationContextObject {\n location: Location;\n navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext<LocationContextObject>(\n null!\n);\n\nif (__DEV__) {\n LocationContext.displayName = \"Location\";\n}\n\nexport interface RouteContextObject {\n outlet: React.ReactElement | null;\n matches: RouteMatch[];\n isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext<RouteContextObject>({\n outlet: null,\n matches: [],\n isDataRoute: false,\n});\n\nif (__DEV__) {\n RouteContext.displayName = \"Route\";\n}\n\nexport const RouteErrorContext = React.createContext<any>(null);\n\nif (__DEV__) {\n RouteErrorContext.displayName = \"RouteError\";\n}\n","import * as React from \"react\";\nimport type {\n Blocker,\n BlockerFunction,\n Location,\n ParamParseKey,\n Params,\n Path,\n PathMatch,\n PathPattern,\n RelativeRoutingType,\n Router as RemixRouter,\n RevalidationState,\n To,\n UIMatch,\n} from \"@remix-run/router\";\nimport {\n IDLE_BLOCKER,\n Action as NavigationType,\n UNSAFE_convertRouteMatchToUiMatch as convertRouteMatchToUiMatch,\n UNSAFE_getResolveToMatches as getResolveToMatches,\n UNSAFE_invariant as invariant,\n isRouteErrorResponse,\n joinPaths,\n matchPath,\n matchRoutes,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n DataRouteMatch,\n NavigateOptions,\n RouteContextObject,\n RouteMatch,\n RouteObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n RouteErrorContext,\n} from \"./context\";\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/hooks/use-href\n */\nexport function useHref(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useHref() may be used only in the context of a <Router> component.`\n );\n\n let { basename, navigator } = React.useContext(NavigationContext);\n let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n let joinedPathname = pathname;\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the href. If this is a root navigation, then just use the raw\n // basename which allows the basename to have full control over the presence\n // of a trailing slash on root links\n if (basename !== \"/\") {\n joinedPathname =\n pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n }\n\n return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a `<Router>`.\n *\n * @see https://reactrouter.com/hooks/use-in-router-context\n */\nexport function useInRouterContext(): boolean {\n return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/hooks/use-location\n */\nexport function useLocation(): Location {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useLocation() may be used only in the context of a <Router> component.`\n );\n\n return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/hooks/use-navigation-type\n */\nexport function useNavigationType(): NavigationType {\n return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * `<NavLink>`.\n *\n * @see https://reactrouter.com/hooks/use-match\n */\nexport function useMatch<\n ParamKey extends ParamParseKey<Path>,\n Path extends string\n>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useMatch() may be used only in the context of a <Router> component.`\n );\n\n let { pathname } = useLocation();\n return React.useMemo(\n () => matchPath<ParamKey, Path>(pattern, pathname),\n [pathname, pattern]\n );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n (to: To, options?: NavigateOptions): void;\n (delta: number): void;\n}\n\nconst navigateEffectWarning =\n `You should call navigate() in a React.useEffect(), not when ` +\n `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n cb: Parameters<typeof React.useLayoutEffect>[0]\n) {\n let isStatic = React.useContext(NavigationContext).static;\n if (!isStatic) {\n // We should be able to get rid of this once react 18.3 is released\n // See: https://github.com/facebook/react/pull/26395\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(cb);\n }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by `<Link>`s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/hooks/use-navigate\n */\nexport function useNavigate(): NavigateFunction {\n let { isDataRoute } = React.useContext(RouteContext);\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useNavigate() may be used only in the context of a <Router> component.`\n );\n\n let dataRouterContext = React.useContext(DataRouterContext);\n let { basename, navigator } = React.useContext(NavigationContext);\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n\n let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our history listener yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n navigator.go(to);\n return;\n }\n\n let path = resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n options.relative === \"path\"\n );\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to handing off to history (but only if we're not in a data router,\n // otherwise it'll prepend the basename inside of the router).\n // If this is a root navigation, then we navigate to the raw basename\n // which allows the basename to have full control over the presence of a\n // trailing slash on root links\n if (dataRouterContext == null && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\"\n ? basename\n : joinPaths([basename, path.pathname]);\n }\n\n (!!options.replace ? navigator.replace : navigator.push)(\n path,\n options.state,\n options\n );\n },\n [\n basename,\n navigator,\n routePathnamesJson,\n locationPathname,\n dataRouterContext,\n ]\n );\n\n return navigate;\n}\n\nconst OutletContext = React.createContext<unknown>(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/hooks/use-outlet-context\n */\nexport function useOutletContext<Context = unknown>(): Context {\n return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `<Outlet>` to render child routes.\n *\n * @see https://reactrouter.com/hooks/use-outlet\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n let outlet = React.useContext(RouteContext).outlet;\n if (outlet) {\n return (\n <OutletContext.Provider value={context}>{outlet}</OutletContext.Provider>\n );\n }\n return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/hooks/use-params\n */\nexport function useParams<\n ParamsOrKey extends string | Record<string, string | undefined> = string\n>(): Readonly<\n [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>\n> {\n let { matches } = React.useContext(RouteContext);\n let routeMatch = matches[matches.length - 1];\n return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/hooks/use-resolved-path\n */\nexport function useResolvedPath(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));\n\n return React.useMemo(\n () =>\n resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n relative === \"path\"\n ),\n [to, routePathnamesJson, locationPathname, relative]\n );\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `<Outlet>` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/hooks/use-routes\n */\nexport function useRoutes(\n routes: RouteObject[],\n locationArg?: Partial<Location> | string\n): React.ReactElement | null {\n return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nexport function useRoutesImpl(\n routes: RouteObject[],\n locationArg?: Partial<Location> | string,\n dataRouterState?: RemixRouter[\"state\"]\n): React.ReactElement | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useRoutes() may be used only in the context of a <Router> component.`\n );\n\n let { navigator } = React.useContext(NavigationContext);\n let { matches: parentMatches } = React.useContext(RouteContext);\n let routeMatch = parentMatches[parentMatches.length - 1];\n let parentParams = routeMatch ? routeMatch.params : {};\n let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n let parentRoute = routeMatch && routeMatch.route;\n\n if (__DEV__) {\n // You won't get a warning about 2 different <Routes> under a <Route>\n // without a trailing *, but this is a best-effort warning anyway since we\n // cannot even give the warning unless they land at the parent route.\n //\n // Example:\n //\n // <Routes>\n // {/* This route path MUST end with /* because otherwise\n // it will never match /blog/post/123 */}\n // <Route path=\"blog\" element={<Blog />} />\n // <Route path=\"blog/feed\" element={<BlogFeed />} />\n // </Routes>\n //\n // function Blog() {\n // return (\n // <Routes>\n // <Route path=\"post/:id\" element={<Post />} />\n // </Routes>\n // );\n // }\n let parentPath = (parentRoute && parentRoute.path) || \"\";\n warningOnce(\n parentPathname,\n !parentRoute || parentPath.endsWith(\"*\"),\n `You rendered descendant <Routes> (or called \\`useRoutes()\\`) at ` +\n `\"${parentPathname}\" (under <Route path=\"${parentPath}\">) but the ` +\n `parent route path has no trailing \"*\". This means if you navigate ` +\n `deeper, the parent won't match anymore and therefore the child ` +\n `routes will never render.\\n\\n` +\n `Please change the parent <Route path=\"${parentPath}\"> to <Route ` +\n `path=\"${parentPath === \"/\" ? \"*\" : `${parentPath}/*`}\">.`\n );\n }\n\n let locationFromContext = useLocation();\n\n let location;\n if (locationArg) {\n let parsedLocationArg =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n invariant(\n parentPathnameBase === \"/\" ||\n parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n `When overriding the location using \\`<Routes location>\\` or \\`useRoutes(routes, location)\\`, ` +\n `the location pathname must begin with the portion of the URL pathname that was ` +\n `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n );\n\n location = parsedLocationArg;\n } else {\n location = locationFromContext;\n }\n\n let pathname = location.pathname || \"/\";\n let remainingPathname =\n parentPathnameBase === \"/\"\n ? pathname\n : pathname.slice(parentPathnameBase.length) || \"/\";\n\n let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n if (__DEV__) {\n warning(\n parentRoute || matches != null,\n `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n );\n\n warning(\n matches == null ||\n matches[matches.length - 1].route.element !== undefined ||\n matches[matches.length - 1].route.Component !== undefined,\n `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n `does not have an element or Component. This means it will render an <Outlet /> with a ` +\n `null value by default resulting in an \"empty\" page.`\n );\n }\n\n let renderedMatches = _renderMatches(\n matches &&\n matches.map((match) =>\n Object.assign({}, match, {\n params: Object.assign({}, parentParams, match.params),\n pathname: joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathname).pathname\n : match.pathname,\n ]),\n pathnameBase:\n match.pathnameBase === \"/\"\n ? parentPathnameBase\n : joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathnameBase).pathname\n : match.pathnameBase,\n ]),\n })\n ),\n parentMatches,\n dataRouterState\n );\n\n // When a user passes in a `locationArg`, the associated routes need to\n // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n // to use the scoped location instead of the global location.\n if (locationArg && renderedMatches) {\n return (\n <LocationContext.Provider\n value={{\n location: {\n pathname: \"/\",\n search: \"\",\n hash: \"\",\n state: null,\n key: \"default\",\n ...location,\n },\n navigationType: NavigationType.Pop,\n }}\n >\n {renderedMatches}\n </LocationContext.Provider>\n );\n }\n\n return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n let error = useRouteError();\n let message = isRouteErrorResponse(error)\n ? `${error.status} ${error.statusText}`\n : error instanceof Error\n ? error.message\n : JSON.stringify(error);\n let stack = error instanceof Error ? error.stack : null;\n let lightgrey = \"rgba(200,200,200, 0.5)\";\n let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n let devInfo = null;\n if (__DEV__) {\n console.error(\n \"Error handled by React Router default ErrorBoundary:\",\n error\n );\n\n devInfo = (\n <>\n <p>💿 Hey developer 👋</p>\n <p>\n You can provide a way better UX than this when your app throws errors\n by providing your own <code style={codeStyles}>ErrorBoundary</code> or{\" \"}\n <code style={codeStyles}>errorElement</code> prop on your route.\n </p>\n </>\n );\n }\n\n return (\n <>\n <h2>Unexpected Application Error!</h2>\n <h3 style={{ fontStyle: \"italic\" }}>{message}</h3>\n {stack ? <pre style={preStyles}>{stack}</pre> : null}\n {devInfo}\n </>\n );\n}\n\nconst defaultErrorElement = <DefaultErrorComponent />;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n location: Location;\n revalidation: RevalidationState;\n error: any;\n component: React.ReactNode;\n routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n location: Location;\n revalidation: RevalidationState;\n error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n RenderErrorBoundaryProps,\n RenderErrorBoundaryState\n> {\n constructor(props: RenderErrorBoundaryProps) {\n super(props);\n this.state = {\n location: props.location,\n revalidation: props.revalidation,\n error: props.error,\n };\n }\n\n static getDerivedStateFromError(error: any) {\n return { error: error };\n }\n\n static getDerivedStateFromProps(\n props: RenderErrorBoundaryProps,\n state: RenderErrorBoundaryState\n ) {\n // When we get into an error state, the user will likely click \"back\" to the\n // previous page that didn't have an error. Because this wraps the entire\n // application, that will have no effect--the error page continues to display.\n // This gives us a mechanism to recover from the error when the location changes.\n //\n // Whether we're in an error state or not, we update the location in state\n // so that when we are in an error state, it gets reset when a new location\n // comes in and the user recovers from the error.\n if (\n state.location !== props.location ||\n (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n ) {\n return {\n error: props.error,\n location: props.location,\n revalidation: props.revalidation,\n };\n }\n\n // If we're not changing locations, preserve the location but still surface\n // any new errors that may come through. We retain the existing error, we do\n // this because the error provided from the app state may be cleared without\n // the location changing.\n return {\n error: props.error || state.error,\n location: state.location,\n revalidation: props.revalidation || state.revalidation,\n };\n }\n\n componentDidCatch(error: any, errorInfo: any) {\n console.error(\n \"React Router caught the following error during render\",\n error,\n errorInfo\n );\n }\n\n render() {\n return this.state.error ? (\n <RouteContext.Provider value={this.props.routeContext}>\n <RouteErrorContext.Provider\n value={this.state.error}\n children={this.props.component}\n />\n </RouteContext.Provider>\n ) : (\n this.props.children\n );\n }\n}\n\ninterface RenderedRouteProps {\n routeContext: RouteContextObject;\n match: RouteMatch<string, RouteObject>;\n children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n let dataRouterContext = React.useContext(DataRouterContext);\n\n // Track how deep we got in our render pass to emulate SSR componentDidCatch\n // in a DataStaticRouter\n if (\n dataRouterContext &&\n dataRouterContext.static &&\n dataRouterContext.staticContext &&\n (match.route.errorElement || match.route.ErrorBoundary)\n ) {\n dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n }\n\n return (\n <RouteContext.Provider value={routeContext}>\n {children}\n </RouteContext.Provider>\n );\n}\n\nexport function _renderMatches(\n matches: RouteMatch[] | null,\n parentMatches: RouteMatch[] = [],\n dataRouterState: RemixRouter[\"state\"] | null = null\n): React.ReactElement | null {\n if (matches == null) {\n if (dataRouterState?.errors) {\n // Don't bail if we have data router errors so we can render them in the\n // boundary. Use the pre-matched (or shimmed) matches\n matches = dataRouterState.matches as DataRouteMatch[];\n } else {\n return null;\n }\n }\n\n let renderedMatches = matches;\n\n // If we have data errors, trim matches to the highest error boundary\n let errors = dataRouterState?.errors;\n if (errors != null) {\n let errorIndex = renderedMatches.findIndex(\n (m) => m.route.id && errors?.[m.route.id]\n );\n invariant(\n errorIndex >= 0,\n `Could not find a matching route for errors on route IDs: ${Object.keys(\n errors\n ).join(\",\")}`\n );\n renderedMatches = renderedMatches.slice(\n 0,\n Math.min(renderedMatches.length, errorIndex + 1)\n );\n }\n\n return renderedMatches.reduceRight((outlet, match, index) => {\n let error = match.route.id ? errors?.[match.route.id] : null;\n // Only data routers handle errors\n let errorElement: React.ReactNode | null = null;\n if (dataRouterState) {\n errorElement = match.route.errorElement || defaultErrorElement;\n }\n let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n let getChildren = () => {\n let children: React.ReactNode;\n if (error) {\n children = errorElement;\n } else if (match.route.Component) {\n // Note: This is a de-optimized path since React won't re-use the\n // ReactElement since it's identity changes with each new\n // React.createElement call. We keep this so folks can use\n // `<Route Component={...}>` in `<Routes>` but generally `Component`\n // usage is only advised in `RouterProvider` when we can convert it to\n // `element` ahead of time.\n children = <match.route.Component />;\n } else if (match.route.element) {\n children = match.route.element;\n } else {\n children = outlet;\n }\n return (\n <RenderedRoute\n match={match}\n routeContext={{\n outlet,\n matches,\n isDataRoute: dataRouterState != null,\n }}\n children={children}\n />\n );\n };\n // Only wrap in an error boundary within data router usages when we have an\n // ErrorBoundary/errorElement on this route. Otherwise let it bubble up to\n // an ancestor ErrorBoundary/errorElement\n return dataRouterState &&\n (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n <RenderErrorBoundary\n location={dataRouterState.location}\n revalidation={dataRouterState.revalidation}\n component={errorElement}\n error={error}\n children={getChildren()}\n routeContext={{ outlet: null, matches, isDataRoute: true }}\n />\n ) : (\n getChildren()\n );\n }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n UseBlocker = \"useBlocker\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n UseBlocker = \"useBlocker\",\n UseLoaderData = \"useLoaderData\",\n UseActionData = \"useActionData\",\n UseRouteError = \"useRouteError\",\n UseNavigation = \"useNavigation\",\n UseRouteLoaderData = \"useRouteLoaderData\",\n UseMatches = \"useMatches\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n hookName: DataRouterHook | DataRouterStateHook\n) {\n return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n let ctx = React.useContext(DataRouterContext);\n invariant(ctx, getDataRouterConsoleError(hookName));\n return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n let state = React.useContext(DataRouterStateContext);\n invariant(state, getDataRouterConsoleError(hookName));\n return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n let route = React.useContext(RouteContext);\n invariant(route, getDataRouterConsoleError(hookName));\n return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n let route = useRouteContext(hookName);\n let thisRoute = route.matches[route.matches.length - 1];\n invariant(\n thisRoute.route.id,\n `${hookName} can only be used on routes that contain a unique \"id\"`\n );\n return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nexport function useNavigation() {\n let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nexport function useRevalidator() {\n let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n return React.useMemo(\n () => ({\n revalidate: dataRouterContext.router.revalidate,\n state: state.revalidation,\n }),\n [dataRouterContext.router.revalidate, state.revalidation]\n );\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nexport function useMatches(): UIMatch[] {\n let { matches, loaderData } = useDataRouterState(\n DataRouterStateHook.UseMatches\n );\n return React.useMemo(\n () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),\n [matches, loaderData]\n );\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nexport function useLoaderData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n if (state.errors && state.errors[routeId] != null) {\n console.error(\n `You cannot \\`useLoaderData\\` in an errorElement (routeId: ${routeId})`\n );\n return undefined;\n }\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nexport function useActionData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseActionData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error. This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nexport function useRouteError(): unknown {\n let error = React.useContext(RouteErrorContext);\n let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n // If this was a render error, we put it in a RouteError context inside\n // of RenderErrorBoundary\n if (error) {\n return error;\n }\n\n // Otherwise look for errors from our data router state\n return state.errors?.[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `<Await />` value\n */\nexport function useAsyncValue(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `<Await />` value\n */\nexport function useAsyncError(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation. Mostly used to avoid\n * using half-filled form data. This does not handle hard-reloads or\n * cross-origin navigations.\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);\n let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n\n let [blockerKey, setBlockerKey] = React.useState(\"\");\n let blockerFunction = React.useCallback<BlockerFunction>(\n (arg) => {\n if (typeof shouldBlock !== \"function\") {\n return !!shouldBlock;\n }\n if (basename === \"/\") {\n return shouldBlock(arg);\n }\n\n // If they provided us a function and we've got an active basename, strip\n // it from the locations we expose to the user to match the behavior of\n // useLocation\n let { currentLocation, nextLocation, historyAction } = arg;\n return shouldBlock({\n currentLocation: {\n ...currentLocation,\n pathname:\n stripBasename(currentLocation.pathname, basename) ||\n currentLocation.pathname,\n },\n nextLocation: {\n ...nextLocation,\n pathname:\n stripBasename(nextLocation.pathname, basename) ||\n nextLocation.pathname,\n },\n historyAction,\n });\n },\n [basename, shouldBlock]\n );\n\n // This effect is in charge of blocker key assignment and deletion (which is\n // tightly coupled to the key)\n React.useEffect(() => {\n let key = String(++blockerId);\n setBlockerKey(key);\n return () => router.deleteBlocker(key);\n }, [router]);\n\n // This effect handles assigning the blockerFunction. This is to handle\n // unstable blocker function identities, and happens only after the prior\n // effect so we don't get an orphaned blockerFunction in the router with a\n // key of \"\". Until then we just have the IDLE_BLOCKER.\n React.useEffect(() => {\n if (blockerKey !== \"\") {\n router.getBlocker(blockerKey, blockerFunction);\n }\n }, [router, blockerKey, blockerFunction]);\n\n // Prefer the blocker from `state` not `router.state` since DataRouterContext\n // is memoized so this ensures we update on blocker state updates\n return blockerKey && state.blockers.has(blockerKey)\n ? state.blockers.get(blockerKey)!\n : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable(): NavigateFunction {\n let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our router subscriber yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n router.navigate(to);\n } else {\n router.navigate(to, { fromRouteId: id, ...options });\n }\n },\n [router, id]\n );\n\n return navigate;\n}\n\nconst alreadyWarned: Record<string, boolean> = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n if (!cond && !alreadyWarned[key]) {\n alreadyWarned[key] = true;\n warning(false, message);\n }\n}\n","import type {\n InitialEntry,\n LazyRouteFunction,\n Location,\n MemoryHistory,\n RelativeRoutingType,\n Router as RemixRouter,\n RouterState,\n RouterSubscriber,\n To,\n TrackedPromise,\n} from \"@remix-run/router\";\nimport {\n AbortedDeferredError,\n Action as NavigationType,\n createMemoryHistory,\n UNSAFE_getResolveToMatches as getResolveToMatches,\n UNSAFE_invariant as invariant,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\nimport * as React from \"react\";\n\nimport type {\n DataRouteObject,\n IndexRouteObject,\n Navigator,\n NonIndexRouteObject,\n RouteMatch,\n RouteObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n} from \"./context\";\nimport {\n _renderMatches,\n useAsyncValue,\n useInRouterContext,\n useLocation,\n useNavigate,\n useOutlet,\n useRoutes,\n useRoutesImpl,\n} from \"./hooks\";\n\nexport interface FutureConfig {\n v7_startTransition: boolean;\n}\n\nexport interface RouterProviderProps {\n fallbackElement?: React.ReactNode;\n router: RemixRouter;\n future?: Partial<FutureConfig>;\n}\n\n/**\n Webpack + React 17 fails to compile on any of the following because webpack\n complains that `startTransition` doesn't exist in `React`:\n * import { startTransition } from \"react\"\n * import * as React from from \"react\";\n \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n * import * as React from from \"react\";\n \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n Moving it to a constant such as the following solves the Webpack/React 17 issue:\n * import * as React from from \"react\";\n const START_TRANSITION = \"startTransition\";\n START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n However, that introduces webpack/terser minification issues in production builds\n in React 18 where minification/obfuscation ends up removing the call of\n React.startTransition entirely from the first half of the ternary. Grabbing\n this exported reference once up front resolves that issue.\n\n See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n fallbackElement,\n router,\n future,\n}: RouterProviderProps): React.ReactElement {\n let [state, setStateImpl] = React.useState(router.state);\n let { v7_startTransition } = future || {};\n\n let setState = React.useCallback<RouterSubscriber>(\n (newState: RouterState) => {\n if (v7_startTransition && startTransitionImpl) {\n startTransitionImpl(() => setStateImpl(newState));\n } else {\n setStateImpl(newState);\n }\n },\n [setStateImpl, v7_startTransition]\n );\n\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n let navigator = React.useMemo((): Navigator => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: (n) => router.navigate(n),\n push: (to, state, opts) =>\n router.navigate(to, {\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n replace: (to, state, opts) =>\n router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n };\n }, [router]);\n\n let basename = router.basename || \"/\";\n\n let dataRouterContext = React.useMemo(\n () => ({\n router,\n navigator,\n static: false,\n basename,\n }),\n [router, navigator, basename]\n );\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a <script> here\n // containing the hydrated server-side staticContext (from StaticRouterProvider).\n // useId relies on the component tree structure to generate deterministic id's\n // so we need to ensure it remains the same on the client even though\n // we don't need the <script> tag\n return (\n <>\n <DataRouterContext.Provider value={dataRouterContext}>\n <DataRouterStateContext.Provider value={state}>\n <Router\n basename={basename}\n location={state.location}\n navigationType={state.historyAction}\n navigator={navigator}\n >\n {state.initialized ? (\n <DataRoutes routes={router.routes} state={state} />\n ) : (\n fallbackElement\n )}\n </Router>\n </DataRouterStateContext.Provider>\n </DataRouterContext.Provider>\n {null}\n </>\n );\n}\n\nfunction DataRoutes({\n routes,\n state,\n}: {\n routes: DataRouteObject[];\n state: RouterState;\n}): React.ReactElement | null {\n return useRoutesImpl(routes, undefined, state);\n}\n\nexport interface MemoryRouterProps {\n basename?: string;\n children?: React.ReactNode;\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n future?: Partial<FutureConfig>;\n}\n\n/**\n * A `<Router>` that stores all entries in memory.\n *\n * @see https://reactrouter.com/router-components/memory-router\n */\nexport function MemoryRouter({\n basename,\n children,\n initialEntries,\n initialIndex,\n future,\n}: MemoryRouterProps): React.ReactElement {\n let historyRef = React.useRef<MemoryHistory>();\n if (historyRef.current == null) {\n historyRef.current = createMemoryHistory({\n initialEntries,\n initialIndex,\n v5Compat: true,\n });\n }\n\n let history = historyRef.current;\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n />\n );\n}\n\nexport interface NavigateProps {\n to: To;\n replace?: boolean;\n state?: any;\n relative?: RelativeRoutingType;\n}\n\n/**\n * Changes the current location.\n *\n * Note: This API is mostly useful in React.Component subclasses that are not\n * able to use hooks. In functional components, we recommend you use the\n * `useNavigate` hook instead.\n *\n * @see https://reactrouter.com/components/navigate\n */\nexport function Navigate({\n to,\n replace,\n state,\n relative,\n}: NavigateProps): null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of\n // the router loaded. We can help them understand how to avoid that.\n `<Navigate> may be used only in the context of a <Router> component.`\n );\n\n warning(\n !React.useContext(NavigationContext).static,\n `<Navigate> must not be used on the initial render in a <StaticRouter>. ` +\n `This is a no-op, but you should modify your code so the <Navigate> is ` +\n `only ever rendered in response to some user interaction or state change.`\n );\n\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n let navigate = useNavigate();\n\n // Resolve the path outside of the effect so that when effects run twice in\n // StrictMode they navigate to the same place\n let path = resolveTo(\n to,\n getResolveToMatches(matches),\n locationPathname,\n relative === \"path\"\n );\n let jsonPath = JSON.stringify(path);\n\n React.useEffect(\n () => navigate(JSON.parse(jsonPath), { replace, state, relative }),\n [navigate, jsonPath, relative, replace, state]\n );\n\n return null;\n}\n\nexport interface OutletProps {\n context?: unknown;\n}\n\n/**\n * Renders the child route's element, if there is one.\n *\n * @see https://reactrouter.com/components/outlet\n */\nexport function Outlet(props: OutletProps): React.ReactElement | null {\n return useOutlet(props.context);\n}\n\nexport interface PathRouteProps {\n caseSensitive?: NonIndexRouteObject[\"caseSensitive\"];\n path?: NonIndexRouteObject[\"path\"];\n id?: NonIndexRouteObject[\"id\"];\n lazy?: LazyRouteFunction<NonIndexRouteObject>;\n loader?: NonIndexRouteObject[\"loader\"];\n action?: NonIndexRouteObject[\"action\"];\n hasErrorBoundary?: NonIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: NonIndexRouteObject[\"shouldRevalidate\"];\n handle?: NonIndexRouteObject[\"handle\"];\n index?: false;\n children?: React.ReactNode;\n element?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n}\n\nexport interface LayoutRouteProps extends PathRouteProps {}\n\nexport interface IndexRouteProps {\n caseSensitive?: IndexRouteObject[\"caseSensitive\"];\n path?: IndexRouteObject[\"path\"];\n id?: IndexRouteObject[\"id\"];\n lazy?: LazyRouteFunction<IndexRouteObject>;\n loader?: IndexRouteObject[\"loader\"];\n action?: IndexRouteObject[\"action\"];\n hasErrorBoundary?: IndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: IndexRouteObject[\"shouldRevalidate\"];\n handle?: IndexRouteObject[\"handle\"];\n index: true;\n children?: undefined;\n element?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n}\n\nexport type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;\n\n/**\n * Declares an element that should be rendered at a certain URL path.\n *\n * @see https://reactrouter.com/components/route\n */\nexport function Route(_props: RouteProps): React.ReactElement | null {\n invariant(\n false,\n `A <Route> is only ever to be used as the child of <Routes> element, ` +\n `never rendered directly. Please wrap your <Route> in a <Routes>.`\n );\n}\n\nexport interface RouterProps {\n basename?: string;\n children?: React.ReactNode;\n location: Partial<Location> | string;\n navigationType?: NavigationType;\n navigator: Navigator;\n static?: boolean;\n}\n\n/**\n * Provides location context for the rest of the app.\n *\n * Note: You usually won't render a `<Router>` directly. Instead, you'll render a\n * router that is more specific to your environment such as a `<BrowserRouter>`\n * in web browsers or a `<StaticRouter>` for server rendering.\n *\n * @see https://reactrouter.com/router-components/router\n */\nexport function Router({\n basename: basenameProp = \"/\",\n children = null,\n location: locationProp,\n navigationType = NavigationType.Pop,\n navigator,\n static: staticProp = false,\n}: RouterProps): React.ReactElement | null {\n invariant(\n !useInRouterContext(),\n `You cannot render a <Router> inside another <Router>.` +\n ` You should never have more than one in your app.`\n );\n\n // Preserve trailing slashes on basename, so we can let the user control\n // the enforcement of trailing slashes throughout the app\n let basename = basenameProp.replace(/^\\/*/, \"/\");\n let navigationContext = React.useMemo(\n () => ({ basename, navigator, static: staticProp }),\n [basename, navigator, staticProp]\n );\n\n if (typeof locationProp === \"string\") {\n locationProp = parsePath(locationProp);\n }\n\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n state = null,\n key = \"default\",\n } = locationProp;\n\n let locationContext = React.useMemo(() => {\n let trailingPathname = stripBasename(pathname, basename);\n\n if (trailingPathname == null) {\n return null;\n }\n\n return {\n location: {\n pathname: trailingPathname,\n search,\n hash,\n state,\n key,\n },\n navigationType,\n };\n }, [basename, pathname, search, hash, state, key, navigationType]);\n\n warning(\n locationContext != null,\n `<Router basename=\"${basename}\"> is not able to match the URL ` +\n `\"${pathname}${search}${hash}\" because it does not start with the ` +\n `basename, so the <Router> won't render anything.`\n );\n\n if (locationContext == null) {\n return null;\n }\n\n return (\n <NavigationContext.Provider value={navigationContext}>\n <LocationContext.Provider children={children} value={locationContext} />\n </NavigationContext.Provider>\n );\n}\n\nexport interface RoutesProps {\n children?: React.ReactNode;\n location?: Partial<Location> | string;\n}\n\n/**\n * A container for a nested tree of `<Route>` elements that renders the branch\n * that best matches the current location.\n *\n * @see https://reactrouter.com/components/routes\n */\nexport function Routes({\n children,\n location,\n}: RoutesProps): React.ReactElement | null {\n return useRoutes(createRoutesFromChildren(children), location);\n}\n\nexport interface AwaitResolveRenderFunction {\n (data: Awaited<any>): React.ReactNode;\n}\n\nexport interface AwaitProps {\n children: React.ReactNode | AwaitResolveRenderFunction;\n errorElement?: React.ReactNode;\n resolve: TrackedPromise | any;\n}\n\n/**\n * Component to use for rendering lazily loaded data from returning defer()\n * in a loader function\n */\nexport function Await({ children, errorElement, resolve }: AwaitProps) {\n return (\n <AwaitErrorBoundary resolve={resolve} errorElement={errorElement}>\n <ResolveAwait>{children}</ResolveAwait>\n </AwaitErrorBoundary>\n );\n}\n\ntype AwaitErrorBoundaryProps = React.PropsWithChildren<{\n errorElement?: React.ReactNode;\n resolve: TrackedPromise | any;\n}>;\n\ntype AwaitErrorBoundaryState = {\n error: any;\n};\n\nenum AwaitRenderStatus {\n pending,\n success,\n error,\n}\n\nconst neverSettledPromise = new Promise(() => {});\n\nclass AwaitErrorBoundary extends React.Component<\n AwaitErrorBoundaryProps,\n AwaitErrorBoundaryState\n> {\n constructor(props: AwaitErrorBoundaryProps) {\n super(props);\n this.state = { error: null };\n }\n\n static getDerivedStateFromError(error: any) {\n return { error };\n }\n\n componentDidCatch(error: any, errorInfo: any) {\n console.error(\n \"<Await> caught the following error during render\",\n error,\n errorInfo\n );\n }\n\n render() {\n let { children, errorElement, resolve } = this.props;\n\n let promise: TrackedPromise | null = null;\n let status: AwaitRenderStatus = AwaitRenderStatus.pending;\n\n if (!(resolve instanceof Promise)) {\n // Didn't get a promise - provide as a resolved promise\n status = AwaitRenderStatus.success;\n promise = Promise.resolve();\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n Object.defineProperty(promise, \"_data\", { get: () => resolve });\n } else if (this.state.error) {\n // Caught a render error, provide it as a rejected promise\n status = AwaitRenderStatus.error;\n let renderError = this.state.error;\n promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n Object.defineProperty(promise, \"_error\", { get: () => renderError });\n } else if ((resolve as TrackedPromise)._tracked) {\n // Already tracked promise - check contents\n promise = resolve;\n status =\n promise._error !== undefined\n ? AwaitRenderStatus.error\n : promise._data !== undefined\n ? AwaitRenderStatus.success\n : AwaitRenderStatus.pending;\n } else {\n // Raw (untracked) promise - track it\n status = AwaitRenderStatus.pending;\n Object.defineProperty(resolve, \"_tracked\", { get: () => true });\n promise = resolve.then(\n (data: any) =>\n Object.defineProperty(resolve, \"_data\", { get: () => data }),\n (error: any) =>\n Object.defineProperty(resolve, \"_error\", { get: () => error })\n );\n }\n\n if (\n status === AwaitRenderStatus.error &&\n promise._error instanceof AbortedDeferredError\n ) {\n // Freeze the UI by throwing a never resolved promise\n throw neverSettledPromise;\n }\n\n if (status === AwaitRenderStatus.error && !errorElement) {\n // No errorElement, throw to the nearest route-level error boundary\n throw promise._error;\n }\n\n if (status === AwaitRenderStatus.error) {\n // Render via our errorElement\n return <AwaitContext.Provider value={promise} children={errorElement} />;\n }\n\n if (status === AwaitRenderStatus.success) {\n // Render children with resolved value\n return <AwaitContext.Provider value={promise} children={children} />;\n }\n\n // Throw to the suspense boundary\n throw promise;\n }\n}\n\n/**\n * @private\n * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`\n */\nfunction ResolveAwait({\n children,\n}: {\n children: React.ReactNode | AwaitResolveRenderFunction;\n}) {\n let data = useAsyncValue();\n let toRender = typeof children === \"function\" ? children(data) : children;\n return <>{toRender}</>;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// UTILS\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Creates a route config from a React \"children\" object, which is usually\n * either a `<Route>` element or an array of them. Used internally by\n * `<Routes>` to create a route config from its children.\n *\n * @see https://reactrouter.com/utils/create-routes-from-children\n */\nexport function createRoutesFromChildren(\n children: React.ReactNode,\n parentPath: number[] = []\n): RouteObject[] {\n let routes: RouteObject[] = [];\n\n React.Children.forEach(children, (element, index) => {\n if (!React.isValidElement(element)) {\n // Ignore non-elements. This allows people to more easily inline\n // conditionals in their route config.\n return;\n }\n\n let treePath = [...parentPath, index];\n\n if (element.type === React.Fragment) {\n // Transparently support React.Fragment and its children.\n routes.push.apply(\n routes,\n createRoutesFromChildren(element.props.children, treePath)\n );\n return;\n }\n\n invariant(\n element.type === Route,\n `[${\n typeof element.type === \"string\" ? element.type : element.type.name\n }] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`\n );\n\n invariant(\n !element.props.index || !element.props.children,\n \"An index route cannot have child routes.\"\n );\n\n let route: RouteObject = {\n id: element.props.id || treePath.join(\"-\"),\n caseSensitive: element.props.caseSensitive,\n element: element.props.element,\n Component: element.props.Component,\n index: element.props.index,\n path: element.props.path,\n loader: element.props.loader,\n action: element.props.action,\n errorElement: element.props.errorElement,\n ErrorBoundary: element.props.ErrorBoundary,\n hasErrorBoundary:\n element.props.ErrorBoundary != null ||\n element.props.errorElement != null,\n shouldRevalidate: element.props.shouldRevalidate,\n handle: element.props.handle,\n lazy: element.props.lazy,\n };\n\n if (element.props.children) {\n route.children = createRoutesFromChildren(\n element.props.children,\n treePath\n );\n }\n\n routes.push(route);\n });\n\n return routes;\n}\n\n/**\n * Renders the result of `matchRoutes()` into a React element.\n */\nexport function renderMatches(\n matches: RouteMatch[] | null\n): React.ReactElement | null {\n return _renderMatches(matches);\n}\n","// extracted by mini-css-extract-plugin\nexport default {\"signIn\":\"SignIn_signIn__3t4GY\",\"signInTransition\":\"SignIn_signInTransition__DVaCC\",\"signInLabel\":\"SignIn_signInLabel__6itNQ\",\"swapSignIn\":\"SignIn_swapSignIn__WlTGP\"};","import { useEffect, useState } from \"react\";\nimport { auth } from \"../../Config/firebase-config\";\nimport { createUserWithEmailAndPassword, signOut } from \"firebase/auth\";\nimport {useNavigate} from \"react-router-dom\";\nimport css from \"./SignIn.module.css\";\n\n\n\n\nconst SignIn = () => {\n\n const [email, setEmail] = useState(\"\");\n const [password, setPassword] = useState(\"\");\n const [signInTransition, setSignInTransition] = useState(false);\n\n console.log(auth?.currentUser?.email)\n\n const singInUser = async () => {\n try{\n await createUserWithEmailAndPassword(auth, email, password);\n } catch (err){\n console.error(err);\n }\n }\n\n const logOut = async () => {\n try{\n await signOut(auth)\n } catch (err){\n console.error(err);\n }\n }\n\n const navigate = useNavigate();\n const toCreateAccount = () => {\n navigate(\"/Friendly-Betting/CreateAccount\");\n }\n\n\n \n\n useEffect(() => {\n const timeout = setTimeout(() => {\n setSignInTransition(true);\n }, 2);\n\n return () => clearTimeout(timeout);\n }, []);\n \n\n return (\n \n <div className={`${css.signIn} ${signInTransition ? \"\" : css.signInTransition}`}>\n <div className={css.signInLabel}>Sign in</div>\n <input \n type=\"text\" \n placeholder=\"Email or Number\" \n onChange={(e) => setEmail(e.target.value)}\n />\n <input \n type=\"password\" \n placeholder=\"password\" \n id=\"\" \n onChange={(e) => setPassword(e.target.value)}\n />\n <button onClick={singInUser}>Sign In</button>\n <div>\n <div onClick={toCreateAccount} className={css.swapSignIn} >Don't have account? Create One!</div>\n </div>\n <br />\n <br />\n <button onClick={logOut}>Log Out</button>\n </div>\n \n\n )\n}\n\nexport default SignIn;","import { Link, useNavigate} from \"react-router-dom\";\nimport { useEffect, useState} from \"react\";\n\nimport css from \"./SignIn.module.css\";\n\n\n\n\n\nconst CreateAccount = () => {\n\n const [signInTransition, setSignInTransition] = useState(false);\n const navigate = useNavigate();\n const toSignIn = () => {\n navigate(\"/Friendly-Betting/SignIn\");\n }\n\nuseEffect(() => {\n const timeout = setTimeout(() => {\n setSignInTransition(true);\n }, 2);\n\n return () => clearTimeout(timeout);\n }, []);\n return (\n <div className={`${css.signIn} ${signInTransition ? \"\" : css.signInTransition}`}>\n <div className={css.signInLabel}>Create Account</div>\n <input type=\"text\" placeholder=\"Email\" />\n <input type=\"text\" placeholder=\"Phone\" />\n <br />\n <input type=\"password\" placeholder=\"password\" name=\"\" id=\"\" />\n <input type=\"password\" placeholder=\"confirm password\" name=\"\" id=\"\" />\n <button>Create Account</button>\n <div>\n <div onClick={toSignIn} className={css.swapSignIn} >Already have account? Sign in!</div>\n </div>\n </div>\n )\n}\n\nexport default CreateAccount;","import type {\n FormEncType,\n HTMLFormMethod,\n RelativeRoutingType,\n} from \"@remix-run/router\";\nimport { stripBasename, UNSAFE_warning as warning } from \"@remix-run/router\";\n\nexport const defaultMethod: HTMLFormMethod = \"get\";\nconst defaultEncType: FormEncType = \"application/x-www-form-urlencoded\";\n\nexport function isHtmlElement(object: any): object is HTMLElement {\n return object != null && typeof object.tagName === \"string\";\n}\n\nexport function isButtonElement(object: any): object is HTMLButtonElement {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"button\";\n}\n\nexport function isFormElement(object: any): object is HTMLFormElement {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"form\";\n}\n\nexport function isInputElement(object: any): object is HTMLInputElement {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"input\";\n}\n\ntype LimitedMouseEvent = Pick<\n MouseEvent,\n \"button\" | \"metaKey\" | \"altKey\" | \"ctrlKey\" | \"shiftKey\"\n>;\n\nfunction isModifiedEvent(event: LimitedMouseEvent) {\n return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);\n}\n\nexport function shouldProcessLinkClick(\n event: LimitedMouseEvent,\n target?: string\n) {\n return (\n event.button === 0 && // Ignore everything but left clicks\n (!target || target === \"_self\") && // Let browser handle \"target=_blank\" etc.\n !isModifiedEvent(event) // Ignore clicks with modifier keys\n );\n}\n\nexport type ParamKeyValuePair = [string, string];\n\nexport type URLSearchParamsInit =\n | string\n | ParamKeyValuePair[]\n | Record<string, string | string[]>\n | URLSearchParams;\n\n/**\n * Creates a URLSearchParams object using the given initializer.\n *\n * This is identical to `new URLSearchParams(init)` except it also\n * supports arrays as values in the object form of the initializer\n * instead of just strings. This is convenient when you need multiple\n * values for a given key, but don't want to use an array initializer.\n *\n * For example, instead of:\n *\n * let searchParams = new URLSearchParams([\n * ['sort', 'name'],\n * ['sort', 'price']\n * ]);\n *\n * you can do:\n *\n * let searchParams = createSearchParams({\n * sort: ['name', 'price']\n * });\n */\nexport function createSearchParams(\n init: URLSearchParamsInit = \"\"\n): URLSearchParams {\n return new URLSearchParams(\n typeof init === \"string\" ||\n Array.isArray(init) ||\n init instanceof URLSearchParams\n ? init\n : Object.keys(init).reduce((memo, key) => {\n let value = init[key];\n return memo.concat(\n Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]\n );\n }, [] as ParamKeyValuePair[])\n );\n}\n\nexport function getSearchParamsForLocation(\n locationSearch: string,\n defaultSearchParams: URLSearchParams | null\n) {\n let searchParams = createSearchParams(locationSearch);\n\n if (defaultSearchParams) {\n // Use `defaultSearchParams.forEach(...)` here instead of iterating of\n // `defaultSearchParams.keys()` to work-around a bug in Firefox related to\n // web extensions. Relevant Bugzilla tickets:\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984\n defaultSearchParams.forEach((_, key) => {\n if (!searchParams.has(key)) {\n defaultSearchParams.getAll(key).forEach((value) => {\n searchParams.append(key, value);\n });\n }\n });\n }\n\n return searchParams;\n}\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\nexport type SubmitTarget =\n | HTMLFormElement\n | HTMLButtonElement\n | HTMLInputElement\n | FormData\n | URLSearchParams\n | JsonValue\n | null;\n\n// One-time check for submitter support\nlet _formDataSupportsSubmitter: boolean | null = null;\n\nfunction isFormDataSubmitterSupported() {\n if (_formDataSupportsSubmitter === null) {\n try {\n new FormData(\n document.createElement(\"form\"),\n // @ts-expect-error if FormData supports the submitter parameter, this will throw\n 0\n );\n _formDataSupportsSubmitter = false;\n } catch (e) {\n _formDataSupportsSubmitter = true;\n }\n }\n return _formDataSupportsSubmitter;\n}\n\nexport interface SubmitOptions {\n /**\n * The HTTP method used to submit the form. Overrides `<form method>`.\n * Defaults to \"GET\".\n */\n method?: HTMLFormMethod;\n\n /**\n * The action URL path used to submit the form. Overrides `<form action>`.\n * Defaults to the path of the current route.\n */\n action?: string;\n\n /**\n * The encoding used to submit the form. Overrides `<form encType>`.\n * Defaults to \"application/x-www-form-urlencoded\".\n */\n encType?: FormEncType;\n\n /**\n * Indicate a specific fetcherKey to use when using navigate=false\n */\n fetcherKey?: string;\n\n /**\n * navigate=false will use a fetcher instead of a navigation\n */\n navigate?: boolean;\n\n /**\n * Set `true` to replace the current entry in the browser's history stack\n * instead of creating a new one (i.e. stay on \"the same page\"). Defaults\n * to `false`.\n */\n replace?: boolean;\n\n /**\n * State object to add to the history stack entry for this navigation\n */\n state?: any;\n\n /**\n * Determines whether the form action is relative to the route hierarchy or\n * the pathname. Use this if you want to opt out of navigating the route\n * hierarchy and want to instead route based on /-delimited URL segments\n */\n relative?: RelativeRoutingType;\n\n /**\n * In browser-based environments, prevent resetting scroll after this\n * navigation when using the <ScrollRestoration> component\n */\n preventScrollReset?: boolean;\n\n /**\n * Enable flushSync for this navigation's state updates\n */\n unstable_flushSync?: boolean;\n\n /**\n * Enable view transitions on this submission navigation\n */\n unstable_viewTransition?: boolean;\n}\n\nconst supportedFormEncTypes: Set<FormEncType> = new Set([\n \"application/x-www-form-urlencoded\",\n \"multipart/form-data\",\n \"text/plain\",\n]);\n\nfunction getFormEncType(encType: string | null) {\n if (encType != null && !supportedFormEncTypes.has(encType as FormEncType)) {\n warning(\n false,\n `\"${encType}\" is not a valid \\`encType\\` for \\`<Form>\\`/\\`<fetcher.Form>\\` ` +\n `and will default to \"${defaultEncType}\"`\n );\n\n return null;\n }\n return encType;\n}\n\nexport function getFormSubmissionInfo(\n target: SubmitTarget,\n basename: string\n): {\n action: string | null;\n method: string;\n encType: string;\n formData: FormData | undefined;\n body: any;\n} {\n let method: string;\n let action: string | null;\n let encType: string;\n let formData: FormData | undefined;\n let body: any;\n\n if (isFormElement(target)) {\n // When grabbing the action from the element, it will have had the basename\n // prefixed to ensure non-JS scenarios work, so strip it since we'll\n // re-prefix in the router\n let attr = target.getAttribute(\"action\");\n action = attr ? stripBasename(attr, basename) : null;\n method = target.getAttribute(\"method\") || defaultMethod;\n encType = getFormEncType(target.getAttribute(\"enctype\")) || defaultEncType;\n\n formData = new FormData(target);\n } else if (\n isButtonElement(target) ||\n (isInputElement(target) &&\n (target.type === \"submit\" || target.type === \"image\"))\n ) {\n let form = target.form;\n\n if (form == null) {\n throw new Error(\n `Cannot submit a <button> or <input type=\"submit\"> without a <form>`\n );\n }\n\n // <button>/<input type=\"submit\"> may override attributes of <form>\n\n // When grabbing the action from the element, it will have had the basename\n // prefixed to ensure non-JS scenarios work, so strip it since we'll\n // re-prefix in the router\n let attr = target.getAttribute(\"formaction\") || form.getAttribute(\"action\");\n action = attr ? stripBasename(attr, basename) : null;\n\n method =\n target.getAttribute(\"formmethod\") ||\n form.getAttribute(\"method\") ||\n defaultMethod;\n encType =\n getFormEncType(target.getAttribute(\"formenctype\")) ||\n getFormEncType(form.getAttribute(\"enctype\")) ||\n defaultEncType;\n\n // Build a FormData object populated from a form and submitter\n formData = new FormData(form, target);\n\n // If this browser doesn't support the `FormData(el, submitter)` format,\n // then tack on the submitter value at the end. This is a lightweight\n // solution that is not 100% spec compliant. For complete support in older\n // browsers, consider using the `formdata-submitter-polyfill` package\n if (!isFormDataSubmitterSupported()) {\n let { name, type, value } = target;\n if (type === \"image\") {\n let prefix = name ? `${name}.` : \"\";\n formData.append(`${prefix}x`, \"0\");\n formData.append(`${prefix}y`, \"0\");\n } else if (name) {\n formData.append(name, value);\n }\n }\n } else if (isHtmlElement(target)) {\n throw new Error(\n `Cannot submit element that is not <form>, <button>, or ` +\n `<input type=\"submit|image\">`\n );\n } else {\n method = defaultMethod;\n action = null;\n encType = defaultEncType;\n body = target;\n }\n\n // Send body for <Form encType=\"text/plain\" so we encode it into text\n if (formData && encType === \"text/plain\") {\n body = formData;\n formData = undefined;\n }\n\n return { action, method: method.toLowerCase(), encType, formData, body };\n}\n","/**\n * NOTE: If you refactor this to split up the modules into separate files,\n * you'll need to update the rollup config for react-router-dom-v5-compat.\n */\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport type {\n DataRouteObject,\n FutureConfig,\n Location,\n NavigateOptions,\n NavigationType,\n Navigator,\n RelativeRoutingType,\n RouteObject,\n RouterProviderProps,\n To,\n} from \"react-router\";\nimport {\n Router,\n createPath,\n useHref,\n useLocation,\n useMatches,\n useNavigate,\n useNavigation,\n useResolvedPath,\n useBlocker,\n UNSAFE_DataRouterContext as DataRouterContext,\n UNSAFE_DataRouterStateContext as DataRouterStateContext,\n UNSAFE_NavigationContext as NavigationContext,\n UNSAFE_RouteContext as RouteContext,\n UNSAFE_mapRouteProperties as mapRouteProperties,\n UNSAFE_useRouteId as useRouteId,\n UNSAFE_useRoutesImpl as useRoutesImpl,\n} from \"react-router\";\nimport type {\n BrowserHistory,\n Fetcher,\n FormEncType,\n FormMethod,\n FutureConfig as RouterFutureConfig,\n GetScrollRestorationKeyFunction,\n HashHistory,\n History,\n HTMLFormMethod,\n HydrationState,\n Router as RemixRouter,\n V7_FormMethod,\n RouterState,\n RouterSubscriber,\n BlockerFunction,\n} from \"@remix-run/router\";\nimport {\n createRouter,\n createBrowserHistory,\n createHashHistory,\n joinPaths,\n stripBasename,\n UNSAFE_ErrorResponseImpl as ErrorResponseImpl,\n UNSAFE_invariant as invariant,\n UNSAFE_warning as warning,\n matchPath,\n IDLE_FETCHER,\n} from \"@remix-run/router\";\n\nimport type {\n SubmitOptions,\n ParamKeyValuePair,\n URLSearchParamsInit,\n SubmitTarget,\n} from \"./dom\";\nimport {\n createSearchParams,\n defaultMethod,\n getFormSubmissionInfo,\n getSearchParamsForLocation,\n shouldProcessLinkClick,\n} from \"./dom\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Re-exports\n////////////////////////////////////////////////////////////////////////////////\n\nexport type {\n FormEncType,\n FormMethod,\n GetScrollRestorationKeyFunction,\n ParamKeyValuePair,\n SubmitOptions,\n URLSearchParamsInit,\n V7_FormMethod,\n};\nexport { createSearchParams };\n\n// Note: Keep in sync with react-router exports!\nexport type {\n ActionFunction,\n ActionFunctionArgs,\n AwaitProps,\n unstable_Blocker,\n unstable_BlockerFunction,\n DataRouteMatch,\n DataRouteObject,\n ErrorResponse,\n Fetcher,\n Hash,\n IndexRouteObject,\n IndexRouteProps,\n JsonFunction,\n LazyRouteFunction,\n LayoutRouteProps,\n LoaderFunction,\n LoaderFunctionArgs,\n Location,\n MemoryRouterProps,\n NavigateFunction,\n NavigateOptions,\n NavigateProps,\n Navigation,\n Navigator,\n NonIndexRouteObject,\n OutletProps,\n Params,\n ParamParseKey,\n Path,\n PathMatch,\n Pathname,\n PathParam,\n PathPattern,\n PathRouteProps,\n RedirectFunction,\n RelativeRoutingType,\n RouteMatch,\n RouteObject,\n RouteProps,\n RouterProps,\n RouterProviderProps,\n RoutesProps,\n Search,\n ShouldRevalidateFunction,\n ShouldRevalidateFunctionArgs,\n To,\n UIMatch,\n} from \"react-router\";\nexport {\n AbortedDeferredError,\n Await,\n MemoryRouter,\n Navigate,\n NavigationType,\n Outlet,\n Route,\n Router,\n Routes,\n createMemoryRouter,\n createPath,\n createRoutesFromChildren,\n createRoutesFromElements,\n defer,\n isRouteErrorResponse,\n generatePath,\n json,\n matchPath,\n matchRoutes,\n parsePath,\n redirect,\n redirectDocument,\n renderMatches,\n resolvePath,\n useActionData,\n useAsyncError,\n useAsyncValue,\n useBlocker,\n useHref,\n useInRouterContext,\n useLoaderData,\n useLocation,\n useMatch,\n useMatches,\n useNavigate,\n useNavigation,\n useNavigationType,\n useOutlet,\n useOutletContext,\n useParams,\n useResolvedPath,\n useRevalidator,\n useRouteError,\n useRouteLoaderData,\n useRoutes,\n} from \"react-router\";\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n UNSAFE_DataRouterContext,\n UNSAFE_DataRouterStateContext,\n UNSAFE_NavigationContext,\n UNSAFE_LocationContext,\n UNSAFE_RouteContext,\n UNSAFE_useRouteId,\n} from \"react-router\";\n//#endregion\n\ndeclare global {\n var __staticRouterHydrationData: HydrationState | undefined;\n interface Document {\n startViewTransition(cb: () => Promise<void> | void): ViewTransition;\n }\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Routers\n////////////////////////////////////////////////////////////////////////////////\n\ninterface DOMRouterOpts {\n basename?: string;\n future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n hydrationData?: HydrationState;\n window?: Window;\n}\n\nexport function createBrowserRouter(\n routes: RouteObject[],\n opts?: DOMRouterOpts\n): RemixRouter {\n return createRouter({\n basename: opts?.basename,\n future: {\n ...opts?.future,\n v7_prependBasename: true,\n },\n history: createBrowserHistory({ window: opts?.window }),\n hydrationData: opts?.hydrationData || parseHydrationData(),\n routes,\n mapRouteProperties,\n window: opts?.window,\n }).initialize();\n}\n\nexport function createHashRouter(\n routes: RouteObject[],\n opts?: DOMRouterOpts\n): RemixRouter {\n return createRouter({\n basename: opts?.basename,\n future: {\n ...opts?.future,\n v7_prependBasename: true,\n },\n history: createHashHistory({ window: opts?.window }),\n hydrationData: opts?.hydrationData || parseHydrationData(),\n routes,\n mapRouteProperties,\n window: opts?.window,\n }).initialize();\n}\n\nfunction parseHydrationData(): HydrationState | undefined {\n let state = window?.__staticRouterHydrationData;\n if (state && state.errors) {\n state = {\n ...state,\n errors: deserializeErrors(state.errors),\n };\n }\n return state;\n}\n\nfunction deserializeErrors(\n errors: RemixRouter[\"state\"][\"errors\"]\n): RemixRouter[\"state\"][\"errors\"] {\n if (!errors) return null;\n let entries = Object.entries(errors);\n let serialized: RemixRouter[\"state\"][\"errors\"] = {};\n for (let [key, val] of entries) {\n // Hey you! If you change this, please change the corresponding logic in\n // serializeErrors in react-router-dom/server.tsx :)\n if (val && val.__type === \"RouteErrorResponse\") {\n serialized[key] = new ErrorResponseImpl(\n val.status,\n val.statusText,\n val.data,\n val.internal === true\n );\n } else if (val && val.__type === \"Error\") {\n // Attempt to reconstruct the right type of Error (i.e., ReferenceError)\n if (val.__subType) {\n let ErrorConstructor = window[val.__subType];\n if (typeof ErrorConstructor === \"function\") {\n try {\n // @ts-expect-error\n let error = new ErrorConstructor(val.message);\n // Wipe away the client-side stack trace. Nothing to fill it in with\n // because we don't serialize SSR stack traces for security reasons\n error.stack = \"\";\n serialized[key] = error;\n } catch (e) {\n // no-op - fall through and create a normal Error\n }\n }\n }\n\n if (serialized[key] == null) {\n let error = new Error(val.message);\n // Wipe away the client-side stack trace. Nothing to fill it in with\n // because we don't serialize SSR stack traces for security reasons\n error.stack = \"\";\n serialized[key] = error;\n }\n } else {\n serialized[key] = val;\n }\n }\n return serialized;\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Contexts\n////////////////////////////////////////////////////////////////////////////////\n\ntype ViewTransitionContextObject =\n | {\n isTransitioning: false;\n }\n | {\n isTransitioning: true;\n flushSync: boolean;\n currentLocation: Location;\n nextLocation: Location;\n };\n\nconst ViewTransitionContext = React.createContext<ViewTransitionContextObject>({\n isTransitioning: false,\n});\nif (__DEV__) {\n ViewTransitionContext.displayName = \"ViewTransition\";\n}\n\nexport { ViewTransitionContext as UNSAFE_ViewTransitionContext };\n\n// TODO: (v7) Change the useFetcher data from `any` to `unknown`\ntype FetchersContextObject = Map<string, any>;\n\nconst FetchersContext = React.createContext<FetchersContextObject>(new Map());\nif (__DEV__) {\n FetchersContext.displayName = \"Fetchers\";\n}\n\nexport { FetchersContext as UNSAFE_FetchersContext };\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Components\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n Webpack + React 17 fails to compile on any of the following because webpack\n complains that `startTransition` doesn't exist in `React`:\n * import { startTransition } from \"react\"\n * import * as React from from \"react\";\n \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n * import * as React from from \"react\";\n \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n Moving it to a constant such as the following solves the Webpack/React 17 issue:\n * import * as React from from \"react\";\n const START_TRANSITION = \"startTransition\";\n START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n However, that introduces webpack/terser minification issues in production builds\n in React 18 where minification/obfuscation ends up removing the call of\n React.startTransition entirely from the first half of the ternary. Grabbing\n this exported reference once up front resolves that issue.\n\n See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\nconst FLUSH_SYNC = \"flushSync\";\nconst flushSyncImpl = ReactDOM[FLUSH_SYNC];\n\nfunction startTransitionSafe(cb: () => void) {\n if (startTransitionImpl) {\n startTransitionImpl(cb);\n } else {\n cb();\n }\n}\n\nfunction flushSyncSafe(cb: () => void) {\n if (flushSyncImpl) {\n flushSyncImpl(cb);\n } else {\n cb();\n }\n}\n\ninterface ViewTransition {\n finished: Promise<void>;\n ready: Promise<void>;\n updateCallbackDone: Promise<void>;\n skipTransition(): void;\n}\n\nclass Deferred<T> {\n status: \"pending\" | \"resolved\" | \"rejected\" = \"pending\";\n promise: Promise<T>;\n // @ts-expect-error - no initializer\n resolve: (value: T) => void;\n // @ts-expect-error - no initializer\n reject: (reason?: unknown) => void;\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = (value) => {\n if (this.status === \"pending\") {\n this.status = \"resolved\";\n resolve(value);\n }\n };\n this.reject = (reason) => {\n if (this.status === \"pending\") {\n this.status = \"rejected\";\n reject(reason);\n }\n };\n });\n }\n}\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n fallbackElement,\n router,\n future,\n}: RouterProviderProps): React.ReactElement {\n let [state, setStateImpl] = React.useState(router.state);\n let [pendingState, setPendingState] = React.useState<RouterState>();\n let [vtContext, setVtContext] = React.useState<ViewTransitionContextObject>({\n isTransitioning: false,\n });\n let [renderDfd, setRenderDfd] = React.useState<Deferred<void>>();\n let [transition, setTransition] = React.useState<ViewTransition>();\n let [interruption, setInterruption] = React.useState<{\n state: RouterState;\n currentLocation: Location;\n nextLocation: Location;\n }>();\n let fetcherData = React.useRef<Map<string, any>>(new Map());\n let { v7_startTransition } = future || {};\n\n let optInStartTransition = React.useCallback(\n (cb: () => void) => {\n if (v7_startTransition) {\n startTransitionSafe(cb);\n } else {\n cb();\n }\n },\n [v7_startTransition]\n );\n\n let setState = React.useCallback<RouterSubscriber>(\n (\n newState: RouterState,\n {\n deletedFetchers,\n unstable_flushSync: flushSync,\n unstable_viewTransitionOpts: viewTransitionOpts,\n }\n ) => {\n deletedFetchers.forEach((key) => fetcherData.current.delete(key));\n newState.fetchers.forEach((fetcher, key) => {\n if (fetcher.data !== undefined) {\n fetcherData.current.set(key, fetcher.data);\n }\n });\n\n let isViewTransitionUnavailable =\n router.window == null ||\n typeof router.window.document.startViewTransition !== \"function\";\n\n // If this isn't a view transition or it's not available in this browser,\n // just update and be done with it\n if (!viewTransitionOpts || isViewTransitionUnavailable) {\n if (flushSync) {\n flushSyncSafe(() => setStateImpl(newState));\n } else {\n optInStartTransition(() => setStateImpl(newState));\n }\n return;\n }\n\n // flushSync + startViewTransition\n if (flushSync) {\n // Flush through the context to mark DOM elements as transition=ing\n flushSyncSafe(() => {\n // Cancel any pending transitions\n if (transition) {\n renderDfd && renderDfd.resolve();\n transition.skipTransition();\n }\n setVtContext({\n isTransitioning: true,\n flushSync: true,\n currentLocation: viewTransitionOpts.currentLocation,\n nextLocation: viewTransitionOpts.nextLocation,\n });\n });\n\n // Update the DOM\n let t = router.window!.document.startViewTransition(() => {\n flushSyncSafe(() => setStateImpl(newState));\n });\n\n // Clean up after the animation completes\n t.finished.finally(() => {\n flushSyncSafe(() => {\n setRenderDfd(undefined);\n setTransition(undefined);\n setPendingState(undefined);\n setVtContext({ isTransitioning: false });\n });\n });\n\n flushSyncSafe(() => setTransition(t));\n return;\n }\n\n // startTransition + startViewTransition\n if (transition) {\n // Interrupting an in-progress transition, cancel and let everything flush\n // out, and then kick off a new transition from the interruption state\n renderDfd && renderDfd.resolve();\n transition.skipTransition();\n setInterruption({\n state: newState,\n currentLocation: viewTransitionOpts.currentLocation,\n nextLocation: viewTransitionOpts.nextLocation,\n });\n } else {\n // Completed navigation update with opted-in view transitions, let 'er rip\n setPendingState(newState);\n setVtContext({\n isTransitioning: true,\n flushSync: false,\n currentLocation: viewTransitionOpts.currentLocation,\n nextLocation: viewTransitionOpts.nextLocation,\n });\n }\n },\n [router.window, transition, renderDfd, fetcherData, optInStartTransition]\n );\n\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n // When we start a view transition, create a Deferred we can use for the\n // eventual \"completed\" render\n React.useEffect(() => {\n if (vtContext.isTransitioning && !vtContext.flushSync) {\n setRenderDfd(new Deferred<void>());\n }\n }, [vtContext]);\n\n // Once the deferred is created, kick off startViewTransition() to update the\n // DOM and then wait on the Deferred to resolve (indicating the DOM update has\n // happened)\n React.useEffect(() => {\n if (renderDfd && pendingState && router.window) {\n let newState = pendingState;\n let renderPromise = renderDfd.promise;\n let transition = router.window.document.startViewTransition(async () => {\n optInStartTransition(() => setStateImpl(newState));\n await renderPromise;\n });\n transition.finished.finally(() => {\n setRenderDfd(undefined);\n setTransition(undefined);\n setPendingState(undefined);\n setVtContext({ isTransitioning: false });\n });\n setTransition(transition);\n }\n }, [optInStartTransition, pendingState, renderDfd, router.window]);\n\n // When the new location finally renders and is committed to the DOM, this\n // effect will run to resolve the transition\n React.useEffect(() => {\n if (\n renderDfd &&\n pendingState &&\n state.location.key === pendingState.location.key\n ) {\n renderDfd.resolve();\n }\n }, [renderDfd, transition, state.location, pendingState]);\n\n // If we get interrupted with a new navigation during a transition, we skip\n // the active transition, let it cleanup, then kick it off again here\n React.useEffect(() => {\n if (!vtContext.isTransitioning && interruption) {\n setPendingState(interruption.state);\n setVtContext({\n isTransitioning: true,\n flushSync: false,\n currentLocation: interruption.currentLocation,\n nextLocation: interruption.nextLocation,\n });\n setInterruption(undefined);\n }\n }, [vtContext.isTransitioning, interruption]);\n\n let navigator = React.useMemo((): Navigator => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: (n) => router.navigate(n),\n push: (to, state, opts) =>\n router.navigate(to, {\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n replace: (to, state, opts) =>\n router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n };\n }, [router]);\n\n let basename = router.basename || \"/\";\n\n let dataRouterContext = React.useMemo(\n () => ({\n router,\n navigator,\n static: false,\n basename,\n }),\n [router, navigator, basename]\n );\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a <script> here\n // containing the hydrated server-side staticContext (from StaticRouterProvider).\n // useId relies on the component tree structure to generate deterministic id's\n // so we need to ensure it remains the same on the client even though\n // we don't need the <script> tag\n return (\n <>\n <DataRouterContext.Provider value={dataRouterContext}>\n <DataRouterStateContext.Provider value={state}>\n <FetchersContext.Provider value={fetcherData.current}>\n <ViewTransitionContext.Provider value={vtContext}>\n <Router\n basename={basename}\n location={state.location}\n navigationType={state.historyAction}\n navigator={navigator}\n >\n {state.initialized ? (\n <DataRoutes routes={router.routes} state={state} />\n ) : (\n fallbackElement\n )}\n </Router>\n </ViewTransitionContext.Provider>\n </FetchersContext.Provider>\n </DataRouterStateContext.Provider>\n </DataRouterContext.Provider>\n {null}\n </>\n );\n}\n\nfunction DataRoutes({\n routes,\n state,\n}: {\n routes: DataRouteObject[];\n state: RouterState;\n}): React.ReactElement | null {\n return useRoutesImpl(routes, undefined, state);\n}\n\nexport interface BrowserRouterProps {\n basename?: string;\n children?: React.ReactNode;\n future?: Partial<FutureConfig>;\n window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Provides the cleanest URLs.\n */\nexport function BrowserRouter({\n basename,\n children,\n future,\n window,\n}: BrowserRouterProps) {\n let historyRef = React.useRef<BrowserHistory>();\n if (historyRef.current == null) {\n historyRef.current = createBrowserHistory({ window, v5Compat: true });\n }\n\n let history = historyRef.current;\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n />\n );\n}\n\nexport interface HashRouterProps {\n basename?: string;\n children?: React.ReactNode;\n future?: Partial<FutureConfig>;\n window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Stores the location in the hash\n * portion of the URL so it is not sent to the server.\n */\nexport function HashRouter({\n basename,\n children,\n future,\n window,\n}: HashRouterProps) {\n let historyRef = React.useRef<HashHistory>();\n if (historyRef.current == null) {\n historyRef.current = createHashHistory({ window, v5Compat: true });\n }\n\n let history = historyRef.current;\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n />\n );\n}\n\nexport interface HistoryRouterProps {\n basename?: string;\n children?: React.ReactNode;\n future?: FutureConfig;\n history: History;\n}\n\n/**\n * A `<Router>` that accepts a pre-instantiated history object. It's important\n * to note that using your own history object is highly discouraged and may add\n * two versions of the history library to your bundles unless you use the same\n * version of the history library that React Router uses internally.\n */\nfunction HistoryRouter({\n basename,\n children,\n future,\n history,\n}: HistoryRouterProps) {\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n />\n );\n}\n\nif (__DEV__) {\n HistoryRouter.displayName = \"unstable_HistoryRouter\";\n}\n\nexport { HistoryRouter as unstable_HistoryRouter };\n\nexport interface LinkProps\n extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> {\n reloadDocument?: boolean;\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n to: To;\n unstable_viewTransition?: boolean;\n}\n\nconst isBrowser =\n typeof window !== \"undefined\" &&\n typeof window.document !== \"undefined\" &&\n typeof window.document.createElement !== \"undefined\";\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\n/**\n * The public API for rendering a history-aware `<a>`.\n */\nexport const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(\n function LinkWithRef(\n {\n onClick,\n relative,\n reloadDocument,\n replace,\n state,\n target,\n to,\n preventScrollReset,\n unstable_viewTransition,\n ...rest\n },\n ref\n ) {\n let { basename } = React.useContext(NavigationContext);\n\n // Rendered into <a href> for absolute URLs\n let absoluteHref;\n let isExternal = false;\n\n if (typeof to === \"string\" && ABSOLUTE_URL_REGEX.test(to)) {\n // Render the absolute href server- and client-side\n absoluteHref = to;\n\n // Only check for external origins client-side\n if (isBrowser) {\n try {\n let currentUrl = new URL(window.location.href);\n let targetUrl = to.startsWith(\"//\")\n ? new URL(currentUrl.protocol + to)\n : new URL(to);\n let path = stripBasename(targetUrl.pathname, basename);\n\n if (targetUrl.origin === currentUrl.origin && path != null) {\n // Strip the protocol/origin/basename for same-origin absolute URLs\n to = path + targetUrl.search + targetUrl.hash;\n } else {\n isExternal = true;\n }\n } catch (e) {\n // We can't do external URL detection without a valid URL\n warning(\n false,\n `<Link to=\"${to}\"> contains an invalid URL which will probably break ` +\n `when clicked - please update to a valid URL path.`\n );\n }\n }\n }\n\n // Rendered into <a href> for relative URLs\n let href = useHref(to, { relative });\n\n let internalOnClick = useLinkClickHandler(to, {\n replace,\n state,\n target,\n preventScrollReset,\n relative,\n unstable_viewTransition,\n });\n function handleClick(\n event: React.MouseEvent<HTMLAnchorElement, MouseEvent>\n ) {\n if (onClick) onClick(event);\n if (!event.defaultPrevented) {\n internalOnClick(event);\n }\n }\n\n return (\n // eslint-disable-next-line jsx-a11y/anchor-has-content\n <a\n {...rest}\n href={absoluteHref || href}\n onClick={isExternal || reloadDocument ? onClick : handleClick}\n ref={ref}\n target={target}\n />\n );\n }\n);\n\nif (__DEV__) {\n Link.displayName = \"Link\";\n}\n\ntype NavLinkRenderProps = {\n isActive: boolean;\n isPending: boolean;\n isTransitioning: boolean;\n};\n\nexport interface NavLinkProps\n extends Omit<LinkProps, \"className\" | \"style\" | \"children\"> {\n children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode);\n caseSensitive?: boolean;\n className?: string | ((props: NavLinkRenderProps) => string | undefined);\n end?: boolean;\n style?:\n | React.CSSProperties\n | ((props: NavLinkRenderProps) => React.CSSProperties | undefined);\n}\n\n/**\n * A `<Link>` wrapper that knows if it's \"active\" or not.\n */\nexport const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(\n function NavLinkWithRef(\n {\n \"aria-current\": ariaCurrentProp = \"page\",\n caseSensitive = false,\n className: classNameProp = \"\",\n end = false,\n style: styleProp,\n to,\n unstable_viewTransition,\n children,\n ...rest\n },\n ref\n ) {\n let path = useResolvedPath(to, { relative: rest.relative });\n let location = useLocation();\n let routerState = React.useContext(DataRouterStateContext);\n let { navigator } = React.useContext(NavigationContext);\n let isTransitioning =\n routerState != null &&\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useViewTransitionState(path) &&\n unstable_viewTransition === true;\n\n let toPathname = navigator.encodeLocation\n ? navigator.encodeLocation(path).pathname\n : path.pathname;\n let locationPathname = location.pathname;\n let nextLocationPathname =\n routerState && routerState.navigation && routerState.navigation.location\n ? routerState.navigation.location.pathname\n : null;\n\n if (!caseSensitive) {\n locationPathname = locationPathname.toLowerCase();\n nextLocationPathname = nextLocationPathname\n ? nextLocationPathname.toLowerCase()\n : null;\n toPathname = toPathname.toLowerCase();\n }\n\n // If the `to` has a trailing slash, look at that exact spot. Otherwise,\n // we're looking for a slash _after_ what's in `to`. For example:\n //\n // <NavLink to=\"/users\"> and <NavLink to=\"/users/\">\n // both want to look for a / at index 6 to match URL `/users/matt`\n const endSlashPosition =\n toPathname !== \"/\" && toPathname.endsWith(\"/\")\n ? toPathname.length - 1\n : toPathname.length;\n let isActive =\n locationPathname === toPathname ||\n (!end &&\n locationPathname.startsWith(toPathname) &&\n locationPathname.charAt(endSlashPosition) === \"/\");\n\n let isPending =\n nextLocationPathname != null &&\n (nextLocationPathname === toPathname ||\n (!end &&\n nextLocationPathname.startsWith(toPathname) &&\n nextLocationPathname.charAt(toPathname.length) === \"/\"));\n\n let renderProps = {\n isActive,\n isPending,\n isTransitioning,\n };\n\n let ariaCurrent = isActive ? ariaCurrentProp : undefined;\n\n let className: string | undefined;\n if (typeof classNameProp === \"function\") {\n className = classNameProp(renderProps);\n } else {\n // If the className prop is not a function, we use a default `active`\n // class for <NavLink />s that are active. In v5 `active` was the default\n // value for `activeClassName`, but we are removing that API and can still\n // use the old default behavior for a cleaner upgrade path and keep the\n // simple styling rules working as they currently do.\n className = [\n classNameProp,\n isActive ? \"active\" : null,\n isPending ? \"pending\" : null,\n isTransitioning ? \"transitioning\" : null,\n ]\n .filter(Boolean)\n .join(\" \");\n }\n\n let style =\n typeof styleProp === \"function\" ? styleProp(renderProps) : styleProp;\n\n return (\n <Link\n {...rest}\n aria-current={ariaCurrent}\n className={className}\n ref={ref}\n style={style}\n to={to}\n unstable_viewTransition={unstable_viewTransition}\n >\n {typeof children === \"function\" ? children(renderProps) : children}\n </Link>\n );\n }\n);\n\nif (__DEV__) {\n NavLink.displayName = \"NavLink\";\n}\n\nexport interface FetcherFormProps\n extends React.FormHTMLAttributes<HTMLFormElement> {\n /**\n * The HTTP verb to use when the form is submit. Supports \"get\", \"post\",\n * \"put\", \"delete\", \"patch\".\n */\n method?: HTMLFormMethod;\n\n /**\n * `<form encType>` - enhancing beyond the normal string type and limiting\n * to the built-in browser supported values\n */\n encType?:\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"text/plain\";\n\n /**\n * Normal `<form action>` but supports React Router's relative paths.\n */\n action?: string;\n\n /**\n * Determines whether the form action is relative to the route hierarchy or\n * the pathname. Use this if you want to opt out of navigating the route\n * hierarchy and want to instead route based on /-delimited URL segments\n */\n relative?: RelativeRoutingType;\n\n /**\n * Prevent the scroll position from resetting to the top of the viewport on\n * completion of the navigation when using the <ScrollRestoration> component\n */\n preventScrollReset?: boolean;\n\n /**\n * A function to call when the form is submitted. If you call\n * `event.preventDefault()` then this form will not do anything.\n */\n onSubmit?: React.FormEventHandler<HTMLFormElement>;\n}\n\nexport interface FormProps extends FetcherFormProps {\n /**\n * Indicate a specific fetcherKey to use when using navigate=false\n */\n fetcherKey?: string;\n\n /**\n * navigate=false will use a fetcher instead of a navigation\n */\n navigate?: boolean;\n\n /**\n * Forces a full document navigation instead of a fetch.\n */\n reloadDocument?: boolean;\n\n /**\n * Replaces the current entry in the browser history stack when the form\n * navigates. Use this if you don't want the user to be able to click \"back\"\n * to the page with the form on it.\n */\n replace?: boolean;\n\n /**\n * State object to add to the history stack entry for this navigation\n */\n state?: any;\n\n /**\n * Enable view transitions on this Form navigation\n */\n unstable_viewTransition?: boolean;\n}\n\ntype HTMLSubmitEvent = React.BaseSyntheticEvent<\n SubmitEvent,\n Event,\n HTMLFormElement\n>;\n\ntype HTMLFormSubmitter = HTMLButtonElement | HTMLInputElement;\n\n/**\n * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except\n * that the interaction with the server is with `fetch` instead of new document\n * requests, allowing components to add nicer UX to the page as the form is\n * submitted and returns with data.\n */\nexport const Form = React.forwardRef<HTMLFormElement, FormProps>(\n (\n {\n fetcherKey,\n navigate,\n reloadDocument,\n replace,\n state,\n method = defaultMethod,\n action,\n onSubmit,\n relative,\n preventScrollReset,\n unstable_viewTransition,\n ...props\n },\n forwardedRef\n ) => {\n let submit = useSubmit();\n let formAction = useFormAction(action, { relative });\n let formMethod: HTMLFormMethod =\n method.toLowerCase() === \"get\" ? \"get\" : \"post\";\n\n let submitHandler: React.FormEventHandler<HTMLFormElement> = (event) => {\n onSubmit && onSubmit(event);\n if (event.defaultPrevented) return;\n event.preventDefault();\n\n let submitter = (event as unknown as HTMLSubmitEvent).nativeEvent\n .submitter as HTMLFormSubmitter | null;\n\n let submitMethod =\n (submitter?.getAttribute(\"formmethod\") as HTMLFormMethod | undefined) ||\n method;\n\n submit(submitter || event.currentTarget, {\n fetcherKey,\n method: submitMethod,\n navigate,\n replace,\n state,\n relative,\n preventScrollReset,\n unstable_viewTransition,\n });\n };\n\n return (\n <form\n ref={forwardedRef}\n method={formMethod}\n action={formAction}\n onSubmit={reloadDocument ? onSubmit : submitHandler}\n {...props}\n />\n );\n }\n);\n\nif (__DEV__) {\n Form.displayName = \"Form\";\n}\n\nexport interface ScrollRestorationProps {\n getKey?: GetScrollRestorationKeyFunction;\n storageKey?: string;\n}\n\n/**\n * This component will emulate the browser's scroll restoration on location\n * changes.\n */\nexport function ScrollRestoration({\n getKey,\n storageKey,\n}: ScrollRestorationProps) {\n useScrollRestoration({ getKey, storageKey });\n return null;\n}\n\nif (__DEV__) {\n ScrollRestoration.displayName = \"ScrollRestoration\";\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hooks\n////////////////////////////////////////////////////////////////////////////////\n\nenum DataRouterHook {\n UseScrollRestoration = \"useScrollRestoration\",\n UseSubmit = \"useSubmit\",\n UseSubmitFetcher = \"useSubmitFetcher\",\n UseFetcher = \"useFetcher\",\n useViewTransitionState = \"useViewTransitionState\",\n}\n\nenum DataRouterStateHook {\n UseFetcher = \"useFetcher\",\n UseFetchers = \"useFetchers\",\n UseScrollRestoration = \"useScrollRestoration\",\n}\n\n// Internal hooks\n\nfunction getDataRouterConsoleError(\n hookName: DataRouterHook | DataRouterStateHook\n) {\n return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n let ctx = React.useContext(DataRouterContext);\n invariant(ctx, getDataRouterConsoleError(hookName));\n return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n let state = React.useContext(DataRouterStateContext);\n invariant(state, getDataRouterConsoleError(hookName));\n return state;\n}\n\n// External hooks\n\n/**\n * Handles the click behavior for router `<Link>` components. This is useful if\n * you need to create custom `<Link>` components with the same click behavior we\n * use in our exported `<Link>`.\n */\nexport function useLinkClickHandler<E extends Element = HTMLAnchorElement>(\n to: To,\n {\n target,\n replace: replaceProp,\n state,\n preventScrollReset,\n relative,\n unstable_viewTransition,\n }: {\n target?: React.HTMLAttributeAnchorTarget;\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_viewTransition?: boolean;\n } = {}\n): (event: React.MouseEvent<E, MouseEvent>) => void {\n let navigate = useNavigate();\n let location = useLocation();\n let path = useResolvedPath(to, { relative });\n\n return React.useCallback(\n (event: React.MouseEvent<E, MouseEvent>) => {\n if (shouldProcessLinkClick(event, target)) {\n event.preventDefault();\n\n // If the URL hasn't changed, a regular <a> will do a replace instead of\n // a push, so do the same here unless the replace prop is explicitly set\n let replace =\n replaceProp !== undefined\n ? replaceProp\n : createPath(location) === createPath(path);\n\n navigate(to, {\n replace,\n state,\n preventScrollReset,\n relative,\n unstable_viewTransition,\n });\n }\n },\n [\n location,\n navigate,\n path,\n replaceProp,\n state,\n target,\n to,\n preventScrollReset,\n relative,\n unstable_viewTransition,\n ]\n );\n}\n\n/**\n * A convenient wrapper for reading and writing search parameters via the\n * URLSearchParams interface.\n */\nexport function useSearchParams(\n defaultInit?: URLSearchParamsInit\n): [URLSearchParams, SetURLSearchParams] {\n warning(\n typeof URLSearchParams !== \"undefined\",\n `You cannot use the \\`useSearchParams\\` hook in a browser that does not ` +\n `support the URLSearchParams API. If you need to support Internet ` +\n `Explorer 11, we recommend you load a polyfill such as ` +\n `https://github.com/ungap/url-search-params\\n\\n` +\n `If you're unsure how to load polyfills, we recommend you check out ` +\n `https://polyfill.io/v3/ which provides some recommendations about how ` +\n `to load polyfills only for users that need them, instead of for every ` +\n `user.`\n );\n\n let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));\n let hasSetSearchParamsRef = React.useRef(false);\n\n let location = useLocation();\n let searchParams = React.useMemo(\n () =>\n // Only merge in the defaults if we haven't yet called setSearchParams.\n // Once we call that we want those to take precedence, otherwise you can't\n // remove a param with setSearchParams({}) if it has an initial value\n getSearchParamsForLocation(\n location.search,\n hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current\n ),\n [location.search]\n );\n\n let navigate = useNavigate();\n let setSearchParams = React.useCallback<SetURLSearchParams>(\n (nextInit, navigateOptions) => {\n const newSearchParams = createSearchParams(\n typeof nextInit === \"function\" ? nextInit(searchParams) : nextInit\n );\n hasSetSearchParamsRef.current = true;\n navigate(\"?\" + newSearchParams, navigateOptions);\n },\n [navigate, searchParams]\n );\n\n return [searchParams, setSearchParams];\n}\n\nexport type SetURLSearchParams = (\n nextInit?:\n | URLSearchParamsInit\n | ((prev: URLSearchParams) => URLSearchParamsInit),\n navigateOpts?: NavigateOptions\n) => void;\n\n/**\n * Submits a HTML `<form>` to the server without reloading the page.\n */\nexport interface SubmitFunction {\n (\n /**\n * Specifies the `<form>` to be submitted to the server, a specific\n * `<button>` or `<input type=\"submit\">` to use to submit the form, or some\n * arbitrary data to submit.\n *\n * Note: When using a `<button>` its `name` and `value` will also be\n * included in the form data that is submitted.\n */\n target: SubmitTarget,\n\n /**\n * Options that override the `<form>`'s own attributes. Required when\n * submitting arbitrary data without a backing `<form>`.\n */\n options?: SubmitOptions\n ): void;\n}\n\n/**\n * Submits a fetcher `<form>` to the server without reloading the page.\n */\nexport interface FetcherSubmitFunction {\n (\n target: SubmitTarget,\n // Fetchers cannot replace or set state because they are not navigation events\n options?: Omit<SubmitOptions, \"replace\" | \"state\">\n ): void;\n}\n\nfunction validateClientSideSubmission() {\n if (typeof document === \"undefined\") {\n throw new Error(\n \"You are calling submit during the server render. \" +\n \"Try calling submit within a `useEffect` or callback instead.\"\n );\n }\n}\n\nlet fetcherId = 0;\nlet getUniqueFetcherId = () => `__${String(++fetcherId)}__`;\n\n/**\n * Returns a function that may be used to programmatically submit a form (or\n * some arbitrary data) to the server.\n */\nexport function useSubmit(): SubmitFunction {\n let { router } = useDataRouterContext(DataRouterHook.UseSubmit);\n let { basename } = React.useContext(NavigationContext);\n let currentRouteId = useRouteId();\n\n return React.useCallback<SubmitFunction>(\n (target, options = {}) => {\n validateClientSideSubmission();\n\n let { action, method, encType, formData, body } = getFormSubmissionInfo(\n target,\n basename\n );\n\n if (options.navigate === false) {\n let key = options.fetcherKey || getUniqueFetcherId();\n router.fetch(key, currentRouteId, options.action || action, {\n preventScrollReset: options.preventScrollReset,\n formData,\n body,\n formMethod: options.method || (method as HTMLFormMethod),\n formEncType: options.encType || (encType as FormEncType),\n unstable_flushSync: options.unstable_flushSync,\n });\n } else {\n router.navigate(options.action || action, {\n preventScrollReset: options.preventScrollReset,\n formData,\n body,\n formMethod: options.method || (method as HTMLFormMethod),\n formEncType: options.encType || (encType as FormEncType),\n replace: options.replace,\n state: options.state,\n fromRouteId: currentRouteId,\n unstable_flushSync: options.unstable_flushSync,\n unstable_viewTransition: options.unstable_viewTransition,\n });\n }\n },\n [router, basename, currentRouteId]\n );\n}\n\n// v7: Eventually we should deprecate this entirely in favor of using the\n// router method directly?\nexport function useFormAction(\n action?: string,\n { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n let { basename } = React.useContext(NavigationContext);\n let routeContext = React.useContext(RouteContext);\n invariant(routeContext, \"useFormAction must be used inside a RouteContext\");\n\n let [match] = routeContext.matches.slice(-1);\n // Shallow clone path so we can modify it below, otherwise we modify the\n // object referenced by useMemo inside useResolvedPath\n let path = { ...useResolvedPath(action ? action : \".\", { relative }) };\n\n // If no action was specified, browsers will persist current search params\n // when determining the path, so match that behavior\n // https://github.com/remix-run/remix/issues/927\n let location = useLocation();\n if (action == null) {\n // Safe to write to this directly here since if action was undefined, we\n // would have called useResolvedPath(\".\") which will never include a search\n path.search = location.search;\n\n // When grabbing search params from the URL, remove any included ?index param\n // since it might not apply to our contextual route. We add it back based\n // on match.route.index below\n let params = new URLSearchParams(path.search);\n if (params.has(\"index\") && params.get(\"index\") === \"\") {\n params.delete(\"index\");\n path.search = params.toString() ? `?${params.toString()}` : \"\";\n }\n }\n\n if ((!action || action === \".\") && match.route.index) {\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n }\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the form action. If this is a root navigation, then just use\n // the raw basename which allows the basename to have full control over the\n // presence of a trailing slash on root actions\n if (basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\nexport type FetcherWithComponents<TData> = Fetcher<TData> & {\n Form: React.ForwardRefExoticComponent<\n FetcherFormProps & React.RefAttributes<HTMLFormElement>\n >;\n submit: FetcherSubmitFunction;\n load: (href: string, opts?: { unstable_flushSync?: boolean }) => void;\n};\n\n// TODO: (v7) Change the useFetcher generic default from `any` to `unknown`\n\n/**\n * Interacts with route loaders and actions without causing a navigation. Great\n * for any interaction that stays on the same page.\n */\nexport function useFetcher<TData = any>({\n key,\n}: { key?: string } = {}): FetcherWithComponents<TData> {\n let { router } = useDataRouterContext(DataRouterHook.UseFetcher);\n let state = useDataRouterState(DataRouterStateHook.UseFetcher);\n let fetcherData = React.useContext(FetchersContext);\n let route = React.useContext(RouteContext);\n let routeId = route.matches[route.matches.length - 1]?.route.id;\n\n invariant(fetcherData, `useFetcher must be used inside a FetchersContext`);\n invariant(route, `useFetcher must be used inside a RouteContext`);\n invariant(\n routeId != null,\n `useFetcher can only be used on routes that contain a unique \"id\"`\n );\n\n // Fetcher key handling\n let [fetcherKey, setFetcherKey] = React.useState<string>(key || \"\");\n if (key && key !== fetcherKey) {\n setFetcherKey(key);\n } else if (!fetcherKey) {\n setFetcherKey(getUniqueFetcherId());\n }\n\n // Registration/cleanup\n React.useEffect(() => {\n router.getFetcher(fetcherKey);\n return () => {\n // Tell the router we've unmounted - if v7_fetcherPersist is enabled this\n // will not delete immediately but instead queue up a delete after the\n // fetcher returns to an `idle` state\n router.deleteFetcher(fetcherKey);\n };\n }, [router, fetcherKey]);\n\n // Fetcher additions\n let load = React.useCallback(\n (href: string, opts?: { unstable_flushSync?: boolean }) => {\n invariant(routeId, \"No routeId available for fetcher.load()\");\n router.fetch(fetcherKey, routeId, href, opts);\n },\n [fetcherKey, routeId, router]\n );\n\n let submitImpl = useSubmit();\n let submit = React.useCallback<FetcherSubmitFunction>(\n (target, opts) => {\n submitImpl(target, {\n ...opts,\n navigate: false,\n fetcherKey,\n });\n },\n [fetcherKey, submitImpl]\n );\n\n let FetcherForm = React.useMemo(() => {\n let FetcherForm = React.forwardRef<HTMLFormElement, FetcherFormProps>(\n (props, ref) => {\n return (\n <Form {...props} navigate={false} fetcherKey={fetcherKey} ref={ref} />\n );\n }\n );\n if (__DEV__) {\n FetcherForm.displayName = \"fetcher.Form\";\n }\n return FetcherForm;\n }, [fetcherKey]);\n\n // Exposed FetcherWithComponents\n let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;\n let data = fetcherData.get(fetcherKey);\n let fetcherWithComponents = React.useMemo(\n () => ({\n Form: FetcherForm,\n submit,\n load,\n ...fetcher,\n data,\n }),\n [FetcherForm, submit, load, fetcher, data]\n );\n\n return fetcherWithComponents;\n}\n\n/**\n * Provides all fetchers currently on the page. Useful for layouts and parent\n * routes that need to provide pending/optimistic UI regarding the fetch.\n */\nexport function useFetchers(): (Fetcher & { key: string })[] {\n let state = useDataRouterState(DataRouterStateHook.UseFetchers);\n return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({\n ...fetcher,\n key,\n }));\n}\n\nconst SCROLL_RESTORATION_STORAGE_KEY = \"react-router-scroll-positions\";\nlet savedScrollPositions: Record<string, number> = {};\n\n/**\n * When rendered inside a RouterProvider, will restore scroll positions on navigations\n */\nfunction useScrollRestoration({\n getKey,\n storageKey,\n}: {\n getKey?: GetScrollRestorationKeyFunction;\n storageKey?: string;\n} = {}) {\n let { router } = useDataRouterContext(DataRouterHook.UseScrollRestoration);\n let { restoreScrollPosition, preventScrollReset } = useDataRouterState(\n DataRouterStateHook.UseScrollRestoration\n );\n let { basename } = React.useContext(NavigationContext);\n let location = useLocation();\n let matches = useMatches();\n let navigation = useNavigation();\n\n // Trigger manual scroll restoration while we're active\n React.useEffect(() => {\n window.history.scrollRestoration = \"manual\";\n return () => {\n window.history.scrollRestoration = \"auto\";\n };\n }, []);\n\n // Save positions on pagehide\n usePageHide(\n React.useCallback(() => {\n if (navigation.state === \"idle\") {\n let key = (getKey ? getKey(location, matches) : null) || location.key;\n savedScrollPositions[key] = window.scrollY;\n }\n try {\n sessionStorage.setItem(\n storageKey || SCROLL_RESTORATION_STORAGE_KEY,\n JSON.stringify(savedScrollPositions)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`\n );\n }\n window.history.scrollRestoration = \"auto\";\n }, [storageKey, getKey, navigation.state, location, matches])\n );\n\n // Read in any saved scroll locations\n if (typeof document !== \"undefined\") {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(() => {\n try {\n let sessionPositions = sessionStorage.getItem(\n storageKey || SCROLL_RESTORATION_STORAGE_KEY\n );\n if (sessionPositions) {\n savedScrollPositions = JSON.parse(sessionPositions);\n }\n } catch (e) {\n // no-op, use default empty object\n }\n }, [storageKey]);\n\n // Enable scroll restoration in the router\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(() => {\n let getKeyWithoutBasename: GetScrollRestorationKeyFunction | undefined =\n getKey && basename !== \"/\"\n ? (location, matches) =>\n getKey(\n // Strip the basename to match useLocation()\n {\n ...location,\n pathname:\n stripBasename(location.pathname, basename) ||\n location.pathname,\n },\n matches\n )\n : getKey;\n let disableScrollRestoration = router?.enableScrollRestoration(\n savedScrollPositions,\n () => window.scrollY,\n getKeyWithoutBasename\n );\n return () => disableScrollRestoration && disableScrollRestoration();\n }, [router, basename, getKey]);\n\n // Restore scrolling when state.restoreScrollPosition changes\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(() => {\n // Explicit false means don't do anything (used for submissions)\n if (restoreScrollPosition === false) {\n return;\n }\n\n // been here before, scroll to it\n if (typeof restoreScrollPosition === \"number\") {\n window.scrollTo(0, restoreScrollPosition);\n return;\n }\n\n // try to scroll to the hash\n if (location.hash) {\n let el = document.getElementById(\n decodeURIComponent(location.hash.slice(1))\n );\n if (el) {\n el.scrollIntoView();\n return;\n }\n }\n\n // Don't reset if this navigation opted out\n if (preventScrollReset === true) {\n return;\n }\n\n // otherwise go to the top on new locations\n window.scrollTo(0, 0);\n }, [location, restoreScrollPosition, preventScrollReset]);\n }\n}\n\nexport { useScrollRestoration as UNSAFE_useScrollRestoration };\n\n/**\n * Setup a callback to be fired on the window's `beforeunload` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nexport function useBeforeUnload(\n callback: (event: BeforeUnloadEvent) => any,\n options?: { capture?: boolean }\n): void {\n let { capture } = options || {};\n React.useEffect(() => {\n let opts = capture != null ? { capture } : undefined;\n window.addEventListener(\"beforeunload\", callback, opts);\n return () => {\n window.removeEventListener(\"beforeunload\", callback, opts);\n };\n }, [callback, capture]);\n}\n\n/**\n * Setup a callback to be fired on the window's `pagehide` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes. This event is better supported than beforeunload across browsers.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nfunction usePageHide(\n callback: (event: PageTransitionEvent) => any,\n options?: { capture?: boolean }\n): void {\n let { capture } = options || {};\n React.useEffect(() => {\n let opts = capture != null ? { capture } : undefined;\n window.addEventListener(\"pagehide\", callback, opts);\n return () => {\n window.removeEventListener(\"pagehide\", callback, opts);\n };\n }, [callback, capture]);\n}\n\n/**\n * Wrapper around useBlocker to show a window.confirm prompt to users instead\n * of building a custom UI with useBlocker.\n *\n * Warning: This has *a lot of rough edges* and behaves very differently (and\n * very incorrectly in some cases) across browsers if user click addition\n * back/forward navigations while the confirm is open. Use at your own risk.\n */\nfunction usePrompt({\n when,\n message,\n}: {\n when: boolean | BlockerFunction;\n message: string;\n}) {\n let blocker = useBlocker(when);\n\n React.useEffect(() => {\n if (blocker.state === \"blocked\") {\n let proceed = window.confirm(message);\n if (proceed) {\n // This timeout is needed to avoid a weird \"race\" on POP navigations\n // between the `window.history` revert navigation and the result of\n // `window.confirm`\n setTimeout(blocker.proceed, 0);\n } else {\n blocker.reset();\n }\n }\n }, [blocker, message]);\n\n React.useEffect(() => {\n if (blocker.state === \"blocked\" && !when) {\n blocker.reset();\n }\n }, [blocker, when]);\n}\n\nexport { usePrompt as unstable_usePrompt };\n\n/**\n * Return a boolean indicating if there is an active view transition to the\n * given href. You can use this value to render CSS classes or viewTransitionName\n * styles onto your elements\n *\n * @param href The destination href\n * @param [opts.relative] Relative routing type (\"route\" | \"path\")\n */\nfunction useViewTransitionState(\n to: To,\n opts: { relative?: RelativeRoutingType } = {}\n) {\n let vtContext = React.useContext(ViewTransitionContext);\n\n invariant(\n vtContext != null,\n \"`unstable_useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. \" +\n \"Did you accidentally import `RouterProvider` from `react-router`?\"\n );\n\n let { basename } = useDataRouterContext(\n DataRouterHook.useViewTransitionState\n );\n let path = useResolvedPath(to, { relative: opts.relative });\n if (!vtContext.isTransitioning) {\n return false;\n }\n\n let currentPath =\n stripBasename(vtContext.currentLocation.pathname, basename) ||\n vtContext.currentLocation.pathname;\n let nextPath =\n stripBasename(vtContext.nextLocation.pathname, basename) ||\n vtContext.nextLocation.pathname;\n\n // Transition is active if we're going to or coming from the indicated\n // destination. This ensures that other PUSH navigations that reverse\n // an indicated transition apply. I.e., on the list view you have:\n //\n // <NavLink to=\"/details/1\" unstable_viewTransition>\n //\n // If you click the breadcrumb back to the list view:\n //\n // <NavLink to=\"/list\" unstable_viewTransition>\n //\n // We should apply the transition because it's indicated as active going\n // from /list -> /details/1 and therefore should be active on the reverse\n // (even though this isn't strictly a POP reverse)\n return (\n matchPath(path.pathname, nextPath) != null ||\n matchPath(path.pathname, currentPath) != null\n );\n}\n\nexport { useViewTransitionState as unstable_useViewTransitionState };\n\n//#endregion\n","import { Link, useLocation} from \"react-router-dom\";\n\n\n\nconst Header = () => {\n const location = useLocation();\n\n return(\n <div className=\"header\">\n <div className=\"x1\">\n <div className=\"logo\"><Link className=\"Link\" to=\"Friendly-Betting/\">logo</Link>\n \n </div>\n </div>\n <div className=\"x1\">Friendly Bets</div>\n <div className=\"flex pages x1\">\n {location.pathname !== \"/SignIn\" ? <Link className=\"Link\" to=\"Friendly-Betting/SignIn\">Sign In</Link>: <Link className=\"Link\" to=\"/\">Sign In</Link>\n \n \n \n }\n <Link className=\"Link\" to=\"Friendly-Betting/Bet\">Bets</Link>\n <Link className=\"Link\" to=\"Friendly-Betting/Friends\">Friends</Link>\n </div>\n </div>\n )\n}\n\nexport default Header;","import React from 'react';\n\nconst NotFound = () => {\n return (\n <div>\n <h1>404</h1>\n <p>Page not found!</p>\n </div>\n );\n};\n\nexport default NotFound;","import React from 'react';\nimport { useState, useEffect } from 'react'; \nimport { auth } from \"../Config/firebase-config\";\nimport { Link } from \"react-router-dom\";\n\n\n\nconst Welcome = () => {\n\n const [signedIn, setSignedIn] = useState(true);\n\n console.log(auth?.currentUser?.email)\n\n useEffect(() => {\n isAuthenticated();\n }, []);\n\n const isAuthenticated = () => {\n const currentUserEmail = auth?.currentUser?.email;\n const isAuthenticated = currentUserEmail !== undefined;\n setSignedIn(isAuthenticated);\n };\n\n return (\n <div className='p-12'>\n {signedIn ? (\n <div>\n \n {/* Render the authenticated content */}\n <h1>Welcome, User!</h1>\n <p>This is the authenticated content.</p>\n </div>\n ) : (\n <div>\n {/* Render the non-authenticated content */}\n <h1>Please sign in to access this content.</h1>\n <Link className=\"Link\" to=\"Friendly-Betting/SignIn\">Sign In</Link>\n </div>\n )}\n </div>\n );\n};\n\nexport default Welcome;","// extracted by mini-css-extract-plugin\nexport default {\"MoneyLine\":\"MoneyLine_MoneyLine__GZY-g\",\"betContainer\":\"MoneyLine_betContainer__MPUkR\",\"bet\":\"MoneyLine_bet__iBwWG\",\"betTextArea\":\"MoneyLine_betTextArea__Q9aMH\",\"contestantInput\":\"MoneyLine_contestantInput__RtHW6\",\"label\":\"MoneyLine_label__SXs1d\",\"odds\":\"MoneyLine_odds__5UKBZ\",\"betLabel\":\"MoneyLine_betLabel__xK-Pn\"};","// extracted by mini-css-extract-plugin\nexport default {\"disable\":\"Players_disable__2Lrxc\",\"friends\":\"Players_friends__S-rHI\",\"addFiendForm\":\"Players_addFiendForm__No56b\",\"x\":\"Players_x__50IpE\",\"shareBet\":\"Players_shareBet__IEGN8\",\"friendsLabel\":\"Players_friendsLabel__doMbx\",\"container\":\"Players_container__wuYC4\",\"checkmark\":\"Players_checkmark__OI0Ce\"};","\nimport React, { useState } from 'react';\nimport css from \"./Players.module.css\";\n\nconst AddFriend = (props) => {\n const [accountNumber, setAccountNumber] = useState('');\n const [phone, setPhone] = useState('');\n const [email, setEmail] = useState('');\n const [name, setName] = useState('');\n\n const handleAccountNumberChange = (e) => {\n setAccountNumber(e.target.value);\n };\n\n const handlePhoneChange = (e) => {\n setPhone(e.target.value);\n };\n\n const handleEmailChange = (e) => {\n setEmail(e.target.value);\n };\n\n const handleNameChange = (e) => {\n setName(e.target.value);\n };\n\n const handleSubmit = (e) => {\n e.preventDefault();\n if(name !== \"\" && email !== \"\" && phone !== \"\"){\n props.addNewPlayers({\n \"name\": name,\n \"email\": email,\n \"phone\": phone\n })\n }\n // Handle form submission here\n // You can access the values using the state variables (accountNumber, phone, email, name)\n };\n\n\n return (\n <form className={css.addFiendForm} onSubmit={handleSubmit}>\n <div className=\"flex justify-center mb-2\"><span className={css.x} onClick={props.disable}>x</span></div>\n <label>\n <span>Account Number:</span>\n <input type=\"text\" value={accountNumber} onChange={handleAccountNumberChange} />\n </label>\n <br />\n <br />\n <div className=\"flex justify-center items-center text-center\">or</div>\n <br />\n <label>\n <span>Name:</span>\n <input type=\"text\" value={name} onChange={handleNameChange} />\n </label>\n <br />\n <label>\n Email:\n <input type=\"email\" value={email} onChange={handleEmailChange} />\n </label>\n <br />\n <label>\n <span>Phone:</span>\n <input type=\"phone\" value={phone} onChange={handlePhoneChange} />\n </label>\n <br />\n <button type=\"submit\" >Add Friend</button>\n </form>\n );\n};\n\nexport default AddFriend;\n","import AddFriend from \"./AddFriend\"\nimport React, { useState } from 'react';\nimport css from \"./Players.module.css\";\n\n\nconst Players = () => {\n\n const [json,setJson] = useState({\n \"friends\": [\n \n {\n \n \n \"name\": \"John\",\n \"email\": \"johnRyan@gmail.com\",\n \"phone\": \"1234567890\"\n \n \n },\n {\n \n \"name\": \"Jack\",\n \"email\": \"JackRyan@gmail.com\",\n \"phone\": \"1234567890\"\n \n \n },\n {\n \n \"name\": \"Another Person\",\n \"email\": \"Person@gmail.com\",\n \"phone\": \"1234567890\"\n \n \n }\n \n ]\n });\n const addJson = (newJson) => {\n setJson(prevJson => ({\n ...prevJson,\n friends: [...prevJson.friends, newJson]\n \n }));\n swapDisplayPlayers();\n \n }\n const [displayPlayers, setDisplayPlayers] = useState(false)\n const swapDisplayPlayers = () => {\n setDisplayPlayers((current) => !current)\n }\n return (\n <div className=\"pt-12 sticky top-0 bottom-0 right-0 left-0\"> \n <div className={css.friends}>\n {json[\"friends\"].map((friend, id) => (\n <div key={id}>\n <h3>{friend[\"name\"]}</h3>\n <p>Email: {friend[\"email\"]}</p>\n <p>Phone: {friend[\"phone\"]}</p>\n </div>\n ))}\n <div>\n {\n displayPlayers ?\n <div>\n <AddFriend addNewPlayers ={addJson} disable={swapDisplayPlayers}/>\n <button className={css.disable} >Add Friend</button>\n </div>\n :\n <button onClick={swapDisplayPlayers} >Add Friend</button>\n }\n \n </div>\n </div>\n </div>\n )\n}\n\nexport default Players","import React from 'react';\nimport css from './Players.module.css';\nimport {useState} from 'react';\n\n\n\n\nconst ShareBet = (props) => {\n\n const [json,setJson] = useState({\n \"friends\": [\n \n {\n \n \n \"name\": \"John\",\n \"email\": \"johnRyan@gmail.com\",\n \"phone\": \"1234567890\"\n \n \n },\n {\n \n \"name\": \"Jack\",\n \"email\": \"JackRyan@gmail.com\",\n \"phone\": \"1234567890\"\n \n \n },\n {\n \n \"name\": \"Another Person\",\n \"email\": \"Person@gmail.com\",\n \"phone\": \"1234567890\"\n \n \n }\n \n ]\n });\n\n \n\n const handleSubmit = (e) => {\n e.preventDefault();\n // Logic to share the bet\n console.log('Sharing bet');\n }\n\n \n return (\n <div className={css.shareBet}>\n <div className=\"flex justify-center mb-2\"><span className={css.x} onClick={props.display}>x</span></div>\n <div className={css.friendsLabel}><span>friends</span></div>\n <form onSubmit={handleSubmit}>\n {//props.friends.map((friend ) => (\n json[\"friends\"].map((friend) => (\n <label className={css.container}>\n {friend.name}\n <input className={css.input} type=\"checkbox\" name=\"\" id=\"\" />\n <span className={css.checkmark}></span>\n \n </label>\n ))}\n <button type=\"submit\">Send</button>\n </form>\n </div>\n \n );\n};\n\nexport default ShareBet;\n","import React, { useState } from 'react';\nimport css from './MoneyLine.module.css';\nimport Players from '../Players/Players';\nimport ShareBet from '../Players/ShareBet';\nimport {db} from '../../../Config/firebase-config';\nimport { addDoc, collection } from 'firebase/firestore';\n\nconst CreateMoneyLine = () => {\n const [bet, setBet] = useState('');\n const [contestant1, setContestant1] = useState('');\n const [contestant2, setContestant2] = useState('');\n\n \n const [odds1, setOdds1] = useState(0);\n const [odds2, setOdds2] = useState(0);\n\n\n\n\n const [shareDisplay, setShareDisplay] = useState(false);\n\n \n\n\n\n const handleShare = () => {\n setShareDisplay((current) => !current);\n }\n\n const handleSubmit = async (e) => {\n e.preventDefault();\n handleShare();\n try {\n await addDoc(collection(db, \"bets\"), {\n type: \"Money Line\",\n bet: bet,\n })\n \n await addDoc(collection(db, \"MoneyLineBets\"), {\n bet: bet,\n contestant1: contestant1,\n contestant1Odds: odds1,\n contestant2: contestant2,\n contestant2Odds: odds2,\n })\n } catch (e) {\n console.error(e);\n }\n // Logic to create the moneyline bet using the team and odds values\n console.log('Creating moneyline bet:');\n };\n\n return (\n <div className='flex'>\n <div className='x2'>\n <form className={css.MoneyLine} onSubmit={handleSubmit}>\n <div className={`pb-8 ${css.betContainer}`}>\n Bet:\n <div className=\"pl-8\">\n <textarea className={css.betTextArea}type=\"text\" name=\"\" id=\"\" onChange={(e) => setBet(e.target.value)} />\n </div>\n </div>\n <div className='flex'>\n <div className=\"flex flex-col my-4 mx-8\">\n <div><span className={css.label}>Contestant 1</span></div>\n <input\n type=\"text\"\n name=\"\"\n value={contestant1}\n className={css.contestantInput}\n onChange={(e) => setContestant1(e.target.value)}\n \n />\n <div className={css.odds}>\n <span>(+ or - odds)</span>\n <input className=\"justify-center items-center\" type=\"number\" onChange={(e) => setOdds1(Number(e.target.value))}/>\n </div>\n </div>\n <div className=\"flex flex-col my-4 mx-8\">\n <div><span className={css.label}>Contestant 2</span></div>\n <input \n type=\"text\"\n name=\"\"\n value={contestant2}\n className={css.contestantInput}\n onChange={(e) => setContestant2(e.target.value)}\n \n /> \n <div className=\"flex justify-center items-center gap-2 p-2\">\n <span className={css.odds}>(+ or - odds)</span>\n <input type=\"number\" onChange={(e) => setOdds2(Number(e.target.value))}/>\n </div>\n </div>\n </div>\n \n <button type=\"submit\">Create Bet</button>\n </form>\n </div>\n <div className=\"x1\">\n <Players />\n </div>\n <div>\n {shareDisplay ? <ShareBet display={handleShare} /> : null}\n \n </div>\n </div>\n );\n};\n\nexport default CreateMoneyLine;\n","import React from 'react';\nimport CreateMoneyLine from './CreateMoneyLine';\n\nconst MoneyLine = () => {\n \n\n return (\n <div className='p-12'>\n <h1>Money Line Bets</h1>\n <CreateMoneyLine />\n </div>\n );\n};\n\nexport default MoneyLine;\n","// extracted by mini-css-extract-plugin\nexport default {\"OverUnder\":\"OverUnder_OverUnder__lZCyp\",\"betContainer\":\"OverUnder_betContainer__GC+uq\",\"BetTextArea\":\"OverUnder_BetTextArea__Y0xal\",\"betLabel\":\"OverUnder_betLabel__fUG2h\",\"lineLabel\":\"OverUnder_lineLabel__uLemh\",\"line\":\"OverUnder_line__xiV+Z\",\"actualLine\":\"OverUnder_actualLine__NevcO\"};","import React from 'react';\nimport css from './OverUnder.module.css';\nimport Players from '../Players/Players';\nimport ShareBet from '../Players/ShareBet';\nimport {useState} from 'react';\nimport {db} from '../../../Config/firebase-config';\nimport { addDoc, collection } from 'firebase/firestore';\n\nconst CreateOverUnder = () => {\n \n const [bet, setBet] = useState('');\n const [line, setLine] = useState(0);\n\n\n const [shareDisplay, setShareDisplay] = useState(false);\n \n const handleShare = () => {\n setShareDisplay((current) => !current);\n }\n\n const handelSubmit = async (e) => {\n e.preventDefault();\n handleShare();\n try {\n await addDoc(collection(db, \"bets\"), {\n type: \"Over Under\",\n bet: bet,\n })\n \n await addDoc(collection(db, \"OverUnderBets\"), {\n bet: bet,\n line: line,\n })\n } catch (e) {\n console.error(e);\n }\n console.log('Creating over under bet');\n }\n\n return (\n <div className='flex'>\n <div className={css.OverUnder}>\n <form onSubmit={handelSubmit}>\n <div className={`flex flex-col gap-4 pb-8 ${css.betContainer}`}>\n Proposition:\n <div className={css.bet}>\n <textarea className={css.BetTextArea} type=\"text\" onChange={(e) => {setBet(e.target.value)}}/>\n </div>\n </div>\n <div>\n <div className=\"flex items-center gap-4 m-2\">\n <span className={css.label}>Line:</span>\n <input className=\"h-6 w-12\" type=\"number\" step=\"0.5\" onChange={(e) =>{setLine(Number(e.target.value))}} />\n </div>\n </div>\n <button type=\"submit\">Create bet</button>\n </form>\n </div>\n\n <div className=\"x1\">\n <Players />\n </div>\n <div>\n {shareDisplay ? <ShareBet display={handleShare} /> : null}\n \n </div>\n \n </div>\n );\n};\n\nexport default CreateOverUnder;\n","import React from 'react';\nimport CreateOverUnder from './CreateOverUnder';\n\nconst OverUnder = () => {\n return (\n <div className='p-12'>\n <h1>OverUnder Component</h1>\n <CreateOverUnder />\n </div>\n );\n};\n\nexport default OverUnder;\n","// extracted by mini-css-extract-plugin\nexport default {\"prop\":\"Prop_prop__DRZFt\",\"betContainer\":\"Prop_betContainer__KSYFf\",\"betTextarea\":\"Prop_betTextarea__fXQn9\",\"PreSetBetting\":\"Prop_PreSetBetting__MzpqW\",\"settings\":\"Prop_settings__9dmn0\",\"title\":\"Prop_title__GEvyW\",\"label\":\"Prop_label__zDU93\",\"x\":\"Prop_x__tu9O2\",\"optionInput\":\"Prop_optionInput__MuLBG\"};","import React, { useState, useEffect } from 'react';\nimport css from './Prop.module.css';\n\nconst PreSetBettingOptions = (prop) => {\n const [howMany, setHowMany] = useState(0);\n const [howManyOptions, setHowManyOptions] = useState([]);\n\n const [options, setOptions] = useState([]);\n\n\n const addOptions = (e, i) => {\n setOptions((current) => {options[i] = e.target.value; return options});\n }\n\n const addOneMore = () => {\n setHowMany(howMany + 1);\n }\n\n useEffect(() => {\n let options = [];\n for (let i = 0; i < howMany; i++) {\n options.push(i);\n }\n setHowManyOptions(options);\n }, [howMany]);\n\n const handleSubmit = (e) => {\n e.preventDefault();\n prop.setOptions(options);\n console.log('Saving preset betting options');\n }\n\n return (\n <div className={css.PreSetBetting}>\n <div className=\"flex justify-center mb-2\"><span className=\"x\" onClick={prop.display}>x</span></div>\n <div className={css.title}><span>Preset Betting Options</span></div>\n <form onSubmit={handleSubmit}>\n {howManyOptions.map((option, index) => (\n <div className=\"flex justify-center items-center gap-2 p-2\" key={index}>\n <span className={css.label}>{option+1}:</span>\n <input className={css.optionInput} type=\"text\" onChange={(e) => addOptions(e, index)} placeholder='Who or what' />\n </div>\n ))}\n <button type=\"submit\">Save</button>\n </form>\n <button onClick={addOneMore}>Add Option</button>\n </div>\n );\n};\n\nexport default PreSetBettingOptions;","import React from 'react';\nimport css from './Prop.module.css';\nimport { useState } from 'react';\nimport PreSetBettingOptions from './PreSetBettingOptions';\nimport Players from '../Players/Players';\nimport ShareBet from '../Players/ShareBet';\nimport {db} from '../../../Config/firebase-config';\nimport { addDoc, collection } from 'firebase/firestore';\n\nconst CreateProp = () => {\n\n const [bet, setBet] = useState('');\n const [Options, setOptions] = useState([]);\n\n\n const [isChecked, setIsChecked] = useState(false);\n const [shareDisplay, setShareDisplay] = useState(false);\n\n const handlesSetOptions = (options) => {\n setOptions(options);\n }\n \n const handleShare = () => {\n setShareDisplay((current) => !current);\n }\n\n \n const handleCheckboxChange = (event) => {\n setIsChecked(event.target.checked);\n };\n\n const handelSubmit = async (e) => { \n e.preventDefault();\n handleShare();\n try {\n await addDoc(collection(db, \"bets\"), {\n type: \"Prop\",\n bet: bet,\n })\n \n await addDoc(collection(db, \"PropBets\"), {\n bet: bet,\n options: Options,\n })\n } catch (e) {\n console.error(e);\n }\n console.log('Creating prop bet');\n }\n return (\n <div className='flex'>\n <div className={css.prop} >\n <form onSubmit={handelSubmit}>\n <div className={`flex flex-col gap-4 pb-8 ${css.betContainer}`}>\n Proposition:\n <div>\n <textarea className=\"betTextarea\" type=\"text\" onChange={(e) => {setBet(e.target.value)}} />\n </div>\n </div>\n <div className=\"flex gap-4 m-4\">\n <input type=\"checkbox\" id=\"preSetBetting\" checked={isChecked} onChange={handleCheckboxChange} />\n <label className={css.settings} htmlFor=\"preSetBetting\">Pre Set Betting Options</label>\n </div>\n <button type=\"submit\">Create bet</button>\n </form>\n </div>\n <div>\n {isChecked ? <PreSetBettingOptions setOptions={handlesSetOptions} display={handleCheckboxChange}/> : null}\n </div>\n <div className=\"x1\">\n <Players />\n </div>\n <div>\n {shareDisplay ? <ShareBet display={handleShare} /> : null}\n \n </div>\n </div>\n );\n};\n\nexport default CreateProp;\n","import React from 'react';\nimport CreateProp from './CreateProp';\n\nconst Prop = () => {\n return (\n <div className='p-12'>\n <h1>Prop Bets</h1>\n <CreateProp />\n </div>\n );\n};\n\nexport default Prop;\n","// extracted by mini-css-extract-plugin\nexport default {\"greenButtons\":\"Components_greenButtons__FGl7E\",\"redSpring\":\"Components_redSpring__YTemv\",\"big\":\"Components_big__0VZG0\",\"small\":\"Components_small__5JtmR\",\"DeleteButton\":\"Components_DeleteButton__X+vUS\"};","import React from 'react';\nimport css from './Components.module.css';\n\n\n\nconst Buttons = (props) => {\n\n const buttonColor = props.a === \"greenButton\" ? css.greenButtons : css.redSpring\n const buttonType = props.size === \"big\" ? css.big : css.small\n\n\n return (\n <div className={buttonColor}>\n <div>{props.text}</div>\n </div>\n );\n}\n\nexport default Buttons;\n","import React from 'react';\nimport {useLocation, useNavigate } from 'react-router-dom';\nimport css from './Components.module.css';\nimport {db} from '../../Config/firebase-config';\nimport { doc, deleteDoc } from \"firebase/firestore\";\n\n\nconst DeleteButton = (props) => {\n\n const navigate = useNavigate();\n\n const location = useLocation()\n const { bet } = location.state\n\n const handleDelete = () => {\n const deleteDocument = async () => {\n try {\n await deleteDoc(doc(db, props.collection, props.docId));\n await deleteDoc(doc(db, \"bets\" , bet.id));\n navigate(\"/Friendly-Betting/Bet\"); \n }\n catch (e) {\n console.error(e);\n }\n }\n deleteDocument();\n };\n \n return (\n <div className='flex justify-center items-center'>\n <button className={css.DeleteButton} onClick={handleDelete}>\n Delete\n </button>\n </div>\n );\n};\n\n\nexport default DeleteButton;\n","import React, { useState, useEffect } from 'react';\nimport css from './MoneyLine.module.css';\nimport Players from '../Players/Players';\nimport ShareBet from '../Players/ShareBet';\nimport Buttons from '../../Components/Buttons';\nimport { useLocation } from 'react-router-dom';\nimport {db} from '../../../Config/firebase-config';\nimport { collection, getDocs, where , query } from 'firebase/firestore';\nimport DeleteButton from '../../Components/DeleteButton';\n\n\nconst ViewMoneyLine = () => {\n\n const [bets, setBets] = useState([])\n const [betId, setBetId] = useState('')\n\n const collectionName = \"MoneyLineBets\"\n\n const location = useLocation()\n const { bet } = location.state\n \n useEffect(() => {\n const fetchBet = async () => {\n try{\n const MoneyLineBetCollection = collection(db, collectionName);\n const q = query(MoneyLineBetCollection, where(\"bet\", \"==\", bet.bet));\n const querySnapshot = await getDocs(q);\n setBets(querySnapshot.docs[0].data());\n setBetId(querySnapshot.docs[0].id);\n \n\n } catch (e) {\n console.error(e);\n }\n }\n fetchBet();\n }, [])\n\n\n return (\n <div className='flex p-12'>\n <div className='x2'>\n <div>\n <div className=\"flex justify-around\">\n <h1 className={`pb-4 bl-4 ${css.betLabel}`}>{bets.bet}</h1>\n <DeleteButton collection={collectionName} docId={betId}/> \n </div>\n \n <div className='blob'>\n <div className=\"flex justify-center items-center gap-8 my-4 mx-8 \">\n <Buttons text=\"Bet\" a=\"greenButton\" size=\"big\"></Buttons>\n <h2>{bets.contestant1} </h2>\n {bets.contestant1Odds > 0 ? <p className='green'>(+{bets.contestant1Odds})</p> : <p className=\"red\">({bets.contestant1Odds})</p>}\n </div>\n <hr />\n <div className=\"flex justify-center items-center gap-8 my-4 mx-8\">\n <Buttons text=\"Bet\" a=\"greenButton\" size=\"big\"></Buttons>\n <h2>{bets.contestant2} </h2>\n {bets.contestant2Odds > 0 ? <p className='green'>(+{bets.contestant2Odds})</p> : <p className='red'>({bets.contestant2Odds})</p>}\n </div>\n </div>\n \n </div>\n\n\n\n </div>\n <div className=\"flex-1\">\n <Players />\n </div>\n </div>\n );\n};\n\nexport default ViewMoneyLine;\n","import React from 'react';\nimport { useState, useEffect } from 'react';\nimport { useLocation } from 'react-router-dom';\nimport Buttons from '../../Components/Buttons';\nimport Players from '../Players/Players';\nimport DeleteButton from '../../Components/DeleteButton';\nimport css from './OverUnder.module.css';\nimport {db} from '../../../Config/firebase-config';\nimport { collection, getDocs, where , query } from 'firebase/firestore';\n\nconst ViewOverUnder = () => {\n\n const [bets, setBets] = useState([])\n const [betId, setBetId] = useState('')\n\n const collectionName = \"OverUnderBets\"\n\n const location = useLocation()\n const { bet } = location.state\n\n\n useEffect(() => {\n\n const fetchBet = async () => {\n try{\n const MoneyLineBetCollection = collection(db, \"OverUnderBets\");\n const q = query(MoneyLineBetCollection, where(\"bet\", \"==\", bet.bet));\n const querySnapshot = await getDocs(q);\n setBets(querySnapshot.docs[0].data());\n setBetId(querySnapshot.docs[0].id);\n\n } catch (e) {\n console.error(e);\n }\n }\n fetchBet();\n }, [])\n return (\n <div className='flex p-12'>\n <div className='x2'>\n <div>\n <div className=\"flex justify-around\">\n <h1 className={css.betLabel} >{bets.bet}</h1>\n <DeleteButton collection={collectionName} docId={betId} />\n </div>\n <div className={`blob row p-16`}>\n <div className=\"flex flex-col justify-center items-center\">\n <Buttons text=\"Under\" a=\"greenButton\" size=\"big\"></Buttons>\n <p>8 others have taken the under</p>\n </div>\n <div className={css.line}>\n <div className={css.lineLabel}><span>Line</span></div>\n <div className={css.actualLine}>{bets.line}</div> \n <div className=\"flex justify-center items-center break-words text-center\">3 people have not voted</div>\n </div>\n <div className=\"flex flex-col justify-center items-center\">\n <Buttons text=\"Over\" a=\"greenButton\" size=\"big\"></Buttons>\n <p className=\"text-center\">12 others have taken the over</p>\n </div>\n </div>\n </div>\n </div>\n <div className=\"x1\">\n \n <Players />\n </div>\n \n </div>\n );\n};\n\nexport default ViewOverUnder;\n","import React from 'react';\nimport { useState, useEffect } from 'react';\nimport { useLocation } from 'react-router-dom';\nimport Players from '../Players/Players';\nimport DeleteButton from '../../Components/DeleteButton';\nimport css from './Prop.module.css';\nimport {db} from '../../../Config/firebase-config';\nimport { collection, getDocs, where , query } from 'firebase/firestore';\nconst ViewProp = () => {\n\n const [bets, setBets] = useState([])\n const [length, setLength] = useState(0)\n const [betId, setBetId] = useState('')\n\n const collectionName = \"PropBets\"\n\n const location = useLocation()\n const { bet } = location.state\n\n\n useEffect(() => {\n\n const fetchBet = async () => {\n try{\n const MoneyLineBetCollection = collection(db, \"PropBets\");\n const q = query(MoneyLineBetCollection, where(\"bet\", \"==\", bet.bet));\n const querySnapshot = await getDocs(q);\n setBets(querySnapshot.docs[0].data());\n setLength(querySnapshot.docs[0].data().options.length)\n setBetId(querySnapshot.docs[0].id);\n \n\n } catch (e) {\n console.error(e);\n }\n }\n fetchBet();\n }, [])\n\n\n return (\n <div>\n <div className='flex p-12'>\n <div className='x2'>\n <div>\n <div className=\"flex justify-around\">\n <h1 className={css.betLabel} >{bets.bet}</h1>\n <DeleteButton collection={collectionName} docId={betId} /> \n </div>\n \n {length > 0 ? (\n <div>\n <h4><span>Betting</span></h4> \n <div className=\"pl-8\">\n {bets.options.map((option, index) => (\n <div key={index}>\n <p>{option}</p>\n </div>\n )\n )}\n </div>\n </div>\n ): (null)}\n </div>\n </div>\n <div className=\"x1\">\n <Players />\n </div>\n \n </div>\n </div>\n );\n};\n\nexport default ViewProp;\n","// extracted by mini-css-extract-plugin\nexport default {\"betNav\":\"Bets_betNav__NdIy7\",\"BettingLinks\":\"Bets_BettingLinks__UtSL7\",\"x\":\"Bets_x__IOVNi\",\"bet\":\"Bets_bet__pvKP6\",\"link\":\"Bets_link__ibFCG\"};","import React from 'react';\nimport {useNavigate } from 'react-router-dom';\nimport css from './Bets.module.css';\n\nconst BetNav = (props) => {\n const navigate = useNavigate();\n\n const goToMoneyLine = () => {\n navigate('/Friendly-Betting/MoneyLineBets')\n }\n const goToOverUnder = () => {\n navigate('/Friendly-Betting/OverUnderBets')\n }\n const goToProps = () => {\n navigate('/Friendly-Betting/PropBets')\n }\n return (\n <div className={css.betNav}>\n <div className={css.x}><span onClick={props.swap} >x</span></div>\n <h1><span>Bets</span></h1>\n <div className={css.BettingLinks}>\n <div>\n <div onClick={goToMoneyLine} className='Link' >Money Line Bets</div>\n </div>\n <div>\n <div onClick={goToOverUnder} className='Link' >Over / Under Bets</div>\n </div>\n <div>\n <div onClick={goToProps} className='Link' >Prop Bets</div>\n </div>\n </div>\n </div>\n );\n};\n\nexport default BetNav;\n","import React from 'react';\nimport css from './Bets.module.css';\nimport {Link} from 'react-router-dom';\n\n\n\nconst DisplayBet = (props) => {\n\n const viewBet = () => {\n if(props.bet.type === \"Money Line\"){\n return \"MoneyLineBets/\"\n }\n else if(props.bet.type === \"Over Under\"){\n return \"OverUnderBets/\"\n }\n else if(props.bet.type === \"Prop\"){\n return \"PropBets/\"\n }\n }\n\n return (\n <div onClick={viewBet}>\n <Link \n to={`/Friendly-Betting/Bet/${viewBet()}`}\n state={{\"bet\":props.bet}}\n className={css.link}\n \n >\n <div className={css.bet} key={props.bet.id}>\n <h4>{props.bet.type}</h4>\n <p>{props.bet.bet}</p>\n </div>\n </Link>\n </div>\n );\n}\n\nexport default DisplayBet;","import React from 'react';\nimport { useState, useEffect } from 'react';\nimport BetNav from './BetNav';\nimport {db} from '../../Config/firebase-config';\nimport { collection, getDocs } from 'firebase/firestore';\nimport DisplayBet from './DisplayBet';\nimport Players from './Players/Players';\n\n\nconst DisplayAllBets = () => {\n\n const [json, setJson] = useState(\"\")\n const [display, setDisplay] = useState(false)\n const [bets, setBets] = useState([])\n\n\n useEffect(() => {\n const getBets = async () => {\n try{\n const data = await getDocs(collection(db, \"bets\"));\n const filteredData = data.docs.map(doc => ({\n ...doc.data(), \n id: doc.id,\n }));\n setBets(filteredData);\n } catch (e) {\n console.error(e);\n }\n }\n \n getBets();\n }, [])\n\n const swapDisplay = () => {\n setDisplay((current) => !current)\n }\n return (\n <div className='flex p-12'>\n <div className='x2'>\n {bets.length < 1 ? (\n <div>\n <h3>You are not in any bets yet</h3>\n <button onClick={swapDisplay}>Create One!</button>\n {display ? <BetNav swap={swapDisplay}/> : null}\n\n </div>\n ) : (\n <div>\n {bets.map((bet, id) => (\n <DisplayBet key={id} bet={bet} />\n ))}\n <button onClick={swapDisplay}>Create One!</button>\n {display ? <BetNav swap={swapDisplay}/> : null}\n </div>\n ) }\n </div>\n <div className='x1'>\n <Players />\n </div>\n </div>\n );\n}\n\nexport default DisplayAllBets;\n","import React from 'react';\n\nfunction Friends() {\n return (\n <div>\n <h1>Friends</h1>\n </div>\n );\n}\n\nexport default Friends;\n","\nimport './App.css';\nimport SignIn from './Components/SignInPage/SignIn';\nimport CreateAccount from './Components/SignInPage/CreateAccount';\nimport Header from './Components/Header';\nimport NotFound from './Components/NotFound';\nimport { BrowserRouter as Router, Routes, Route } from 'react-router-dom';\nimport Welcome from './Components/Welcome';\nimport MoneyLine from './Components/Bets/MoneyLineBets/MoneyLine';\nimport OverUnder from './Components/Bets/OverUnderBets/OverUnder';\nimport Prop from './Components/Bets/PropBets/Prop';\nimport ViewMoneyLine from './Components/Bets/MoneyLineBets/ViewMoneyLine';\nimport ViewOverUnder from './Components/Bets/OverUnderBets/ViewOverUnder';\nimport ViewProp from './Components/Bets/PropBets/ViewProp';\nimport DisplayAllBets from './Components/Bets/DisplayAllBets';\nimport Friends from './Components/Friends/Friends';\n\n\n\n\n\n\nfunction App() {\n\n \n \n return (\n <Router>\n <Header />\n <Routes>\n <Route path=\"Friendly-Betting/\" element={<Welcome />} />\n \n <Route path=\"Friendly-Betting/SignIn\" element={ <SignIn />} />\n \n <Route path=\"Friendly-Betting/CreateAccount\" element={<CreateAccount />} />\n <Route path=\"Friendly-Betting/Bet\" element={<DisplayAllBets />} />\n <Route path=\"Friendly-Betting/Friends\" element={<Friends />} />\n\n <Route path=\"Friendly-Betting/MoneyLineBets\" element={<MoneyLine />} />\n <Route path=\"Friendly-Betting/OverUnderBets\" element={<OverUnder />} />\n <Route path=\"Friendly-Betting/PropBets\" element={<Prop />} />\n\n <Route path=\"/Friendly-Betting/Bet/MoneyLineBets/\" element={<ViewMoneyLine />} />\n <Route path=\"/Friendly-Betting/Bet/OverUnderBets/\" element={<ViewOverUnder />} />\n <Route path=\"/Friendly-Betting/Bet/PropBets/\" element={<ViewProp />} />\n\n\n\n <Route path=\"/*\" element={<NotFound />} />\n </Routes>\n </Router>\n );\n}\n\nexport default App;\n","const reportWebVitals = onPerfEntry => {\n if (onPerfEntry && onPerfEntry instanceof Function) {\n import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {\n getCLS(onPerfEntry);\n getFID(onPerfEntry);\n getFCP(onPerfEntry);\n getLCP(onPerfEntry);\n getTTFB(onPerfEntry);\n });\n }\n};\n\nexport default reportWebVitals;\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport './index.css';\nimport App from './App';\nimport reportWebVitals from './reportWebVitals';\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(\n <React.StrictMode>\n <App />\n </React.StrictMode>\n);\n\n// If you want to start measuring performance in your app, pass a function\n// to log results (for example: reportWebVitals(console.log))\n// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals\nreportWebVitals();\n"],"names":["aa","require","ca","p","a","b","c","arguments","length","encodeURIComponent","da","Set","ea","fa","ha","add","ia","window","document","createElement","ja","Object","prototype","hasOwnProperty","ka","la","ma","v","d","e","f","g","this","acceptsBooleans","attributeName","attributeNamespace","mustUseProperty","propertyName","type","sanitizeURL","removeEmptyString","z","split","forEach","toLowerCase","ra","sa","toUpperCase","ta","slice","pa","isNaN","qa","call","test","oa","removeAttribute","setAttribute","setAttributeNS","replace","xlinkHref","ua","__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED","va","Symbol","for","wa","ya","za","Aa","Ba","Ca","Da","Ea","Fa","Ga","Ha","Ia","Ja","iterator","Ka","La","A","assign","Ma","Error","stack","trim","match","Na","Oa","prepareStackTrace","defineProperty","set","Reflect","construct","l","h","k","displayName","includes","name","Pa","tag","render","Qa","$$typeof","_context","_payload","_init","Ra","Sa","Ta","nodeName","Va","_valueTracker","getOwnPropertyDescriptor","constructor","get","configurable","enumerable","getValue","setValue","stopTracking","Ua","Wa","checked","value","Xa","activeElement","body","Ya","defaultChecked","defaultValue","_wrapperState","initialChecked","Za","initialValue","controlled","ab","bb","cb","db","ownerDocument","eb","Array","isArray","fb","options","selected","defaultSelected","disabled","gb","dangerouslySetInnerHTML","children","hb","ib","jb","textContent","kb","lb","mb","nb","namespaceURI","innerHTML","valueOf","toString","firstChild","removeChild","appendChild","MSApp","execUnsafeLocalFunction","ob","lastChild","nodeType","nodeValue","pb","animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth","qb","rb","sb","style","indexOf","setProperty","keys","charAt","substring","tb","menuitem","area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr","ub","vb","is","wb","xb","target","srcElement","correspondingUseElement","parentNode","yb","zb","Ab","Bb","Cb","stateNode","Db","Eb","push","Fb","Gb","Hb","Ib","Jb","Kb","Lb","Mb","addEventListener","removeEventListener","Nb","apply","m","onError","Ob","Pb","Qb","Rb","Sb","Tb","Vb","alternate","return","flags","Wb","memoizedState","dehydrated","Xb","Zb","child","sibling","current","Yb","$b","ac","unstable_scheduleCallback","bc","unstable_cancelCallback","cc","unstable_shouldYield","dc","unstable_requestPaint","B","unstable_now","ec","unstable_getCurrentPriorityLevel","fc","unstable_ImmediatePriority","gc","unstable_UserBlockingPriority","hc","unstable_NormalPriority","ic","unstable_LowPriority","jc","unstable_IdlePriority","kc","lc","oc","Math","clz32","pc","qc","log","LN2","rc","sc","tc","uc","pendingLanes","suspendedLanes","pingedLanes","entangledLanes","entanglements","vc","xc","yc","zc","Ac","eventTimes","Cc","C","Dc","Ec","Fc","Gc","Hc","Ic","Jc","Kc","Lc","Mc","Nc","Oc","Map","Pc","Qc","Rc","Sc","delete","pointerId","Tc","nativeEvent","blockedOn","domEventName","eventSystemFlags","targetContainers","Vc","Wc","priority","isDehydrated","containerInfo","Xc","Yc","dispatchEvent","shift","Zc","$c","ad","bd","cd","ReactCurrentBatchConfig","dd","ed","transition","fd","gd","hd","id","Uc","stopPropagation","jd","kd","ld","md","nd","od","keyCode","charCode","pd","qd","rd","_reactName","_targetInst","currentTarget","isDefaultPrevented","defaultPrevented","returnValue","isPropagationStopped","preventDefault","cancelBubble","persist","isPersistent","wd","xd","yd","sd","eventPhase","bubbles","cancelable","timeStamp","Date","now","isTrusted","td","ud","view","detail","vd","Ad","screenX","screenY","clientX","clientY","pageX","pageY","ctrlKey","shiftKey","altKey","metaKey","getModifierState","zd","button","buttons","relatedTarget","fromElement","toElement","movementX","movementY","Bd","Dd","dataTransfer","Fd","Hd","animationName","elapsedTime","pseudoElement","Id","clipboardData","Jd","Ld","data","Md","Esc","Spacebar","Left","Up","Right","Down","Del","Win","Menu","Apps","Scroll","MozPrintableKey","Nd","Od","Alt","Control","Meta","Shift","Pd","Qd","key","String","fromCharCode","code","location","repeat","locale","which","Rd","Td","width","height","pressure","tangentialPressure","tiltX","tiltY","twist","pointerType","isPrimary","Vd","touches","targetTouches","changedTouches","Xd","Yd","deltaX","wheelDeltaX","deltaY","wheelDeltaY","wheelDelta","deltaZ","deltaMode","Zd","$d","ae","be","documentMode","ce","de","ee","fe","ge","he","ie","le","color","date","datetime","email","month","number","password","range","search","tel","text","time","url","week","me","ne","oe","event","listeners","pe","qe","re","se","te","ue","ve","we","xe","ye","ze","oninput","Ae","detachEvent","Be","Ce","attachEvent","De","Ee","Fe","He","Ie","Je","Ke","node","offset","nextSibling","Le","contains","compareDocumentPosition","Me","HTMLIFrameElement","contentWindow","href","Ne","contentEditable","Oe","focusedElem","selectionRange","documentElement","start","end","selectionStart","selectionEnd","min","defaultView","getSelection","extend","rangeCount","anchorNode","anchorOffset","focusNode","focusOffset","createRange","setStart","removeAllRanges","addRange","setEnd","element","left","scrollLeft","top","scrollTop","focus","Pe","Qe","Re","Se","Te","Ue","Ve","We","animationend","animationiteration","animationstart","transitionend","Xe","Ye","Ze","animation","$e","af","bf","cf","df","ef","ff","gf","hf","lf","mf","concat","nf","Ub","instance","listener","D","of","has","pf","qf","rf","random","sf","bind","capture","passive","n","t","J","x","u","w","F","tf","uf","parentWindow","vf","wf","na","xa","$a","ba","je","char","ke","unshift","xf","yf","zf","Af","Bf","Cf","Df","Ef","__html","Ff","setTimeout","Gf","clearTimeout","Hf","Promise","Jf","queueMicrotask","resolve","then","catch","If","Kf","Lf","Mf","previousSibling","Nf","Of","Pf","Qf","Rf","Sf","Tf","Uf","E","G","Vf","H","Wf","Xf","Yf","contextTypes","__reactInternalMemoizedUnmaskedChildContext","__reactInternalMemoizedMaskedChildContext","Zf","childContextTypes","$f","ag","bg","getChildContext","cg","__reactInternalMemoizedMergedChildContext","dg","eg","fg","gg","hg","jg","kg","lg","mg","ng","og","pg","qg","rg","sg","tg","ug","vg","wg","xg","yg","I","zg","Ag","Bg","elementType","deletions","Cg","pendingProps","overflow","treeContext","retryLane","Dg","mode","Eg","Fg","Gg","memoizedProps","Hg","Ig","Jg","Kg","Lg","defaultProps","Mg","Ng","Og","Pg","Qg","Rg","_currentValue","Sg","childLanes","Tg","dependencies","firstContext","lanes","Ug","Vg","context","memoizedValue","next","Wg","Xg","Yg","interleaved","Zg","$g","ah","updateQueue","baseState","firstBaseUpdate","lastBaseUpdate","shared","pending","effects","bh","ch","eventTime","lane","payload","callback","dh","K","eh","fh","gh","q","r","y","hh","ih","jh","Component","refs","kh","nh","isMounted","_reactInternals","enqueueSetState","L","lh","mh","enqueueReplaceState","enqueueForceUpdate","oh","shouldComponentUpdate","isPureReactComponent","ph","contextType","state","updater","qh","componentWillReceiveProps","UNSAFE_componentWillReceiveProps","rh","props","getDerivedStateFromProps","getSnapshotBeforeUpdate","UNSAFE_componentWillMount","componentWillMount","componentDidMount","sh","ref","_owner","_stringRef","th","join","uh","vh","index","wh","xh","yh","implementation","zh","Ah","done","Bh","Ch","Dh","Eh","Fh","Gh","Hh","Ih","tagName","Jh","Kh","Lh","M","Mh","revealOrder","Nh","Oh","_workInProgressVersionPrimary","Ph","ReactCurrentDispatcher","Qh","Rh","N","O","P","Sh","Th","Uh","Vh","Q","Wh","Xh","Yh","Zh","$h","ai","bi","ci","baseQueue","queue","di","ei","fi","lastRenderedReducer","action","hasEagerState","eagerState","lastRenderedState","dispatch","gi","hi","ii","ji","ki","getSnapshot","li","mi","R","ni","lastEffect","stores","oi","pi","qi","ri","create","destroy","deps","si","ti","ui","vi","wi","xi","yi","zi","Ai","Bi","Ci","Di","Ei","Fi","Gi","Hi","Ii","Ji","readContext","useCallback","useContext","useEffect","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useReducer","useRef","useState","useDebugValue","useDeferredValue","useTransition","useMutableSource","useSyncExternalStore","useId","unstable_isNewReconciler","identifierPrefix","Ki","message","digest","Li","Mi","console","error","Ni","WeakMap","Oi","Pi","Qi","Ri","getDerivedStateFromError","componentDidCatch","Si","componentStack","Ti","pingCache","Ui","Vi","Wi","Xi","ReactCurrentOwner","Yi","Zi","$i","aj","bj","compare","cj","dj","ej","baseLanes","cachePool","transitions","fj","gj","hj","ij","jj","UNSAFE_componentWillUpdate","componentWillUpdate","componentDidUpdate","kj","lj","pendingContext","mj","Aj","Bj","Cj","Dj","nj","oj","pj","fallback","qj","rj","tj","dataset","dgst","uj","vj","_reactRetry","sj","subtreeFlags","wj","xj","isBackwards","rendering","renderingStartTime","last","tail","tailMode","yj","Ej","S","Fj","Gj","wasMultiple","multiple","suppressHydrationWarning","onClick","onclick","size","createElementNS","autoFocus","createTextNode","T","Hj","Ij","Jj","Kj","U","Lj","WeakSet","V","Mj","W","Nj","Oj","Qj","Rj","Sj","Tj","Uj","Vj","Wj","insertBefore","_reactRootContainer","Xj","X","Yj","Zj","ak","onCommitFiberUnmount","componentWillUnmount","bk","ck","dk","ek","fk","isHidden","gk","hk","display","ik","jk","kk","lk","__reactInternalSnapshotBeforeUpdate","src","Wk","mk","ceil","nk","ok","pk","Y","Z","qk","rk","sk","tk","uk","Infinity","vk","wk","xk","yk","zk","Ak","Bk","Ck","Dk","Ek","callbackNode","expirationTimes","expiredLanes","wc","callbackPriority","ig","Fk","Gk","Hk","Ik","Jk","Kk","Lk","Mk","Nk","Ok","Pk","finishedWork","finishedLanes","Qk","timeoutHandle","Rk","Sk","Tk","Uk","Vk","mutableReadLanes","Bc","Pj","onCommitFiberRoot","mc","onRecoverableError","Xk","onPostCommitFiberRoot","Yk","Zk","al","isReactComponent","pendingChildren","bl","mutableSourceEagerHydrationData","cl","cache","pendingSuspenseBoundaries","el","fl","gl","hl","il","jl","zj","$k","ll","reportError","ml","_internalRoot","nl","ol","pl","ql","sl","rl","unmount","unstable_scheduleHydration","splice","querySelectorAll","JSON","stringify","form","tl","usingClientEntryPoint","Events","ul","findFiberByHostInstance","bundleType","version","rendererPackageName","vl","rendererConfig","overrideHookState","overrideHookStateDeletePath","overrideHookStateRenamePath","overrideProps","overridePropsDeletePath","overridePropsRenamePath","setErrorHandler","setSuspenseHandler","scheduleUpdate","currentDispatcherRef","findHostInstanceByFiber","findHostInstancesForRefresh","scheduleRefresh","scheduleRoot","setRefreshHandler","getCurrentFiber","reconcilerVersion","__REACT_DEVTOOLS_GLOBAL_HOOK__","wl","isDisabled","supportsFiber","inject","exports","createPortal","dl","createRoot","unstable_strictMode","findDOMNode","flushSync","hydrate","hydrateRoot","hydratedSources","_getVersion","_source","unmountComponentAtNode","unstable_batchedUpdates","unstable_renderSubtreeIntoContainer","checkDCE","err","module","__self","__source","jsx","jsxs","setState","forceUpdate","escape","_status","_result","default","Children","map","count","toArray","only","Fragment","Profiler","PureComponent","StrictMode","Suspense","cloneElement","createContext","_currentValue2","_threadCount","Provider","Consumer","_defaultValue","_globalName","createFactory","createRef","forwardRef","isValidElement","lazy","memo","startTransition","unstable_act","pop","sortIndex","performance","setImmediate","startTime","expirationTime","priorityLevel","navigator","scheduling","isInputPending","MessageChannel","port2","port1","onmessage","postMessage","unstable_Profiling","unstable_continueExecution","unstable_forceFrameRate","floor","unstable_getFirstCallbackNode","unstable_next","unstable_pauseExecution","unstable_runWithPriority","delay","unstable_wrapCallback","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","leafPrototypes","getProto","getPrototypeOf","obj","__esModule","ns","def","getOwnPropertyNames","definition","o","chunkId","all","reduce","promises","miniCssF","globalThis","Function","prop","inProgress","dataWebpackPrefix","script","needAttach","scripts","getElementsByTagName","i","s","getAttribute","charset","timeout","nc","onScriptComplete","prev","onerror","onload","doneFns","fn","head","toStringTag","installedChunks","j","installedChunkData","promise","reject","errorType","realSrc","request","webpackJsonpCallback","parentChunkLoadingFunction","chunkIds","moreModules","runtime","some","chunkLoadingGlobal","self","stringToByteArray$1","str","out","charCodeAt","base64","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","webSafe","init_","byteToCharMap","output","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","encodeString","btoa","decodeString","bytes","pos","c1","c2","c3","byteArrayToString","decodeStringToByteArray","charToByteMap","byte4","DecodeBase64StringError","base64urlEncodeWithoutPadding","utf8Bytes","base64Encode","base64Decode","getDefaultsFromGlobal","global","getGlobal","__FIREBASE_DEFAULTS__","getDefaults","getDefaultsFromEnvVariable","process","defaultsJsonString","parse","getDefaultsFromCookie","cookie","decoded","info","getDefaultEmulatorHost","productName","_a","_b","emulatorHosts","getDefaultAppConfig","config","getExperimentalSetting","Deferred","wrapCallback","getUA","isBrowserExtension","chrome","browser","isIndexedDBAvailable","indexedDB","validateIndexedDBOpenable","preExist","DB_CHECK_NAME","open","onsuccess","result","close","deleteDatabase","onupgradeneeded","FirebaseError","customData","super","setPrototypeOf","captureStackTrace","ErrorFactory","service","serviceName","errors","fullCode","template","PATTERN","_","replaceTemplate","fullMessage","deepEqual","aKeys","bKeys","aProp","bProp","isObject","thing","querystring","querystringParams","params","entries","arrayVal","querystringDecode","token","decodeURIComponent","extractQuerystring","queryStart","fragmentStart","ObserverProxy","executor","onNoObservers","observers","unsubscribes","observerCount","task","finalized","forEachObserver","observer","complete","subscribe","nextOrObserver","methods","method","implementsAnyMethods","noop","unsub","unsubscribeOne","finalError","sendOne","DEFAULT_INTERVAL_MILLIS","DEFAULT_BACKOFF_FACTOR","MAX_VALUE_MILLIS","RANDOM_FACTOR","calculateBackoffMillis","backoffCount","backoffFactor","currBaseValue","pow","randomWait","round","getModularInstance","_delegate","instanceFactory","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","setMultipleInstances","setServiceProps","setInstanceCreatedCallback","DEFAULT_ENTRY_NAME","container","component","instances","instancesDeferred","instancesOptions","onInitCallbacks","identifier","normalizedIdentifier","normalizeInstanceIdentifier","deferred","isInitialized","shouldAutoInitialize","getOrInitializeService","instanceIdentifier","getImmediate","optional","getComponent","setComponent","isComponentEager","instanceDeferred","clearInstance","services","from","values","filter","INTERNAL","_delete","isComponentSet","getOptions","initialize","opts","onInit","existingCallbacks","existingInstance","invokeOnInitCallbacks","callbacks","_ref","ComponentContainer","providers","addComponent","provider","getProvider","addOrOverwriteComponent","getProviders","LogLevel","levelStringToEnum","DEBUG","VERBOSE","INFO","WARN","ERROR","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","logType","logLevel","toISOString","_len","args","_key","Logger","_logLevel","_logHandler","_userLogHandler","val","TypeError","setLogLevel","logHandler","userLogHandler","debug","_len2","_key2","_len3","_key3","_len4","_key4","warn","_len5","_key5","_len6","_key6","instanceOfAny","object","constructors","idbProxyableTypes","cursorAdvanceMethods","cursorRequestMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","idbProxyTraps","receiver","IDBTransaction","objectStoreNames","objectStore","wrap","wrapFunction","func","IDBDatabase","transaction","IDBCursor","advance","continue","continuePrimaryKey","unwrap","storeNames","tx","sort","transformCachableValue","unlisten","DOMException","cacheDonePromiseForTransaction","IDBObjectStore","IDBIndex","Proxy","IDBRequest","success","promisifyRequest","newValue","readMethods","writeMethods","cachedMethods","getMethod","targetFuncName","useIndex","isWrite","async","storeName","store","oldTraps","PlatformLoggerServiceImpl","getPlatformInfoString","isVersionServiceProvider","library","logString","logger","PLATFORM_LOG_STRING","name$o","_apps","_components","_addComponent","app","_registerComponent","componentName","_getProvider","heartbeatController","triggerHeartbeat","ERROR_FACTORY","FirebaseAppImpl","_isDeleted","_options","_config","_name","_automaticDataCollectionEnabled","automaticDataCollectionEnabled","_container","checkDestroyed","isDeleted","appName","SDK_VERSION","initializeApp","rawConfig","existingApp","newApp","getApp","registerVersion","libraryKeyOrName","variant","libraryMismatch","versionMismatch","warning","DB_NAME","DB_VERSION","STORE_NAME","dbPromise","getDbPromise","blocked","upgrade","blocking","terminated","openPromise","oldVersion","newVersion","openDB","createObjectStore","originalErrorMessage","writeHeartbeatsToIndexedDB","heartbeatObject","put","computeKey","idbGetError","appId","HeartbeatServiceImpl","_heartbeatsCache","_storage","HeartbeatStorageImpl","_heartbeatsCachePromise","read","agent","getUTCDateString","heartbeats","lastSentHeartbeatDate","singleDateHeartbeat","hbTimestamp","overwrite","getHeartbeatsHeader","heartbeatsToSend","unsentEntries","heartbeatsCache","maxSize","heartbeatEntry","find","dates","countBytes","extractHeartbeatsForHeader","headerString","_canUseIndexedDBPromise","runIndexedDBEnvironmentCheck","idbHeartbeatObject","readHeartbeatsFromIndexedDB","heartbeatsObject","existingHeartbeatsObject","version$1","replaceTraps","PENDING_TIMEOUT_MS","PACKAGE_VERSION","INTERNAL_AUTH_VERSION","INSTALLATIONS_API_URL","TOKEN_EXPIRATION_BUFFER","isServerError","getInstallationsEndpoint","projectId","extractAuthTokenInfoFromResponse","response","requestStatus","expiresIn","responseExpiresIn","Number","creationTime","getErrorFromResponse","requestName","errorData","json","serverCode","serverMessage","serverStatus","status","getHeaders","_ref2","apiKey","Headers","Accept","getHeadersWithAuth","appConfig","_ref3","refreshToken","headers","append","getAuthorizationHeader","retryIfServerError","sleep","ms","VALID_FID_PATTERN","INVALID_FID","generateFid","fidByteArray","Uint8Array","crypto","msCrypto","getRandomValues","fid","b64String","array","substr","encode","getKey","fidChangeCallbacks","fidChanged","callFidChangeCallbacks","channel","getBroadcastChannel","closeBroadcastChannel","broadcastFidChange","broadcastChannel","BroadcastChannel","DATABASE_NAME","DATABASE_VERSION","OBJECT_STORE_NAME","oldValue","remove","update","updateFn","getInstallationEntry","installations","registrationPromise","installationEntry","oldEntry","entry","registrationStatus","clearTimedOutRequest","updateOrCreateInstallationEntry","entryWithPromise","onLine","inProgressEntry","registrationTime","registeredInstallationEntry","_ref4","_ref5","heartbeatServiceProvider","endpoint","heartbeatService","heartbeatsHeader","authVersion","sdkVersion","fetch","responseValue","authToken","createInstallationRequest","registerInstallation","waitUntilFidRegistration","triggerRegistrationIfNecessary","updateInstallationRequest","generateAuthTokenRequest","_ref6","_ref7","getGenerateAuthTokenEndpoint","installation","refreshAuthToken","tokenPromise","forceRefresh","isEntryRegistered","oldAuthToken","isAuthTokenExpired","isAuthTokenValid","updateAuthTokenRequest","waitUntilAuthTokenRequest","inProgressAuthToken","requestTime","makeAuthTokenRequestInProgressEntry","updatedInstallationEntry","fetchAuthTokenFromServer","getToken","installationsImpl","completeInstallationRegistration","getMissingValueError","valueName","INSTALLATIONS_NAME","publicFactory","configKeys","keyName","extractAppConfig","internalFactory","getId","ANALYTICS_TYPE","GA_FID_KEY","ORIGIN_KEY","FETCH_TIMEOUT_MILLIS","DYNAMIC_CONFIG_URL","GTAG_URL","createGtagTrustedTypesScriptURL","startsWith","gtagURL","promiseAllSettled","insertScriptTag","dataLayerName","measurementId","trustedTypesPolicy","policyName","policyOptions","trustedTypes","createPolicy","createTrustedTypesPolicy","createScriptURL","gtagScriptURL","wrapGtag","gtagCore","initializationPromisesMap","dynamicConfigPromisesList","measurementIdToAppId","command","gtagParams","initializationPromisesToWaitFor","gaSendToList","dynamicConfigResults","sendToId","foundConfig","initializationPromise","gtagOnEvent","correspondingAppId","gtagOnConfig","fieldName","customParams","LONG_RETRY_FACTOR","defaultRetryData","throttleMetadata","intervalMillis","getThrottleMetadata","setThrottleMetadata","metadata","deleteThrottleMetadata","fetchDynamicConfigWithRetry","retryData","timeoutMillis","throttleEndTimeMillis","signal","AnalyticsAbortSignal","abort","attemptFetchDynamicConfigWithRetry","appFields","backoffMillis","max","setAbortableTimeout","appUrl","errorMessage","jsonResponse","_ignored","httpStatus","responseMessage","fetchDynamicConfig","isRetriableError","defaultEventParametersForInit","defaultConsentSettingsForInit","_setConsentDefaultForInit","consentSettings","_setDefaultEventParametersForInit","_initializeAnalytics","dynamicConfigPromise","fidPromise","errorInfo","validateIndexedDB","envIsValid","dynamicConfig","scriptTags","findGtagScriptOnPage","configProperties","AnalyticsService","gtagCoreFunction","wrappedGtagFunction","gtagName","globalInitDone","warnOnBrowserContextMismatch","mismatchedEnvMessages","cookieEnabled","details","factory","dataLayer","getOrCreateDataLayer","wrappedGtag","gtagFunctionName","_args","wrapOrCreateGtag","logEvent","analyticsInstance","eventName","eventParams","gtagFunction","logEvent$1","analyticsOptions","analytics","reason","__rest","getOwnPropertySymbols","propertyIsEnumerable","SuppressedError","_prodErrorMap","prodErrorMap","_DEFAULT_AUTH_ERROR_FACTORY","logClient","_logError","msg","_fail","authOrCode","rest","createErrorInternal","_createError","_errorWithCustomMessage","auth","errorMap","fullParams","_errorFactory","_assert","assertion","_key7","debugFail","failure","debugAssert","_getCurrentUrl","_isHttpOrHttps","_getCurrentScheme","protocol","Delay","shortDelay","longDelay","isMobile","_emulatorUrl","path","emulator","FetchProvider","fetchImpl","headersImpl","responseImpl","Response","SERVER_ERROR_MAP","DEFAULT_API_TIMEOUT_MS","_addTidIfNecessary","tenantId","_performApiRequest","_performFetchWithErrorHandling","query","_getAdditionalHeaders","languageCode","_getFinalTarget","apiHost","referrerPolicy","customErrorMap","fetchFn","_canInitEmulator","networkTimeout","NetworkTimeout","race","clearNetworkTimeout","_makeTaggedError","serverErrorCode","serverErrorMessage","authError","_performSignInRequest","serverResponse","_serverResponse","host","apiScheme","_parseEnforcementState","enforcementStateStr","timer","errorParams","phoneNumber","_tokenResponse","isEnterprise","grecaptcha","enterprise","RecaptchaConfig","siteKey","recaptchaEnforcementState","recaptchaKey","getProviderEnforcementState","providerStr","enforcementState","isProviderEnabled","getRecaptchaConfig","utcTimestampToDateString","utcTimestamp","getTime","toUTCString","secondsStringToMilliseconds","seconds","_parseToken","algorithm","signature","_logoutIfInvalidated","user","isUserInvalidated","currentUser","signOut","ProactiveRefresh","isRunning","timerId","errorBackoff","_start","schedule","_stop","getInterval","wasError","interval","stsTokenManager","iteration","getIdToken","UserMetadata","createdAt","lastLoginAt","_initializeTime","lastSignInTime","_copy","toJSON","_reloadWithoutSaving","idToken","getAccountInfo","users","coreAccount","_notifyReloadListener","newProviderData","providerUserInfo","providerId","uid","rawId","photoURL","photoUrl","providerData","original","newData","oldIsAnonymous","isAnonymous","newIsAnonymous","passwordHash","updates","localId","emailVerified","StsTokenManager","accessToken","isExpired","updateFromServerResponse","parsedToken","exp","iat","_tokenExpiresIn","updateTokensAndExpiration","refresh","clearRefreshToken","oldToken","tokenApiHost","access_token","expires_in","refresh_token","requestStsToken","expiresInSec","fromJSON","manager","_assign","_clone","_performRefresh","assertStringOrUndefined","UserImpl","opt","proactiveRefresh","reloadUserInfo","reloadListener","_persistUserIfCurrent","_notifyListenersIfCurrent","getIdTokenResult","userInternal","claims","auth_time","firebase","signInProvider","authTime","issuedAtTime","signInSecondFactor","reload","userInfo","newUser","_onReload","_startProactiveRefresh","_stopProactiveRefresh","_updateTokensIfNecessary","tokensRefreshed","deleteAccount","_redirectEventId","_fromJSON","_c","_d","_e","_f","_g","_h","plainObjectTokenManager","_fromIdTokenResponse","idTokenResponse","instanceCache","_getInstance","cls","InMemoryPersistence","storage","_isAvailable","_set","_get","_remove","_addListener","_listener","_removeListener","inMemoryPersistence","_persistenceKeyName","PersistenceUserManager","persistence","userKey","fullUserKey","fullPersistenceKey","boundEventHandler","_onStorageEvent","setCurrentUser","getCurrentUser","blob","removeCurrentUser","savePersistenceForRedirect","setPersistence","newPersistence","persistenceHierarchy","availablePersistences","selectedPersistence","userToMigrate","migrationHierarchy","_shouldAllowMigration","_getBrowserName","userAgent","_isIEMobile","_isFirefox","_isBlackBerry","_isWebOS","_isSafari","_isChromeIOS","_isAndroid","matches","_isIOS","_isIE10","isIE","_isMobileBrowser","_getClientVersion","clientPlatform","reportedPlatform","frameworks","reportedFrameworks","AuthMiddlewareQueue","pushCallback","onAbort","wrappedCallback","runMiddleware","nextUser","onAbortStack","beforeStateCallback","reverse","originalMessage","PasswordPolicyImpl","responseOptions","customStrengthOptions","minPasswordLength","maxPasswordLength","containsLowercaseCharacter","containsLowercaseLetter","containsUppercaseCharacter","containsUppercaseLetter","containsNumericCharacter","containsNonAlphanumericCharacter","allowedNonAlphanumericCharacters","forceUpgradeOnSignin","schemaVersion","validatePassword","isValid","passwordPolicy","validatePasswordLengthOptions","validatePasswordCharacterOptions","meetsMinPasswordLength","meetsMaxPasswordLength","passwordChar","updatePasswordCharacterOptionsStatuses","AuthImpl","appCheckServiceProvider","emulatorConfig","operations","authStateSubscription","Subscription","idTokenSubscription","beforeStateQueue","redirectUser","isProactiveRefreshEnabled","EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION","_isInitialized","_deleted","_initializationPromise","_popupRedirectResolver","_agentRecaptchaConfig","_tenantRecaptchaConfigs","_projectPasswordPolicy","_tenantPasswordPolicies","lastNotifiedUid","settings","appVerificationDisabledForTesting","clientVersion","sdkClientVersion","_initializeWithPersistence","popupRedirectResolver","persistenceManager","_shouldInitProactively","_initialize","initializeCurrentUser","assertedPersistence","_currentUser","_updateCurrentUser","previouslyStoredUser","futureCurrentUser","needsTocheckMiddleware","authDomain","getOrInitRedirectPersistenceManager","redirectUserEventId","storedUserEventId","tryRedirectSignIn","directlySetCurrentUser","_overrideRedirectResult","reloadAndSetCurrentUserOrClear","redirectResolver","_completeRedirectFn","_setRedirectUser","useDeviceLanguage","navigatorLanguage","languages","language","_getUserLanguage","updateCurrentUser","userExtern","skipBeforeStateCallbacks","notifyAuthListeners","redirectPersistenceManager","_getRecaptchaConfig","_getPasswordPolicyInternal","_updatePasswordPolicy","_getPasswordPolicy","_getPersistence","_updateErrorMap","onAuthStateChanged","completed","registerStateListener","beforeAuthStateChanged","onIdTokenChanged","authStateReady","unsubscribe","revokeAccessToken","tokenType","revokeToken","redirectManager","resolver","_redirectPersistence","_redirectUserForId","currentUid","subscription","isUnsubscribed","addObserver","_logFramework","framework","_getFrameworks","appCheckToken","_getAppCheckToken","appCheckTokenResult","_logWarn","_castAuth","proxy","createSubscribe","_loadJS","getScriptParentElement","_generateCallbackName","prefix","RecaptchaEnterpriseVerifier","authExtern","verify","retrieveRecaptchaToken","ready","execute","clientType","retrieveSiteKey","injectRecaptchaFields","captchaResp","verifier","captchaResponse","newRequest","handleRecaptchaFlow","authInstance","actionName","actionMethod","requestWithRecaptcha","connectAuthEmulator","authInternal","disableWarnings","extractProtocol","port","authority","exec","hostAndPort","bracketedIPv6","parsePort","extractHostAndPort","portStr","freeze","attachBanner","sty","innerText","position","backgroundColor","border","bottom","margin","textAlign","classList","readyState","emitEmulatorWarning","protocolEnd","AuthCredential","signInMethod","_getIdTokenResponse","_auth","_linkToIdToken","_idToken","_getReauthenticationResolver","linkEmailPassword","signInWithPassword","EmailAuthCredential","_email","_password","_tenantId","_fromEmailAndPassword","_fromEmailAndCode","oobCode","returnSecureToken","signInWithEmailLink$1","signInWithEmailLinkForLinking","signInWithIdp","OAuthCredential","pendingToken","_fromParams","cred","nonce","oauthToken","oauthTokenSecret","secret","buildRequest","autoCreate","requestUri","postBody","VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_","PhoneAuthCredential","_fromVerification","verificationId","verificationCode","_fromTokenResponse","temporaryProof","signInWithPhoneNumber$1","_makeVerificationRequest","linkWithPhoneNumber$1","operation","verifyPhoneNumberForExisting","sessionInfo","ActionCodeURL","actionLink","searchParams","parseMode","continueUrl","parseLink","doubleDeepLink","iOSDeepLink","parseDeepLink","EmailAuthProvider","PROVIDER_ID","credential","credentialWithLink","emailLink","actionCodeUrl","EMAIL_PASSWORD_SIGN_IN_METHOD","EMAIL_LINK_SIGN_IN_METHOD","FederatedAuthProvider","defaultLanguageCode","customParameters","setDefaultLanguage","setCustomParameters","customOAuthParameters","getCustomParameters","BaseOAuthProvider","scopes","addScope","scope","getScopes","FacebookAuthProvider","FACEBOOK_SIGN_IN_METHOD","credentialFromResult","userCredential","credentialFromTaggedObject","credentialFromError","tokenResponse","oauthAccessToken","GoogleAuthProvider","GOOGLE_SIGN_IN_METHOD","oauthIdToken","GithubAuthProvider","GITHUB_SIGN_IN_METHOD","TwitterAuthProvider","TWITTER_SIGN_IN_METHOD","signUp","UserCredentialImpl","operationType","providerIdForResponse","_forOperation","MultiFactorError","_fromErrorAndOperation","_processCredentialSavingMfaContextIfNecessary","_link$1","bypassAuthState","_reauthenticate","parsed","sub","_signInWithCredential","recachePasswordPolicy","STORAGE_AVAILABLE_KEY","BrowserPersistenceClass","storageRetriever","setItem","removeItem","getItem","BrowserLocalPersistence","localStorage","poll","onStorageEvent","localCache","pollTimer","safariLocalStorageNotSynced","_iframeCannotSyncWebStorage","_isIframe","fallbackToPolling","forAllChangedKeys","_oldValue","notifyListeners","detachListener","stopPolling","storedValue","triggerListeners","startPolling","setInterval","StorageEvent","clearInterval","attachListener","browserLocalPersistence","BrowserSessionPersistence","sessionStorage","browserSessionPersistence","Receiver","eventTarget","handlersMap","handleEvent","receivers","isListeningto","newInstance","messageEvent","eventId","eventType","handlers","ports","handler","origin","fulfilled","_allSettled","_subscribe","eventHandler","_unsubscribe","_generateEventId","digits","Sender","removeMessageHandler","messageChannel","onMessage","_send","completionTimer","ackTimer","finally","_window","_isWorker","DB_OBJECTSTORE_NAME","DB_DATA_KEYPATH","DBPromise","toPromise","getObjectStore","isReadWrite","_openDatabase","keyPath","_deleteDatabase","_putObject","_deleteObject","IndexedDBLocalPersistence","pendingWrites","sender","serviceWorkerReceiverAvailable","activeServiceWorker","_workerInitializationPromise","initializeServiceWorkerMessaging","_openDb","_withRetries","op","numAttempts","initializeReceiver","initializeSender","_origin","keyProcessed","_poll","_data","serviceWorker","active","_getActiveServiceWorker","results","notifyServiceWorker","controller","_getServiceWorkerController","_withPendingWrite","write","getObject","getAllRequest","getAll","keysInResult","fbase_key","localKey","indexedDBLocalPersistence","RECAPTCHA_VERIFIER_TYPE","_verifyPhoneNumber","recaptchaToken","phoneInfoOptions","session","startEnrollPhoneMfa","phoneEnrollmentInfo","phoneSessionInfo","mfaEnrollmentId","multiFactorHint","multiFactorUid","startSignInPhoneMfa","mfaPendingCredential","phoneSignInInfo","phoneResponseInfo","sendPhoneVerificationCode","_reset","PhoneAuthProvider","verifyPhoneNumber","phoneOptions","applicationVerifier","_ref12","_withDefaultResolver","resolverOverride","PHONE_SIGN_IN_METHOD","IdpCredential","_buildIdpRequest","sessionId","returnIdpCredential","_signIn","_reauth","_link","AbstractPopupRedirectOperation","pendingPromise","eventManager","onExecution","registerConsumer","onAuthEvent","urlResponse","getIdpTask","unregisterAndCleanUp","unregisterConsumer","cleanUp","_POLL_WINDOW_CLOSE_TIMEOUT","PopupOperation","authWindow","pollId","currentPopupAction","cancel","executeNotNull","_openPopup","associatedEvent","_originValidation","_isIframeWebStorageSupported","isSupported","pollUserCancellation","closed","PENDING_REDIRECT_KEY","redirectOutcomeMap","RedirectAction","readyOutcome","hasPendingRedirect","pendingRedirectKey","resolverPersistence","_getAndClearPendingRedirectStatus","_getRedirectResult","resolverExtern","AuthEventManager","cachedEventUids","consumers","queuedRedirectEvent","hasHandledPotentialRedirect","lastProcessedEventTime","authEventConsumer","isEventForConsumer","sendToConsumer","saveEventToCache","onEvent","hasEventBeenHandled","handled","consumer","isNullRedirectEvent","isRedirectEvent","eventIdMatches","clear","eventUid","_ref13","IP_ADDRESS_REGEX","HTTP_REGEX","_validateOrigin","authorizedDomains","_getProjectConfig","domain","matchDomain","expected","currentUrl","hostname","URL","ceUrl","escapedDomainPattern","RegExp","NETWORK_TIMEOUT","resetUnloadedGapiModules","beacon","___jsl","hint","CP","cachedGApiLoader","_loadGapi","loadGapiIframe","gapi","load","iframes","getContext","ontimeout","Iframe","cbName","loadGapi","PING_TIMEOUT","IFRAME_PATH","EMULATED_IFRAME_PATH","IFRAME_ATTRIBUTES","tabindex","EID_FROM_APIHOST","getIframeUrl","eid","fw","BASE_POPUP_OPTIONS","resizable","statusbar","toolbar","AuthPopup","_open","screen","availHeight","availWidth","scrollbars","optionsString","accum","_ref14","standalone","_isIOSStandalone","click","createEvent","initMouseEvent","openAsNewWindowIOS","newWin","WIDGET_PATH","EMULATOR_WIDGET_PATH","FIREBASE_APP_CHECK_FRAGMENT_ID","_getRedirectUrl","authType","redirectUrl","additionalParams","isEmpty","tid","paramsDict","appCheckTokenFragment","_ref15","getHandlerBase","WEB_STORAGE_SUPPORT_KEY","browserPopupRedirectResolver","eventManagers","originValidationPromises","_openRedirect","_setWindowLocation","initAndGetManager","iframe","where","messageHandlersFilter","CROSS_ORIGIN_IFRAMES_FILTER","attributes","dontclear","restyle","setHideOnLeave","networkError","networkErrorTimer","clearTimerAndResolve","ping","_openIframe","register","iframeEvent","authEvent","send","AuthInterop","internalListeners","getUid","assertAuthConfigured","addAuthTokenListener","updateProactiveRefresh","removeAuthTokenListener","authIdTokenMaxAge","lastPostedIdToken","_ref16","hierarchy","_initializeAuthInstance","_instanceIdentifier","_instance","getVersionForPlatform","goog","commonjsGlobal","$","parseFloat","parseInt","once","addListener","removeListener","reset","initializeRunner","module$contents$goog$async$run_run.processWorkQueue","ga","STAT_EVENT","stat","NO_ERROR","TIMEOUT","OPEN","XMLHttpRequest","getResponseHeader","TextDecoder","decode","stream","getAllResponseHeaders","abs","decodeURI","encodeURI","PerformanceNavigationTiming","getEntriesByType","nextHopProtocol","onabort","responseType","responseText","statusText","onreadystatechange","credentials","Request","arrayBuffer","ReadableStream","getReader","setRequestHeader","mozResponseArrayBuffer","Cd","internalChannelParams","Ed","xmlHttpFactory","useFetchStreams","supportsCrossDomainXhr","concurrentRequestLimit","fastHandshake","encodeInitMessageHeaders","forceLongPolling","detectBufferingProxy","longPollingTimeout","Gd","sendBeacon","Image","Kd","isActive","messageUrlParams","messageHeaders","clientProtocolHeaderRequired","initMessageHeaders","messageContentType","sendRawJson","httpSessionIdParam","__headers__","statusCode","__status__","__sm__","blockSize","Sd","FormData","withCredentials","__data__","isFinite","Ud","Wd","and","or","xor","createWebChannel","HTTP_ERROR","COMPLETE","EventType","CLOSE","MESSAGE","listen","listenOnce","getLastError","getLastErrorCode","getStatus","getResponseJson","getResponseText","setWithCredentials","multiply","modulo","toNumber","getBits","fromNumber","fromString","createWebChannelTransport","esm","getStatEventTarget","ErrorCode","Event","Stat","PROXY","NOPROXY","FetchXmlHttpFactory","WebChannel","XhrIo","Md5","Integer","User","isAuthenticated","toKey","isEqual","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","__PRIVATE_getLogLevel","__PRIVATE_logDebug","__PRIVATE_argToString","__PRIVATE_logError","__PRIVATE_logWarn","fail","__PRIVATE_hardAssert","__PRIVATE_debugCast","OK","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","UNAVAILABLE","DATA_LOSS","FirestoreError","__PRIVATE_Deferred","__PRIVATE_OAuthToken","__PRIVATE_EmptyAuthCredentialsProvider","invalidateToken","enqueueRetryable","shutdown","__PRIVATE_EmulatorAuthCredentialsProvider","changeListener","__PRIVATE_FirebaseAuthCredentialsProvider","__PRIVATE_guardedChangeListener","__PRIVATE_awaitNextToken","__PRIVATE_registerAuth","__PRIVATE_FirstPartyToken","__PRIVATE_FirstPartyAuthCredentialsProvider","AppCheckToken","__PRIVATE_FirebaseAppCheckTokenProvider","appCheck","onTokenChanged","__PRIVATE_registerAppCheck","addTokenListener","removeTokenListener","__PRIVATE_randomBytes","__PRIVATE_AutoId","newId","__PRIVATE_primitiveComparator","__PRIVATE_arrayEquals","every","Timestamp","nanoseconds","fromMillis","fromDate","toDate","toMillis","_compareTo","padStart","SnapshotVersion","timestamp","fromTimestamp","compareTo","toMicroseconds","toTimestamp","BasePath","segments","len","comparator","limit","popFirst","popLast","firstSegment","lastSegment","isPrefixOf","isImmediateParentOf","ResourcePath","canonicalString","emptyPath","FieldPath$1","isValidIdentifier","isKeyField","keyField","fromServerFormat","__PRIVATE_addCurrentSegment","DocumentKey","fromPath","fromName","empty","collectionGroup","hasCollectionId","getCollectionGroup","getCollectionPath","isDocumentKey","fromSegments","FieldIndex","indexId","fields","indexState","UNKNOWN_ID","__PRIVATE_newIndexOffsetSuccessorFromReadTime","IndexOffset","__PRIVATE_newIndexOffsetFromDocument","readTime","documentKey","largestBatchId","__PRIVATE_indexOffsetComparator","PersistenceTransaction","onCommittedListeners","addOnCommittedListener","raiseOnCommittedEvent","__PRIVATE_ignoreIfPrimaryLeaseLoss","PersistencePromise","nextCallback","catchCallback","isDone","callbackAttached","wrapFailure","wrapSuccess","wrapUserFunction","waitFor","mapArray","doWhile","__PRIVATE_isIndexedDbTransactionError","__PRIVATE_ListenSequence","previousValue","sequenceNumberHandler","writeSequenceNumber","__PRIVATE_isNullOrUndefined","__PRIVATE_isNegativeZero","isSafeInteger","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","__PRIVATE_objectSize","SortedMap","root","LLRBNode","EMPTY","insert","copy","BLACK","right","minKey","maxKey","inorderTraversal","reverseTraversal","getIterator","SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","isReverse","nodeStack","getNext","hasNext","peek","RED","fixUp","removeMin","isRed","moveRedLeft","rotateRight","moveRedRight","rotateLeft","colorFlip","checkMaxDepth","check","SortedSet","first","forEachInRange","forEachWhile","firstAfterOrEqual","SortedSetIterator","unionWith","iter","FieldMask","covers","__PRIVATE_Base64DecodeError","ByteString","binaryString","fromBase64String","fromUint8Array","toBase64","toUint8Array","approximateByteSize","EMPTY_BYTE_STRING","__PRIVATE_normalizeTimestamp","nanos","__PRIVATE_normalizeNumber","__PRIVATE_normalizeByteString","__PRIVATE_isServerTimestamp","mapValue","__type__","stringValue","__PRIVATE_getPreviousValue","__previous_value__","__PRIVATE_getLocalWriteTime","__local_write_time__","timestampValue","DatabaseInfo","databaseId","persistenceKey","ssl","autoDetectLongPolling","longPollingOptions","DatabaseId","database","isDefaultDatabase","__PRIVATE_typeOrder","__PRIVATE_isMaxValue","__PRIVATE_valueEquals","booleanValue","bytesValue","referenceValue","geoPointValue","latitude","longitude","integerValue","doubleValue","arrayValue","__PRIVATE_arrayValueContains","__PRIVATE_valueCompare","__PRIVATE_compareTimestamps","canonicalId","__PRIVATE_canonifyValue","__PRIVATE_refValue","__PRIVATE_isNullValue","__PRIVATE_isNanValue","__PRIVATE_isMapValue","__PRIVATE_deepClone","ObjectValue","field","getFieldsMap","setAll","applyChanges","clone","__PRIVATE_extractFieldMask","MutableDocument","documentType","createTime","documentState","newInvalidDocument","newFoundDocument","newNoDocument","newUnknownDocument","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","Bound","inclusive","__PRIVATE_boundCompareToDocument","dir","__PRIVATE_boundEquals","OrderBy","__PRIVATE_orderByEquals","Filter","FieldFilter","createKeyFieldInFilter","__PRIVATE_KeyFieldFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","__PRIVATE_NotInFilter","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_KeyFieldInFilter","__PRIVATE_KeyFieldNotInFilter","matchesComparison","isInequality","getFlattenedFilters","getFilters","CompositeFilter","filters","__PRIVATE_compositeFilterIsConjunction","__PRIVATE_compositeFilterIsFlatConjunction","__PRIVATE_compositeFilterIsFlat","__PRIVATE_canonifyFilter","__PRIVATE_filterEquals","__PRIVATE_stringifyFilter","__PRIVATE_extractDocumentKeysFromArrayValue","nullValue","__PRIVATE_TargetImpl","orderBy","startAt","endAt","__PRIVATE_newTarget","__PRIVATE_canonifyTarget","__PRIVATE_targetEquals","__PRIVATE_targetIsDocumentTarget","__PRIVATE_QueryImpl","explicitOrderBy","limitType","__PRIVATE_newQuery","__PRIVATE_newQueryForPath","__PRIVATE_queryMatchesAllDocuments","__PRIVATE_isCollectionGroupQuery","__PRIVATE_queryNormalizedOrderBy","__PRIVATE_queryToTarget","__PRIVATE__queryToTarget","__PRIVATE_queryWithAddedFilter","__PRIVATE_queryWithLimit","__PRIVATE_queryEquals","__PRIVATE_canonifyQuery","__PRIVATE_stringifyQuery","__PRIVATE_queryMatches","__PRIVATE_queryCollectionGroup","__PRIVATE_newQueryComparator","__PRIVATE_compareDocs","ObjectMap","mapKeyFn","equalsFn","inner","innerSize","__PRIVATE_mutableDocumentMap","documentMap","__PRIVATE_convertOverlayedDocumentMapToDocumentMap","overlayedDocument","__PRIVATE_newOverlayMap","__PRIVATE_newDocumentKeyMap","__PRIVATE_newMutationMap","__PRIVATE_documentKeySet","__PRIVATE_targetIdSet","__PRIVATE_toDouble","useProto3Json","__PRIVATE_toInteger","TransformOperation","__PRIVATE_applyTransformOperationToLocalView","__PRIVATE_ServerTimestampTransform","__PRIVATE_ArrayUnionTransformOperation","__PRIVATE_applyArrayUnionTransformOperation","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_applyArrayRemoveTransformOperation","__PRIVATE_computeTransformOperationBaseValue","asNumber","serializer","__PRIVATE_applyTransformOperationToRemoteDocument","__PRIVATE_NumericIncrementTransformOperation","elements","__PRIVATE_coercedFieldValuesArray","MutationResult","transformResults","Precondition","updateTime","exists","none","isNone","__PRIVATE_preconditionIsValidForDocument","Mutation","__PRIVATE_calculateOverlayMutation","__PRIVATE_DeleteMutation","__PRIVATE_SetMutation","__PRIVATE_PatchMutation","__PRIVATE_mutationApplyToRemoteDocument","__PRIVATE_serverTransformResults","fieldTransforms","precondition","__PRIVATE_getPatch","__PRIVATE_mutationApplyToLocalView","__PRIVATE_localTransformResults","fieldMask","__PRIVATE_mutationExtractBaseValue","transform","__PRIVATE_mutationEquals","__PRIVATE_fieldTransformEquals","getFieldMask","__PRIVATE_VerifyMutation","MutationBatch","batchId","localWriteTime","baseMutations","mutations","applyToRemoteDocument","mutationResults","applyToLocalView","applyToLocalDocumentSet","mutatedFields","MutationBatchResult","batch","commitVersion","docVersions","Overlay","mutation","ExistenceFilter","unchangedNames","__PRIVATE_isPermanentError","__PRIVATE_mapCodeFromRpcCode","__PRIVATE_newTextEncoder","TextEncoder","__PRIVATE_getMd5HashValue","__PRIVATE_get64BitUints","DataView","buffer","getUint32","BloomFilter","bitmap","padding","hashCount","__PRIVATE_BloomFilterError","mightContain","RemoteEvent","snapshotVersion","targetChanges","targetMismatches","documentUpdates","resolvedLimboDocuments","createSynthesizedRemoteEventForCurrentChange","TargetChange","createSynthesizedTargetChangeForCurrentChange","resumeToken","addedDocuments","modifiedDocuments","removedDocuments","__PRIVATE_DocumentWatchChange","removedTargetIds","__PRIVATE_ExistenceFilterChange","targetId","__PRIVATE_WatchTargetChange","targetIds","cause","__PRIVATE_TargetState","__PRIVATE_snapshotChangesMap","__PRIVATE_WatchChangeAggregator","__PRIVATE_documentTargetMap","Ge","forEachTarget","removeTarget","et","tt","localCacheCount","existenceFilterCount","bloomFilter","applied","bitmapLength","bits","nt","rt","getRemoteKeysForTarget","it","st","purpose","ot","_t","asc","desc","in","JsonProtoSerializer","__PRIVATE_toInt32Proto","__PRIVATE_toBytes","__PRIVATE_toVersion","__PRIVATE_fromVersion","__PRIVATE_toResourceName","__PRIVATE_fromResourceName","__PRIVATE_isValidResourceName","__PRIVATE_toName","__PRIVATE_extractLocalPathFromResourceName","__PRIVATE_toQueryPath","__PRIVATE_fromQueryPath","__PRIVATE_getEncodedDatabaseId","__PRIVATE_toMutationDocument","toMutation","updateMask","__PRIVATE_toDocumentMask","updateTransforms","fieldPath","setToServerValue","appendMissingElements","removeAllFromArray","increment","currentDocument","__PRIVATE_toDocumentsTarget","documents","__PRIVATE_toQueryTarget","structuredQuery","parent","collectionId","allDescendants","__PRIVATE_toFilter","__PRIVATE_toFieldPathReference","direction","__PRIVATE_toDirection","before","__PRIVATE_convertQueryTargetToQuery","__PRIVATE_fromFilter","__PRIVATE_fromFieldPathReference","unaryFilter","NaN","fieldFilter","compositeFilter","__PRIVATE_toOperatorName","__PRIVATE_toCompositeOperatorName","fieldPaths","TargetData","sequenceNumber","lastLimboFreeSnapshotVersion","expectedCount","withSequenceNumber","withResumeToken","withExpectedCount","withLastLimboFreeSnapshotVersion","__PRIVATE_LocalSerializer","ut","__PRIVATE_fromBundledQuery","__PRIVATE_FirestoreIndexValueWriter","ht","Pt","It","Tt","Et","dt","At","Rt","Vt","ft","gt","yt","wt","St","__PRIVATE_MemoryIndexManager","on","__PRIVATE_MemoryCollectionParentIndex","addToCollectionParentIndex","getCollectionParents","getEntries","addFieldIndex","deleteFieldIndex","deleteAllFieldIndexes","createTargetIndexes","getDocumentsMatchingTarget","getIndexType","getFieldIndexes","getNextCollectionGroupToUpdate","getMinOffset","getMinOffsetFromCollectionGroup","updateCollectionGroup","updateIndexEntries","LruParams","cacheSizeCollectionThreshold","percentileToCollect","maximumSequenceNumbersToCollect","withCacheSize","DEFAULT_COLLECTION_PERCENTILE","DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT","DEFAULT","DISABLED","__PRIVATE_TargetIdGenerator","xn","On","Nn","RemoteDocumentChangeBuffer","changes","changesApplied","addEntry","assertNotApplied","removeEntry","getEntry","getFromCache","getAllFromCache","OverlayedDocument","LocalDocumentsView","remoteDocumentCache","mutationQueue","documentOverlayCache","indexManager","getDocument","getOverlay","getDocuments","getLocalViewOfDocuments","populateOverlays","computeViews","getOverlayedDocuments","getOverlays","recalculateAndSaveOverlays","getAllMutationBatchesAffectingDocumentKeys","saveOverlays","recalculateAndSaveOverlaysForDocumentKeys","getDocumentsMatchingQuery","getDocumentsMatchingDocumentQuery","getDocumentsMatchingCollectionGroupQuery","getDocumentsMatchingCollectionQuery","getNextDocuments","getAllFromCollectionGroup","getOverlaysForCollectionGroup","getOverlaysForCollection","__PRIVATE_MemoryBundleCache","ur","cr","getBundleMetadata","saveBundleMetadata","getNamedQuery","saveNamedQuery","bundledQuery","__PRIVATE_MemoryDocumentOverlayCache","overlays","lr","lt","removeOverlaysForBatchId","__PRIVATE_ReferenceSet","__PRIVATE_DocReference","Pr","Ir","Tr","addReference","Er","removeReference","dr","Ar","Rr","Vr","mr","containsKey","gr","__PRIVATE_MemoryMutationQueue","referenceDelegate","pr","yr","checkEmpty","addMutationBatch","lookupMutationBatch","wr","getNextMutationBatchAfterBatchId","Sr","getHighestUnacknowledgedBatchId","getAllMutationBatches","getAllMutationBatchesAffectingDocumentKey","POSITIVE_INFINITY","getAllMutationBatchesAffectingQuery","removeMutationBatch","Dr","markPotentiallyOrphaned","Fn","performConsistencyCheck","__PRIVATE_MemoryRemoteDocumentCacheImpl","Cr","docs","setIndexManager","vr","newChangeBuffer","__PRIVATE_MemoryRemoteDocumentChangeBuffer","getSize","_r","__PRIVATE_MemoryTargetCache","Fr","lastRemoteSnapshotVersion","highestTargetId","Mr","Or","targetCount","Nr","getLastRemoteSnapshotVersion","getHighestSequenceNumber","allocateTargetId","setTargetsMetadata","kn","addTargetData","updateTargetData","removeTargetData","removeTargets","removeMatchingKeysForTargetId","getTargetCount","getTargetData","addMatchingKeys","removeMatchingKeys","getMatchingKeysForTargetId","__PRIVATE_MemoryPersistence","Br","Lr","kr","qr","Qr","Kr","started","setDatabaseDeletedListener","setNetworkEnabled","getIndexManager","getDocumentOverlayCache","getMutationQueue","getTargetCache","getRemoteDocumentCache","getBundleCache","runTransaction","__PRIVATE_MemoryTransaction","$r","Ur","Wr","currentSequenceNumber","__PRIVATE_MemoryEagerDelegate","Gr","zr","jr","Hr","Jr","updateLimboDocument","__PRIVATE_LocalViewChanges","fromCache","docChanges","doc","QueryContext","_documentReadCount","documentReadCount","incrementDocumentReadCount","__PRIVATE_QueryEngine","__PRIVATE_LocalStoreImpl","es","ts","rs","ss","os","localDocuments","collectGarbage","collect","__PRIVATE_newLocalStore","__PRIVATE_localStoreHandleUserChange","_s","removedBatchIds","addedBatchIds","__PRIVATE_localStoreGetLastRemoteSnapshotVersion","__PRIVATE_populateDocumentChangeBuffer","us","cs","__PRIVATE_localStoreGetNextMutationBatch","__PRIVATE_localStoreAllocateTarget","__PRIVATE_localStoreReleaseTarget","__PRIVATE_localStoreExecuteQuery","__PRIVATE_setMaxReadTime","ls","__PRIVATE_LocalClientState","activeTargetIds","ds","As","Es","updateTimeMs","__PRIVATE_MemorySharedClientState","eo","no","onlineStateHandler","addPendingMutation","updateMutationState","addLocalQueryTarget","updateQueryState","removeLocalQueryTarget","isLocalQueryTarget","clearQueryState","getAllActiveQueryTargets","isActiveQueryTarget","handleUserChange","setOnlineState","notifyBundleLoaded","__PRIVATE_NoopConnectivityMonitor","ro","__PRIVATE_BrowserConnectivityMonitor","io","so","oo","_o","ao","uo","__PRIVATE_generateUniqueDebugId","BatchGetDocuments","Commit","RunQuery","RunAggregationQuery","__PRIVATE_StreamBridge","co","lo","ho","Po","Io","To","Eo","Ao","Ro","Vo","__PRIVATE_WebChannelConnection","databaseInfo","mo","fo","po","yo","wo","So","bo","Do","Co","vo","forwardChannelRequestTimeoutMs","timeoutSeconds","__PRIVATE_closeFn","__PRIVATE_unguardedEventListen","__PRIVATE_newSerializer","__PRIVATE_ExponentialBackoff","Fo","Mo","xo","Oo","No","Bo","Lo","ko","qo","enqueueAfterDelay","Qo","skipDelay","__PRIVATE_PersistentStream","Ko","$o","connection","authCredentialsProvider","appCheckCredentialsProvider","Uo","Wo","Go","zo","jo","Ho","Jo","stop","Yo","Zo","Xo","e_","t_","n_","r_","i_","_ref9","s_","o_","__","enqueueAndForget","__PRIVATE_PersistentListenStream","targetChange","targetChangeType","documentChange","documentDelete","documentRemove","__PRIVATE_fromWatchChange","a_","u_","addTarget","__PRIVATE_toListenRequestLabels","labels","c_","__PRIVATE_PersistentWriteStream","l_","h_","lastStreamToken","P_","streamToken","__PRIVATE_fromWriteResults","writeResults","commitTime","I_","T_","E_","writes","__PRIVATE_DatastoreImpl","authCredentials","appCheckCredentials","d_","A_","_ref10","_ref11","terminate","__PRIVATE_OnlineStateTracker","asyncQueue","V_","m_","f_","g_","p_","y_","w_","S_","__PRIVATE_RemoteStoreImpl","localStore","datastore","remoteSyncer","b_","D_","C_","v_","F_","__PRIVATE_canUseNetwork","__PRIVATE_disableNetworkInternal","M_","__PRIVATE_enableNetworkInternal","__PRIVATE_remoteStoreListen","__PRIVATE_shouldStartWatchStream","__PRIVATE_startWatchStream","__PRIVATE_ensureWatchStream","__PRIVATE_sendWatchRequest","__PRIVATE_remoteStoreUnlisten","__PRIVATE_sendUnwatchRequest","x_","__PRIVATE_getDatabaseId","__PRIVATE_cleanUpWatchStreamState","__PRIVATE_onWatchStreamOpen","__PRIVATE_onWatchStreamClose","__PRIVATE_onWatchStreamChange","rejectListen","__PRIVATE_disableNetworkUntilRecovery","applyRemoteEvent","__PRIVATE_executeWithRecovery","__PRIVATE_fillWritePipeline","__PRIVATE_ensureWriteStream","__PRIVATE_canAddToWritePipeline","__PRIVATE_addToWritePipeline","__PRIVATE_shouldStartWriteStream","__PRIVATE_startWriteStream","__PRIVATE_onWriteStreamOpen","__PRIVATE_onWriteHandshakeComplete","__PRIVATE_onMutationResult","applySuccessfulWrite","__PRIVATE_onWriteStreamClose","rejectFailedWrite","__PRIVATE_remoteStoreHandleCredentialChange","verifyOperationInProgress","handleCredentialChange","__PRIVATE_remoteStoreApplyPrimaryState","O_","N_","DelayedOperation","targetTimeMs","removalCallback","createAndSchedule","timerHandle","handleDelayElapsed","__PRIVATE_wrapInUserErrorIfRecoverable","DocumentSet","keyedMap","sortedSet","emptySet","__PRIVATE_DocumentChangeSet","B_","L_","ViewSnapshot","oldDocs","mutatedKeys","syncStateChanged","excludesMetadataChanges","hasCachedResults","fromInitialDocuments","__PRIVATE_QueryListenersInfo","k_","__PRIVATE_EventManagerImpl","queries","onlineState","q_","__PRIVATE_eventManagerListen","onListen","Q_","K_","__PRIVATE_raiseSnapshotsInSyncEvent","__PRIVATE_eventManagerUnlisten","onUnlisten","__PRIVATE_eventManagerOnWatchChange","__PRIVATE_eventManagerOnWatchError","__PRIVATE_QueryListener","U_","W_","G_","includeMetadataChanges","z_","j_","H_","J_","__PRIVATE_AddedLimboDocument","__PRIVATE_RemovedLimboDocument","__PRIVATE_View","snapshot","__PRIVATE_QueryView","LimboResolution","__PRIVATE_SyncEngineImpl","remoteStore","sharedClientState","maxConcurrentLimboResolutions","isPrimaryClient","__PRIVATE_syncEngineListen","__PRIVATE_ensureWatchCallbacks","__PRIVATE_initializeViewAndComputeSnapshot","__PRIVATE_updateTrackedLimbos","__PRIVATE_syncEngineUnlisten","__PRIVATE_removeAndCleanupTarget","__PRIVATE_syncEngineApplyRemoteEvent","trackRemovals","__PRIVATE_localStoreApplyRemoteEventToLocalCache","__PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore","__PRIVATE_syncEngineApplyOnlineStateChange","__PRIVATE_syncEngineRejectListen","__PRIVATE_pumpEnqueuedLimboResolutions","__PRIVATE_syncEngineApplySuccessfulWrite","__PRIVATE_localStoreAcknowledgeBatch","__PRIVATE_processUserCallback","__PRIVATE_triggerPendingWritesCallbacks","__PRIVATE_syncEngineRejectFailedWrite","__PRIVATE_removeLimboTarget","__PRIVATE_trackLimboChange","__PRIVATE_syncEngineHandleCredentialChange","__PRIVATE_syncEngineGetRemoteKeysForTarget","__PRIVATE_syncEngineEnsureWriteCallbacks","MemoryOfflineComponentProvider","synchronizeTabs","createSharedClientState","createPersistence","createLocalStore","gcScheduler","createGarbageCollectionScheduler","indexBackfillerScheduler","createIndexBackfillerScheduler","initialUser","OnlineComponentProvider","createDatastore","createRemoteStore","createEventManager","syncEngine","createSyncEngine","__PRIVATE_AsyncObserver","muted","FirestoreClient","clientId","authCredentialListener","appCheckCredentialListener","getConfiguration","setCredentialChangeListener","setAppCheckTokenChangeListener","verifyNotTerminated","isShuttingDown","enterRestrictedMode","enqueueAndForgetEvenWhileRestricted","_onlineComponents","_offlineComponents","__PRIVATE_setOfflineComponentProvider","__PRIVATE_setOnlineComponentProvider","__PRIVATE_ensureOfflineComponents","__PRIVATE_canFallbackFromIndexedDbError","_uninitializedComponentsProvider","_offline","__PRIVATE_ensureOnlineComponents","_online","__PRIVATE_getSyncEngine","__PRIVATE_getEventManager","__PRIVATE_firestoreClientGetDocumentsViaSnapshotListener","__PRIVATE_cloneLongPollingOptions","__PRIVATE_validateNonEmptyArgument","__PRIVATE_validateDocumentPath","__PRIVATE_validateCollectionPath","__PRIVATE_valueDescription","__PRIVATE_cast","FirestoreSettingsImpl","ignoreUndefinedProperties","cacheSizeBytes","__PRIVATE_validateIsNotUsedTogether","experimentalForceLongPolling","experimentalAutoDetectLongPolling","experimentalLongPollingOptions","Firestore$1","_authCredentials","_appCheckCredentials","_databaseId","_app","_persistenceKey","_settings","_settingsFrozen","_initialized","_terminated","_terminateTask","_setSettings","sessionIndex","iamToken","authTokenFactory","client","_getSettings","_freezeSettings","_terminate","connectFirestoreEmulator","mockUserToken","project","user_id","iss","aud","sign_in_provider","identities","alg","createMockUserToken","Query","converter","_query","firestore","withConverter","DocumentReference","_path","CollectionReference","collection","_len7","_len8","_key8","__PRIVATE_AsyncQueueImpl","eu","tu","nu","ru","iu","visibilityState","enqueue","su","ou","_u","au","uu","cu","lu","hu","Firestore","_queue","_firestoreClient","__PRIVATE_configureFirestore","ensureFirestoreConfigured","_offlineComponentProvider","_onlineComponentProvider","_offlineKind","kind","Bytes","_byteString","FieldPath","_len9","_key9","_internalPath","FieldValue","_methodName","GeoPoint","_lat","_long","ParsedSetData","__PRIVATE_isWrite","__PRIVATE_ParseContextImpl","Pu","Iu","Tu","Eu","du","Au","Ru","Vu","mu","__PRIVATE_createError","methodName","fu","gu","__PRIVATE_UserDataReader","pu","__PRIVATE_newUserDataReader","__PRIVATE_parseSetData","merge","mergeFields","__PRIVATE_validatePlainObject","__PRIVATE_parseObject","__PRIVATE_fieldPathFromArgument$1","__PRIVATE_fieldMaskContains","__PRIVATE_parseQueryValue","__PRIVATE_parseData","__PRIVATE_looksLikeJsonObject","_toFieldTransform","__PRIVATE_fieldPathFromDotSeparatedString","DocumentSnapshot$1","_firestore","_userDataWriter","_document","_converter","QueryDocumentSnapshot$1","fromFirestore","convertValue","__PRIVATE_fieldPathFromArgument","__PRIVATE_validateHasExplicitOrderByForLimitToLast","AppliableConstraint","QueryConstraint","_len10","_key10","QueryCompositeFilterConstraint","QueryFieldFilterConstraint","_apply","_field","_op","_value","_create","_parse","__PRIVATE_validateNewFieldFilter","__PRIVATE_validateDisjunctiveFilterElements","__PRIVATE_parseDocumentIdValue","_queryConstraints","_getOperator","_getQueryConstraints","AbstractUserDataWriter","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertObjectMap","convertDocumentKey","__PRIVATE_applyFirestoreDataConverter","toFirestore","SnapshotMetadata","DocumentSnapshot","_firestoreImpl","QueryDocumentSnapshot","serverTimestamps","QuerySnapshot","_snapshot","_cachedChanges","_cachedChangesIncludeMetadataChanges","oldIndex","newIndex","__PRIVATE_resultChangeType","__PRIVATE_ExpUserDataWriter","getDocs","deleteDoc","executeWrite","addDoc","__PRIVATE_syncEngineWrite","storageBucket","messagingSenderId","analyticsProvider","initializeAnalytics","getAnalytics","initializeAuth","authTokenSyncUrl","mintCookie","idTokenResult","idTokenAge","authEmulatorHost","getAuth","separatorIndex","lastIndexOf","getDefaultEmulatorHostnameAndPort","getFirestore","Action","PopStateEventType","invariant","cond","getHistoryState","usr","idx","createLocation","to","_extends","pathname","hash","parsePath","createPath","parsedPath","hashIndex","searchIndex","getUrlBasedHistory","getLocation","createHref","validateLocation","v5Compat","globalHistory","history","Pop","getIndex","handlePop","nextIndex","delta","createURL","replaceState","encodeLocation","Push","historyState","pushState","Replace","go","ResultType","matchRoutes","routes","locationArg","basename","stripBasename","branches","flattenRoutes","score","siblings","compareIndexes","routesMeta","childrenIndex","rankRouteBranches","matchRouteBranch","safelyDecodeURI","parentsMeta","parentPath","flattenRoute","route","relativePath","caseSensitive","joinPaths","computeScore","_route$path","exploded","explodeOptionalSegments","isOptional","endsWith","required","restExploded","subpath","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","initialScore","segment","branch","matchedParams","matchedPathname","remainingPathname","matchPath","pathnameBase","normalizePathname","pattern","matcher","compiledParams","regexpSource","paramName","compilePath","captureGroups","splatValue","safelyDecodeURIComponent","startIndex","nextChar","getInvalidPathError","dest","getPathContributingMatches","getResolveToMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","isEmptyPath","toPathname","toSegments","routePathnameIndex","fromPathname","resolvePathname","normalizeSearch","normalizeHash","resolvePath","hasExplicitTrailingSlash","hasCurrentTrailingSlash","paths","isRouteErrorResponse","internal","validMutationMethodsArr","validRequestMethodsArr","DataRouterContext","React","DataRouterStateContext","NavigationContext","LocationContext","RouteContext","outlet","isDataRoute","RouteErrorContext","useInRouterContext","useLocation","UNSAFE_invariant","useIsomorphicLayoutEffect","static","useNavigate","router","useDataRouterContext","DataRouterHook","UseNavigateStable","useCurrentRouteId","DataRouterStateHook","activeRef","navigate","fromRouteId","useNavigateStable","dataRouterContext","routePathnamesJson","UNSAFE_getResolveToMatches","relative","useNavigateUnstable","useResolvedPath","_temp2","useRoutesImpl","dataRouterState","parentMatches","routeMatch","parentParams","parentPathnameBase","locationFromContext","_parsedLocationArg$pa","parsedLocationArg","renderedMatches","_renderMatches","navigationType","DefaultErrorComponent","_state$errors","useDataRouterState","UseRouteError","routeId","useRouteError","lightgrey","preStyles","fontStyle","defaultErrorElement","RenderErrorBoundary","revalidation","routeContext","RenderedRoute","staticContext","errorElement","ErrorBoundary","_deepestRenderedBoundaryId","_dataRouterState2","_dataRouterState","errorIndex","findIndex","reduceRight","getChildren","hookName","ctx","useRouteContext","thisRoute","Route","_props","Router","basenameProp","locationProp","staticProp","navigationContext","locationContext","trailingPathname","Routes","createRoutesFromChildren","treePath","loader","hasErrorBoundary","shouldRevalidate","handle","SignIn","_auth$currentUser","setEmail","setPassword","signInTransition","setSignInTransition","_jsxs","className","css","_jsx","placeholder","onChange","signUpResponse","createUserWithEmailAndPassword","toCreateAccount","CreateAccount","toSignIn","startTransitionImpl","ReactDOM","BrowserRouter","future","historyRef","setStateImpl","v7_startTransition","newState","isBrowser","ABSOLUTE_URL_REGEX","Link","absoluteHref","reloadDocument","preventScrollReset","unstable_viewTransition","_objectWithoutPropertiesLoose","_excluded","UNSAFE_NavigationContext","isExternal","targetUrl","_temp","joinedPathname","useHref","internalOnClick","replaceProp","isModifiedEvent","shouldProcessLinkClick","useLinkClickHandler","Header","NotFound","Welcome","signedIn","setSignedIn","_auth$currentUser2","currentUserEmail","accountNumber","setAccountNumber","phone","setPhone","setName","addFiendForm","onSubmit","addNewPlayers","disable","Players","setJson","displayPlayers","setDisplayPlayers","swapDisplayPlayers","friends","friend","AddFriend","newJson","prevJson","shareBet","friendsLabel","checkmark","CreateMoneyLine","bet","setBet","contestant1","setContestant1","contestant2","setContestant2","odds1","setOdds1","odds2","setOdds2","shareDisplay","setShareDisplay","handleShare","contestant1Odds","contestant2Odds","ShareBet","MoneyLine","CreateOverUnder","line","setLine","OverUnder","betContainer","BetTextArea","label","step","howMany","setHowMany","howManyOptions","setHowManyOptions","setOptions","PreSetBetting","title","option","optionInput","addOptions","addOneMore","CreateProp","Options","isChecked","setIsChecked","handleCheckboxChange","htmlFor","PreSetBettingOptions","Prop","buttonColor","handleDelete","docId","deleteDocument","ViewMoneyLine","bets","setBets","betId","setBetId","collectionName","querySnapshot","fetchBet","DeleteButton","Buttons","ViewOverUnder","betLabel","lineLabel","actualLine","ViewProp","setLength","swap","goToMoneyLine","goToOverUnder","goToProps","viewBet","DisplayAllBets","setDisplay","filteredData","getBets","swapDisplay","BetNav","DisplayBet","Friends","onPerfEntry","getCLS","getFID","getFCP","getLCP","getTTFB","getElementById","App","reportWebVitals"],"sourceRoot":""} \ No newline at end of file